diff --git a/lib/index.js b/lib/index.js index 7397b91..d9fda72 100644 --- a/lib/index.js +++ b/lib/index.js @@ -5,7 +5,7 @@ const require = __dshCreateRequire(import.meta.url); const __filename = __dshFileURLToPath(import.meta.url); const __dirname = __dshDirname(__filename); var LIe=Object.create;var DM=Object.defineProperty;var UIe=Object.getOwnPropertyDescriptor;var HIe=Object.getOwnPropertyNames;var KIe=Object.getPrototypeOf,xIe=Object.prototype.hasOwnProperty;var $e=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var ue=(n,t)=>()=>(n&&(t=n(n=0)),t);var $=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),Pr=(n,t)=>{for(var o in t)DM(n,o,{get:t[o],enumerable:!0})},YIe=(n,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of HIe(t))!xIe.call(n,e)&&e!==o&&DM(n,e,{get:()=>t[e],enumerable:!(i=UIe(t,e))||i.enumerable});return n};var Je=(n,t,o)=>(o=n!=null?LIe(KIe(n)):{},YIe(t||!n||!n.__esModule?DM(o,"default",{value:n,enumerable:!0}):o,n));var e3=$((drA,$1)=>{var X1=$e("stream").Stream,nfe=$e("util");$1.exports=En;function En(){this.source=null,this.dataSize=0,this.maxDataSize=1024*1024,this.pauseStream=!0,this._maxDataSizeExceeded=!1,this._released=!1,this._bufferedEvents=[]}nfe.inherits(En,X1);En.create=function(n,t){var o=new this;t=t||{};for(var i in t)o[i]=t[i];o.source=n;var e=n.emit;return n.emit=function(){return o._handleEmit(arguments),e.apply(n,arguments)},n.on("error",function(){}),o.pauseStream&&n.pause(),o};Object.defineProperty(En.prototype,"readable",{configurable:!0,enumerable:!0,get:function(){return this.source.readable}});En.prototype.setEncoding=function(){return this.source.setEncoding.apply(this.source,arguments)};En.prototype.resume=function(){this._released||this.release(),this.source.resume()};En.prototype.pause=function(){this.source.pause()};En.prototype.release=function(){this._released=!0,this._bufferedEvents.forEach(function(n){this.emit.apply(this,n)}.bind(this)),this._bufferedEvents=[]};En.prototype.pipe=function(){var n=X1.prototype.pipe.apply(this,arguments);return this.resume(),n};En.prototype._handleEmit=function(n){if(this._released){this.emit.apply(this,n);return}n[0]==="data"&&(this.dataSize+=n[1].length,this._checkIfMaxDataSizeExceeded()),this._bufferedEvents.push(n)};En.prototype._checkIfMaxDataSizeExceeded=function(){if(!this._maxDataSizeExceeded&&!(this.dataSize<=this.maxDataSize)){this._maxDataSizeExceeded=!0;var n="DelayedStream#maxDataSize of "+this.maxDataSize+" bytes exceeded.";this.emit("error",new Error(n))}}});var a3=$((hrA,r3)=>{var sfe=$e("util"),t3=$e("stream").Stream,A3=e3();r3.exports=Er;function Er(){this.writable=!1,this.readable=!0,this.dataSize=0,this.maxDataSize=2*1024*1024,this.pauseStreams=!0,this._released=!1,this._streams=[],this._currentStream=null,this._insideLoop=!1,this._pendingNext=!1}sfe.inherits(Er,t3);Er.create=function(n){var t=new this;n=n||{};for(var o in n)t[o]=n[o];return t};Er.isStreamLike=function(n){return typeof n!="function"&&typeof n!="string"&&typeof n!="boolean"&&typeof n!="number"&&!Buffer.isBuffer(n)};Er.prototype.append=function(n){var t=Er.isStreamLike(n);if(t){if(!(n instanceof A3)){var o=A3.create(n,{maxDataSize:1/0,pauseStream:this.pauseStreams});n.on("data",this._checkDataSize.bind(this)),n=o}this._handleErrors(n),this.pauseStreams&&n.pause()}return this._streams.push(n),this};Er.prototype.pipe=function(n,t){return t3.prototype.pipe.call(this,n,t),this.resume(),n};Er.prototype._getNext=function(){if(this._currentStream=null,this._insideLoop){this._pendingNext=!0;return}this._insideLoop=!0;try{do this._pendingNext=!1,this._realGetNext();while(this._pendingNext)}finally{this._insideLoop=!1}};Er.prototype._realGetNext=function(){var n=this._streams.shift();if(typeof n>"u"){this.end();return}if(typeof n!="function"){this._pipeNext(n);return}var t=n;t(function(o){var i=Er.isStreamLike(o);i&&(o.on("data",this._checkDataSize.bind(this)),this._handleErrors(o)),this._pipeNext(o)}.bind(this))};Er.prototype._pipeNext=function(n){this._currentStream=n;var t=Er.isStreamLike(n);if(t){n.on("end",this._getNext.bind(this)),n.pipe(this,{end:!1});return}var o=n;this.write(o),this._getNext()};Er.prototype._handleErrors=function(n){var t=this;n.on("error",function(o){t._emitError(o)})};Er.prototype.write=function(n){this.emit("data",n)};Er.prototype.pause=function(){this.pauseStreams&&(this.pauseStreams&&this._currentStream&&typeof this._currentStream.pause=="function"&&this._currentStream.pause(),this.emit("pause"))};Er.prototype.resume=function(){this._released||(this._released=!0,this.writable=!0,this._getNext()),this.pauseStreams&&this._currentStream&&typeof this._currentStream.resume=="function"&&this._currentStream.resume(),this.emit("resume")};Er.prototype.end=function(){this._reset(),this.emit("end")};Er.prototype.destroy=function(){this._reset(),this.emit("close")};Er.prototype._reset=function(){this.writable=!1,this._streams=[],this._currentStream=null};Er.prototype._checkDataSize=function(){if(this._updateDataSize(),!(this.dataSize<=this.maxDataSize)){var n="DelayedStream#maxDataSize of "+this.maxDataSize+" bytes exceeded.";this._emitError(new Error(n))}};Er.prototype._updateDataSize=function(){this.dataSize=0;var n=this;this._streams.forEach(function(t){t.dataSize&&(n.dataSize+=t.dataSize)}),this._currentStream&&this._currentStream.dataSize&&(this.dataSize+=this._currentStream.dataSize)};Er.prototype._emitError=function(n){this._reset(),this.emit("error",n)}});var i3=$((ErA,gfe)=>{gfe.exports={"application/1d-interleaved-parityfec":{source:"iana"},"application/3gpdash-qoe-report+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/3gpp-ims+xml":{source:"iana",compressible:!0},"application/3gpphal+json":{source:"iana",compressible:!0},"application/3gpphalforms+json":{source:"iana",compressible:!0},"application/a2l":{source:"iana"},"application/ace+cbor":{source:"iana"},"application/activemessage":{source:"iana"},"application/activity+json":{source:"iana",compressible:!0},"application/alto-costmap+json":{source:"iana",compressible:!0},"application/alto-costmapfilter+json":{source:"iana",compressible:!0},"application/alto-directory+json":{source:"iana",compressible:!0},"application/alto-endpointcost+json":{source:"iana",compressible:!0},"application/alto-endpointcostparams+json":{source:"iana",compressible:!0},"application/alto-endpointprop+json":{source:"iana",compressible:!0},"application/alto-endpointpropparams+json":{source:"iana",compressible:!0},"application/alto-error+json":{source:"iana",compressible:!0},"application/alto-networkmap+json":{source:"iana",compressible:!0},"application/alto-networkmapfilter+json":{source:"iana",compressible:!0},"application/alto-updatestreamcontrol+json":{source:"iana",compressible:!0},"application/alto-updatestreamparams+json":{source:"iana",compressible:!0},"application/aml":{source:"iana"},"application/andrew-inset":{source:"iana",extensions:["ez"]},"application/applefile":{source:"iana"},"application/applixware":{source:"apache",extensions:["aw"]},"application/at+jwt":{source:"iana"},"application/atf":{source:"iana"},"application/atfx":{source:"iana"},"application/atom+xml":{source:"iana",compressible:!0,extensions:["atom"]},"application/atomcat+xml":{source:"iana",compressible:!0,extensions:["atomcat"]},"application/atomdeleted+xml":{source:"iana",compressible:!0,extensions:["atomdeleted"]},"application/atomicmail":{source:"iana"},"application/atomsvc+xml":{source:"iana",compressible:!0,extensions:["atomsvc"]},"application/atsc-dwd+xml":{source:"iana",compressible:!0,extensions:["dwd"]},"application/atsc-dynamic-event-message":{source:"iana"},"application/atsc-held+xml":{source:"iana",compressible:!0,extensions:["held"]},"application/atsc-rdt+json":{source:"iana",compressible:!0},"application/atsc-rsat+xml":{source:"iana",compressible:!0,extensions:["rsat"]},"application/atxml":{source:"iana"},"application/auth-policy+xml":{source:"iana",compressible:!0},"application/bacnet-xdd+zip":{source:"iana",compressible:!1},"application/batch-smtp":{source:"iana"},"application/bdoc":{compressible:!1,extensions:["bdoc"]},"application/beep+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/calendar+json":{source:"iana",compressible:!0},"application/calendar+xml":{source:"iana",compressible:!0,extensions:["xcs"]},"application/call-completion":{source:"iana"},"application/cals-1840":{source:"iana"},"application/captive+json":{source:"iana",compressible:!0},"application/cbor":{source:"iana"},"application/cbor-seq":{source:"iana"},"application/cccex":{source:"iana"},"application/ccmp+xml":{source:"iana",compressible:!0},"application/ccxml+xml":{source:"iana",compressible:!0,extensions:["ccxml"]},"application/cdfx+xml":{source:"iana",compressible:!0,extensions:["cdfx"]},"application/cdmi-capability":{source:"iana",extensions:["cdmia"]},"application/cdmi-container":{source:"iana",extensions:["cdmic"]},"application/cdmi-domain":{source:"iana",extensions:["cdmid"]},"application/cdmi-object":{source:"iana",extensions:["cdmio"]},"application/cdmi-queue":{source:"iana",extensions:["cdmiq"]},"application/cdni":{source:"iana"},"application/cea":{source:"iana"},"application/cea-2018+xml":{source:"iana",compressible:!0},"application/cellml+xml":{source:"iana",compressible:!0},"application/cfw":{source:"iana"},"application/city+json":{source:"iana",compressible:!0},"application/clr":{source:"iana"},"application/clue+xml":{source:"iana",compressible:!0},"application/clue_info+xml":{source:"iana",compressible:!0},"application/cms":{source:"iana"},"application/cnrp+xml":{source:"iana",compressible:!0},"application/coap-group+json":{source:"iana",compressible:!0},"application/coap-payload":{source:"iana"},"application/commonground":{source:"iana"},"application/conference-info+xml":{source:"iana",compressible:!0},"application/cose":{source:"iana"},"application/cose-key":{source:"iana"},"application/cose-key-set":{source:"iana"},"application/cpl+xml":{source:"iana",compressible:!0,extensions:["cpl"]},"application/csrattrs":{source:"iana"},"application/csta+xml":{source:"iana",compressible:!0},"application/cstadata+xml":{source:"iana",compressible:!0},"application/csvm+json":{source:"iana",compressible:!0},"application/cu-seeme":{source:"apache",extensions:["cu"]},"application/cwt":{source:"iana"},"application/cybercash":{source:"iana"},"application/dart":{compressible:!0},"application/dash+xml":{source:"iana",compressible:!0,extensions:["mpd"]},"application/dash-patch+xml":{source:"iana",compressible:!0,extensions:["mpp"]},"application/dashdelta":{source:"iana"},"application/davmount+xml":{source:"iana",compressible:!0,extensions:["davmount"]},"application/dca-rft":{source:"iana"},"application/dcd":{source:"iana"},"application/dec-dx":{source:"iana"},"application/dialog-info+xml":{source:"iana",compressible:!0},"application/dicom":{source:"iana"},"application/dicom+json":{source:"iana",compressible:!0},"application/dicom+xml":{source:"iana",compressible:!0},"application/dii":{source:"iana"},"application/dit":{source:"iana"},"application/dns":{source:"iana"},"application/dns+json":{source:"iana",compressible:!0},"application/dns-message":{source:"iana"},"application/docbook+xml":{source:"apache",compressible:!0,extensions:["dbk"]},"application/dots+cbor":{source:"iana"},"application/dskpp+xml":{source:"iana",compressible:!0},"application/dssc+der":{source:"iana",extensions:["dssc"]},"application/dssc+xml":{source:"iana",compressible:!0,extensions:["xdssc"]},"application/dvcs":{source:"iana"},"application/ecmascript":{source:"iana",compressible:!0,extensions:["es","ecma"]},"application/edi-consent":{source:"iana"},"application/edi-x12":{source:"iana",compressible:!1},"application/edifact":{source:"iana",compressible:!1},"application/efi":{source:"iana"},"application/elm+json":{source:"iana",charset:"UTF-8",compressible:!0},"application/elm+xml":{source:"iana",compressible:!0},"application/emergencycalldata.cap+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/emergencycalldata.comment+xml":{source:"iana",compressible:!0},"application/emergencycalldata.control+xml":{source:"iana",compressible:!0},"application/emergencycalldata.deviceinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.ecall.msd":{source:"iana"},"application/emergencycalldata.providerinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.serviceinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.subscriberinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.veds+xml":{source:"iana",compressible:!0},"application/emma+xml":{source:"iana",compressible:!0,extensions:["emma"]},"application/emotionml+xml":{source:"iana",compressible:!0,extensions:["emotionml"]},"application/encaprtp":{source:"iana"},"application/epp+xml":{source:"iana",compressible:!0},"application/epub+zip":{source:"iana",compressible:!1,extensions:["epub"]},"application/eshop":{source:"iana"},"application/exi":{source:"iana",extensions:["exi"]},"application/expect-ct-report+json":{source:"iana",compressible:!0},"application/express":{source:"iana",extensions:["exp"]},"application/fastinfoset":{source:"iana"},"application/fastsoap":{source:"iana"},"application/fdt+xml":{source:"iana",compressible:!0,extensions:["fdt"]},"application/fhir+json":{source:"iana",charset:"UTF-8",compressible:!0},"application/fhir+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/fido.trusted-apps+json":{compressible:!0},"application/fits":{source:"iana"},"application/flexfec":{source:"iana"},"application/font-sfnt":{source:"iana"},"application/font-tdpfr":{source:"iana",extensions:["pfr"]},"application/font-woff":{source:"iana",compressible:!1},"application/framework-attributes+xml":{source:"iana",compressible:!0},"application/geo+json":{source:"iana",compressible:!0,extensions:["geojson"]},"application/geo+json-seq":{source:"iana"},"application/geopackage+sqlite3":{source:"iana"},"application/geoxacml+xml":{source:"iana",compressible:!0},"application/gltf-buffer":{source:"iana"},"application/gml+xml":{source:"iana",compressible:!0,extensions:["gml"]},"application/gpx+xml":{source:"apache",compressible:!0,extensions:["gpx"]},"application/gxf":{source:"apache",extensions:["gxf"]},"application/gzip":{source:"iana",compressible:!1,extensions:["gz"]},"application/h224":{source:"iana"},"application/held+xml":{source:"iana",compressible:!0},"application/hjson":{extensions:["hjson"]},"application/http":{source:"iana"},"application/hyperstudio":{source:"iana",extensions:["stk"]},"application/ibe-key-request+xml":{source:"iana",compressible:!0},"application/ibe-pkg-reply+xml":{source:"iana",compressible:!0},"application/ibe-pp-data":{source:"iana"},"application/iges":{source:"iana"},"application/im-iscomposing+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/index":{source:"iana"},"application/index.cmd":{source:"iana"},"application/index.obj":{source:"iana"},"application/index.response":{source:"iana"},"application/index.vnd":{source:"iana"},"application/inkml+xml":{source:"iana",compressible:!0,extensions:["ink","inkml"]},"application/iotp":{source:"iana"},"application/ipfix":{source:"iana",extensions:["ipfix"]},"application/ipp":{source:"iana"},"application/isup":{source:"iana"},"application/its+xml":{source:"iana",compressible:!0,extensions:["its"]},"application/java-archive":{source:"apache",compressible:!1,extensions:["jar","war","ear"]},"application/java-serialized-object":{source:"apache",compressible:!1,extensions:["ser"]},"application/java-vm":{source:"apache",compressible:!1,extensions:["class"]},"application/javascript":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["js","mjs"]},"application/jf2feed+json":{source:"iana",compressible:!0},"application/jose":{source:"iana"},"application/jose+json":{source:"iana",compressible:!0},"application/jrd+json":{source:"iana",compressible:!0},"application/jscalendar+json":{source:"iana",compressible:!0},"application/json":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["json","map"]},"application/json-patch+json":{source:"iana",compressible:!0},"application/json-seq":{source:"iana"},"application/json5":{extensions:["json5"]},"application/jsonml+json":{source:"apache",compressible:!0,extensions:["jsonml"]},"application/jwk+json":{source:"iana",compressible:!0},"application/jwk-set+json":{source:"iana",compressible:!0},"application/jwt":{source:"iana"},"application/kpml-request+xml":{source:"iana",compressible:!0},"application/kpml-response+xml":{source:"iana",compressible:!0},"application/ld+json":{source:"iana",compressible:!0,extensions:["jsonld"]},"application/lgr+xml":{source:"iana",compressible:!0,extensions:["lgr"]},"application/link-format":{source:"iana"},"application/load-control+xml":{source:"iana",compressible:!0},"application/lost+xml":{source:"iana",compressible:!0,extensions:["lostxml"]},"application/lostsync+xml":{source:"iana",compressible:!0},"application/lpf+zip":{source:"iana",compressible:!1},"application/lxf":{source:"iana"},"application/mac-binhex40":{source:"iana",extensions:["hqx"]},"application/mac-compactpro":{source:"apache",extensions:["cpt"]},"application/macwriteii":{source:"iana"},"application/mads+xml":{source:"iana",compressible:!0,extensions:["mads"]},"application/manifest+json":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["webmanifest"]},"application/marc":{source:"iana",extensions:["mrc"]},"application/marcxml+xml":{source:"iana",compressible:!0,extensions:["mrcx"]},"application/mathematica":{source:"iana",extensions:["ma","nb","mb"]},"application/mathml+xml":{source:"iana",compressible:!0,extensions:["mathml"]},"application/mathml-content+xml":{source:"iana",compressible:!0},"application/mathml-presentation+xml":{source:"iana",compressible:!0},"application/mbms-associated-procedure-description+xml":{source:"iana",compressible:!0},"application/mbms-deregister+xml":{source:"iana",compressible:!0},"application/mbms-envelope+xml":{source:"iana",compressible:!0},"application/mbms-msk+xml":{source:"iana",compressible:!0},"application/mbms-msk-response+xml":{source:"iana",compressible:!0},"application/mbms-protection-description+xml":{source:"iana",compressible:!0},"application/mbms-reception-report+xml":{source:"iana",compressible:!0},"application/mbms-register+xml":{source:"iana",compressible:!0},"application/mbms-register-response+xml":{source:"iana",compressible:!0},"application/mbms-schedule+xml":{source:"iana",compressible:!0},"application/mbms-user-service-description+xml":{source:"iana",compressible:!0},"application/mbox":{source:"iana",extensions:["mbox"]},"application/media-policy-dataset+xml":{source:"iana",compressible:!0,extensions:["mpf"]},"application/media_control+xml":{source:"iana",compressible:!0},"application/mediaservercontrol+xml":{source:"iana",compressible:!0,extensions:["mscml"]},"application/merge-patch+json":{source:"iana",compressible:!0},"application/metalink+xml":{source:"apache",compressible:!0,extensions:["metalink"]},"application/metalink4+xml":{source:"iana",compressible:!0,extensions:["meta4"]},"application/mets+xml":{source:"iana",compressible:!0,extensions:["mets"]},"application/mf4":{source:"iana"},"application/mikey":{source:"iana"},"application/mipc":{source:"iana"},"application/missing-blocks+cbor-seq":{source:"iana"},"application/mmt-aei+xml":{source:"iana",compressible:!0,extensions:["maei"]},"application/mmt-usd+xml":{source:"iana",compressible:!0,extensions:["musd"]},"application/mods+xml":{source:"iana",compressible:!0,extensions:["mods"]},"application/moss-keys":{source:"iana"},"application/moss-signature":{source:"iana"},"application/mosskey-data":{source:"iana"},"application/mosskey-request":{source:"iana"},"application/mp21":{source:"iana",extensions:["m21","mp21"]},"application/mp4":{source:"iana",extensions:["mp4s","m4p"]},"application/mpeg4-generic":{source:"iana"},"application/mpeg4-iod":{source:"iana"},"application/mpeg4-iod-xmt":{source:"iana"},"application/mrb-consumer+xml":{source:"iana",compressible:!0},"application/mrb-publish+xml":{source:"iana",compressible:!0},"application/msc-ivr+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/msc-mixer+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/msword":{source:"iana",compressible:!1,extensions:["doc","dot"]},"application/mud+json":{source:"iana",compressible:!0},"application/multipart-core":{source:"iana"},"application/mxf":{source:"iana",extensions:["mxf"]},"application/n-quads":{source:"iana",extensions:["nq"]},"application/n-triples":{source:"iana",extensions:["nt"]},"application/nasdata":{source:"iana"},"application/news-checkgroups":{source:"iana",charset:"US-ASCII"},"application/news-groupinfo":{source:"iana",charset:"US-ASCII"},"application/news-transmission":{source:"iana"},"application/nlsml+xml":{source:"iana",compressible:!0},"application/node":{source:"iana",extensions:["cjs"]},"application/nss":{source:"iana"},"application/oauth-authz-req+jwt":{source:"iana"},"application/oblivious-dns-message":{source:"iana"},"application/ocsp-request":{source:"iana"},"application/ocsp-response":{source:"iana"},"application/octet-stream":{source:"iana",compressible:!1,extensions:["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},"application/oda":{source:"iana",extensions:["oda"]},"application/odm+xml":{source:"iana",compressible:!0},"application/odx":{source:"iana"},"application/oebps-package+xml":{source:"iana",compressible:!0,extensions:["opf"]},"application/ogg":{source:"iana",compressible:!1,extensions:["ogx"]},"application/omdoc+xml":{source:"apache",compressible:!0,extensions:["omdoc"]},"application/onenote":{source:"apache",extensions:["onetoc","onetoc2","onetmp","onepkg"]},"application/opc-nodeset+xml":{source:"iana",compressible:!0},"application/oscore":{source:"iana"},"application/oxps":{source:"iana",extensions:["oxps"]},"application/p21":{source:"iana"},"application/p21+zip":{source:"iana",compressible:!1},"application/p2p-overlay+xml":{source:"iana",compressible:!0,extensions:["relo"]},"application/parityfec":{source:"iana"},"application/passport":{source:"iana"},"application/patch-ops-error+xml":{source:"iana",compressible:!0,extensions:["xer"]},"application/pdf":{source:"iana",compressible:!1,extensions:["pdf"]},"application/pdx":{source:"iana"},"application/pem-certificate-chain":{source:"iana"},"application/pgp-encrypted":{source:"iana",compressible:!1,extensions:["pgp"]},"application/pgp-keys":{source:"iana",extensions:["asc"]},"application/pgp-signature":{source:"iana",extensions:["asc","sig"]},"application/pics-rules":{source:"apache",extensions:["prf"]},"application/pidf+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/pidf-diff+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/pkcs10":{source:"iana",extensions:["p10"]},"application/pkcs12":{source:"iana"},"application/pkcs7-mime":{source:"iana",extensions:["p7m","p7c"]},"application/pkcs7-signature":{source:"iana",extensions:["p7s"]},"application/pkcs8":{source:"iana",extensions:["p8"]},"application/pkcs8-encrypted":{source:"iana"},"application/pkix-attr-cert":{source:"iana",extensions:["ac"]},"application/pkix-cert":{source:"iana",extensions:["cer"]},"application/pkix-crl":{source:"iana",extensions:["crl"]},"application/pkix-pkipath":{source:"iana",extensions:["pkipath"]},"application/pkixcmp":{source:"iana",extensions:["pki"]},"application/pls+xml":{source:"iana",compressible:!0,extensions:["pls"]},"application/poc-settings+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/postscript":{source:"iana",compressible:!0,extensions:["ai","eps","ps"]},"application/ppsp-tracker+json":{source:"iana",compressible:!0},"application/problem+json":{source:"iana",compressible:!0},"application/problem+xml":{source:"iana",compressible:!0},"application/provenance+xml":{source:"iana",compressible:!0,extensions:["provx"]},"application/prs.alvestrand.titrax-sheet":{source:"iana"},"application/prs.cww":{source:"iana",extensions:["cww"]},"application/prs.cyn":{source:"iana",charset:"7-BIT"},"application/prs.hpub+zip":{source:"iana",compressible:!1},"application/prs.nprend":{source:"iana"},"application/prs.plucker":{source:"iana"},"application/prs.rdf-xml-crypt":{source:"iana"},"application/prs.xsf+xml":{source:"iana",compressible:!0},"application/pskc+xml":{source:"iana",compressible:!0,extensions:["pskcxml"]},"application/pvd+json":{source:"iana",compressible:!0},"application/qsig":{source:"iana"},"application/raml+yaml":{compressible:!0,extensions:["raml"]},"application/raptorfec":{source:"iana"},"application/rdap+json":{source:"iana",compressible:!0},"application/rdf+xml":{source:"iana",compressible:!0,extensions:["rdf","owl"]},"application/reginfo+xml":{source:"iana",compressible:!0,extensions:["rif"]},"application/relax-ng-compact-syntax":{source:"iana",extensions:["rnc"]},"application/remote-printing":{source:"iana"},"application/reputon+json":{source:"iana",compressible:!0},"application/resource-lists+xml":{source:"iana",compressible:!0,extensions:["rl"]},"application/resource-lists-diff+xml":{source:"iana",compressible:!0,extensions:["rld"]},"application/rfc+xml":{source:"iana",compressible:!0},"application/riscos":{source:"iana"},"application/rlmi+xml":{source:"iana",compressible:!0},"application/rls-services+xml":{source:"iana",compressible:!0,extensions:["rs"]},"application/route-apd+xml":{source:"iana",compressible:!0,extensions:["rapd"]},"application/route-s-tsid+xml":{source:"iana",compressible:!0,extensions:["sls"]},"application/route-usd+xml":{source:"iana",compressible:!0,extensions:["rusd"]},"application/rpki-ghostbusters":{source:"iana",extensions:["gbr"]},"application/rpki-manifest":{source:"iana",extensions:["mft"]},"application/rpki-publication":{source:"iana"},"application/rpki-roa":{source:"iana",extensions:["roa"]},"application/rpki-updown":{source:"iana"},"application/rsd+xml":{source:"apache",compressible:!0,extensions:["rsd"]},"application/rss+xml":{source:"apache",compressible:!0,extensions:["rss"]},"application/rtf":{source:"iana",compressible:!0,extensions:["rtf"]},"application/rtploopback":{source:"iana"},"application/rtx":{source:"iana"},"application/samlassertion+xml":{source:"iana",compressible:!0},"application/samlmetadata+xml":{source:"iana",compressible:!0},"application/sarif+json":{source:"iana",compressible:!0},"application/sarif-external-properties+json":{source:"iana",compressible:!0},"application/sbe":{source:"iana"},"application/sbml+xml":{source:"iana",compressible:!0,extensions:["sbml"]},"application/scaip+xml":{source:"iana",compressible:!0},"application/scim+json":{source:"iana",compressible:!0},"application/scvp-cv-request":{source:"iana",extensions:["scq"]},"application/scvp-cv-response":{source:"iana",extensions:["scs"]},"application/scvp-vp-request":{source:"iana",extensions:["spq"]},"application/scvp-vp-response":{source:"iana",extensions:["spp"]},"application/sdp":{source:"iana",extensions:["sdp"]},"application/secevent+jwt":{source:"iana"},"application/senml+cbor":{source:"iana"},"application/senml+json":{source:"iana",compressible:!0},"application/senml+xml":{source:"iana",compressible:!0,extensions:["senmlx"]},"application/senml-etch+cbor":{source:"iana"},"application/senml-etch+json":{source:"iana",compressible:!0},"application/senml-exi":{source:"iana"},"application/sensml+cbor":{source:"iana"},"application/sensml+json":{source:"iana",compressible:!0},"application/sensml+xml":{source:"iana",compressible:!0,extensions:["sensmlx"]},"application/sensml-exi":{source:"iana"},"application/sep+xml":{source:"iana",compressible:!0},"application/sep-exi":{source:"iana"},"application/session-info":{source:"iana"},"application/set-payment":{source:"iana"},"application/set-payment-initiation":{source:"iana",extensions:["setpay"]},"application/set-registration":{source:"iana"},"application/set-registration-initiation":{source:"iana",extensions:["setreg"]},"application/sgml":{source:"iana"},"application/sgml-open-catalog":{source:"iana"},"application/shf+xml":{source:"iana",compressible:!0,extensions:["shf"]},"application/sieve":{source:"iana",extensions:["siv","sieve"]},"application/simple-filter+xml":{source:"iana",compressible:!0},"application/simple-message-summary":{source:"iana"},"application/simplesymbolcontainer":{source:"iana"},"application/sipc":{source:"iana"},"application/slate":{source:"iana"},"application/smil":{source:"iana"},"application/smil+xml":{source:"iana",compressible:!0,extensions:["smi","smil"]},"application/smpte336m":{source:"iana"},"application/soap+fastinfoset":{source:"iana"},"application/soap+xml":{source:"iana",compressible:!0},"application/sparql-query":{source:"iana",extensions:["rq"]},"application/sparql-results+xml":{source:"iana",compressible:!0,extensions:["srx"]},"application/spdx+json":{source:"iana",compressible:!0},"application/spirits-event+xml":{source:"iana",compressible:!0},"application/sql":{source:"iana"},"application/srgs":{source:"iana",extensions:["gram"]},"application/srgs+xml":{source:"iana",compressible:!0,extensions:["grxml"]},"application/sru+xml":{source:"iana",compressible:!0,extensions:["sru"]},"application/ssdl+xml":{source:"apache",compressible:!0,extensions:["ssdl"]},"application/ssml+xml":{source:"iana",compressible:!0,extensions:["ssml"]},"application/stix+json":{source:"iana",compressible:!0},"application/swid+xml":{source:"iana",compressible:!0,extensions:["swidtag"]},"application/tamp-apex-update":{source:"iana"},"application/tamp-apex-update-confirm":{source:"iana"},"application/tamp-community-update":{source:"iana"},"application/tamp-community-update-confirm":{source:"iana"},"application/tamp-error":{source:"iana"},"application/tamp-sequence-adjust":{source:"iana"},"application/tamp-sequence-adjust-confirm":{source:"iana"},"application/tamp-status-query":{source:"iana"},"application/tamp-status-response":{source:"iana"},"application/tamp-update":{source:"iana"},"application/tamp-update-confirm":{source:"iana"},"application/tar":{compressible:!0},"application/taxii+json":{source:"iana",compressible:!0},"application/td+json":{source:"iana",compressible:!0},"application/tei+xml":{source:"iana",compressible:!0,extensions:["tei","teicorpus"]},"application/tetra_isi":{source:"iana"},"application/thraud+xml":{source:"iana",compressible:!0,extensions:["tfi"]},"application/timestamp-query":{source:"iana"},"application/timestamp-reply":{source:"iana"},"application/timestamped-data":{source:"iana",extensions:["tsd"]},"application/tlsrpt+gzip":{source:"iana"},"application/tlsrpt+json":{source:"iana",compressible:!0},"application/tnauthlist":{source:"iana"},"application/token-introspection+jwt":{source:"iana"},"application/toml":{compressible:!0,extensions:["toml"]},"application/trickle-ice-sdpfrag":{source:"iana"},"application/trig":{source:"iana",extensions:["trig"]},"application/ttml+xml":{source:"iana",compressible:!0,extensions:["ttml"]},"application/tve-trigger":{source:"iana"},"application/tzif":{source:"iana"},"application/tzif-leap":{source:"iana"},"application/ubjson":{compressible:!1,extensions:["ubj"]},"application/ulpfec":{source:"iana"},"application/urc-grpsheet+xml":{source:"iana",compressible:!0},"application/urc-ressheet+xml":{source:"iana",compressible:!0,extensions:["rsheet"]},"application/urc-targetdesc+xml":{source:"iana",compressible:!0,extensions:["td"]},"application/urc-uisocketdesc+xml":{source:"iana",compressible:!0},"application/vcard+json":{source:"iana",compressible:!0},"application/vcard+xml":{source:"iana",compressible:!0},"application/vemmi":{source:"iana"},"application/vividence.scriptfile":{source:"apache"},"application/vnd.1000minds.decision-model+xml":{source:"iana",compressible:!0,extensions:["1km"]},"application/vnd.3gpp-prose+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc3ch+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-v2x-local-service-information":{source:"iana"},"application/vnd.3gpp.5gnas":{source:"iana"},"application/vnd.3gpp.access-transfer-events+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.bsf+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.gmop+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.gtpc":{source:"iana"},"application/vnd.3gpp.interworking-data":{source:"iana"},"application/vnd.3gpp.lpp":{source:"iana"},"application/vnd.3gpp.mc-signalling-ear":{source:"iana"},"application/vnd.3gpp.mcdata-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-payload":{source:"iana"},"application/vnd.3gpp.mcdata-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-signalling":{source:"iana"},"application/vnd.3gpp.mcdata-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-floor-request+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-location-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-mbms-usage-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-signed+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-ue-init-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-affiliation-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-location-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-mbms-usage-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-transmission-request+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mid-call+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.ngap":{source:"iana"},"application/vnd.3gpp.pfcp":{source:"iana"},"application/vnd.3gpp.pic-bw-large":{source:"iana",extensions:["plb"]},"application/vnd.3gpp.pic-bw-small":{source:"iana",extensions:["psb"]},"application/vnd.3gpp.pic-bw-var":{source:"iana",extensions:["pvb"]},"application/vnd.3gpp.s1ap":{source:"iana"},"application/vnd.3gpp.sms":{source:"iana"},"application/vnd.3gpp.sms+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.srvcc-ext+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.srvcc-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.state-and-event-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.ussd+xml":{source:"iana",compressible:!0},"application/vnd.3gpp2.bcmcsinfo+xml":{source:"iana",compressible:!0},"application/vnd.3gpp2.sms":{source:"iana"},"application/vnd.3gpp2.tcap":{source:"iana",extensions:["tcap"]},"application/vnd.3lightssoftware.imagescal":{source:"iana"},"application/vnd.3m.post-it-notes":{source:"iana",extensions:["pwn"]},"application/vnd.accpac.simply.aso":{source:"iana",extensions:["aso"]},"application/vnd.accpac.simply.imp":{source:"iana",extensions:["imp"]},"application/vnd.acucobol":{source:"iana",extensions:["acu"]},"application/vnd.acucorp":{source:"iana",extensions:["atc","acutc"]},"application/vnd.adobe.air-application-installer-package+zip":{source:"apache",compressible:!1,extensions:["air"]},"application/vnd.adobe.flash.movie":{source:"iana"},"application/vnd.adobe.formscentral.fcdt":{source:"iana",extensions:["fcdt"]},"application/vnd.adobe.fxp":{source:"iana",extensions:["fxp","fxpl"]},"application/vnd.adobe.partial-upload":{source:"iana"},"application/vnd.adobe.xdp+xml":{source:"iana",compressible:!0,extensions:["xdp"]},"application/vnd.adobe.xfdf":{source:"iana",extensions:["xfdf"]},"application/vnd.aether.imp":{source:"iana"},"application/vnd.afpc.afplinedata":{source:"iana"},"application/vnd.afpc.afplinedata-pagedef":{source:"iana"},"application/vnd.afpc.cmoca-cmresource":{source:"iana"},"application/vnd.afpc.foca-charset":{source:"iana"},"application/vnd.afpc.foca-codedfont":{source:"iana"},"application/vnd.afpc.foca-codepage":{source:"iana"},"application/vnd.afpc.modca":{source:"iana"},"application/vnd.afpc.modca-cmtable":{source:"iana"},"application/vnd.afpc.modca-formdef":{source:"iana"},"application/vnd.afpc.modca-mediummap":{source:"iana"},"application/vnd.afpc.modca-objectcontainer":{source:"iana"},"application/vnd.afpc.modca-overlay":{source:"iana"},"application/vnd.afpc.modca-pagesegment":{source:"iana"},"application/vnd.age":{source:"iana",extensions:["age"]},"application/vnd.ah-barcode":{source:"iana"},"application/vnd.ahead.space":{source:"iana",extensions:["ahead"]},"application/vnd.airzip.filesecure.azf":{source:"iana",extensions:["azf"]},"application/vnd.airzip.filesecure.azs":{source:"iana",extensions:["azs"]},"application/vnd.amadeus+json":{source:"iana",compressible:!0},"application/vnd.amazon.ebook":{source:"apache",extensions:["azw"]},"application/vnd.amazon.mobi8-ebook":{source:"iana"},"application/vnd.americandynamics.acc":{source:"iana",extensions:["acc"]},"application/vnd.amiga.ami":{source:"iana",extensions:["ami"]},"application/vnd.amundsen.maze+xml":{source:"iana",compressible:!0},"application/vnd.android.ota":{source:"iana"},"application/vnd.android.package-archive":{source:"apache",compressible:!1,extensions:["apk"]},"application/vnd.anki":{source:"iana"},"application/vnd.anser-web-certificate-issue-initiation":{source:"iana",extensions:["cii"]},"application/vnd.anser-web-funds-transfer-initiation":{source:"apache",extensions:["fti"]},"application/vnd.antix.game-component":{source:"iana",extensions:["atx"]},"application/vnd.apache.arrow.file":{source:"iana"},"application/vnd.apache.arrow.stream":{source:"iana"},"application/vnd.apache.thrift.binary":{source:"iana"},"application/vnd.apache.thrift.compact":{source:"iana"},"application/vnd.apache.thrift.json":{source:"iana"},"application/vnd.api+json":{source:"iana",compressible:!0},"application/vnd.aplextor.warrp+json":{source:"iana",compressible:!0},"application/vnd.apothekende.reservation+json":{source:"iana",compressible:!0},"application/vnd.apple.installer+xml":{source:"iana",compressible:!0,extensions:["mpkg"]},"application/vnd.apple.keynote":{source:"iana",extensions:["key"]},"application/vnd.apple.mpegurl":{source:"iana",extensions:["m3u8"]},"application/vnd.apple.numbers":{source:"iana",extensions:["numbers"]},"application/vnd.apple.pages":{source:"iana",extensions:["pages"]},"application/vnd.apple.pkpass":{compressible:!1,extensions:["pkpass"]},"application/vnd.arastra.swi":{source:"iana"},"application/vnd.aristanetworks.swi":{source:"iana",extensions:["swi"]},"application/vnd.artisan+json":{source:"iana",compressible:!0},"application/vnd.artsquare":{source:"iana"},"application/vnd.astraea-software.iota":{source:"iana",extensions:["iota"]},"application/vnd.audiograph":{source:"iana",extensions:["aep"]},"application/vnd.autopackage":{source:"iana"},"application/vnd.avalon+json":{source:"iana",compressible:!0},"application/vnd.avistar+xml":{source:"iana",compressible:!0},"application/vnd.balsamiq.bmml+xml":{source:"iana",compressible:!0,extensions:["bmml"]},"application/vnd.balsamiq.bmpr":{source:"iana"},"application/vnd.banana-accounting":{source:"iana"},"application/vnd.bbf.usp.error":{source:"iana"},"application/vnd.bbf.usp.msg":{source:"iana"},"application/vnd.bbf.usp.msg+json":{source:"iana",compressible:!0},"application/vnd.bekitzur-stech+json":{source:"iana",compressible:!0},"application/vnd.bint.med-content":{source:"iana"},"application/vnd.biopax.rdf+xml":{source:"iana",compressible:!0},"application/vnd.blink-idb-value-wrapper":{source:"iana"},"application/vnd.blueice.multipass":{source:"iana",extensions:["mpm"]},"application/vnd.bluetooth.ep.oob":{source:"iana"},"application/vnd.bluetooth.le.oob":{source:"iana"},"application/vnd.bmi":{source:"iana",extensions:["bmi"]},"application/vnd.bpf":{source:"iana"},"application/vnd.bpf3":{source:"iana"},"application/vnd.businessobjects":{source:"iana",extensions:["rep"]},"application/vnd.byu.uapi+json":{source:"iana",compressible:!0},"application/vnd.cab-jscript":{source:"iana"},"application/vnd.canon-cpdl":{source:"iana"},"application/vnd.canon-lips":{source:"iana"},"application/vnd.capasystems-pg+json":{source:"iana",compressible:!0},"application/vnd.cendio.thinlinc.clientconf":{source:"iana"},"application/vnd.century-systems.tcp_stream":{source:"iana"},"application/vnd.chemdraw+xml":{source:"iana",compressible:!0,extensions:["cdxml"]},"application/vnd.chess-pgn":{source:"iana"},"application/vnd.chipnuts.karaoke-mmd":{source:"iana",extensions:["mmd"]},"application/vnd.ciedi":{source:"iana"},"application/vnd.cinderella":{source:"iana",extensions:["cdy"]},"application/vnd.cirpack.isdn-ext":{source:"iana"},"application/vnd.citationstyles.style+xml":{source:"iana",compressible:!0,extensions:["csl"]},"application/vnd.claymore":{source:"iana",extensions:["cla"]},"application/vnd.cloanto.rp9":{source:"iana",extensions:["rp9"]},"application/vnd.clonk.c4group":{source:"iana",extensions:["c4g","c4d","c4f","c4p","c4u"]},"application/vnd.cluetrust.cartomobile-config":{source:"iana",extensions:["c11amc"]},"application/vnd.cluetrust.cartomobile-config-pkg":{source:"iana",extensions:["c11amz"]},"application/vnd.coffeescript":{source:"iana"},"application/vnd.collabio.xodocuments.document":{source:"iana"},"application/vnd.collabio.xodocuments.document-template":{source:"iana"},"application/vnd.collabio.xodocuments.presentation":{source:"iana"},"application/vnd.collabio.xodocuments.presentation-template":{source:"iana"},"application/vnd.collabio.xodocuments.spreadsheet":{source:"iana"},"application/vnd.collabio.xodocuments.spreadsheet-template":{source:"iana"},"application/vnd.collection+json":{source:"iana",compressible:!0},"application/vnd.collection.doc+json":{source:"iana",compressible:!0},"application/vnd.collection.next+json":{source:"iana",compressible:!0},"application/vnd.comicbook+zip":{source:"iana",compressible:!1},"application/vnd.comicbook-rar":{source:"iana"},"application/vnd.commerce-battelle":{source:"iana"},"application/vnd.commonspace":{source:"iana",extensions:["csp"]},"application/vnd.contact.cmsg":{source:"iana",extensions:["cdbcmsg"]},"application/vnd.coreos.ignition+json":{source:"iana",compressible:!0},"application/vnd.cosmocaller":{source:"iana",extensions:["cmc"]},"application/vnd.crick.clicker":{source:"iana",extensions:["clkx"]},"application/vnd.crick.clicker.keyboard":{source:"iana",extensions:["clkk"]},"application/vnd.crick.clicker.palette":{source:"iana",extensions:["clkp"]},"application/vnd.crick.clicker.template":{source:"iana",extensions:["clkt"]},"application/vnd.crick.clicker.wordbank":{source:"iana",extensions:["clkw"]},"application/vnd.criticaltools.wbs+xml":{source:"iana",compressible:!0,extensions:["wbs"]},"application/vnd.cryptii.pipe+json":{source:"iana",compressible:!0},"application/vnd.crypto-shade-file":{source:"iana"},"application/vnd.cryptomator.encrypted":{source:"iana"},"application/vnd.cryptomator.vault":{source:"iana"},"application/vnd.ctc-posml":{source:"iana",extensions:["pml"]},"application/vnd.ctct.ws+xml":{source:"iana",compressible:!0},"application/vnd.cups-pdf":{source:"iana"},"application/vnd.cups-postscript":{source:"iana"},"application/vnd.cups-ppd":{source:"iana",extensions:["ppd"]},"application/vnd.cups-raster":{source:"iana"},"application/vnd.cups-raw":{source:"iana"},"application/vnd.curl":{source:"iana"},"application/vnd.curl.car":{source:"apache",extensions:["car"]},"application/vnd.curl.pcurl":{source:"apache",extensions:["pcurl"]},"application/vnd.cyan.dean.root+xml":{source:"iana",compressible:!0},"application/vnd.cybank":{source:"iana"},"application/vnd.cyclonedx+json":{source:"iana",compressible:!0},"application/vnd.cyclonedx+xml":{source:"iana",compressible:!0},"application/vnd.d2l.coursepackage1p0+zip":{source:"iana",compressible:!1},"application/vnd.d3m-dataset":{source:"iana"},"application/vnd.d3m-problem":{source:"iana"},"application/vnd.dart":{source:"iana",compressible:!0,extensions:["dart"]},"application/vnd.data-vision.rdz":{source:"iana",extensions:["rdz"]},"application/vnd.datapackage+json":{source:"iana",compressible:!0},"application/vnd.dataresource+json":{source:"iana",compressible:!0},"application/vnd.dbf":{source:"iana",extensions:["dbf"]},"application/vnd.debian.binary-package":{source:"iana"},"application/vnd.dece.data":{source:"iana",extensions:["uvf","uvvf","uvd","uvvd"]},"application/vnd.dece.ttml+xml":{source:"iana",compressible:!0,extensions:["uvt","uvvt"]},"application/vnd.dece.unspecified":{source:"iana",extensions:["uvx","uvvx"]},"application/vnd.dece.zip":{source:"iana",extensions:["uvz","uvvz"]},"application/vnd.denovo.fcselayout-link":{source:"iana",extensions:["fe_launch"]},"application/vnd.desmume.movie":{source:"iana"},"application/vnd.dir-bi.plate-dl-nosuffix":{source:"iana"},"application/vnd.dm.delegation+xml":{source:"iana",compressible:!0},"application/vnd.dna":{source:"iana",extensions:["dna"]},"application/vnd.document+json":{source:"iana",compressible:!0},"application/vnd.dolby.mlp":{source:"apache",extensions:["mlp"]},"application/vnd.dolby.mobile.1":{source:"iana"},"application/vnd.dolby.mobile.2":{source:"iana"},"application/vnd.doremir.scorecloud-binary-document":{source:"iana"},"application/vnd.dpgraph":{source:"iana",extensions:["dpg"]},"application/vnd.dreamfactory":{source:"iana",extensions:["dfac"]},"application/vnd.drive+json":{source:"iana",compressible:!0},"application/vnd.ds-keypoint":{source:"apache",extensions:["kpxx"]},"application/vnd.dtg.local":{source:"iana"},"application/vnd.dtg.local.flash":{source:"iana"},"application/vnd.dtg.local.html":{source:"iana"},"application/vnd.dvb.ait":{source:"iana",extensions:["ait"]},"application/vnd.dvb.dvbisl+xml":{source:"iana",compressible:!0},"application/vnd.dvb.dvbj":{source:"iana"},"application/vnd.dvb.esgcontainer":{source:"iana"},"application/vnd.dvb.ipdcdftnotifaccess":{source:"iana"},"application/vnd.dvb.ipdcesgaccess":{source:"iana"},"application/vnd.dvb.ipdcesgaccess2":{source:"iana"},"application/vnd.dvb.ipdcesgpdd":{source:"iana"},"application/vnd.dvb.ipdcroaming":{source:"iana"},"application/vnd.dvb.iptv.alfec-base":{source:"iana"},"application/vnd.dvb.iptv.alfec-enhancement":{source:"iana"},"application/vnd.dvb.notif-aggregate-root+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-container+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-generic+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-msglist+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-registration-request+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-registration-response+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-init+xml":{source:"iana",compressible:!0},"application/vnd.dvb.pfr":{source:"iana"},"application/vnd.dvb.service":{source:"iana",extensions:["svc"]},"application/vnd.dxr":{source:"iana"},"application/vnd.dynageo":{source:"iana",extensions:["geo"]},"application/vnd.dzr":{source:"iana"},"application/vnd.easykaraoke.cdgdownload":{source:"iana"},"application/vnd.ecdis-update":{source:"iana"},"application/vnd.ecip.rlp":{source:"iana"},"application/vnd.eclipse.ditto+json":{source:"iana",compressible:!0},"application/vnd.ecowin.chart":{source:"iana",extensions:["mag"]},"application/vnd.ecowin.filerequest":{source:"iana"},"application/vnd.ecowin.fileupdate":{source:"iana"},"application/vnd.ecowin.series":{source:"iana"},"application/vnd.ecowin.seriesrequest":{source:"iana"},"application/vnd.ecowin.seriesupdate":{source:"iana"},"application/vnd.efi.img":{source:"iana"},"application/vnd.efi.iso":{source:"iana"},"application/vnd.emclient.accessrequest+xml":{source:"iana",compressible:!0},"application/vnd.enliven":{source:"iana",extensions:["nml"]},"application/vnd.enphase.envoy":{source:"iana"},"application/vnd.eprints.data+xml":{source:"iana",compressible:!0},"application/vnd.epson.esf":{source:"iana",extensions:["esf"]},"application/vnd.epson.msf":{source:"iana",extensions:["msf"]},"application/vnd.epson.quickanime":{source:"iana",extensions:["qam"]},"application/vnd.epson.salt":{source:"iana",extensions:["slt"]},"application/vnd.epson.ssf":{source:"iana",extensions:["ssf"]},"application/vnd.ericsson.quickcall":{source:"iana"},"application/vnd.espass-espass+zip":{source:"iana",compressible:!1},"application/vnd.eszigno3+xml":{source:"iana",compressible:!0,extensions:["es3","et3"]},"application/vnd.etsi.aoc+xml":{source:"iana",compressible:!0},"application/vnd.etsi.asic-e+zip":{source:"iana",compressible:!1},"application/vnd.etsi.asic-s+zip":{source:"iana",compressible:!1},"application/vnd.etsi.cug+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvcommand+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvdiscovery+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvprofile+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-bc+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-cod+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-npvr+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvservice+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsync+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvueprofile+xml":{source:"iana",compressible:!0},"application/vnd.etsi.mcid+xml":{source:"iana",compressible:!0},"application/vnd.etsi.mheg5":{source:"iana"},"application/vnd.etsi.overload-control-policy-dataset+xml":{source:"iana",compressible:!0},"application/vnd.etsi.pstn+xml":{source:"iana",compressible:!0},"application/vnd.etsi.sci+xml":{source:"iana",compressible:!0},"application/vnd.etsi.simservs+xml":{source:"iana",compressible:!0},"application/vnd.etsi.timestamp-token":{source:"iana"},"application/vnd.etsi.tsl+xml":{source:"iana",compressible:!0},"application/vnd.etsi.tsl.der":{source:"iana"},"application/vnd.eu.kasparian.car+json":{source:"iana",compressible:!0},"application/vnd.eudora.data":{source:"iana"},"application/vnd.evolv.ecig.profile":{source:"iana"},"application/vnd.evolv.ecig.settings":{source:"iana"},"application/vnd.evolv.ecig.theme":{source:"iana"},"application/vnd.exstream-empower+zip":{source:"iana",compressible:!1},"application/vnd.exstream-package":{source:"iana"},"application/vnd.ezpix-album":{source:"iana",extensions:["ez2"]},"application/vnd.ezpix-package":{source:"iana",extensions:["ez3"]},"application/vnd.f-secure.mobile":{source:"iana"},"application/vnd.familysearch.gedcom+zip":{source:"iana",compressible:!1},"application/vnd.fastcopy-disk-image":{source:"iana"},"application/vnd.fdf":{source:"iana",extensions:["fdf"]},"application/vnd.fdsn.mseed":{source:"iana",extensions:["mseed"]},"application/vnd.fdsn.seed":{source:"iana",extensions:["seed","dataless"]},"application/vnd.ffsns":{source:"iana"},"application/vnd.ficlab.flb+zip":{source:"iana",compressible:!1},"application/vnd.filmit.zfc":{source:"iana"},"application/vnd.fints":{source:"iana"},"application/vnd.firemonkeys.cloudcell":{source:"iana"},"application/vnd.flographit":{source:"iana",extensions:["gph"]},"application/vnd.fluxtime.clip":{source:"iana",extensions:["ftc"]},"application/vnd.font-fontforge-sfd":{source:"iana"},"application/vnd.framemaker":{source:"iana",extensions:["fm","frame","maker","book"]},"application/vnd.frogans.fnc":{source:"iana",extensions:["fnc"]},"application/vnd.frogans.ltf":{source:"iana",extensions:["ltf"]},"application/vnd.fsc.weblaunch":{source:"iana",extensions:["fsc"]},"application/vnd.fujifilm.fb.docuworks":{source:"iana"},"application/vnd.fujifilm.fb.docuworks.binder":{source:"iana"},"application/vnd.fujifilm.fb.docuworks.container":{source:"iana"},"application/vnd.fujifilm.fb.jfi+xml":{source:"iana",compressible:!0},"application/vnd.fujitsu.oasys":{source:"iana",extensions:["oas"]},"application/vnd.fujitsu.oasys2":{source:"iana",extensions:["oa2"]},"application/vnd.fujitsu.oasys3":{source:"iana",extensions:["oa3"]},"application/vnd.fujitsu.oasysgp":{source:"iana",extensions:["fg5"]},"application/vnd.fujitsu.oasysprs":{source:"iana",extensions:["bh2"]},"application/vnd.fujixerox.art-ex":{source:"iana"},"application/vnd.fujixerox.art4":{source:"iana"},"application/vnd.fujixerox.ddd":{source:"iana",extensions:["ddd"]},"application/vnd.fujixerox.docuworks":{source:"iana",extensions:["xdw"]},"application/vnd.fujixerox.docuworks.binder":{source:"iana",extensions:["xbd"]},"application/vnd.fujixerox.docuworks.container":{source:"iana"},"application/vnd.fujixerox.hbpl":{source:"iana"},"application/vnd.fut-misnet":{source:"iana"},"application/vnd.futoin+cbor":{source:"iana"},"application/vnd.futoin+json":{source:"iana",compressible:!0},"application/vnd.fuzzysheet":{source:"iana",extensions:["fzs"]},"application/vnd.genomatix.tuxedo":{source:"iana",extensions:["txd"]},"application/vnd.gentics.grd+json":{source:"iana",compressible:!0},"application/vnd.geo+json":{source:"iana",compressible:!0},"application/vnd.geocube+xml":{source:"iana",compressible:!0},"application/vnd.geogebra.file":{source:"iana",extensions:["ggb"]},"application/vnd.geogebra.slides":{source:"iana"},"application/vnd.geogebra.tool":{source:"iana",extensions:["ggt"]},"application/vnd.geometry-explorer":{source:"iana",extensions:["gex","gre"]},"application/vnd.geonext":{source:"iana",extensions:["gxt"]},"application/vnd.geoplan":{source:"iana",extensions:["g2w"]},"application/vnd.geospace":{source:"iana",extensions:["g3w"]},"application/vnd.gerber":{source:"iana"},"application/vnd.globalplatform.card-content-mgt":{source:"iana"},"application/vnd.globalplatform.card-content-mgt-response":{source:"iana"},"application/vnd.gmx":{source:"iana",extensions:["gmx"]},"application/vnd.google-apps.document":{compressible:!1,extensions:["gdoc"]},"application/vnd.google-apps.presentation":{compressible:!1,extensions:["gslides"]},"application/vnd.google-apps.spreadsheet":{compressible:!1,extensions:["gsheet"]},"application/vnd.google-earth.kml+xml":{source:"iana",compressible:!0,extensions:["kml"]},"application/vnd.google-earth.kmz":{source:"iana",compressible:!1,extensions:["kmz"]},"application/vnd.gov.sk.e-form+xml":{source:"iana",compressible:!0},"application/vnd.gov.sk.e-form+zip":{source:"iana",compressible:!1},"application/vnd.gov.sk.xmldatacontainer+xml":{source:"iana",compressible:!0},"application/vnd.grafeq":{source:"iana",extensions:["gqf","gqs"]},"application/vnd.gridmp":{source:"iana"},"application/vnd.groove-account":{source:"iana",extensions:["gac"]},"application/vnd.groove-help":{source:"iana",extensions:["ghf"]},"application/vnd.groove-identity-message":{source:"iana",extensions:["gim"]},"application/vnd.groove-injector":{source:"iana",extensions:["grv"]},"application/vnd.groove-tool-message":{source:"iana",extensions:["gtm"]},"application/vnd.groove-tool-template":{source:"iana",extensions:["tpl"]},"application/vnd.groove-vcard":{source:"iana",extensions:["vcg"]},"application/vnd.hal+json":{source:"iana",compressible:!0},"application/vnd.hal+xml":{source:"iana",compressible:!0,extensions:["hal"]},"application/vnd.handheld-entertainment+xml":{source:"iana",compressible:!0,extensions:["zmm"]},"application/vnd.hbci":{source:"iana",extensions:["hbci"]},"application/vnd.hc+json":{source:"iana",compressible:!0},"application/vnd.hcl-bireports":{source:"iana"},"application/vnd.hdt":{source:"iana"},"application/vnd.heroku+json":{source:"iana",compressible:!0},"application/vnd.hhe.lesson-player":{source:"iana",extensions:["les"]},"application/vnd.hl7cda+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.hl7v2+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.hp-hpgl":{source:"iana",extensions:["hpgl"]},"application/vnd.hp-hpid":{source:"iana",extensions:["hpid"]},"application/vnd.hp-hps":{source:"iana",extensions:["hps"]},"application/vnd.hp-jlyt":{source:"iana",extensions:["jlt"]},"application/vnd.hp-pcl":{source:"iana",extensions:["pcl"]},"application/vnd.hp-pclxl":{source:"iana",extensions:["pclxl"]},"application/vnd.httphone":{source:"iana"},"application/vnd.hydrostatix.sof-data":{source:"iana",extensions:["sfd-hdstx"]},"application/vnd.hyper+json":{source:"iana",compressible:!0},"application/vnd.hyper-item+json":{source:"iana",compressible:!0},"application/vnd.hyperdrive+json":{source:"iana",compressible:!0},"application/vnd.hzn-3d-crossword":{source:"iana"},"application/vnd.ibm.afplinedata":{source:"iana"},"application/vnd.ibm.electronic-media":{source:"iana"},"application/vnd.ibm.minipay":{source:"iana",extensions:["mpy"]},"application/vnd.ibm.modcap":{source:"iana",extensions:["afp","listafp","list3820"]},"application/vnd.ibm.rights-management":{source:"iana",extensions:["irm"]},"application/vnd.ibm.secure-container":{source:"iana",extensions:["sc"]},"application/vnd.iccprofile":{source:"iana",extensions:["icc","icm"]},"application/vnd.ieee.1905":{source:"iana"},"application/vnd.igloader":{source:"iana",extensions:["igl"]},"application/vnd.imagemeter.folder+zip":{source:"iana",compressible:!1},"application/vnd.imagemeter.image+zip":{source:"iana",compressible:!1},"application/vnd.immervision-ivp":{source:"iana",extensions:["ivp"]},"application/vnd.immervision-ivu":{source:"iana",extensions:["ivu"]},"application/vnd.ims.imsccv1p1":{source:"iana"},"application/vnd.ims.imsccv1p2":{source:"iana"},"application/vnd.ims.imsccv1p3":{source:"iana"},"application/vnd.ims.lis.v2.result+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolconsumerprofile+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolproxy+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolproxy.id+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolsettings+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolsettings.simple+json":{source:"iana",compressible:!0},"application/vnd.informedcontrol.rms+xml":{source:"iana",compressible:!0},"application/vnd.informix-visionary":{source:"iana"},"application/vnd.infotech.project":{source:"iana"},"application/vnd.infotech.project+xml":{source:"iana",compressible:!0},"application/vnd.innopath.wamp.notification":{source:"iana"},"application/vnd.insors.igm":{source:"iana",extensions:["igm"]},"application/vnd.intercon.formnet":{source:"iana",extensions:["xpw","xpx"]},"application/vnd.intergeo":{source:"iana",extensions:["i2g"]},"application/vnd.intertrust.digibox":{source:"iana"},"application/vnd.intertrust.nncp":{source:"iana"},"application/vnd.intu.qbo":{source:"iana",extensions:["qbo"]},"application/vnd.intu.qfx":{source:"iana",extensions:["qfx"]},"application/vnd.iptc.g2.catalogitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.conceptitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.knowledgeitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.newsitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.newsmessage+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.packageitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.planningitem+xml":{source:"iana",compressible:!0},"application/vnd.ipunplugged.rcprofile":{source:"iana",extensions:["rcprofile"]},"application/vnd.irepository.package+xml":{source:"iana",compressible:!0,extensions:["irp"]},"application/vnd.is-xpr":{source:"iana",extensions:["xpr"]},"application/vnd.isac.fcs":{source:"iana",extensions:["fcs"]},"application/vnd.iso11783-10+zip":{source:"iana",compressible:!1},"application/vnd.jam":{source:"iana",extensions:["jam"]},"application/vnd.japannet-directory-service":{source:"iana"},"application/vnd.japannet-jpnstore-wakeup":{source:"iana"},"application/vnd.japannet-payment-wakeup":{source:"iana"},"application/vnd.japannet-registration":{source:"iana"},"application/vnd.japannet-registration-wakeup":{source:"iana"},"application/vnd.japannet-setstore-wakeup":{source:"iana"},"application/vnd.japannet-verification":{source:"iana"},"application/vnd.japannet-verification-wakeup":{source:"iana"},"application/vnd.jcp.javame.midlet-rms":{source:"iana",extensions:["rms"]},"application/vnd.jisp":{source:"iana",extensions:["jisp"]},"application/vnd.joost.joda-archive":{source:"iana",extensions:["joda"]},"application/vnd.jsk.isdn-ngn":{source:"iana"},"application/vnd.kahootz":{source:"iana",extensions:["ktz","ktr"]},"application/vnd.kde.karbon":{source:"iana",extensions:["karbon"]},"application/vnd.kde.kchart":{source:"iana",extensions:["chrt"]},"application/vnd.kde.kformula":{source:"iana",extensions:["kfo"]},"application/vnd.kde.kivio":{source:"iana",extensions:["flw"]},"application/vnd.kde.kontour":{source:"iana",extensions:["kon"]},"application/vnd.kde.kpresenter":{source:"iana",extensions:["kpr","kpt"]},"application/vnd.kde.kspread":{source:"iana",extensions:["ksp"]},"application/vnd.kde.kword":{source:"iana",extensions:["kwd","kwt"]},"application/vnd.kenameaapp":{source:"iana",extensions:["htke"]},"application/vnd.kidspiration":{source:"iana",extensions:["kia"]},"application/vnd.kinar":{source:"iana",extensions:["kne","knp"]},"application/vnd.koan":{source:"iana",extensions:["skp","skd","skt","skm"]},"application/vnd.kodak-descriptor":{source:"iana",extensions:["sse"]},"application/vnd.las":{source:"iana"},"application/vnd.las.las+json":{source:"iana",compressible:!0},"application/vnd.las.las+xml":{source:"iana",compressible:!0,extensions:["lasxml"]},"application/vnd.laszip":{source:"iana"},"application/vnd.leap+json":{source:"iana",compressible:!0},"application/vnd.liberty-request+xml":{source:"iana",compressible:!0},"application/vnd.llamagraphics.life-balance.desktop":{source:"iana",extensions:["lbd"]},"application/vnd.llamagraphics.life-balance.exchange+xml":{source:"iana",compressible:!0,extensions:["lbe"]},"application/vnd.logipipe.circuit+zip":{source:"iana",compressible:!1},"application/vnd.loom":{source:"iana"},"application/vnd.lotus-1-2-3":{source:"iana",extensions:["123"]},"application/vnd.lotus-approach":{source:"iana",extensions:["apr"]},"application/vnd.lotus-freelance":{source:"iana",extensions:["pre"]},"application/vnd.lotus-notes":{source:"iana",extensions:["nsf"]},"application/vnd.lotus-organizer":{source:"iana",extensions:["org"]},"application/vnd.lotus-screencam":{source:"iana",extensions:["scm"]},"application/vnd.lotus-wordpro":{source:"iana",extensions:["lwp"]},"application/vnd.macports.portpkg":{source:"iana",extensions:["portpkg"]},"application/vnd.mapbox-vector-tile":{source:"iana",extensions:["mvt"]},"application/vnd.marlin.drm.actiontoken+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.conftoken+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.license+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.mdcf":{source:"iana"},"application/vnd.mason+json":{source:"iana",compressible:!0},"application/vnd.maxar.archive.3tz+zip":{source:"iana",compressible:!1},"application/vnd.maxmind.maxmind-db":{source:"iana"},"application/vnd.mcd":{source:"iana",extensions:["mcd"]},"application/vnd.medcalcdata":{source:"iana",extensions:["mc1"]},"application/vnd.mediastation.cdkey":{source:"iana",extensions:["cdkey"]},"application/vnd.meridian-slingshot":{source:"iana"},"application/vnd.mfer":{source:"iana",extensions:["mwf"]},"application/vnd.mfmp":{source:"iana",extensions:["mfm"]},"application/vnd.micro+json":{source:"iana",compressible:!0},"application/vnd.micrografx.flo":{source:"iana",extensions:["flo"]},"application/vnd.micrografx.igx":{source:"iana",extensions:["igx"]},"application/vnd.microsoft.portable-executable":{source:"iana"},"application/vnd.microsoft.windows.thumbnail-cache":{source:"iana"},"application/vnd.miele+json":{source:"iana",compressible:!0},"application/vnd.mif":{source:"iana",extensions:["mif"]},"application/vnd.minisoft-hp3000-save":{source:"iana"},"application/vnd.mitsubishi.misty-guard.trustweb":{source:"iana"},"application/vnd.mobius.daf":{source:"iana",extensions:["daf"]},"application/vnd.mobius.dis":{source:"iana",extensions:["dis"]},"application/vnd.mobius.mbk":{source:"iana",extensions:["mbk"]},"application/vnd.mobius.mqy":{source:"iana",extensions:["mqy"]},"application/vnd.mobius.msl":{source:"iana",extensions:["msl"]},"application/vnd.mobius.plc":{source:"iana",extensions:["plc"]},"application/vnd.mobius.txf":{source:"iana",extensions:["txf"]},"application/vnd.mophun.application":{source:"iana",extensions:["mpn"]},"application/vnd.mophun.certificate":{source:"iana",extensions:["mpc"]},"application/vnd.motorola.flexsuite":{source:"iana"},"application/vnd.motorola.flexsuite.adsi":{source:"iana"},"application/vnd.motorola.flexsuite.fis":{source:"iana"},"application/vnd.motorola.flexsuite.gotap":{source:"iana"},"application/vnd.motorola.flexsuite.kmr":{source:"iana"},"application/vnd.motorola.flexsuite.ttc":{source:"iana"},"application/vnd.motorola.flexsuite.wem":{source:"iana"},"application/vnd.motorola.iprm":{source:"iana"},"application/vnd.mozilla.xul+xml":{source:"iana",compressible:!0,extensions:["xul"]},"application/vnd.ms-3mfdocument":{source:"iana"},"application/vnd.ms-artgalry":{source:"iana",extensions:["cil"]},"application/vnd.ms-asf":{source:"iana"},"application/vnd.ms-cab-compressed":{source:"iana",extensions:["cab"]},"application/vnd.ms-color.iccprofile":{source:"apache"},"application/vnd.ms-excel":{source:"iana",compressible:!1,extensions:["xls","xlm","xla","xlc","xlt","xlw"]},"application/vnd.ms-excel.addin.macroenabled.12":{source:"iana",extensions:["xlam"]},"application/vnd.ms-excel.sheet.binary.macroenabled.12":{source:"iana",extensions:["xlsb"]},"application/vnd.ms-excel.sheet.macroenabled.12":{source:"iana",extensions:["xlsm"]},"application/vnd.ms-excel.template.macroenabled.12":{source:"iana",extensions:["xltm"]},"application/vnd.ms-fontobject":{source:"iana",compressible:!0,extensions:["eot"]},"application/vnd.ms-htmlhelp":{source:"iana",extensions:["chm"]},"application/vnd.ms-ims":{source:"iana",extensions:["ims"]},"application/vnd.ms-lrm":{source:"iana",extensions:["lrm"]},"application/vnd.ms-office.activex+xml":{source:"iana",compressible:!0},"application/vnd.ms-officetheme":{source:"iana",extensions:["thmx"]},"application/vnd.ms-opentype":{source:"apache",compressible:!0},"application/vnd.ms-outlook":{compressible:!1,extensions:["msg"]},"application/vnd.ms-package.obfuscated-opentype":{source:"apache"},"application/vnd.ms-pki.seccat":{source:"apache",extensions:["cat"]},"application/vnd.ms-pki.stl":{source:"apache",extensions:["stl"]},"application/vnd.ms-playready.initiator+xml":{source:"iana",compressible:!0},"application/vnd.ms-powerpoint":{source:"iana",compressible:!1,extensions:["ppt","pps","pot"]},"application/vnd.ms-powerpoint.addin.macroenabled.12":{source:"iana",extensions:["ppam"]},"application/vnd.ms-powerpoint.presentation.macroenabled.12":{source:"iana",extensions:["pptm"]},"application/vnd.ms-powerpoint.slide.macroenabled.12":{source:"iana",extensions:["sldm"]},"application/vnd.ms-powerpoint.slideshow.macroenabled.12":{source:"iana",extensions:["ppsm"]},"application/vnd.ms-powerpoint.template.macroenabled.12":{source:"iana",extensions:["potm"]},"application/vnd.ms-printdevicecapabilities+xml":{source:"iana",compressible:!0},"application/vnd.ms-printing.printticket+xml":{source:"apache",compressible:!0},"application/vnd.ms-printschematicket+xml":{source:"iana",compressible:!0},"application/vnd.ms-project":{source:"iana",extensions:["mpp","mpt"]},"application/vnd.ms-tnef":{source:"iana"},"application/vnd.ms-windows.devicepairing":{source:"iana"},"application/vnd.ms-windows.nwprinting.oob":{source:"iana"},"application/vnd.ms-windows.printerpairing":{source:"iana"},"application/vnd.ms-windows.wsd.oob":{source:"iana"},"application/vnd.ms-wmdrm.lic-chlg-req":{source:"iana"},"application/vnd.ms-wmdrm.lic-resp":{source:"iana"},"application/vnd.ms-wmdrm.meter-chlg-req":{source:"iana"},"application/vnd.ms-wmdrm.meter-resp":{source:"iana"},"application/vnd.ms-word.document.macroenabled.12":{source:"iana",extensions:["docm"]},"application/vnd.ms-word.template.macroenabled.12":{source:"iana",extensions:["dotm"]},"application/vnd.ms-works":{source:"iana",extensions:["wps","wks","wcm","wdb"]},"application/vnd.ms-wpl":{source:"iana",extensions:["wpl"]},"application/vnd.ms-xpsdocument":{source:"iana",compressible:!1,extensions:["xps"]},"application/vnd.msa-disk-image":{source:"iana"},"application/vnd.mseq":{source:"iana",extensions:["mseq"]},"application/vnd.msign":{source:"iana"},"application/vnd.multiad.creator":{source:"iana"},"application/vnd.multiad.creator.cif":{source:"iana"},"application/vnd.music-niff":{source:"iana"},"application/vnd.musician":{source:"iana",extensions:["mus"]},"application/vnd.muvee.style":{source:"iana",extensions:["msty"]},"application/vnd.mynfc":{source:"iana",extensions:["taglet"]},"application/vnd.nacamar.ybrid+json":{source:"iana",compressible:!0},"application/vnd.ncd.control":{source:"iana"},"application/vnd.ncd.reference":{source:"iana"},"application/vnd.nearst.inv+json":{source:"iana",compressible:!0},"application/vnd.nebumind.line":{source:"iana"},"application/vnd.nervana":{source:"iana"},"application/vnd.netfpx":{source:"iana"},"application/vnd.neurolanguage.nlu":{source:"iana",extensions:["nlu"]},"application/vnd.nimn":{source:"iana"},"application/vnd.nintendo.nitro.rom":{source:"iana"},"application/vnd.nintendo.snes.rom":{source:"iana"},"application/vnd.nitf":{source:"iana",extensions:["ntf","nitf"]},"application/vnd.noblenet-directory":{source:"iana",extensions:["nnd"]},"application/vnd.noblenet-sealer":{source:"iana",extensions:["nns"]},"application/vnd.noblenet-web":{source:"iana",extensions:["nnw"]},"application/vnd.nokia.catalogs":{source:"iana"},"application/vnd.nokia.conml+wbxml":{source:"iana"},"application/vnd.nokia.conml+xml":{source:"iana",compressible:!0},"application/vnd.nokia.iptv.config+xml":{source:"iana",compressible:!0},"application/vnd.nokia.isds-radio-presets":{source:"iana"},"application/vnd.nokia.landmark+wbxml":{source:"iana"},"application/vnd.nokia.landmark+xml":{source:"iana",compressible:!0},"application/vnd.nokia.landmarkcollection+xml":{source:"iana",compressible:!0},"application/vnd.nokia.n-gage.ac+xml":{source:"iana",compressible:!0,extensions:["ac"]},"application/vnd.nokia.n-gage.data":{source:"iana",extensions:["ngdat"]},"application/vnd.nokia.n-gage.symbian.install":{source:"iana",extensions:["n-gage"]},"application/vnd.nokia.ncd":{source:"iana"},"application/vnd.nokia.pcd+wbxml":{source:"iana"},"application/vnd.nokia.pcd+xml":{source:"iana",compressible:!0},"application/vnd.nokia.radio-preset":{source:"iana",extensions:["rpst"]},"application/vnd.nokia.radio-presets":{source:"iana",extensions:["rpss"]},"application/vnd.novadigm.edm":{source:"iana",extensions:["edm"]},"application/vnd.novadigm.edx":{source:"iana",extensions:["edx"]},"application/vnd.novadigm.ext":{source:"iana",extensions:["ext"]},"application/vnd.ntt-local.content-share":{source:"iana"},"application/vnd.ntt-local.file-transfer":{source:"iana"},"application/vnd.ntt-local.ogw_remote-access":{source:"iana"},"application/vnd.ntt-local.sip-ta_remote":{source:"iana"},"application/vnd.ntt-local.sip-ta_tcp_stream":{source:"iana"},"application/vnd.oasis.opendocument.chart":{source:"iana",extensions:["odc"]},"application/vnd.oasis.opendocument.chart-template":{source:"iana",extensions:["otc"]},"application/vnd.oasis.opendocument.database":{source:"iana",extensions:["odb"]},"application/vnd.oasis.opendocument.formula":{source:"iana",extensions:["odf"]},"application/vnd.oasis.opendocument.formula-template":{source:"iana",extensions:["odft"]},"application/vnd.oasis.opendocument.graphics":{source:"iana",compressible:!1,extensions:["odg"]},"application/vnd.oasis.opendocument.graphics-template":{source:"iana",extensions:["otg"]},"application/vnd.oasis.opendocument.image":{source:"iana",extensions:["odi"]},"application/vnd.oasis.opendocument.image-template":{source:"iana",extensions:["oti"]},"application/vnd.oasis.opendocument.presentation":{source:"iana",compressible:!1,extensions:["odp"]},"application/vnd.oasis.opendocument.presentation-template":{source:"iana",extensions:["otp"]},"application/vnd.oasis.opendocument.spreadsheet":{source:"iana",compressible:!1,extensions:["ods"]},"application/vnd.oasis.opendocument.spreadsheet-template":{source:"iana",extensions:["ots"]},"application/vnd.oasis.opendocument.text":{source:"iana",compressible:!1,extensions:["odt"]},"application/vnd.oasis.opendocument.text-master":{source:"iana",extensions:["odm"]},"application/vnd.oasis.opendocument.text-template":{source:"iana",extensions:["ott"]},"application/vnd.oasis.opendocument.text-web":{source:"iana",extensions:["oth"]},"application/vnd.obn":{source:"iana"},"application/vnd.ocf+cbor":{source:"iana"},"application/vnd.oci.image.manifest.v1+json":{source:"iana",compressible:!0},"application/vnd.oftn.l10n+json":{source:"iana",compressible:!0},"application/vnd.oipf.contentaccessdownload+xml":{source:"iana",compressible:!0},"application/vnd.oipf.contentaccessstreaming+xml":{source:"iana",compressible:!0},"application/vnd.oipf.cspg-hexbinary":{source:"iana"},"application/vnd.oipf.dae.svg+xml":{source:"iana",compressible:!0},"application/vnd.oipf.dae.xhtml+xml":{source:"iana",compressible:!0},"application/vnd.oipf.mippvcontrolmessage+xml":{source:"iana",compressible:!0},"application/vnd.oipf.pae.gem":{source:"iana"},"application/vnd.oipf.spdiscovery+xml":{source:"iana",compressible:!0},"application/vnd.oipf.spdlist+xml":{source:"iana",compressible:!0},"application/vnd.oipf.ueprofile+xml":{source:"iana",compressible:!0},"application/vnd.oipf.userprofile+xml":{source:"iana",compressible:!0},"application/vnd.olpc-sugar":{source:"iana",extensions:["xo"]},"application/vnd.oma-scws-config":{source:"iana"},"application/vnd.oma-scws-http-request":{source:"iana"},"application/vnd.oma-scws-http-response":{source:"iana"},"application/vnd.oma.bcast.associated-procedure-parameter+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.drm-trigger+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.imd+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.ltkm":{source:"iana"},"application/vnd.oma.bcast.notification+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.provisioningtrigger":{source:"iana"},"application/vnd.oma.bcast.sgboot":{source:"iana"},"application/vnd.oma.bcast.sgdd+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.sgdu":{source:"iana"},"application/vnd.oma.bcast.simple-symbol-container":{source:"iana"},"application/vnd.oma.bcast.smartcard-trigger+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.sprov+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.stkm":{source:"iana"},"application/vnd.oma.cab-address-book+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-feature-handler+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-pcc+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-subs-invite+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-user-prefs+xml":{source:"iana",compressible:!0},"application/vnd.oma.dcd":{source:"iana"},"application/vnd.oma.dcdc":{source:"iana"},"application/vnd.oma.dd2+xml":{source:"iana",compressible:!0,extensions:["dd2"]},"application/vnd.oma.drm.risd+xml":{source:"iana",compressible:!0},"application/vnd.oma.group-usage-list+xml":{source:"iana",compressible:!0},"application/vnd.oma.lwm2m+cbor":{source:"iana"},"application/vnd.oma.lwm2m+json":{source:"iana",compressible:!0},"application/vnd.oma.lwm2m+tlv":{source:"iana"},"application/vnd.oma.pal+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.detailed-progress-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.final-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.groups+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.invocation-descriptor+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.optimized-progress-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.push":{source:"iana"},"application/vnd.oma.scidm.messages+xml":{source:"iana",compressible:!0},"application/vnd.oma.xcap-directory+xml":{source:"iana",compressible:!0},"application/vnd.omads-email+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omads-file+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omads-folder+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omaloc-supl-init":{source:"iana"},"application/vnd.onepager":{source:"iana"},"application/vnd.onepagertamp":{source:"iana"},"application/vnd.onepagertamx":{source:"iana"},"application/vnd.onepagertat":{source:"iana"},"application/vnd.onepagertatp":{source:"iana"},"application/vnd.onepagertatx":{source:"iana"},"application/vnd.openblox.game+xml":{source:"iana",compressible:!0,extensions:["obgx"]},"application/vnd.openblox.game-binary":{source:"iana"},"application/vnd.openeye.oeb":{source:"iana"},"application/vnd.openofficeorg.extension":{source:"apache",extensions:["oxt"]},"application/vnd.openstreetmap.data+xml":{source:"iana",compressible:!0,extensions:["osm"]},"application/vnd.opentimestamps.ots":{source:"iana"},"application/vnd.openxmlformats-officedocument.custom-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.customxmlproperties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawing+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.chart+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.extended-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{source:"iana",compressible:!1,extensions:["pptx"]},"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slide":{source:"iana",extensions:["sldx"]},"application/vnd.openxmlformats-officedocument.presentationml.slide+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slideshow":{source:"iana",extensions:["ppsx"]},"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.tags+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.template":{source:"iana",extensions:["potx"]},"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{source:"iana",compressible:!1,extensions:["xlsx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.template":{source:"iana",extensions:["xltx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.theme+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.themeoverride+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.vmldrawing":{source:"iana"},"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{source:"iana",compressible:!1,extensions:["docx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.template":{source:"iana",extensions:["dotx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.core-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.relationships+xml":{source:"iana",compressible:!0},"application/vnd.oracle.resource+json":{source:"iana",compressible:!0},"application/vnd.orange.indata":{source:"iana"},"application/vnd.osa.netdeploy":{source:"iana"},"application/vnd.osgeo.mapguide.package":{source:"iana",extensions:["mgp"]},"application/vnd.osgi.bundle":{source:"iana"},"application/vnd.osgi.dp":{source:"iana",extensions:["dp"]},"application/vnd.osgi.subsystem":{source:"iana",extensions:["esa"]},"application/vnd.otps.ct-kip+xml":{source:"iana",compressible:!0},"application/vnd.oxli.countgraph":{source:"iana"},"application/vnd.pagerduty+json":{source:"iana",compressible:!0},"application/vnd.palm":{source:"iana",extensions:["pdb","pqa","oprc"]},"application/vnd.panoply":{source:"iana"},"application/vnd.paos.xml":{source:"iana"},"application/vnd.patentdive":{source:"iana"},"application/vnd.patientecommsdoc":{source:"iana"},"application/vnd.pawaafile":{source:"iana",extensions:["paw"]},"application/vnd.pcos":{source:"iana"},"application/vnd.pg.format":{source:"iana",extensions:["str"]},"application/vnd.pg.osasli":{source:"iana",extensions:["ei6"]},"application/vnd.piaccess.application-licence":{source:"iana"},"application/vnd.picsel":{source:"iana",extensions:["efif"]},"application/vnd.pmi.widget":{source:"iana",extensions:["wg"]},"application/vnd.poc.group-advertisement+xml":{source:"iana",compressible:!0},"application/vnd.pocketlearn":{source:"iana",extensions:["plf"]},"application/vnd.powerbuilder6":{source:"iana",extensions:["pbd"]},"application/vnd.powerbuilder6-s":{source:"iana"},"application/vnd.powerbuilder7":{source:"iana"},"application/vnd.powerbuilder7-s":{source:"iana"},"application/vnd.powerbuilder75":{source:"iana"},"application/vnd.powerbuilder75-s":{source:"iana"},"application/vnd.preminet":{source:"iana"},"application/vnd.previewsystems.box":{source:"iana",extensions:["box"]},"application/vnd.proteus.magazine":{source:"iana",extensions:["mgz"]},"application/vnd.psfs":{source:"iana"},"application/vnd.publishare-delta-tree":{source:"iana",extensions:["qps"]},"application/vnd.pvi.ptid1":{source:"iana",extensions:["ptid"]},"application/vnd.pwg-multiplexed":{source:"iana"},"application/vnd.pwg-xhtml-print+xml":{source:"iana",compressible:!0},"application/vnd.qualcomm.brew-app-res":{source:"iana"},"application/vnd.quarantainenet":{source:"iana"},"application/vnd.quark.quarkxpress":{source:"iana",extensions:["qxd","qxt","qwd","qwt","qxl","qxb"]},"application/vnd.quobject-quoxdocument":{source:"iana"},"application/vnd.radisys.moml+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-conf+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-conn+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-dialog+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-stream+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-conf+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-base+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-fax-detect+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-fax-sendrecv+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-group+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-speech+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-transform+xml":{source:"iana",compressible:!0},"application/vnd.rainstor.data":{source:"iana"},"application/vnd.rapid":{source:"iana"},"application/vnd.rar":{source:"iana",extensions:["rar"]},"application/vnd.realvnc.bed":{source:"iana",extensions:["bed"]},"application/vnd.recordare.musicxml":{source:"iana",extensions:["mxl"]},"application/vnd.recordare.musicxml+xml":{source:"iana",compressible:!0,extensions:["musicxml"]},"application/vnd.renlearn.rlprint":{source:"iana"},"application/vnd.resilient.logic":{source:"iana"},"application/vnd.restful+json":{source:"iana",compressible:!0},"application/vnd.rig.cryptonote":{source:"iana",extensions:["cryptonote"]},"application/vnd.rim.cod":{source:"apache",extensions:["cod"]},"application/vnd.rn-realmedia":{source:"apache",extensions:["rm"]},"application/vnd.rn-realmedia-vbr":{source:"apache",extensions:["rmvb"]},"application/vnd.route66.link66+xml":{source:"iana",compressible:!0,extensions:["link66"]},"application/vnd.rs-274x":{source:"iana"},"application/vnd.ruckus.download":{source:"iana"},"application/vnd.s3sms":{source:"iana"},"application/vnd.sailingtracker.track":{source:"iana",extensions:["st"]},"application/vnd.sar":{source:"iana"},"application/vnd.sbm.cid":{source:"iana"},"application/vnd.sbm.mid2":{source:"iana"},"application/vnd.scribus":{source:"iana"},"application/vnd.sealed.3df":{source:"iana"},"application/vnd.sealed.csf":{source:"iana"},"application/vnd.sealed.doc":{source:"iana"},"application/vnd.sealed.eml":{source:"iana"},"application/vnd.sealed.mht":{source:"iana"},"application/vnd.sealed.net":{source:"iana"},"application/vnd.sealed.ppt":{source:"iana"},"application/vnd.sealed.tiff":{source:"iana"},"application/vnd.sealed.xls":{source:"iana"},"application/vnd.sealedmedia.softseal.html":{source:"iana"},"application/vnd.sealedmedia.softseal.pdf":{source:"iana"},"application/vnd.seemail":{source:"iana",extensions:["see"]},"application/vnd.seis+json":{source:"iana",compressible:!0},"application/vnd.sema":{source:"iana",extensions:["sema"]},"application/vnd.semd":{source:"iana",extensions:["semd"]},"application/vnd.semf":{source:"iana",extensions:["semf"]},"application/vnd.shade-save-file":{source:"iana"},"application/vnd.shana.informed.formdata":{source:"iana",extensions:["ifm"]},"application/vnd.shana.informed.formtemplate":{source:"iana",extensions:["itp"]},"application/vnd.shana.informed.interchange":{source:"iana",extensions:["iif"]},"application/vnd.shana.informed.package":{source:"iana",extensions:["ipk"]},"application/vnd.shootproof+json":{source:"iana",compressible:!0},"application/vnd.shopkick+json":{source:"iana",compressible:!0},"application/vnd.shp":{source:"iana"},"application/vnd.shx":{source:"iana"},"application/vnd.sigrok.session":{source:"iana"},"application/vnd.simtech-mindmapper":{source:"iana",extensions:["twd","twds"]},"application/vnd.siren+json":{source:"iana",compressible:!0},"application/vnd.smaf":{source:"iana",extensions:["mmf"]},"application/vnd.smart.notebook":{source:"iana"},"application/vnd.smart.teacher":{source:"iana",extensions:["teacher"]},"application/vnd.snesdev-page-table":{source:"iana"},"application/vnd.software602.filler.form+xml":{source:"iana",compressible:!0,extensions:["fo"]},"application/vnd.software602.filler.form-xml-zip":{source:"iana"},"application/vnd.solent.sdkm+xml":{source:"iana",compressible:!0,extensions:["sdkm","sdkd"]},"application/vnd.spotfire.dxp":{source:"iana",extensions:["dxp"]},"application/vnd.spotfire.sfs":{source:"iana",extensions:["sfs"]},"application/vnd.sqlite3":{source:"iana"},"application/vnd.sss-cod":{source:"iana"},"application/vnd.sss-dtf":{source:"iana"},"application/vnd.sss-ntf":{source:"iana"},"application/vnd.stardivision.calc":{source:"apache",extensions:["sdc"]},"application/vnd.stardivision.draw":{source:"apache",extensions:["sda"]},"application/vnd.stardivision.impress":{source:"apache",extensions:["sdd"]},"application/vnd.stardivision.math":{source:"apache",extensions:["smf"]},"application/vnd.stardivision.writer":{source:"apache",extensions:["sdw","vor"]},"application/vnd.stardivision.writer-global":{source:"apache",extensions:["sgl"]},"application/vnd.stepmania.package":{source:"iana",extensions:["smzip"]},"application/vnd.stepmania.stepchart":{source:"iana",extensions:["sm"]},"application/vnd.street-stream":{source:"iana"},"application/vnd.sun.wadl+xml":{source:"iana",compressible:!0,extensions:["wadl"]},"application/vnd.sun.xml.calc":{source:"apache",extensions:["sxc"]},"application/vnd.sun.xml.calc.template":{source:"apache",extensions:["stc"]},"application/vnd.sun.xml.draw":{source:"apache",extensions:["sxd"]},"application/vnd.sun.xml.draw.template":{source:"apache",extensions:["std"]},"application/vnd.sun.xml.impress":{source:"apache",extensions:["sxi"]},"application/vnd.sun.xml.impress.template":{source:"apache",extensions:["sti"]},"application/vnd.sun.xml.math":{source:"apache",extensions:["sxm"]},"application/vnd.sun.xml.writer":{source:"apache",extensions:["sxw"]},"application/vnd.sun.xml.writer.global":{source:"apache",extensions:["sxg"]},"application/vnd.sun.xml.writer.template":{source:"apache",extensions:["stw"]},"application/vnd.sus-calendar":{source:"iana",extensions:["sus","susp"]},"application/vnd.svd":{source:"iana",extensions:["svd"]},"application/vnd.swiftview-ics":{source:"iana"},"application/vnd.sycle+xml":{source:"iana",compressible:!0},"application/vnd.syft+json":{source:"iana",compressible:!0},"application/vnd.symbian.install":{source:"apache",extensions:["sis","sisx"]},"application/vnd.syncml+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["xsm"]},"application/vnd.syncml.dm+wbxml":{source:"iana",charset:"UTF-8",extensions:["bdm"]},"application/vnd.syncml.dm+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["xdm"]},"application/vnd.syncml.dm.notification":{source:"iana"},"application/vnd.syncml.dmddf+wbxml":{source:"iana"},"application/vnd.syncml.dmddf+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["ddf"]},"application/vnd.syncml.dmtnds+wbxml":{source:"iana"},"application/vnd.syncml.dmtnds+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.syncml.ds.notification":{source:"iana"},"application/vnd.tableschema+json":{source:"iana",compressible:!0},"application/vnd.tao.intent-module-archive":{source:"iana",extensions:["tao"]},"application/vnd.tcpdump.pcap":{source:"iana",extensions:["pcap","cap","dmp"]},"application/vnd.think-cell.ppttc+json":{source:"iana",compressible:!0},"application/vnd.tmd.mediaflex.api+xml":{source:"iana",compressible:!0},"application/vnd.tml":{source:"iana"},"application/vnd.tmobile-livetv":{source:"iana",extensions:["tmo"]},"application/vnd.tri.onesource":{source:"iana"},"application/vnd.trid.tpt":{source:"iana",extensions:["tpt"]},"application/vnd.triscape.mxs":{source:"iana",extensions:["mxs"]},"application/vnd.trueapp":{source:"iana",extensions:["tra"]},"application/vnd.truedoc":{source:"iana"},"application/vnd.ubisoft.webplayer":{source:"iana"},"application/vnd.ufdl":{source:"iana",extensions:["ufd","ufdl"]},"application/vnd.uiq.theme":{source:"iana",extensions:["utz"]},"application/vnd.umajin":{source:"iana",extensions:["umj"]},"application/vnd.unity":{source:"iana",extensions:["unityweb"]},"application/vnd.uoml+xml":{source:"iana",compressible:!0,extensions:["uoml"]},"application/vnd.uplanet.alert":{source:"iana"},"application/vnd.uplanet.alert-wbxml":{source:"iana"},"application/vnd.uplanet.bearer-choice":{source:"iana"},"application/vnd.uplanet.bearer-choice-wbxml":{source:"iana"},"application/vnd.uplanet.cacheop":{source:"iana"},"application/vnd.uplanet.cacheop-wbxml":{source:"iana"},"application/vnd.uplanet.channel":{source:"iana"},"application/vnd.uplanet.channel-wbxml":{source:"iana"},"application/vnd.uplanet.list":{source:"iana"},"application/vnd.uplanet.list-wbxml":{source:"iana"},"application/vnd.uplanet.listcmd":{source:"iana"},"application/vnd.uplanet.listcmd-wbxml":{source:"iana"},"application/vnd.uplanet.signal":{source:"iana"},"application/vnd.uri-map":{source:"iana"},"application/vnd.valve.source.material":{source:"iana"},"application/vnd.vcx":{source:"iana",extensions:["vcx"]},"application/vnd.vd-study":{source:"iana"},"application/vnd.vectorworks":{source:"iana"},"application/vnd.vel+json":{source:"iana",compressible:!0},"application/vnd.verimatrix.vcas":{source:"iana"},"application/vnd.veritone.aion+json":{source:"iana",compressible:!0},"application/vnd.veryant.thin":{source:"iana"},"application/vnd.ves.encrypted":{source:"iana"},"application/vnd.vidsoft.vidconference":{source:"iana"},"application/vnd.visio":{source:"iana",extensions:["vsd","vst","vss","vsw"]},"application/vnd.visionary":{source:"iana",extensions:["vis"]},"application/vnd.vividence.scriptfile":{source:"iana"},"application/vnd.vsf":{source:"iana",extensions:["vsf"]},"application/vnd.wap.sic":{source:"iana"},"application/vnd.wap.slc":{source:"iana"},"application/vnd.wap.wbxml":{source:"iana",charset:"UTF-8",extensions:["wbxml"]},"application/vnd.wap.wmlc":{source:"iana",extensions:["wmlc"]},"application/vnd.wap.wmlscriptc":{source:"iana",extensions:["wmlsc"]},"application/vnd.webturbo":{source:"iana",extensions:["wtb"]},"application/vnd.wfa.dpp":{source:"iana"},"application/vnd.wfa.p2p":{source:"iana"},"application/vnd.wfa.wsc":{source:"iana"},"application/vnd.windows.devicepairing":{source:"iana"},"application/vnd.wmc":{source:"iana"},"application/vnd.wmf.bootstrap":{source:"iana"},"application/vnd.wolfram.mathematica":{source:"iana"},"application/vnd.wolfram.mathematica.package":{source:"iana"},"application/vnd.wolfram.player":{source:"iana",extensions:["nbp"]},"application/vnd.wordperfect":{source:"iana",extensions:["wpd"]},"application/vnd.wqd":{source:"iana",extensions:["wqd"]},"application/vnd.wrq-hp3000-labelled":{source:"iana"},"application/vnd.wt.stf":{source:"iana",extensions:["stf"]},"application/vnd.wv.csp+wbxml":{source:"iana"},"application/vnd.wv.csp+xml":{source:"iana",compressible:!0},"application/vnd.wv.ssp+xml":{source:"iana",compressible:!0},"application/vnd.xacml+json":{source:"iana",compressible:!0},"application/vnd.xara":{source:"iana",extensions:["xar"]},"application/vnd.xfdl":{source:"iana",extensions:["xfdl"]},"application/vnd.xfdl.webform":{source:"iana"},"application/vnd.xmi+xml":{source:"iana",compressible:!0},"application/vnd.xmpie.cpkg":{source:"iana"},"application/vnd.xmpie.dpkg":{source:"iana"},"application/vnd.xmpie.plan":{source:"iana"},"application/vnd.xmpie.ppkg":{source:"iana"},"application/vnd.xmpie.xlim":{source:"iana"},"application/vnd.yamaha.hv-dic":{source:"iana",extensions:["hvd"]},"application/vnd.yamaha.hv-script":{source:"iana",extensions:["hvs"]},"application/vnd.yamaha.hv-voice":{source:"iana",extensions:["hvp"]},"application/vnd.yamaha.openscoreformat":{source:"iana",extensions:["osf"]},"application/vnd.yamaha.openscoreformat.osfpvg+xml":{source:"iana",compressible:!0,extensions:["osfpvg"]},"application/vnd.yamaha.remote-setup":{source:"iana"},"application/vnd.yamaha.smaf-audio":{source:"iana",extensions:["saf"]},"application/vnd.yamaha.smaf-phrase":{source:"iana",extensions:["spf"]},"application/vnd.yamaha.through-ngn":{source:"iana"},"application/vnd.yamaha.tunnel-udpencap":{source:"iana"},"application/vnd.yaoweme":{source:"iana"},"application/vnd.yellowriver-custom-menu":{source:"iana",extensions:["cmp"]},"application/vnd.youtube.yt":{source:"iana"},"application/vnd.zul":{source:"iana",extensions:["zir","zirz"]},"application/vnd.zzazz.deck+xml":{source:"iana",compressible:!0,extensions:["zaz"]},"application/voicexml+xml":{source:"iana",compressible:!0,extensions:["vxml"]},"application/voucher-cms+json":{source:"iana",compressible:!0},"application/vq-rtcpxr":{source:"iana"},"application/wasm":{source:"iana",compressible:!0,extensions:["wasm"]},"application/watcherinfo+xml":{source:"iana",compressible:!0,extensions:["wif"]},"application/webpush-options+json":{source:"iana",compressible:!0},"application/whoispp-query":{source:"iana"},"application/whoispp-response":{source:"iana"},"application/widget":{source:"iana",extensions:["wgt"]},"application/winhlp":{source:"apache",extensions:["hlp"]},"application/wita":{source:"iana"},"application/wordperfect5.1":{source:"iana"},"application/wsdl+xml":{source:"iana",compressible:!0,extensions:["wsdl"]},"application/wspolicy+xml":{source:"iana",compressible:!0,extensions:["wspolicy"]},"application/x-7z-compressed":{source:"apache",compressible:!1,extensions:["7z"]},"application/x-abiword":{source:"apache",extensions:["abw"]},"application/x-ace-compressed":{source:"apache",extensions:["ace"]},"application/x-amf":{source:"apache"},"application/x-apple-diskimage":{source:"apache",extensions:["dmg"]},"application/x-arj":{compressible:!1,extensions:["arj"]},"application/x-authorware-bin":{source:"apache",extensions:["aab","x32","u32","vox"]},"application/x-authorware-map":{source:"apache",extensions:["aam"]},"application/x-authorware-seg":{source:"apache",extensions:["aas"]},"application/x-bcpio":{source:"apache",extensions:["bcpio"]},"application/x-bdoc":{compressible:!1,extensions:["bdoc"]},"application/x-bittorrent":{source:"apache",extensions:["torrent"]},"application/x-blorb":{source:"apache",extensions:["blb","blorb"]},"application/x-bzip":{source:"apache",compressible:!1,extensions:["bz"]},"application/x-bzip2":{source:"apache",compressible:!1,extensions:["bz2","boz"]},"application/x-cbr":{source:"apache",extensions:["cbr","cba","cbt","cbz","cb7"]},"application/x-cdlink":{source:"apache",extensions:["vcd"]},"application/x-cfs-compressed":{source:"apache",extensions:["cfs"]},"application/x-chat":{source:"apache",extensions:["chat"]},"application/x-chess-pgn":{source:"apache",extensions:["pgn"]},"application/x-chrome-extension":{extensions:["crx"]},"application/x-cocoa":{source:"nginx",extensions:["cco"]},"application/x-compress":{source:"apache"},"application/x-conference":{source:"apache",extensions:["nsc"]},"application/x-cpio":{source:"apache",extensions:["cpio"]},"application/x-csh":{source:"apache",extensions:["csh"]},"application/x-deb":{compressible:!1},"application/x-debian-package":{source:"apache",extensions:["deb","udeb"]},"application/x-dgc-compressed":{source:"apache",extensions:["dgc"]},"application/x-director":{source:"apache",extensions:["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},"application/x-doom":{source:"apache",extensions:["wad"]},"application/x-dtbncx+xml":{source:"apache",compressible:!0,extensions:["ncx"]},"application/x-dtbook+xml":{source:"apache",compressible:!0,extensions:["dtb"]},"application/x-dtbresource+xml":{source:"apache",compressible:!0,extensions:["res"]},"application/x-dvi":{source:"apache",compressible:!1,extensions:["dvi"]},"application/x-envoy":{source:"apache",extensions:["evy"]},"application/x-eva":{source:"apache",extensions:["eva"]},"application/x-font-bdf":{source:"apache",extensions:["bdf"]},"application/x-font-dos":{source:"apache"},"application/x-font-framemaker":{source:"apache"},"application/x-font-ghostscript":{source:"apache",extensions:["gsf"]},"application/x-font-libgrx":{source:"apache"},"application/x-font-linux-psf":{source:"apache",extensions:["psf"]},"application/x-font-pcf":{source:"apache",extensions:["pcf"]},"application/x-font-snf":{source:"apache",extensions:["snf"]},"application/x-font-speedo":{source:"apache"},"application/x-font-sunos-news":{source:"apache"},"application/x-font-type1":{source:"apache",extensions:["pfa","pfb","pfm","afm"]},"application/x-font-vfont":{source:"apache"},"application/x-freearc":{source:"apache",extensions:["arc"]},"application/x-futuresplash":{source:"apache",extensions:["spl"]},"application/x-gca-compressed":{source:"apache",extensions:["gca"]},"application/x-glulx":{source:"apache",extensions:["ulx"]},"application/x-gnumeric":{source:"apache",extensions:["gnumeric"]},"application/x-gramps-xml":{source:"apache",extensions:["gramps"]},"application/x-gtar":{source:"apache",extensions:["gtar"]},"application/x-gzip":{source:"apache"},"application/x-hdf":{source:"apache",extensions:["hdf"]},"application/x-httpd-php":{compressible:!0,extensions:["php"]},"application/x-install-instructions":{source:"apache",extensions:["install"]},"application/x-iso9660-image":{source:"apache",extensions:["iso"]},"application/x-iwork-keynote-sffkey":{extensions:["key"]},"application/x-iwork-numbers-sffnumbers":{extensions:["numbers"]},"application/x-iwork-pages-sffpages":{extensions:["pages"]},"application/x-java-archive-diff":{source:"nginx",extensions:["jardiff"]},"application/x-java-jnlp-file":{source:"apache",compressible:!1,extensions:["jnlp"]},"application/x-javascript":{compressible:!0},"application/x-keepass2":{extensions:["kdbx"]},"application/x-latex":{source:"apache",compressible:!1,extensions:["latex"]},"application/x-lua-bytecode":{extensions:["luac"]},"application/x-lzh-compressed":{source:"apache",extensions:["lzh","lha"]},"application/x-makeself":{source:"nginx",extensions:["run"]},"application/x-mie":{source:"apache",extensions:["mie"]},"application/x-mobipocket-ebook":{source:"apache",extensions:["prc","mobi"]},"application/x-mpegurl":{compressible:!1},"application/x-ms-application":{source:"apache",extensions:["application"]},"application/x-ms-shortcut":{source:"apache",extensions:["lnk"]},"application/x-ms-wmd":{source:"apache",extensions:["wmd"]},"application/x-ms-wmz":{source:"apache",extensions:["wmz"]},"application/x-ms-xbap":{source:"apache",extensions:["xbap"]},"application/x-msaccess":{source:"apache",extensions:["mdb"]},"application/x-msbinder":{source:"apache",extensions:["obd"]},"application/x-mscardfile":{source:"apache",extensions:["crd"]},"application/x-msclip":{source:"apache",extensions:["clp"]},"application/x-msdos-program":{extensions:["exe"]},"application/x-msdownload":{source:"apache",extensions:["exe","dll","com","bat","msi"]},"application/x-msmediaview":{source:"apache",extensions:["mvb","m13","m14"]},"application/x-msmetafile":{source:"apache",extensions:["wmf","wmz","emf","emz"]},"application/x-msmoney":{source:"apache",extensions:["mny"]},"application/x-mspublisher":{source:"apache",extensions:["pub"]},"application/x-msschedule":{source:"apache",extensions:["scd"]},"application/x-msterminal":{source:"apache",extensions:["trm"]},"application/x-mswrite":{source:"apache",extensions:["wri"]},"application/x-netcdf":{source:"apache",extensions:["nc","cdf"]},"application/x-ns-proxy-autoconfig":{compressible:!0,extensions:["pac"]},"application/x-nzb":{source:"apache",extensions:["nzb"]},"application/x-perl":{source:"nginx",extensions:["pl","pm"]},"application/x-pilot":{source:"nginx",extensions:["prc","pdb"]},"application/x-pkcs12":{source:"apache",compressible:!1,extensions:["p12","pfx"]},"application/x-pkcs7-certificates":{source:"apache",extensions:["p7b","spc"]},"application/x-pkcs7-certreqresp":{source:"apache",extensions:["p7r"]},"application/x-pki-message":{source:"iana"},"application/x-rar-compressed":{source:"apache",compressible:!1,extensions:["rar"]},"application/x-redhat-package-manager":{source:"nginx",extensions:["rpm"]},"application/x-research-info-systems":{source:"apache",extensions:["ris"]},"application/x-sea":{source:"nginx",extensions:["sea"]},"application/x-sh":{source:"apache",compressible:!0,extensions:["sh"]},"application/x-shar":{source:"apache",extensions:["shar"]},"application/x-shockwave-flash":{source:"apache",compressible:!1,extensions:["swf"]},"application/x-silverlight-app":{source:"apache",extensions:["xap"]},"application/x-sql":{source:"apache",extensions:["sql"]},"application/x-stuffit":{source:"apache",compressible:!1,extensions:["sit"]},"application/x-stuffitx":{source:"apache",extensions:["sitx"]},"application/x-subrip":{source:"apache",extensions:["srt"]},"application/x-sv4cpio":{source:"apache",extensions:["sv4cpio"]},"application/x-sv4crc":{source:"apache",extensions:["sv4crc"]},"application/x-t3vm-image":{source:"apache",extensions:["t3"]},"application/x-tads":{source:"apache",extensions:["gam"]},"application/x-tar":{source:"apache",compressible:!0,extensions:["tar"]},"application/x-tcl":{source:"apache",extensions:["tcl","tk"]},"application/x-tex":{source:"apache",extensions:["tex"]},"application/x-tex-tfm":{source:"apache",extensions:["tfm"]},"application/x-texinfo":{source:"apache",extensions:["texinfo","texi"]},"application/x-tgif":{source:"apache",extensions:["obj"]},"application/x-ustar":{source:"apache",extensions:["ustar"]},"application/x-virtualbox-hdd":{compressible:!0,extensions:["hdd"]},"application/x-virtualbox-ova":{compressible:!0,extensions:["ova"]},"application/x-virtualbox-ovf":{compressible:!0,extensions:["ovf"]},"application/x-virtualbox-vbox":{compressible:!0,extensions:["vbox"]},"application/x-virtualbox-vbox-extpack":{compressible:!1,extensions:["vbox-extpack"]},"application/x-virtualbox-vdi":{compressible:!0,extensions:["vdi"]},"application/x-virtualbox-vhd":{compressible:!0,extensions:["vhd"]},"application/x-virtualbox-vmdk":{compressible:!0,extensions:["vmdk"]},"application/x-wais-source":{source:"apache",extensions:["src"]},"application/x-web-app-manifest+json":{compressible:!0,extensions:["webapp"]},"application/x-www-form-urlencoded":{source:"iana",compressible:!0},"application/x-x509-ca-cert":{source:"iana",extensions:["der","crt","pem"]},"application/x-x509-ca-ra-cert":{source:"iana"},"application/x-x509-next-ca-cert":{source:"iana"},"application/x-xfig":{source:"apache",extensions:["fig"]},"application/x-xliff+xml":{source:"apache",compressible:!0,extensions:["xlf"]},"application/x-xpinstall":{source:"apache",compressible:!1,extensions:["xpi"]},"application/x-xz":{source:"apache",extensions:["xz"]},"application/x-zmachine":{source:"apache",extensions:["z1","z2","z3","z4","z5","z6","z7","z8"]},"application/x400-bp":{source:"iana"},"application/xacml+xml":{source:"iana",compressible:!0},"application/xaml+xml":{source:"apache",compressible:!0,extensions:["xaml"]},"application/xcap-att+xml":{source:"iana",compressible:!0,extensions:["xav"]},"application/xcap-caps+xml":{source:"iana",compressible:!0,extensions:["xca"]},"application/xcap-diff+xml":{source:"iana",compressible:!0,extensions:["xdf"]},"application/xcap-el+xml":{source:"iana",compressible:!0,extensions:["xel"]},"application/xcap-error+xml":{source:"iana",compressible:!0},"application/xcap-ns+xml":{source:"iana",compressible:!0,extensions:["xns"]},"application/xcon-conference-info+xml":{source:"iana",compressible:!0},"application/xcon-conference-info-diff+xml":{source:"iana",compressible:!0},"application/xenc+xml":{source:"iana",compressible:!0,extensions:["xenc"]},"application/xhtml+xml":{source:"iana",compressible:!0,extensions:["xhtml","xht"]},"application/xhtml-voice+xml":{source:"apache",compressible:!0},"application/xliff+xml":{source:"iana",compressible:!0,extensions:["xlf"]},"application/xml":{source:"iana",compressible:!0,extensions:["xml","xsl","xsd","rng"]},"application/xml-dtd":{source:"iana",compressible:!0,extensions:["dtd"]},"application/xml-external-parsed-entity":{source:"iana"},"application/xml-patch+xml":{source:"iana",compressible:!0},"application/xmpp+xml":{source:"iana",compressible:!0},"application/xop+xml":{source:"iana",compressible:!0,extensions:["xop"]},"application/xproc+xml":{source:"apache",compressible:!0,extensions:["xpl"]},"application/xslt+xml":{source:"iana",compressible:!0,extensions:["xsl","xslt"]},"application/xspf+xml":{source:"apache",compressible:!0,extensions:["xspf"]},"application/xv+xml":{source:"iana",compressible:!0,extensions:["mxml","xhvml","xvml","xvm"]},"application/yang":{source:"iana",extensions:["yang"]},"application/yang-data+json":{source:"iana",compressible:!0},"application/yang-data+xml":{source:"iana",compressible:!0},"application/yang-patch+json":{source:"iana",compressible:!0},"application/yang-patch+xml":{source:"iana",compressible:!0},"application/yin+xml":{source:"iana",compressible:!0,extensions:["yin"]},"application/zip":{source:"iana",compressible:!1,extensions:["zip"]},"application/zlib":{source:"iana"},"application/zstd":{source:"iana"},"audio/1d-interleaved-parityfec":{source:"iana"},"audio/32kadpcm":{source:"iana"},"audio/3gpp":{source:"iana",compressible:!1,extensions:["3gpp"]},"audio/3gpp2":{source:"iana"},"audio/aac":{source:"iana"},"audio/ac3":{source:"iana"},"audio/adpcm":{source:"apache",extensions:["adp"]},"audio/amr":{source:"iana",extensions:["amr"]},"audio/amr-wb":{source:"iana"},"audio/amr-wb+":{source:"iana"},"audio/aptx":{source:"iana"},"audio/asc":{source:"iana"},"audio/atrac-advanced-lossless":{source:"iana"},"audio/atrac-x":{source:"iana"},"audio/atrac3":{source:"iana"},"audio/basic":{source:"iana",compressible:!1,extensions:["au","snd"]},"audio/bv16":{source:"iana"},"audio/bv32":{source:"iana"},"audio/clearmode":{source:"iana"},"audio/cn":{source:"iana"},"audio/dat12":{source:"iana"},"audio/dls":{source:"iana"},"audio/dsr-es201108":{source:"iana"},"audio/dsr-es202050":{source:"iana"},"audio/dsr-es202211":{source:"iana"},"audio/dsr-es202212":{source:"iana"},"audio/dv":{source:"iana"},"audio/dvi4":{source:"iana"},"audio/eac3":{source:"iana"},"audio/encaprtp":{source:"iana"},"audio/evrc":{source:"iana"},"audio/evrc-qcp":{source:"iana"},"audio/evrc0":{source:"iana"},"audio/evrc1":{source:"iana"},"audio/evrcb":{source:"iana"},"audio/evrcb0":{source:"iana"},"audio/evrcb1":{source:"iana"},"audio/evrcnw":{source:"iana"},"audio/evrcnw0":{source:"iana"},"audio/evrcnw1":{source:"iana"},"audio/evrcwb":{source:"iana"},"audio/evrcwb0":{source:"iana"},"audio/evrcwb1":{source:"iana"},"audio/evs":{source:"iana"},"audio/flexfec":{source:"iana"},"audio/fwdred":{source:"iana"},"audio/g711-0":{source:"iana"},"audio/g719":{source:"iana"},"audio/g722":{source:"iana"},"audio/g7221":{source:"iana"},"audio/g723":{source:"iana"},"audio/g726-16":{source:"iana"},"audio/g726-24":{source:"iana"},"audio/g726-32":{source:"iana"},"audio/g726-40":{source:"iana"},"audio/g728":{source:"iana"},"audio/g729":{source:"iana"},"audio/g7291":{source:"iana"},"audio/g729d":{source:"iana"},"audio/g729e":{source:"iana"},"audio/gsm":{source:"iana"},"audio/gsm-efr":{source:"iana"},"audio/gsm-hr-08":{source:"iana"},"audio/ilbc":{source:"iana"},"audio/ip-mr_v2.5":{source:"iana"},"audio/isac":{source:"apache"},"audio/l16":{source:"iana"},"audio/l20":{source:"iana"},"audio/l24":{source:"iana",compressible:!1},"audio/l8":{source:"iana"},"audio/lpc":{source:"iana"},"audio/melp":{source:"iana"},"audio/melp1200":{source:"iana"},"audio/melp2400":{source:"iana"},"audio/melp600":{source:"iana"},"audio/mhas":{source:"iana"},"audio/midi":{source:"apache",extensions:["mid","midi","kar","rmi"]},"audio/mobile-xmf":{source:"iana",extensions:["mxmf"]},"audio/mp3":{compressible:!1,extensions:["mp3"]},"audio/mp4":{source:"iana",compressible:!1,extensions:["m4a","mp4a"]},"audio/mp4a-latm":{source:"iana"},"audio/mpa":{source:"iana"},"audio/mpa-robust":{source:"iana"},"audio/mpeg":{source:"iana",compressible:!1,extensions:["mpga","mp2","mp2a","mp3","m2a","m3a"]},"audio/mpeg4-generic":{source:"iana"},"audio/musepack":{source:"apache"},"audio/ogg":{source:"iana",compressible:!1,extensions:["oga","ogg","spx","opus"]},"audio/opus":{source:"iana"},"audio/parityfec":{source:"iana"},"audio/pcma":{source:"iana"},"audio/pcma-wb":{source:"iana"},"audio/pcmu":{source:"iana"},"audio/pcmu-wb":{source:"iana"},"audio/prs.sid":{source:"iana"},"audio/qcelp":{source:"iana"},"audio/raptorfec":{source:"iana"},"audio/red":{source:"iana"},"audio/rtp-enc-aescm128":{source:"iana"},"audio/rtp-midi":{source:"iana"},"audio/rtploopback":{source:"iana"},"audio/rtx":{source:"iana"},"audio/s3m":{source:"apache",extensions:["s3m"]},"audio/scip":{source:"iana"},"audio/silk":{source:"apache",extensions:["sil"]},"audio/smv":{source:"iana"},"audio/smv-qcp":{source:"iana"},"audio/smv0":{source:"iana"},"audio/sofa":{source:"iana"},"audio/sp-midi":{source:"iana"},"audio/speex":{source:"iana"},"audio/t140c":{source:"iana"},"audio/t38":{source:"iana"},"audio/telephone-event":{source:"iana"},"audio/tetra_acelp":{source:"iana"},"audio/tetra_acelp_bb":{source:"iana"},"audio/tone":{source:"iana"},"audio/tsvcis":{source:"iana"},"audio/uemclip":{source:"iana"},"audio/ulpfec":{source:"iana"},"audio/usac":{source:"iana"},"audio/vdvi":{source:"iana"},"audio/vmr-wb":{source:"iana"},"audio/vnd.3gpp.iufp":{source:"iana"},"audio/vnd.4sb":{source:"iana"},"audio/vnd.audiokoz":{source:"iana"},"audio/vnd.celp":{source:"iana"},"audio/vnd.cisco.nse":{source:"iana"},"audio/vnd.cmles.radio-events":{source:"iana"},"audio/vnd.cns.anp1":{source:"iana"},"audio/vnd.cns.inf1":{source:"iana"},"audio/vnd.dece.audio":{source:"iana",extensions:["uva","uvva"]},"audio/vnd.digital-winds":{source:"iana",extensions:["eol"]},"audio/vnd.dlna.adts":{source:"iana"},"audio/vnd.dolby.heaac.1":{source:"iana"},"audio/vnd.dolby.heaac.2":{source:"iana"},"audio/vnd.dolby.mlp":{source:"iana"},"audio/vnd.dolby.mps":{source:"iana"},"audio/vnd.dolby.pl2":{source:"iana"},"audio/vnd.dolby.pl2x":{source:"iana"},"audio/vnd.dolby.pl2z":{source:"iana"},"audio/vnd.dolby.pulse.1":{source:"iana"},"audio/vnd.dra":{source:"iana",extensions:["dra"]},"audio/vnd.dts":{source:"iana",extensions:["dts"]},"audio/vnd.dts.hd":{source:"iana",extensions:["dtshd"]},"audio/vnd.dts.uhd":{source:"iana"},"audio/vnd.dvb.file":{source:"iana"},"audio/vnd.everad.plj":{source:"iana"},"audio/vnd.hns.audio":{source:"iana"},"audio/vnd.lucent.voice":{source:"iana",extensions:["lvp"]},"audio/vnd.ms-playready.media.pya":{source:"iana",extensions:["pya"]},"audio/vnd.nokia.mobile-xmf":{source:"iana"},"audio/vnd.nortel.vbk":{source:"iana"},"audio/vnd.nuera.ecelp4800":{source:"iana",extensions:["ecelp4800"]},"audio/vnd.nuera.ecelp7470":{source:"iana",extensions:["ecelp7470"]},"audio/vnd.nuera.ecelp9600":{source:"iana",extensions:["ecelp9600"]},"audio/vnd.octel.sbc":{source:"iana"},"audio/vnd.presonus.multitrack":{source:"iana"},"audio/vnd.qcelp":{source:"iana"},"audio/vnd.rhetorex.32kadpcm":{source:"iana"},"audio/vnd.rip":{source:"iana",extensions:["rip"]},"audio/vnd.rn-realaudio":{compressible:!1},"audio/vnd.sealedmedia.softseal.mpeg":{source:"iana"},"audio/vnd.vmx.cvsd":{source:"iana"},"audio/vnd.wave":{compressible:!1},"audio/vorbis":{source:"iana",compressible:!1},"audio/vorbis-config":{source:"iana"},"audio/wav":{compressible:!1,extensions:["wav"]},"audio/wave":{compressible:!1,extensions:["wav"]},"audio/webm":{source:"apache",compressible:!1,extensions:["weba"]},"audio/x-aac":{source:"apache",compressible:!1,extensions:["aac"]},"audio/x-aiff":{source:"apache",extensions:["aif","aiff","aifc"]},"audio/x-caf":{source:"apache",compressible:!1,extensions:["caf"]},"audio/x-flac":{source:"apache",extensions:["flac"]},"audio/x-m4a":{source:"nginx",extensions:["m4a"]},"audio/x-matroska":{source:"apache",extensions:["mka"]},"audio/x-mpegurl":{source:"apache",extensions:["m3u"]},"audio/x-ms-wax":{source:"apache",extensions:["wax"]},"audio/x-ms-wma":{source:"apache",extensions:["wma"]},"audio/x-pn-realaudio":{source:"apache",extensions:["ram","ra"]},"audio/x-pn-realaudio-plugin":{source:"apache",extensions:["rmp"]},"audio/x-realaudio":{source:"nginx",extensions:["ra"]},"audio/x-tta":{source:"apache"},"audio/x-wav":{source:"apache",extensions:["wav"]},"audio/xm":{source:"apache",extensions:["xm"]},"chemical/x-cdx":{source:"apache",extensions:["cdx"]},"chemical/x-cif":{source:"apache",extensions:["cif"]},"chemical/x-cmdf":{source:"apache",extensions:["cmdf"]},"chemical/x-cml":{source:"apache",extensions:["cml"]},"chemical/x-csml":{source:"apache",extensions:["csml"]},"chemical/x-pdb":{source:"apache"},"chemical/x-xyz":{source:"apache",extensions:["xyz"]},"font/collection":{source:"iana",extensions:["ttc"]},"font/otf":{source:"iana",compressible:!0,extensions:["otf"]},"font/sfnt":{source:"iana"},"font/ttf":{source:"iana",compressible:!0,extensions:["ttf"]},"font/woff":{source:"iana",extensions:["woff"]},"font/woff2":{source:"iana",extensions:["woff2"]},"image/aces":{source:"iana",extensions:["exr"]},"image/apng":{compressible:!1,extensions:["apng"]},"image/avci":{source:"iana",extensions:["avci"]},"image/avcs":{source:"iana",extensions:["avcs"]},"image/avif":{source:"iana",compressible:!1,extensions:["avif"]},"image/bmp":{source:"iana",compressible:!0,extensions:["bmp"]},"image/cgm":{source:"iana",extensions:["cgm"]},"image/dicom-rle":{source:"iana",extensions:["drle"]},"image/emf":{source:"iana",extensions:["emf"]},"image/fits":{source:"iana",extensions:["fits"]},"image/g3fax":{source:"iana",extensions:["g3"]},"image/gif":{source:"iana",compressible:!1,extensions:["gif"]},"image/heic":{source:"iana",extensions:["heic"]},"image/heic-sequence":{source:"iana",extensions:["heics"]},"image/heif":{source:"iana",extensions:["heif"]},"image/heif-sequence":{source:"iana",extensions:["heifs"]},"image/hej2k":{source:"iana",extensions:["hej2"]},"image/hsj2":{source:"iana",extensions:["hsj2"]},"image/ief":{source:"iana",extensions:["ief"]},"image/jls":{source:"iana",extensions:["jls"]},"image/jp2":{source:"iana",compressible:!1,extensions:["jp2","jpg2"]},"image/jpeg":{source:"iana",compressible:!1,extensions:["jpeg","jpg","jpe"]},"image/jph":{source:"iana",extensions:["jph"]},"image/jphc":{source:"iana",extensions:["jhc"]},"image/jpm":{source:"iana",compressible:!1,extensions:["jpm"]},"image/jpx":{source:"iana",compressible:!1,extensions:["jpx","jpf"]},"image/jxr":{source:"iana",extensions:["jxr"]},"image/jxra":{source:"iana",extensions:["jxra"]},"image/jxrs":{source:"iana",extensions:["jxrs"]},"image/jxs":{source:"iana",extensions:["jxs"]},"image/jxsc":{source:"iana",extensions:["jxsc"]},"image/jxsi":{source:"iana",extensions:["jxsi"]},"image/jxss":{source:"iana",extensions:["jxss"]},"image/ktx":{source:"iana",extensions:["ktx"]},"image/ktx2":{source:"iana",extensions:["ktx2"]},"image/naplps":{source:"iana"},"image/pjpeg":{compressible:!1},"image/png":{source:"iana",compressible:!1,extensions:["png"]},"image/prs.btif":{source:"iana",extensions:["btif"]},"image/prs.pti":{source:"iana",extensions:["pti"]},"image/pwg-raster":{source:"iana"},"image/sgi":{source:"apache",extensions:["sgi"]},"image/svg+xml":{source:"iana",compressible:!0,extensions:["svg","svgz"]},"image/t38":{source:"iana",extensions:["t38"]},"image/tiff":{source:"iana",compressible:!1,extensions:["tif","tiff"]},"image/tiff-fx":{source:"iana",extensions:["tfx"]},"image/vnd.adobe.photoshop":{source:"iana",compressible:!0,extensions:["psd"]},"image/vnd.airzip.accelerator.azv":{source:"iana",extensions:["azv"]},"image/vnd.cns.inf2":{source:"iana"},"image/vnd.dece.graphic":{source:"iana",extensions:["uvi","uvvi","uvg","uvvg"]},"image/vnd.djvu":{source:"iana",extensions:["djvu","djv"]},"image/vnd.dvb.subtitle":{source:"iana",extensions:["sub"]},"image/vnd.dwg":{source:"iana",extensions:["dwg"]},"image/vnd.dxf":{source:"iana",extensions:["dxf"]},"image/vnd.fastbidsheet":{source:"iana",extensions:["fbs"]},"image/vnd.fpx":{source:"iana",extensions:["fpx"]},"image/vnd.fst":{source:"iana",extensions:["fst"]},"image/vnd.fujixerox.edmics-mmr":{source:"iana",extensions:["mmr"]},"image/vnd.fujixerox.edmics-rlc":{source:"iana",extensions:["rlc"]},"image/vnd.globalgraphics.pgb":{source:"iana"},"image/vnd.microsoft.icon":{source:"iana",compressible:!0,extensions:["ico"]},"image/vnd.mix":{source:"iana"},"image/vnd.mozilla.apng":{source:"iana"},"image/vnd.ms-dds":{compressible:!0,extensions:["dds"]},"image/vnd.ms-modi":{source:"iana",extensions:["mdi"]},"image/vnd.ms-photo":{source:"apache",extensions:["wdp"]},"image/vnd.net-fpx":{source:"iana",extensions:["npx"]},"image/vnd.pco.b16":{source:"iana",extensions:["b16"]},"image/vnd.radiance":{source:"iana"},"image/vnd.sealed.png":{source:"iana"},"image/vnd.sealedmedia.softseal.gif":{source:"iana"},"image/vnd.sealedmedia.softseal.jpg":{source:"iana"},"image/vnd.svf":{source:"iana"},"image/vnd.tencent.tap":{source:"iana",extensions:["tap"]},"image/vnd.valve.source.texture":{source:"iana",extensions:["vtf"]},"image/vnd.wap.wbmp":{source:"iana",extensions:["wbmp"]},"image/vnd.xiff":{source:"iana",extensions:["xif"]},"image/vnd.zbrush.pcx":{source:"iana",extensions:["pcx"]},"image/webp":{source:"apache",extensions:["webp"]},"image/wmf":{source:"iana",extensions:["wmf"]},"image/x-3ds":{source:"apache",extensions:["3ds"]},"image/x-cmu-raster":{source:"apache",extensions:["ras"]},"image/x-cmx":{source:"apache",extensions:["cmx"]},"image/x-freehand":{source:"apache",extensions:["fh","fhc","fh4","fh5","fh7"]},"image/x-icon":{source:"apache",compressible:!0,extensions:["ico"]},"image/x-jng":{source:"nginx",extensions:["jng"]},"image/x-mrsid-image":{source:"apache",extensions:["sid"]},"image/x-ms-bmp":{source:"nginx",compressible:!0,extensions:["bmp"]},"image/x-pcx":{source:"apache",extensions:["pcx"]},"image/x-pict":{source:"apache",extensions:["pic","pct"]},"image/x-portable-anymap":{source:"apache",extensions:["pnm"]},"image/x-portable-bitmap":{source:"apache",extensions:["pbm"]},"image/x-portable-graymap":{source:"apache",extensions:["pgm"]},"image/x-portable-pixmap":{source:"apache",extensions:["ppm"]},"image/x-rgb":{source:"apache",extensions:["rgb"]},"image/x-tga":{source:"apache",extensions:["tga"]},"image/x-xbitmap":{source:"apache",extensions:["xbm"]},"image/x-xcf":{compressible:!1},"image/x-xpixmap":{source:"apache",extensions:["xpm"]},"image/x-xwindowdump":{source:"apache",extensions:["xwd"]},"message/cpim":{source:"iana"},"message/delivery-status":{source:"iana"},"message/disposition-notification":{source:"iana",extensions:["disposition-notification"]},"message/external-body":{source:"iana"},"message/feedback-report":{source:"iana"},"message/global":{source:"iana",extensions:["u8msg"]},"message/global-delivery-status":{source:"iana",extensions:["u8dsn"]},"message/global-disposition-notification":{source:"iana",extensions:["u8mdn"]},"message/global-headers":{source:"iana",extensions:["u8hdr"]},"message/http":{source:"iana",compressible:!1},"message/imdn+xml":{source:"iana",compressible:!0},"message/news":{source:"iana"},"message/partial":{source:"iana",compressible:!1},"message/rfc822":{source:"iana",compressible:!0,extensions:["eml","mime"]},"message/s-http":{source:"iana"},"message/sip":{source:"iana"},"message/sipfrag":{source:"iana"},"message/tracking-status":{source:"iana"},"message/vnd.si.simp":{source:"iana"},"message/vnd.wfa.wsc":{source:"iana",extensions:["wsc"]},"model/3mf":{source:"iana",extensions:["3mf"]},"model/e57":{source:"iana"},"model/gltf+json":{source:"iana",compressible:!0,extensions:["gltf"]},"model/gltf-binary":{source:"iana",compressible:!0,extensions:["glb"]},"model/iges":{source:"iana",compressible:!1,extensions:["igs","iges"]},"model/mesh":{source:"iana",compressible:!1,extensions:["msh","mesh","silo"]},"model/mtl":{source:"iana",extensions:["mtl"]},"model/obj":{source:"iana",extensions:["obj"]},"model/step":{source:"iana"},"model/step+xml":{source:"iana",compressible:!0,extensions:["stpx"]},"model/step+zip":{source:"iana",compressible:!1,extensions:["stpz"]},"model/step-xml+zip":{source:"iana",compressible:!1,extensions:["stpxz"]},"model/stl":{source:"iana",extensions:["stl"]},"model/vnd.collada+xml":{source:"iana",compressible:!0,extensions:["dae"]},"model/vnd.dwf":{source:"iana",extensions:["dwf"]},"model/vnd.flatland.3dml":{source:"iana"},"model/vnd.gdl":{source:"iana",extensions:["gdl"]},"model/vnd.gs-gdl":{source:"apache"},"model/vnd.gs.gdl":{source:"iana"},"model/vnd.gtw":{source:"iana",extensions:["gtw"]},"model/vnd.moml+xml":{source:"iana",compressible:!0},"model/vnd.mts":{source:"iana",extensions:["mts"]},"model/vnd.opengex":{source:"iana",extensions:["ogex"]},"model/vnd.parasolid.transmit.binary":{source:"iana",extensions:["x_b"]},"model/vnd.parasolid.transmit.text":{source:"iana",extensions:["x_t"]},"model/vnd.pytha.pyox":{source:"iana"},"model/vnd.rosette.annotated-data-model":{source:"iana"},"model/vnd.sap.vds":{source:"iana",extensions:["vds"]},"model/vnd.usdz+zip":{source:"iana",compressible:!1,extensions:["usdz"]},"model/vnd.valve.source.compiled-map":{source:"iana",extensions:["bsp"]},"model/vnd.vtu":{source:"iana",extensions:["vtu"]},"model/vrml":{source:"iana",compressible:!1,extensions:["wrl","vrml"]},"model/x3d+binary":{source:"apache",compressible:!1,extensions:["x3db","x3dbz"]},"model/x3d+fastinfoset":{source:"iana",extensions:["x3db"]},"model/x3d+vrml":{source:"apache",compressible:!1,extensions:["x3dv","x3dvz"]},"model/x3d+xml":{source:"iana",compressible:!0,extensions:["x3d","x3dz"]},"model/x3d-vrml":{source:"iana",extensions:["x3dv"]},"multipart/alternative":{source:"iana",compressible:!1},"multipart/appledouble":{source:"iana"},"multipart/byteranges":{source:"iana"},"multipart/digest":{source:"iana"},"multipart/encrypted":{source:"iana",compressible:!1},"multipart/form-data":{source:"iana",compressible:!1},"multipart/header-set":{source:"iana"},"multipart/mixed":{source:"iana"},"multipart/multilingual":{source:"iana"},"multipart/parallel":{source:"iana"},"multipart/related":{source:"iana",compressible:!1},"multipart/report":{source:"iana"},"multipart/signed":{source:"iana",compressible:!1},"multipart/vnd.bint.med-plus":{source:"iana"},"multipart/voice-message":{source:"iana"},"multipart/x-mixed-replace":{source:"iana"},"text/1d-interleaved-parityfec":{source:"iana"},"text/cache-manifest":{source:"iana",compressible:!0,extensions:["appcache","manifest"]},"text/calendar":{source:"iana",extensions:["ics","ifb"]},"text/calender":{compressible:!0},"text/cmd":{compressible:!0},"text/coffeescript":{extensions:["coffee","litcoffee"]},"text/cql":{source:"iana"},"text/cql-expression":{source:"iana"},"text/cql-identifier":{source:"iana"},"text/css":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["css"]},"text/csv":{source:"iana",compressible:!0,extensions:["csv"]},"text/csv-schema":{source:"iana"},"text/directory":{source:"iana"},"text/dns":{source:"iana"},"text/ecmascript":{source:"iana"},"text/encaprtp":{source:"iana"},"text/enriched":{source:"iana"},"text/fhirpath":{source:"iana"},"text/flexfec":{source:"iana"},"text/fwdred":{source:"iana"},"text/gff3":{source:"iana"},"text/grammar-ref-list":{source:"iana"},"text/html":{source:"iana",compressible:!0,extensions:["html","htm","shtml"]},"text/jade":{extensions:["jade"]},"text/javascript":{source:"iana",compressible:!0},"text/jcr-cnd":{source:"iana"},"text/jsx":{compressible:!0,extensions:["jsx"]},"text/less":{compressible:!0,extensions:["less"]},"text/markdown":{source:"iana",compressible:!0,extensions:["markdown","md"]},"text/mathml":{source:"nginx",extensions:["mml"]},"text/mdx":{compressible:!0,extensions:["mdx"]},"text/mizar":{source:"iana"},"text/n3":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["n3"]},"text/parameters":{source:"iana",charset:"UTF-8"},"text/parityfec":{source:"iana"},"text/plain":{source:"iana",compressible:!0,extensions:["txt","text","conf","def","list","log","in","ini"]},"text/provenance-notation":{source:"iana",charset:"UTF-8"},"text/prs.fallenstein.rst":{source:"iana"},"text/prs.lines.tag":{source:"iana",extensions:["dsc"]},"text/prs.prop.logic":{source:"iana"},"text/raptorfec":{source:"iana"},"text/red":{source:"iana"},"text/rfc822-headers":{source:"iana"},"text/richtext":{source:"iana",compressible:!0,extensions:["rtx"]},"text/rtf":{source:"iana",compressible:!0,extensions:["rtf"]},"text/rtp-enc-aescm128":{source:"iana"},"text/rtploopback":{source:"iana"},"text/rtx":{source:"iana"},"text/sgml":{source:"iana",extensions:["sgml","sgm"]},"text/shaclc":{source:"iana"},"text/shex":{source:"iana",extensions:["shex"]},"text/slim":{extensions:["slim","slm"]},"text/spdx":{source:"iana",extensions:["spdx"]},"text/strings":{source:"iana"},"text/stylus":{extensions:["stylus","styl"]},"text/t140":{source:"iana"},"text/tab-separated-values":{source:"iana",compressible:!0,extensions:["tsv"]},"text/troff":{source:"iana",extensions:["t","tr","roff","man","me","ms"]},"text/turtle":{source:"iana",charset:"UTF-8",extensions:["ttl"]},"text/ulpfec":{source:"iana"},"text/uri-list":{source:"iana",compressible:!0,extensions:["uri","uris","urls"]},"text/vcard":{source:"iana",compressible:!0,extensions:["vcard"]},"text/vnd.a":{source:"iana"},"text/vnd.abc":{source:"iana"},"text/vnd.ascii-art":{source:"iana"},"text/vnd.curl":{source:"iana",extensions:["curl"]},"text/vnd.curl.dcurl":{source:"apache",extensions:["dcurl"]},"text/vnd.curl.mcurl":{source:"apache",extensions:["mcurl"]},"text/vnd.curl.scurl":{source:"apache",extensions:["scurl"]},"text/vnd.debian.copyright":{source:"iana",charset:"UTF-8"},"text/vnd.dmclientscript":{source:"iana"},"text/vnd.dvb.subtitle":{source:"iana",extensions:["sub"]},"text/vnd.esmertec.theme-descriptor":{source:"iana",charset:"UTF-8"},"text/vnd.familysearch.gedcom":{source:"iana",extensions:["ged"]},"text/vnd.ficlab.flt":{source:"iana"},"text/vnd.fly":{source:"iana",extensions:["fly"]},"text/vnd.fmi.flexstor":{source:"iana",extensions:["flx"]},"text/vnd.gml":{source:"iana"},"text/vnd.graphviz":{source:"iana",extensions:["gv"]},"text/vnd.hans":{source:"iana"},"text/vnd.hgl":{source:"iana"},"text/vnd.in3d.3dml":{source:"iana",extensions:["3dml"]},"text/vnd.in3d.spot":{source:"iana",extensions:["spot"]},"text/vnd.iptc.newsml":{source:"iana"},"text/vnd.iptc.nitf":{source:"iana"},"text/vnd.latex-z":{source:"iana"},"text/vnd.motorola.reflex":{source:"iana"},"text/vnd.ms-mediapackage":{source:"iana"},"text/vnd.net2phone.commcenter.command":{source:"iana"},"text/vnd.radisys.msml-basic-layout":{source:"iana"},"text/vnd.senx.warpscript":{source:"iana"},"text/vnd.si.uricatalogue":{source:"iana"},"text/vnd.sosi":{source:"iana"},"text/vnd.sun.j2me.app-descriptor":{source:"iana",charset:"UTF-8",extensions:["jad"]},"text/vnd.trolltech.linguist":{source:"iana",charset:"UTF-8"},"text/vnd.wap.si":{source:"iana"},"text/vnd.wap.sl":{source:"iana"},"text/vnd.wap.wml":{source:"iana",extensions:["wml"]},"text/vnd.wap.wmlscript":{source:"iana",extensions:["wmls"]},"text/vtt":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["vtt"]},"text/x-asm":{source:"apache",extensions:["s","asm"]},"text/x-c":{source:"apache",extensions:["c","cc","cxx","cpp","h","hh","dic"]},"text/x-component":{source:"nginx",extensions:["htc"]},"text/x-fortran":{source:"apache",extensions:["f","for","f77","f90"]},"text/x-gwt-rpc":{compressible:!0},"text/x-handlebars-template":{extensions:["hbs"]},"text/x-java-source":{source:"apache",extensions:["java"]},"text/x-jquery-tmpl":{compressible:!0},"text/x-lua":{extensions:["lua"]},"text/x-markdown":{compressible:!0,extensions:["mkd"]},"text/x-nfo":{source:"apache",extensions:["nfo"]},"text/x-opml":{source:"apache",extensions:["opml"]},"text/x-org":{compressible:!0,extensions:["org"]},"text/x-pascal":{source:"apache",extensions:["p","pas"]},"text/x-processing":{compressible:!0,extensions:["pde"]},"text/x-sass":{extensions:["sass"]},"text/x-scss":{extensions:["scss"]},"text/x-setext":{source:"apache",extensions:["etx"]},"text/x-sfv":{source:"apache",extensions:["sfv"]},"text/x-suse-ymp":{compressible:!0,extensions:["ymp"]},"text/x-uuencode":{source:"apache",extensions:["uu"]},"text/x-vcalendar":{source:"apache",extensions:["vcs"]},"text/x-vcard":{source:"apache",extensions:["vcf"]},"text/xml":{source:"iana",compressible:!0,extensions:["xml"]},"text/xml-external-parsed-entity":{source:"iana"},"text/yaml":{compressible:!0,extensions:["yaml","yml"]},"video/1d-interleaved-parityfec":{source:"iana"},"video/3gpp":{source:"iana",extensions:["3gp","3gpp"]},"video/3gpp-tt":{source:"iana"},"video/3gpp2":{source:"iana",extensions:["3g2"]},"video/av1":{source:"iana"},"video/bmpeg":{source:"iana"},"video/bt656":{source:"iana"},"video/celb":{source:"iana"},"video/dv":{source:"iana"},"video/encaprtp":{source:"iana"},"video/ffv1":{source:"iana"},"video/flexfec":{source:"iana"},"video/h261":{source:"iana",extensions:["h261"]},"video/h263":{source:"iana",extensions:["h263"]},"video/h263-1998":{source:"iana"},"video/h263-2000":{source:"iana"},"video/h264":{source:"iana",extensions:["h264"]},"video/h264-rcdo":{source:"iana"},"video/h264-svc":{source:"iana"},"video/h265":{source:"iana"},"video/iso.segment":{source:"iana",extensions:["m4s"]},"video/jpeg":{source:"iana",extensions:["jpgv"]},"video/jpeg2000":{source:"iana"},"video/jpm":{source:"apache",extensions:["jpm","jpgm"]},"video/jxsv":{source:"iana"},"video/mj2":{source:"iana",extensions:["mj2","mjp2"]},"video/mp1s":{source:"iana"},"video/mp2p":{source:"iana"},"video/mp2t":{source:"iana",extensions:["ts"]},"video/mp4":{source:"iana",compressible:!1,extensions:["mp4","mp4v","mpg4"]},"video/mp4v-es":{source:"iana"},"video/mpeg":{source:"iana",compressible:!1,extensions:["mpeg","mpg","mpe","m1v","m2v"]},"video/mpeg4-generic":{source:"iana"},"video/mpv":{source:"iana"},"video/nv":{source:"iana"},"video/ogg":{source:"iana",compressible:!1,extensions:["ogv"]},"video/parityfec":{source:"iana"},"video/pointer":{source:"iana"},"video/quicktime":{source:"iana",compressible:!1,extensions:["qt","mov"]},"video/raptorfec":{source:"iana"},"video/raw":{source:"iana"},"video/rtp-enc-aescm128":{source:"iana"},"video/rtploopback":{source:"iana"},"video/rtx":{source:"iana"},"video/scip":{source:"iana"},"video/smpte291":{source:"iana"},"video/smpte292m":{source:"iana"},"video/ulpfec":{source:"iana"},"video/vc1":{source:"iana"},"video/vc2":{source:"iana"},"video/vnd.cctv":{source:"iana"},"video/vnd.dece.hd":{source:"iana",extensions:["uvh","uvvh"]},"video/vnd.dece.mobile":{source:"iana",extensions:["uvm","uvvm"]},"video/vnd.dece.mp4":{source:"iana"},"video/vnd.dece.pd":{source:"iana",extensions:["uvp","uvvp"]},"video/vnd.dece.sd":{source:"iana",extensions:["uvs","uvvs"]},"video/vnd.dece.video":{source:"iana",extensions:["uvv","uvvv"]},"video/vnd.directv.mpeg":{source:"iana"},"video/vnd.directv.mpeg-tts":{source:"iana"},"video/vnd.dlna.mpeg-tts":{source:"iana"},"video/vnd.dvb.file":{source:"iana",extensions:["dvb"]},"video/vnd.fvt":{source:"iana",extensions:["fvt"]},"video/vnd.hns.video":{source:"iana"},"video/vnd.iptvforum.1dparityfec-1010":{source:"iana"},"video/vnd.iptvforum.1dparityfec-2005":{source:"iana"},"video/vnd.iptvforum.2dparityfec-1010":{source:"iana"},"video/vnd.iptvforum.2dparityfec-2005":{source:"iana"},"video/vnd.iptvforum.ttsavc":{source:"iana"},"video/vnd.iptvforum.ttsmpeg2":{source:"iana"},"video/vnd.motorola.video":{source:"iana"},"video/vnd.motorola.videop":{source:"iana"},"video/vnd.mpegurl":{source:"iana",extensions:["mxu","m4u"]},"video/vnd.ms-playready.media.pyv":{source:"iana",extensions:["pyv"]},"video/vnd.nokia.interleaved-multimedia":{source:"iana"},"video/vnd.nokia.mp4vr":{source:"iana"},"video/vnd.nokia.videovoip":{source:"iana"},"video/vnd.objectvideo":{source:"iana"},"video/vnd.radgamettools.bink":{source:"iana"},"video/vnd.radgamettools.smacker":{source:"iana"},"video/vnd.sealed.mpeg1":{source:"iana"},"video/vnd.sealed.mpeg4":{source:"iana"},"video/vnd.sealed.swf":{source:"iana"},"video/vnd.sealedmedia.softseal.mov":{source:"iana"},"video/vnd.uvvu.mp4":{source:"iana",extensions:["uvu","uvvu"]},"video/vnd.vivo":{source:"iana",extensions:["viv"]},"video/vnd.youtube.yt":{source:"iana"},"video/vp8":{source:"iana"},"video/vp9":{source:"iana"},"video/webm":{source:"apache",compressible:!1,extensions:["webm"]},"video/x-f4v":{source:"apache",extensions:["f4v"]},"video/x-fli":{source:"apache",extensions:["fli"]},"video/x-flv":{source:"apache",compressible:!1,extensions:["flv"]},"video/x-m4v":{source:"apache",extensions:["m4v"]},"video/x-matroska":{source:"apache",compressible:!1,extensions:["mkv","mk3d","mks"]},"video/x-mng":{source:"apache",extensions:["mng"]},"video/x-ms-asf":{source:"apache",extensions:["asf","asx"]},"video/x-ms-vob":{source:"apache",extensions:["vob"]},"video/x-ms-wm":{source:"apache",extensions:["wm"]},"video/x-ms-wmv":{source:"apache",compressible:!1,extensions:["wmv"]},"video/x-ms-wmx":{source:"apache",extensions:["wmx"]},"video/x-ms-wvx":{source:"apache",extensions:["wvx"]},"video/x-msvideo":{source:"apache",extensions:["avi"]},"video/x-sgi-movie":{source:"apache",extensions:["movie"]},"video/x-smv":{source:"apache",extensions:["smv"]},"x-conference/x-cooltalk":{source:"apache",extensions:["ice"]},"x-shader/x-fragment":{compressible:!0},"x-shader/x-vertex":{compressible:!0}}});var n3=$((CrA,o3)=>{o3.exports=i3()});var c3=$(_i=>{"use strict";var ty=n3(),cfe=$e("path").extname,s3=/^\s*([^;\s]*)(?:;|\s|$)/,Ife=/^text\//i;_i.charset=g3;_i.charsets={lookup:g3};_i.contentType=lfe;_i.extension=pfe;_i.extensions=Object.create(null);_i.lookup=dfe;_i.types=Object.create(null);hfe(_i.extensions,_i.types);function g3(n){if(!n||typeof n!="string")return!1;var t=s3.exec(n),o=t&&ty[t[1].toLowerCase()];return o&&o.charset?o.charset:t&&Ife.test(t[1])?"UTF-8":!1}function lfe(n){if(!n||typeof n!="string")return!1;var t=n.indexOf("/")===-1?_i.lookup(n):n;if(!t)return!1;if(t.indexOf("charset")===-1){var o=_i.charset(t);o&&(t+="; charset="+o.toLowerCase())}return t}function pfe(n){if(!n||typeof n!="string")return!1;var t=s3.exec(n),o=t&&_i.extensions[t[1].toLowerCase()];return!o||!o.length?!1:o[0]}function dfe(n){if(!n||typeof n!="string")return!1;var t=cfe("x."+n).toLowerCase().substr(1);return t&&_i.types[t]||!1}function hfe(n,t){var o=["nginx","apache",void 0,"iana"];Object.keys(ty).forEach(function(e){var a=ty[e],A=a.extensions;if(!(!A||!A.length)){n[e]=A;for(var r=0;rc||g===c&&t[s].substr(0,12)==="application/"))continue}t[s]=e}}})}});var l3=$((BrA,I3)=>{I3.exports=Efe;function Efe(n){var t=typeof setImmediate=="function"?setImmediate:typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:null;t?t(n):setTimeout(n,0)}});var Z_=$((frA,d3)=>{var p3=l3();d3.exports=Cfe;function Cfe(n){var t=!1;return p3(function(){t=!0}),function(i,e){t?n(i,e):p3(function(){n(i,e)})}}});var X_=$((QrA,h3)=>{h3.exports=ufe;function ufe(n){Object.keys(n.jobs).forEach(Bfe.bind(n)),n.jobs={}}function Bfe(n){typeof this.jobs[n]=="function"&&this.jobs[n]()}});var $_=$((yrA,C3)=>{var E3=Z_(),ffe=X_();C3.exports=Qfe;function Qfe(n,t,o,i){var e=o.keyedList?o.keyedList[o.index]:o.index;o.jobs[e]=yfe(t,e,n[e],function(a,A){e in o.jobs&&(delete o.jobs[e],a?ffe(o):o.results[e]=A,i(a,o.results))})}function yfe(n,t,o,i){var e;return n.length==2?e=n(o,E3(i)):e=n(o,t,E3(i)),e}});var eT=$((mrA,u3)=>{u3.exports=mfe;function mfe(n,t){var o=!Array.isArray(n),i={index:0,keyedList:o||t?Object.keys(n):null,jobs:{},results:o?{}:[],size:o?Object.keys(n).length:n.length};return t&&i.keyedList.sort(o?t:function(e,a){return t(n[e],n[a])}),i}});var AT=$((SrA,B3)=>{var Sfe=X_(),wfe=Z_();B3.exports=Dfe;function Dfe(n){Object.keys(this.jobs).length&&(this.index=this.size,Sfe(this),wfe(n)(null,this.results))}});var Q3=$((wrA,f3)=>{var Ofe=$_(),bfe=eT(),Mfe=AT();f3.exports=_fe;function _fe(n,t,o){for(var i=bfe(n);i.index<(i.keyedList||n).length;)Ofe(n,t,i,function(e,a){if(e){o(e,a);return}if(Object.keys(i.jobs).length===0){o(null,i.results);return}}),i.index++;return Mfe.bind(i,o)}});var tT=$((DrA,ry)=>{var y3=$_(),Tfe=eT(),Nfe=AT();ry.exports=Rfe;ry.exports.ascending=m3;ry.exports.descending=kfe;function Rfe(n,t,o,i){var e=Tfe(n,o);return y3(n,t,e,function a(A,r){if(A){i(A,r);return}if(e.index++,e.index<(e.keyedList||n).length){y3(n,t,e,a);return}i(null,e.results)}),Nfe.bind(e,i)}function m3(n,t){return nt?1:0}function kfe(n,t){return-1*m3(n,t)}});var w3=$((OrA,S3)=>{var vfe=tT();S3.exports=Pfe;function Pfe(n,t,o){return vfe(n,t,null,o)}});var O3=$((brA,D3)=>{D3.exports={parallel:Q3(),serial:w3(),serialOrdered:tT()}});var rT=$((MrA,b3)=>{"use strict";b3.exports=Object});var _3=$((_rA,M3)=>{"use strict";M3.exports=Error});var N3=$((TrA,T3)=>{"use strict";T3.exports=EvalError});var k3=$((NrA,R3)=>{"use strict";R3.exports=RangeError});var P3=$((RrA,v3)=>{"use strict";v3.exports=ReferenceError});var F3=$((krA,G3)=>{"use strict";G3.exports=SyntaxError});var sc=$((vrA,L3)=>{"use strict";L3.exports=TypeError});var H3=$((PrA,U3)=>{"use strict";U3.exports=URIError});var x3=$((GrA,K3)=>{"use strict";K3.exports=Math.abs});var j3=$((FrA,Y3)=>{"use strict";Y3.exports=Math.floor});var q3=$((LrA,J3)=>{"use strict";J3.exports=Math.max});var V3=$((UrA,z3)=>{"use strict";z3.exports=Math.min});var Z3=$((HrA,W3)=>{"use strict";W3.exports=Math.pow});var $3=$((KrA,X3)=>{"use strict";X3.exports=Math.round});var Aj=$((xrA,ej)=>{"use strict";ej.exports=Number.isNaN||function(t){return t!==t}});var rj=$((YrA,tj)=>{"use strict";var Gfe=Aj();tj.exports=function(t){return Gfe(t)||t===0?t:t<0?-1:1}});var ij=$((jrA,aj)=>{"use strict";aj.exports=Object.getOwnPropertyDescriptor});var aT=$((JrA,oj)=>{"use strict";var ay=ij();if(ay)try{ay([],"length")}catch{ay=null}oj.exports=ay});var iT=$((qrA,nj)=>{"use strict";var iy=Object.defineProperty||!1;if(iy)try{iy({},"a",{value:1})}catch{iy=!1}nj.exports=iy});var oT=$((zrA,sj)=>{"use strict";sj.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var t={},o=Symbol("test"),i=Object(o);if(typeof o=="string"||Object.prototype.toString.call(o)!=="[object Symbol]"||Object.prototype.toString.call(i)!=="[object Symbol]")return!1;var e=42;t[o]=e;for(var a in t)return!1;if(typeof Object.keys=="function"&&Object.keys(t).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(t).length!==0)return!1;var A=Object.getOwnPropertySymbols(t);if(A.length!==1||A[0]!==o||!Object.prototype.propertyIsEnumerable.call(t,o))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var r=Object.getOwnPropertyDescriptor(t,o);if(r.value!==e||r.enumerable!==!0)return!1}return!0}});var Ij=$((VrA,cj)=>{"use strict";var gj=typeof Symbol<"u"&&Symbol,Ffe=oT();cj.exports=function(){return typeof gj!="function"||typeof Symbol!="function"||typeof gj("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:Ffe()}});var nT=$((WrA,lj)=>{"use strict";lj.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var sT=$((ZrA,pj)=>{"use strict";var Lfe=rT();pj.exports=Lfe.getPrototypeOf||null});var Ej=$((XrA,hj)=>{"use strict";var Ufe="Function.prototype.bind called on incompatible ",Hfe=Object.prototype.toString,Kfe=Math.max,xfe="[object Function]",dj=function(t,o){for(var i=[],e=0;e{"use strict";var Jfe=Ej();Cj.exports=Function.prototype.bind||Jfe});var oy=$((eaA,uj)=>{"use strict";uj.exports=Function.prototype.call});var gT=$((AaA,Bj)=>{"use strict";Bj.exports=Function.prototype.apply});var Qj=$((taA,fj)=>{"use strict";fj.exports=typeof Reflect<"u"&&Reflect&&Reflect.apply});var mj=$((raA,yj)=>{"use strict";var qfe=aC(),zfe=gT(),Vfe=oy(),Wfe=Qj();yj.exports=Wfe||qfe.call(Vfe,zfe)});var cT=$((aaA,Sj)=>{"use strict";var Zfe=aC(),Xfe=sc(),$fe=oy(),eQe=mj();Sj.exports=function(t){if(t.length<1||typeof t[0]!="function")throw new Xfe("a function is required");return eQe(Zfe,$fe,t)}});var _j=$((iaA,Mj)=>{"use strict";var AQe=cT(),wj=aT(),Oj;try{Oj=[].__proto__===Array.prototype}catch(n){if(!n||typeof n!="object"||!("code"in n)||n.code!=="ERR_PROTO_ACCESS")throw n}var IT=!!Oj&&wj&&wj(Object.prototype,"__proto__"),bj=Object,Dj=bj.getPrototypeOf;Mj.exports=IT&&typeof IT.get=="function"?AQe([IT.get]):typeof Dj=="function"?function(t){return Dj(t==null?t:bj(t))}:!1});var vj=$((oaA,kj)=>{"use strict";var Tj=nT(),Nj=sT(),Rj=_j();kj.exports=Tj?function(t){return Tj(t)}:Nj?function(t){if(!t||typeof t!="object"&&typeof t!="function")throw new TypeError("getProto: not an object");return Nj(t)}:Rj?function(t){return Rj(t)}:null});var ny=$((naA,Pj)=>{"use strict";var tQe=Function.prototype.call,rQe=Object.prototype.hasOwnProperty,aQe=aC();Pj.exports=aQe.call(tQe,rQe)});var sC=$((saA,Kj)=>{"use strict";var it,iQe=rT(),oQe=_3(),nQe=N3(),sQe=k3(),gQe=P3(),Vp=F3(),zp=sc(),cQe=H3(),IQe=x3(),lQe=j3(),pQe=q3(),dQe=V3(),hQe=Z3(),EQe=$3(),CQe=rj(),Uj=Function,lT=function(n){try{return Uj('"use strict"; return ('+n+").constructor;")()}catch{}},iC=aT(),uQe=iT(),pT=function(){throw new zp},BQe=iC?(function(){try{return arguments.callee,pT}catch{try{return iC(arguments,"callee").get}catch{return pT}}})():pT,Jp=Ij()(),ra=vj(),fQe=sT(),QQe=nT(),Hj=gT(),oC=oy(),qp={},yQe=typeof Uint8Array>"u"||!ra?it:ra(Uint8Array),vI={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?it:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?it:ArrayBuffer,"%ArrayIteratorPrototype%":Jp&&ra?ra([][Symbol.iterator]()):it,"%AsyncFromSyncIteratorPrototype%":it,"%AsyncFunction%":qp,"%AsyncGenerator%":qp,"%AsyncGeneratorFunction%":qp,"%AsyncIteratorPrototype%":qp,"%Atomics%":typeof Atomics>"u"?it:Atomics,"%BigInt%":typeof BigInt>"u"?it:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?it:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?it:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?it:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":oQe,"%eval%":eval,"%EvalError%":nQe,"%Float16Array%":typeof Float16Array>"u"?it:Float16Array,"%Float32Array%":typeof Float32Array>"u"?it:Float32Array,"%Float64Array%":typeof Float64Array>"u"?it:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?it:FinalizationRegistry,"%Function%":Uj,"%GeneratorFunction%":qp,"%Int8Array%":typeof Int8Array>"u"?it:Int8Array,"%Int16Array%":typeof Int16Array>"u"?it:Int16Array,"%Int32Array%":typeof Int32Array>"u"?it:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Jp&&ra?ra(ra([][Symbol.iterator]())):it,"%JSON%":typeof JSON=="object"?JSON:it,"%Map%":typeof Map>"u"?it:Map,"%MapIteratorPrototype%":typeof Map>"u"||!Jp||!ra?it:ra(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":iQe,"%Object.getOwnPropertyDescriptor%":iC,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?it:Promise,"%Proxy%":typeof Proxy>"u"?it:Proxy,"%RangeError%":sQe,"%ReferenceError%":gQe,"%Reflect%":typeof Reflect>"u"?it:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?it:Set,"%SetIteratorPrototype%":typeof Set>"u"||!Jp||!ra?it:ra(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?it:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Jp&&ra?ra(""[Symbol.iterator]()):it,"%Symbol%":Jp?Symbol:it,"%SyntaxError%":Vp,"%ThrowTypeError%":BQe,"%TypedArray%":yQe,"%TypeError%":zp,"%Uint8Array%":typeof Uint8Array>"u"?it:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?it:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?it:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?it:Uint32Array,"%URIError%":cQe,"%WeakMap%":typeof WeakMap>"u"?it:WeakMap,"%WeakRef%":typeof WeakRef>"u"?it:WeakRef,"%WeakSet%":typeof WeakSet>"u"?it:WeakSet,"%Function.prototype.call%":oC,"%Function.prototype.apply%":Hj,"%Object.defineProperty%":uQe,"%Object.getPrototypeOf%":fQe,"%Math.abs%":IQe,"%Math.floor%":lQe,"%Math.max%":pQe,"%Math.min%":dQe,"%Math.pow%":hQe,"%Math.round%":EQe,"%Math.sign%":CQe,"%Reflect.getPrototypeOf%":QQe};if(ra)try{null.error}catch(n){Gj=ra(ra(n)),vI["%Error.prototype%"]=Gj}var Gj,mQe=function n(t){var o;if(t==="%AsyncFunction%")o=lT("async function () {}");else if(t==="%GeneratorFunction%")o=lT("function* () {}");else if(t==="%AsyncGeneratorFunction%")o=lT("async function* () {}");else if(t==="%AsyncGenerator%"){var i=n("%AsyncGeneratorFunction%");i&&(o=i.prototype)}else if(t==="%AsyncIteratorPrototype%"){var e=n("%AsyncGenerator%");e&&ra&&(o=ra(e.prototype))}return vI[t]=o,o},Fj={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},nC=aC(),sy=ny(),SQe=nC.call(oC,Array.prototype.concat),wQe=nC.call(Hj,Array.prototype.splice),Lj=nC.call(oC,String.prototype.replace),gy=nC.call(oC,String.prototype.slice),DQe=nC.call(oC,RegExp.prototype.exec),OQe=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,bQe=/\\(\\)?/g,MQe=function(t){var o=gy(t,0,1),i=gy(t,-1);if(o==="%"&&i!=="%")throw new Vp("invalid intrinsic syntax, expected closing `%`");if(i==="%"&&o!=="%")throw new Vp("invalid intrinsic syntax, expected opening `%`");var e=[];return Lj(t,OQe,function(a,A,r,s){e[e.length]=r?Lj(s,bQe,"$1"):A||a}),e},_Qe=function(t,o){var i=t,e;if(sy(Fj,i)&&(e=Fj[i],i="%"+e[0]+"%"),sy(vI,i)){var a=vI[i];if(a===qp&&(a=mQe(i)),typeof a>"u"&&!o)throw new zp("intrinsic "+t+" exists, but is not available. Please file an issue!");return{alias:e,name:i,value:a}}throw new Vp("intrinsic "+t+" does not exist!")};Kj.exports=function(t,o){if(typeof t!="string"||t.length===0)throw new zp("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof o!="boolean")throw new zp('"allowMissing" argument must be a boolean');if(DQe(/^%?[^%]*%?$/,t)===null)throw new Vp("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=MQe(t),e=i.length>0?i[0]:"",a=_Qe("%"+e+"%",o),A=a.name,r=a.value,s=!1,g=a.alias;g&&(e=g[0],wQe(i,SQe([0,1],g)));for(var c=1,I=!0;c=i.length){var Q=iC(r,d);I=!!Q,I&&"get"in Q&&!("originalValue"in Q.get)?r=Q.get:r=r[d]}else I=sy(r,d),r=r[d];I&&!s&&(vI[A]=r)}}return r}});var Yj=$((gaA,xj)=>{"use strict";var TQe=oT();xj.exports=function(){return TQe()&&!!Symbol.toStringTag}});var qj=$((caA,Jj)=>{"use strict";var NQe=sC(),jj=NQe("%Object.defineProperty%",!0),RQe=Yj()(),kQe=ny(),vQe=sc(),cy=RQe?Symbol.toStringTag:null;Jj.exports=function(t,o){var i=arguments.length>2&&!!arguments[2]&&arguments[2].force,e=arguments.length>2&&!!arguments[2]&&arguments[2].nonConfigurable;if(typeof i<"u"&&typeof i!="boolean"||typeof e<"u"&&typeof e!="boolean")throw new vQe("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");cy&&(i||!kQe(t,cy))&&(jj?jj(t,cy,{configurable:!e,enumerable:!1,value:o,writable:!1}):t[cy]=o)}});var Vj=$((IaA,zj)=>{"use strict";zj.exports=function(n,t){return Object.keys(t).forEach(function(o){n[o]=n[o]||t[o]}),n}});var Xj=$((laA,Zj)=>{"use strict";var CT=a3(),PQe=$e("util"),dT=$e("path"),GQe=$e("http"),FQe=$e("https"),LQe=$e("url").parse,UQe=$e("fs"),HQe=$e("stream").Stream,KQe=$e("crypto"),hT=c3(),xQe=O3(),YQe=qj(),gc=ny(),ET=Vj();function Wj(n){return String(n).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22")}function Et(n){if(!(this instanceof Et))return new Et(n);this._overheadLength=0,this._valueLength=0,this._valuesToMeasure=[],CT.call(this),n=n||{};for(var t in n)this[t]=n[t]}PQe.inherits(Et,CT);Et.LINE_BREAK=`\r -`;Et.DEFAULT_CONTENT_TYPE="application/octet-stream";Et.prototype.append=function(n,t,o){o=o||{},typeof o=="string"&&(o={filename:o});var i=CT.prototype.append.bind(this);if((typeof t=="number"||t==null)&&(t=String(t)),Array.isArray(t)){this._error(new Error("Arrays are not supported."));return}var e=this._multiPartHeader(n,t,o),a=this._multiPartFooter();i(e),i(t),i(a),this._trackLength(e,t,o)};Et.prototype._trackLength=function(n,t,o){var i=0;o.knownLength!=null?i+=Number(o.knownLength):Buffer.isBuffer(t)?i=t.length:typeof t=="string"&&(i=Buffer.byteLength(t)),this._valueLength+=i,this._overheadLength+=Buffer.byteLength(n)+Et.LINE_BREAK.length,!(!t||!t.path&&!(t.readable&&gc(t,"httpVersion"))&&!(t instanceof HQe))&&(o.knownLength||this._valuesToMeasure.push(t))};Et.prototype._lengthRetriever=function(n,t){gc(n,"fd")?n.end!=null&&n.end!=1/0&&n.start!=null?t(null,n.end+1-(n.start?n.start:0)):UQe.stat(n.path,function(o,i){if(o){t(o);return}var e=i.size-(n.start?n.start:0);t(null,e)}):gc(n,"httpVersion")?t(null,Number(n.headers["content-length"])):gc(n,"httpModule")?(n.on("response",function(o){n.pause(),t(null,Number(o.headers["content-length"]))}),n.resume()):t("Unknown stream")};Et.prototype._multiPartHeader=function(n,t,o){if(typeof o.header=="string")return o.header;var i=this._getContentDisposition(t,o),e=this._getContentType(t,o),a="",A={"Content-Disposition":["form-data",'name="'+Wj(n)+'"'].concat(i||[]),"Content-Type":[].concat(e||[])};typeof o.header=="object"&&ET(A,o.header);var r;for(var s in A)if(gc(A,s)){if(r=A[s],r==null)continue;Array.isArray(r)||(r=[r]),r.length&&(a+=s+": "+r.join("; ")+Et.LINE_BREAK)}return"--"+this.getBoundary()+Et.LINE_BREAK+a+Et.LINE_BREAK};Et.prototype._getContentDisposition=function(n,t){var o;if(typeof t.filepath=="string"?o=dT.normalize(t.filepath).replace(/\\/g,"/"):t.filename||n&&(n.name||n.path)?o=dT.basename(t.filename||n&&(n.name||n.path)):n&&n.readable&&gc(n,"httpVersion")&&(o=dT.basename(n.client._httpMessage.path||"")),o)return'filename="'+Wj(o)+'"'};Et.prototype._getContentType=function(n,t){var o=t.contentType;return!o&&n&&n.name&&(o=hT.lookup(n.name)),!o&&n&&n.path&&(o=hT.lookup(n.path)),!o&&n&&n.readable&&gc(n,"httpVersion")&&(o=n.headers["content-type"]),!o&&(t.filepath||t.filename)&&(o=hT.lookup(t.filepath||t.filename)),!o&&n&&typeof n=="object"&&(o=Et.DEFAULT_CONTENT_TYPE),o};Et.prototype._multiPartFooter=function(){return function(n){var t=Et.LINE_BREAK,o=this._streams.length===0;o&&(t+=this._lastBoundary()),n(t)}.bind(this)};Et.prototype._lastBoundary=function(){return"--"+this.getBoundary()+"--"+Et.LINE_BREAK};Et.prototype.getHeaders=function(n){var t,o={"content-type":"multipart/form-data; boundary="+this.getBoundary()};for(t in n)gc(n,t)&&(o[t.toLowerCase()]=n[t]);return o};Et.prototype.setBoundary=function(n){if(typeof n!="string")throw new TypeError("FormData boundary must be a string");this._boundary=n};Et.prototype.getBoundary=function(){return this._boundary||this._generateBoundary(),this._boundary};Et.prototype.getBuffer=function(){for(var n=new Buffer.alloc(0),t=this.getBoundary(),o=0,i=this._streams.length;o{var Xp=1e3,$p=Xp*60,ed=$p*60,FI=ed*24,pye=FI*7,dye=FI*365.25;hJ.exports=function(n,t){t=t||{};var o=typeof n;if(o==="string"&&n.length>0)return hye(n);if(o==="number"&&isFinite(n))return t.long?Cye(n):Eye(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function hye(n){if(n=String(n),!(n.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(t){var o=parseFloat(t[1]),i=(t[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return o*dye;case"weeks":case"week":case"w":return o*pye;case"days":case"day":case"d":return o*FI;case"hours":case"hour":case"hrs":case"hr":case"h":return o*ed;case"minutes":case"minute":case"mins":case"min":case"m":return o*$p;case"seconds":case"second":case"secs":case"sec":case"s":return o*Xp;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}function Eye(n){var t=Math.abs(n);return t>=FI?Math.round(n/FI)+"d":t>=ed?Math.round(n/ed)+"h":t>=$p?Math.round(n/$p)+"m":t>=Xp?Math.round(n/Xp)+"s":n+"ms"}function Cye(n){var t=Math.abs(n);return t>=FI?hy(n,t,FI,"day"):t>=ed?hy(n,t,ed,"hour"):t>=$p?hy(n,t,$p,"minute"):t>=Xp?hy(n,t,Xp,"second"):n+" ms"}function hy(n,t,o,i){var e=t>=o*1.5;return Math.round(n/o)+" "+i+(e?"s":"")}});var RT=$((BiA,CJ)=>{function uye(n){o.debug=o,o.default=o,o.coerce=s,o.disable=A,o.enable=e,o.enabled=r,o.humanize=EJ(),o.destroy=g,Object.keys(n).forEach(c=>{o[c]=n[c]}),o.names=[],o.skips=[],o.formatters={};function t(c){let I=0;for(let d=0;d{if(K==="%%")return"%";R++;let q=o.formatters[L];if(typeof q=="function"){let z=y[R];K=q.call(m,z),y.splice(R,1),R--}return K}),o.formatArgs.call(m,y),(m.log||o.log).apply(m,y)}return Q.namespace=c,Q.useColors=o.useColors(),Q.color=o.selectColor(c),Q.extend=i,Q.destroy=o.destroy,Object.defineProperty(Q,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(B!==o.namespaces&&(B=o.namespaces,f=o.enabled(c)),f),set:y=>{d=y}}),typeof o.init=="function"&&o.init(Q),Q}function i(c,I){let d=o(this.namespace+(typeof I>"u"?":":I)+c);return d.log=this.log,d}function e(c){o.save(c),o.namespaces=c,o.names=[],o.skips=[];let I=(typeof c=="string"?c:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of I)d[0]==="-"?o.skips.push(d.slice(1)):o.names.push(d)}function a(c,I){let d=0,B=0,f=-1,Q=0;for(;d"-"+I)].join(",");return o.enable(""),c}function r(c){for(let I of o.skips)if(a(c,I))return!1;for(let I of o.names)if(a(c,I))return!0;return!1}function s(c){return c instanceof Error?c.stack||c.message:c}function g(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return o.enable(o.load()),o}CJ.exports=uye});var uJ=$((Ti,Ey)=>{Ti.formatArgs=fye;Ti.save=Qye;Ti.load=yye;Ti.useColors=Bye;Ti.storage=mye();Ti.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Ti.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Bye(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function fye(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Ey.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;n.splice(1,0,t,"color: inherit");let o=0,i=0;n[0].replace(/%[a-zA-Z%]/g,e=>{e!=="%%"&&(o++,e==="%c"&&(i=o))}),n.splice(i,0,t)}Ti.log=console.debug||console.log||(()=>{});function Qye(n){try{n?Ti.storage.setItem("debug",n):Ti.storage.removeItem("debug")}catch{}}function yye(){let n;try{n=Ti.storage.getItem("debug")||Ti.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function mye(){try{return localStorage}catch{}}Ey.exports=RT()(Ti);var{formatters:Sye}=Ey.exports;Sye.j=function(n){try{return JSON.stringify(n)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var fJ=$((aa,uy)=>{var wye=$e("tty"),Cy=$e("util");aa.init=Nye;aa.log=Mye;aa.formatArgs=Oye;aa.save=_ye;aa.load=Tye;aa.useColors=Dye;aa.destroy=Cy.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");aa.colors=[6,2,3,4,5,1];try{let n=$e("supports-color");n&&(n.stderr||n).level>=2&&(aa.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}aa.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,t)=>{let o=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,a)=>a.toUpperCase()),i=process.env[t];return/^(yes|on|true|enabled)$/i.test(i)?i=!0:/^(no|off|false|disabled)$/i.test(i)?i=!1:i==="null"?i=null:i=Number(i),n[o]=i,n},{});function Dye(){return"colors"in aa.inspectOpts?!!aa.inspectOpts.colors:wye.isatty(process.stderr.fd)}function Oye(n){let{namespace:t,useColors:o}=this;if(o){let i=this.color,e="\x1B[3"+(i<8?i:"8;5;"+i),a=` ${e};1m${t} \x1B[0m`;n[0]=a+n[0].split(` +`;Et.DEFAULT_CONTENT_TYPE="application/octet-stream";Et.prototype.append=function(n,t,o){o=o||{},typeof o=="string"&&(o={filename:o});var i=CT.prototype.append.bind(this);if((typeof t=="number"||t==null)&&(t=String(t)),Array.isArray(t)){this._error(new Error("Arrays are not supported."));return}var e=this._multiPartHeader(n,t,o),a=this._multiPartFooter();i(e),i(t),i(a),this._trackLength(e,t,o)};Et.prototype._trackLength=function(n,t,o){var i=0;o.knownLength!=null?i+=Number(o.knownLength):Buffer.isBuffer(t)?i=t.length:typeof t=="string"&&(i=Buffer.byteLength(t)),this._valueLength+=i,this._overheadLength+=Buffer.byteLength(n)+Et.LINE_BREAK.length,!(!t||!t.path&&!(t.readable&&gc(t,"httpVersion"))&&!(t instanceof HQe))&&(o.knownLength||this._valuesToMeasure.push(t))};Et.prototype._lengthRetriever=function(n,t){gc(n,"fd")?n.end!=null&&n.end!=1/0&&n.start!=null?t(null,n.end+1-(n.start?n.start:0)):UQe.stat(n.path,function(o,i){if(o){t(o);return}var e=i.size-(n.start?n.start:0);t(null,e)}):gc(n,"httpVersion")?t(null,Number(n.headers["content-length"])):gc(n,"httpModule")?(n.on("response",function(o){n.pause(),t(null,Number(o.headers["content-length"]))}),n.resume()):t("Unknown stream")};Et.prototype._multiPartHeader=function(n,t,o){if(typeof o.header=="string")return o.header;var i=this._getContentDisposition(t,o),e=this._getContentType(t,o),a="",A={"Content-Disposition":["form-data",'name="'+Wj(n)+'"'].concat(i||[]),"Content-Type":[].concat(e||[])};typeof o.header=="object"&&ET(A,o.header);var r;for(var s in A)if(gc(A,s)){if(r=A[s],r==null)continue;Array.isArray(r)||(r=[r]),r.length&&(a+=s+": "+r.join("; ")+Et.LINE_BREAK)}return"--"+this.getBoundary()+Et.LINE_BREAK+a+Et.LINE_BREAK};Et.prototype._getContentDisposition=function(n,t){var o;if(typeof t.filepath=="string"?o=dT.normalize(t.filepath).replace(/\\/g,"/"):t.filename||n&&(n.name||n.path)?o=dT.basename(t.filename||n&&(n.name||n.path)):n&&n.readable&&gc(n,"httpVersion")&&(o=dT.basename(n.client._httpMessage.path||"")),o)return'filename="'+Wj(o)+'"'};Et.prototype._getContentType=function(n,t){var o=t.contentType;return!o&&n&&n.name&&(o=hT.lookup(n.name)),!o&&n&&n.path&&(o=hT.lookup(n.path)),!o&&n&&n.readable&&gc(n,"httpVersion")&&(o=n.headers["content-type"]),!o&&(t.filepath||t.filename)&&(o=hT.lookup(t.filepath||t.filename)),!o&&n&&typeof n=="object"&&(o=Et.DEFAULT_CONTENT_TYPE),o};Et.prototype._multiPartFooter=function(){return function(n){var t=Et.LINE_BREAK,o=this._streams.length===0;o&&(t+=this._lastBoundary()),n(t)}.bind(this)};Et.prototype._lastBoundary=function(){return"--"+this.getBoundary()+"--"+Et.LINE_BREAK};Et.prototype.getHeaders=function(n){var t,o={"content-type":"multipart/form-data; boundary="+this.getBoundary()};for(t in n)gc(n,t)&&(o[t.toLowerCase()]=n[t]);return o};Et.prototype.setBoundary=function(n){if(typeof n!="string")throw new TypeError("FormData boundary must be a string");this._boundary=n};Et.prototype.getBoundary=function(){return this._boundary||this._generateBoundary(),this._boundary};Et.prototype.getBuffer=function(){for(var n=new Buffer.alloc(0),t=this.getBoundary(),o=0,i=this._streams.length;o{var Xp=1e3,$p=Xp*60,ed=$p*60,FI=ed*24,pye=FI*7,dye=FI*365.25;hJ.exports=function(n,t){t=t||{};var o=typeof n;if(o==="string"&&n.length>0)return hye(n);if(o==="number"&&isFinite(n))return t.long?Cye(n):Eye(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function hye(n){if(n=String(n),!(n.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(t){var o=parseFloat(t[1]),i=(t[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return o*dye;case"weeks":case"week":case"w":return o*pye;case"days":case"day":case"d":return o*FI;case"hours":case"hour":case"hrs":case"hr":case"h":return o*ed;case"minutes":case"minute":case"mins":case"min":case"m":return o*$p;case"seconds":case"second":case"secs":case"sec":case"s":return o*Xp;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}function Eye(n){var t=Math.abs(n);return t>=FI?Math.round(n/FI)+"d":t>=ed?Math.round(n/ed)+"h":t>=$p?Math.round(n/$p)+"m":t>=Xp?Math.round(n/Xp)+"s":n+"ms"}function Cye(n){var t=Math.abs(n);return t>=FI?hy(n,t,FI,"day"):t>=ed?hy(n,t,ed,"hour"):t>=$p?hy(n,t,$p,"minute"):t>=Xp?hy(n,t,Xp,"second"):n+" ms"}function hy(n,t,o,i){var e=t>=o*1.5;return Math.round(n/o)+" "+i+(e?"s":"")}});var RT=$((BiA,CJ)=>{function uye(n){o.debug=o,o.default=o,o.coerce=s,o.disable=A,o.enable=e,o.enabled=r,o.humanize=EJ(),o.destroy=g,Object.keys(n).forEach(c=>{o[c]=n[c]}),o.names=[],o.skips=[],o.formatters={};function t(c){let I=0;for(let d=0;d{if(U==="%%")return"%";R++;let q=o.formatters[F];if(typeof q=="function"){let z=y[R];U=q.call(m,z),y.splice(R,1),R--}return U}),o.formatArgs.call(m,y),(m.log||o.log).apply(m,y)}return Q.namespace=c,Q.useColors=o.useColors(),Q.color=o.selectColor(c),Q.extend=i,Q.destroy=o.destroy,Object.defineProperty(Q,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(B!==o.namespaces&&(B=o.namespaces,f=o.enabled(c)),f),set:y=>{d=y}}),typeof o.init=="function"&&o.init(Q),Q}function i(c,I){let d=o(this.namespace+(typeof I>"u"?":":I)+c);return d.log=this.log,d}function e(c){o.save(c),o.namespaces=c,o.names=[],o.skips=[];let I=(typeof c=="string"?c:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of I)d[0]==="-"?o.skips.push(d.slice(1)):o.names.push(d)}function a(c,I){let d=0,B=0,f=-1,Q=0;for(;d"-"+I)].join(",");return o.enable(""),c}function r(c){for(let I of o.skips)if(a(c,I))return!1;for(let I of o.names)if(a(c,I))return!0;return!1}function s(c){return c instanceof Error?c.stack||c.message:c}function g(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return o.enable(o.load()),o}CJ.exports=uye});var uJ=$((Ti,Ey)=>{Ti.formatArgs=fye;Ti.save=Qye;Ti.load=yye;Ti.useColors=Bye;Ti.storage=mye();Ti.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Ti.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Bye(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function fye(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Ey.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;n.splice(1,0,t,"color: inherit");let o=0,i=0;n[0].replace(/%[a-zA-Z%]/g,e=>{e!=="%%"&&(o++,e==="%c"&&(i=o))}),n.splice(i,0,t)}Ti.log=console.debug||console.log||(()=>{});function Qye(n){try{n?Ti.storage.setItem("debug",n):Ti.storage.removeItem("debug")}catch{}}function yye(){let n;try{n=Ti.storage.getItem("debug")||Ti.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function mye(){try{return localStorage}catch{}}Ey.exports=RT()(Ti);var{formatters:Sye}=Ey.exports;Sye.j=function(n){try{return JSON.stringify(n)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var fJ=$((aa,uy)=>{var wye=$e("tty"),Cy=$e("util");aa.init=Nye;aa.log=Mye;aa.formatArgs=Oye;aa.save=_ye;aa.load=Tye;aa.useColors=Dye;aa.destroy=Cy.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");aa.colors=[6,2,3,4,5,1];try{let n=$e("supports-color");n&&(n.stderr||n).level>=2&&(aa.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}aa.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,t)=>{let o=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,a)=>a.toUpperCase()),i=process.env[t];return/^(yes|on|true|enabled)$/i.test(i)?i=!0:/^(no|off|false|disabled)$/i.test(i)?i=!1:i==="null"?i=null:i=Number(i),n[o]=i,n},{});function Dye(){return"colors"in aa.inspectOpts?!!aa.inspectOpts.colors:wye.isatty(process.stderr.fd)}function Oye(n){let{namespace:t,useColors:o}=this;if(o){let i=this.color,e="\x1B[3"+(i<8?i:"8;5;"+i),a=` ${e};1m${t} \x1B[0m`;n[0]=a+n[0].split(` `).join(` `+a),n.push(e+"m+"+uy.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=bye()+t+" "+n[0]}function bye(){return aa.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Mye(...n){return process.stderr.write(Cy.formatWithOptions(aa.inspectOpts,...n)+` `)}function _ye(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function Tye(){return process.env.DEBUG}function Nye(n){n.inspectOpts={};let t=Object.keys(aa.inspectOpts);for(let o=0;o{"use strict";var Hye=LI&&LI.__awaiter||function(n,t,o,i){function e(a){return a instanceof o?a:new o(function(A){A(a)})}return new(o||(o=Promise))(function(a,A){function r(c){try{g(i.next(c))}catch(I){A(I)}}function s(c){try{g(i.throw(c))}catch(I){A(I)}}function g(c){c.done?a(c.value):e(c.value).then(r,s)}g((i=i.apply(n,t||[])).next())})},Ad=LI&&LI.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(LI,"__esModule",{value:!0});var DJ=Ad($e("net")),OJ=Ad($e("tls")),Kye=Ad($e("url")),xye=Ad($e("assert")),Yye=Ad(ct()),jye=SJ(),Jye=Ad(wJ()),CC=Yye.default("https-proxy-agent:agent"),FT=class extends jye.Agent{constructor(t){let o;if(typeof t=="string"?o=Kye.default.parse(t):o=t,!o)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");CC("creating new HttpsProxyAgent instance: %o",o),super(o);let i=Object.assign({},o);this.secureProxy=o.secureProxy||Vye(i.protocol),i.host=i.hostname||i.host,typeof i.port=="string"&&(i.port=parseInt(i.port,10)),!i.port&&i.host&&(i.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in i)&&(i.ALPNProtocols=["http 1.1"]),i.host&&i.path&&(delete i.path,delete i.pathname),this.proxy=i}callback(t,o){return Hye(this,void 0,void 0,function*(){let{proxy:i,secureProxy:e}=this,a;e?(CC("Creating `tls.Socket`: %o",i),a=OJ.default.connect(i)):(CC("Creating `net.Socket`: %o",i),a=DJ.default.connect(i));let A=Object.assign({},i.headers),s=`CONNECT ${`${o.host}:${o.port}`} HTTP/1.1\r `;i.auth&&(A["Proxy-Authorization"]=`Basic ${Buffer.from(i.auth).toString("base64")}`);let{host:g,port:c,secureEndpoint:I}=o;zye(c,I)||(g+=`:${c}`),A.Host=g,A.Connection="close";for(let y of Object.keys(A))s+=`${y}: ${A[y]}\r `;let d=Jye.default(a);a.write(`${s}\r -`);let{statusCode:B,buffered:f}=yield d;if(B===200){if(t.once("socket",qye),o.secureEndpoint){CC("Upgrading socket connection to TLS");let y=o.servername||o.host;return OJ.default.connect(Object.assign(Object.assign({},Wye(o,"host","hostname","path","port")),{socket:a,servername:y}))}return a}a.destroy();let Q=new DJ.default.Socket({writable:!1});return Q.readable=!0,t.once("socket",y=>{CC("replaying proxy buffer for failed request"),xye.default(y.listenerCount("data")>0),y.push(f),y.push(null)}),Q})}};LI.default=FT;function qye(n){n.resume()}function zye(n,t){return!!(!t&&n===80||t&&n===443)}function Vye(n){return typeof n=="string"?/^https:?$/i.test(n):!1}function Wye(n,...t){let o={},i;for(i in n)t.includes(i)||(o[i]=n[i]);return o}});var KT=$((HT,MJ)=>{"use strict";var Zye=HT&&HT.__importDefault||function(n){return n&&n.__esModule?n:{default:n}},LT=Zye(bJ());function UT(n){return new LT.default(n)}(function(n){n.HttpsProxyAgent=LT.default,n.prototype=LT.default.prototype})(UT||(UT={}));MJ.exports=UT});var TJ=$((SiA,_J)=>{var uC;_J.exports=function(){if(!uC){try{uC=ct()("follow-redirects")}catch{}typeof uC!="function"&&(uC=function(){})}uC.apply(null,arguments)}});var PJ=$((wiA,e0)=>{var fC=$e("url"),BC=fC.URL,Xye=$e("http"),$ye=$e("https"),qT=$e("stream").Writable,zT=$e("assert"),NJ=TJ();(function(){var t=typeof process<"u",o=typeof window<"u"&&typeof document<"u",i=HI(Error.captureStackTrace);!t&&(o||!i)&&console.warn("The follow-redirects package should be excluded from browser builds.")})();var VT=!1;try{zT(new BC(""))}catch(n){VT=n.code==="ERR_INVALID_URL"}var eme=["Authorization","Proxy-Authorization","Cookie"],Ame=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],WT=["abort","aborted","connect","error","socket","timeout"],ZT=Object.create(null);WT.forEach(function(n){ZT[n]=function(t,o,i){this._redirectable.emit(n,t,o,i)}});var YT=QC("ERR_INVALID_URL","Invalid URL",TypeError),jT=QC("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),tme=QC("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",jT),rme=QC("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),ame=QC("ERR_STREAM_WRITE_AFTER_END","write after end"),ime=qT.prototype.destroy||kJ;function Ni(n,t){qT.call(this),this._sanitizeOptions(n),this._options=n,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],t&&this.on("response",t);var o=this;this._onNativeResponse=function(i){try{o._processResponse(i)}catch(e){o.emit("error",e instanceof jT?e:new jT({cause:e}))}},this._headerFilter=new RegExp("^(?:"+eme.concat(n.sensitiveHeaders).map(Ime).join("|")+")$","i"),this._performRequest()}Ni.prototype=Object.create(qT.prototype);Ni.prototype.abort=function(){$T(this._currentRequest),this._currentRequest.abort(),this.emit("abort")};Ni.prototype.destroy=function(n){return $T(this._currentRequest,n),ime.call(this,n),this};Ni.prototype.write=function(n,t,o){if(this._ending)throw new ame;if(!UI(n)&&!gme(n))throw new TypeError("data should be a string, Buffer or Uint8Array");if(HI(t)&&(o=t,t=null),n.length===0){o&&o();return}this._requestBodyLength+n.length<=this._options.maxBodyLength?(this._requestBodyLength+=n.length,this._requestBodyBuffers.push({data:n,encoding:t}),this._currentRequest.write(n,t,o)):(this.emit("error",new rme),this.abort())};Ni.prototype.end=function(n,t,o){if(HI(n)?(o=n,n=t=null):HI(t)&&(o=t,t=null),!n)this._ended=this._ending=!0,this._currentRequest.end(null,null,o);else{var i=this,e=this._currentRequest;this.write(n,t,function(){i._ended=!0,e.end(null,null,o)}),this._ending=!0}};Ni.prototype.setHeader=function(n,t){this._options.headers[n]=t,this._currentRequest.setHeader(n,t)};Ni.prototype.removeHeader=function(n){delete this._options.headers[n],this._currentRequest.removeHeader(n)};Ni.prototype.setTimeout=function(n,t){var o=this;function i(A){A.setTimeout(n),A.removeListener("timeout",A.destroy),A.addListener("timeout",A.destroy)}function e(A){o._timeout&&clearTimeout(o._timeout),o._timeout=setTimeout(function(){o.emit("timeout"),a()},n),i(A)}function a(){o._timeout&&(clearTimeout(o._timeout),o._timeout=null),o.removeListener("abort",a),o.removeListener("error",a),o.removeListener("response",a),o.removeListener("close",a),t&&o.removeListener("timeout",t),o.socket||o._currentRequest.removeListener("socket",e)}return t&&this.on("timeout",t),this.socket?e(this.socket):this._currentRequest.once("socket",e),this.on("socket",i),this.on("abort",a),this.on("error",a),this.on("response",a),this.on("close",a),this};["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(n){Ni.prototype[n]=function(t,o){return this._currentRequest[n](t,o)}});["aborted","connection","socket"].forEach(function(n){Object.defineProperty(Ni.prototype,n,{get:function(){return this._currentRequest[n]}})});Ni.prototype._sanitizeOptions=function(n){if(n.headers||(n.headers={}),sme(n.sensitiveHeaders)||(n.sensitiveHeaders=[]),n.host&&(n.hostname||(n.hostname=n.host),delete n.host),!n.pathname&&n.path){var t=n.path.indexOf("?");t<0?n.pathname=n.path:(n.pathname=n.path.substring(0,t),n.search=n.path.substring(t))}};Ni.prototype._performRequest=function(){var n=this._options.protocol,t=this._options.nativeProtocols[n];if(!t)throw new TypeError("Unsupported protocol "+n);if(this._options.agents){var o=n.slice(0,-1);this._options.agent=this._options.agents[o]}var i=this._currentRequest=t.request(this._options,this._onNativeResponse);i._redirectable=this;for(var e of WT)i.on(e,ZT[e]);if(this._currentUrl=/^\//.test(this._options.path)?fC.format(this._options):this._options.path,this._isRedirect){var a=0,A=this,r=this._requestBodyBuffers;(function s(g){if(i===A._currentRequest)if(g)A.emit("error",g);else if(a=400){n.responseUrl=this._currentUrl,n.redirects=this._redirects,this.emit("response",n),this._requestBodyBuffers=[];return}if($T(this._currentRequest),n.destroy(),++this._redirectCount>this._options.maxRedirects)throw new tme;var i,e=this._options.beforeRedirect;e&&(i=Object.assign({Host:n.req.getHeader("host")},this._options.headers));var a=this._options.method;((t===301||t===302)&&this._options.method==="POST"||t===303&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],xT(/^content-/i,this._options.headers));var A=xT(/^host$/i,this._options.headers),r=XT(this._currentUrl),s=A||r.host,g=/^\w+:/.test(o)?this._currentUrl:fC.format(Object.assign(r,{host:s})),c=ome(o,g);if(NJ("redirecting to",c.href),this._isRedirect=!0,JT(c,this._options),(c.protocol!==r.protocol&&c.protocol!=="https:"||c.host!==s&&!nme(c.host,s))&&xT(this._headerFilter,this._options.headers),HI(e)){var I={headers:n.headers,statusCode:t},d={url:g,method:a,headers:i};e(this._options,I,d),this._sanitizeOptions(this._options)}this._performRequest()};function RJ(n){var t={maxRedirects:21,maxBodyLength:10485760},o={};return Object.keys(n).forEach(function(i){var e=i+":",a=o[e]=n[i],A=t[i]=Object.create(a);function r(g,c,I){return cme(g)?g=JT(g):UI(g)?g=JT(XT(g)):(I=c,c=vJ(g),g={protocol:e}),HI(c)&&(I=c,c=null),c=Object.assign({maxRedirects:t.maxRedirects,maxBodyLength:t.maxBodyLength},g,c),c.nativeProtocols=o,!UI(c.host)&&!UI(c.hostname)&&(c.hostname="::1"),zT.equal(c.protocol,e,"protocol mismatch"),NJ("options",c),new Ni(c,I)}function s(g,c,I){var d=A.request(g,c,I);return d.end(),d}Object.defineProperties(A,{request:{value:r,configurable:!0,enumerable:!0,writable:!0},get:{value:s,configurable:!0,enumerable:!0,writable:!0}})}),t}function kJ(){}function XT(n){var t;if(VT)t=new BC(n);else if(t=vJ(fC.parse(n)),!UI(t.protocol))throw new YT({input:n});return t}function ome(n,t){return VT?new BC(n,t):XT(fC.resolve(t,n))}function vJ(n){if(/^\[/.test(n.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(n.hostname))throw new YT({input:n.href||n});if(/^\[/.test(n.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(n.host))throw new YT({input:n.href||n});return n}function JT(n,t){var o=t||{};for(var i of Ame)o[i]=n[i];return o.hostname.startsWith("[")&&(o.hostname=o.hostname.slice(1,-1)),o.port!==""&&(o.port=Number(o.port)),o.path=o.search?o.pathname+o.search:o.pathname,o}function xT(n,t){var o;for(var i in t)n.test(i)&&(o=t[i],delete t[i]);return o===null||typeof o>"u"?void 0:String(o).trim()}function QC(n,t,o){function i(e){HI(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,e||{}),this.code=n,this.message=this.cause?t+": "+this.cause.message:t}return i.prototype=new(o||Error),Object.defineProperties(i.prototype,{constructor:{value:i,enumerable:!1},name:{value:"Error ["+n+"]",enumerable:!1}}),i}function $T(n,t){for(var o of WT)n.removeListener(o,ZT[o]);n.on("error",kJ),n.destroy(t)}function nme(n,t){zT(UI(n)&&UI(t));var o=n.length-t.length-1;return o>0&&n[o]==="."&&n.endsWith(t)}function sme(n){return n instanceof Array}function UI(n){return typeof n=="string"||n instanceof String}function HI(n){return typeof n=="function"}function gme(n){return typeof n=="object"&&"length"in n}function cme(n){return BC&&n instanceof BC}function Ime(n){return n.replace(/[\]\\/()*+?.$]/g,"\\$&")}e0.exports=RJ({http:Xye,https:$ye});e0.exports.wrap=RJ});var Lq=$((qsA,Fq)=>{Fq.exports=$e("util").inspect});var TC=$((zsA,i4)=>{var T0=typeof Map=="function"&&Map.prototype,y0=Object.getOwnPropertyDescriptor&&T0?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,My=T0&&y0&&typeof y0.get=="function"?y0.get:null,Uq=T0&&Map.prototype.forEach,N0=typeof Set=="function"&&Set.prototype,m0=Object.getOwnPropertyDescriptor&&N0?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,_y=N0&&m0&&typeof m0.get=="function"?m0.get:null,Hq=N0&&Set.prototype.forEach,TSe=typeof WeakMap=="function"&&WeakMap.prototype,bC=TSe?WeakMap.prototype.has:null,NSe=typeof WeakSet=="function"&&WeakSet.prototype,MC=NSe?WeakSet.prototype.has:null,RSe=typeof WeakRef=="function"&&WeakRef.prototype,Kq=RSe?WeakRef.prototype.deref:null,kSe=Boolean.prototype.valueOf,vSe=Object.prototype.toString,PSe=Function.prototype.toString,GSe=String.prototype.match,R0=String.prototype.slice,lc=String.prototype.replace,FSe=String.prototype.toUpperCase,xq=String.prototype.toLowerCase,Xq=RegExp.prototype.test,Yq=Array.prototype.concat,rs=Array.prototype.join,LSe=Array.prototype.slice,jq=Math.floor,D0=typeof BigInt=="function"?BigInt.prototype.valueOf:null,S0=Object.getOwnPropertySymbols,O0=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,id=typeof Symbol=="function"&&typeof Symbol.iterator=="object",_C=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===id||!0)?Symbol.toStringTag:null,$q=Object.prototype.propertyIsEnumerable,Jq=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(n){return n.__proto__}:null);function qq(n,t){if(n===1/0||n===-1/0||n!==n||n&&n>-1e3&&n<1e3||Xq.call(/e/,t))return t;var o=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof n=="number"){var i=n<0?-jq(-n):jq(n);if(i!==n){var e=String(i),a=R0.call(t,e.length+1);return lc.call(e,o,"$&_")+"."+lc.call(lc.call(a,/([0-9]{3})/g,"$&_"),/_$/,"")}}return lc.call(t,o,"$&_")}var b0=Lq(),zq=b0.custom,Vq=t4(zq)?zq:null,e4={__proto__:null,double:'"',single:"'"},USe={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};i4.exports=function n(t,o,i,e){var a=o||{};if(gg(a,"quoteStyle")&&!gg(e4,a.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(gg(a,"maxStringLength")&&(typeof a.maxStringLength=="number"?a.maxStringLength<0&&a.maxStringLength!==1/0:a.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var A=gg(a,"customInspect")?a.customInspect:!0;if(typeof A!="boolean"&&A!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(gg(a,"indent")&&a.indent!==null&&a.indent!==" "&&!(parseInt(a.indent,10)===a.indent&&a.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(gg(a,"numericSeparator")&&typeof a.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var r=a.numericSeparator;if(typeof t>"u")return"undefined";if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="string")return a4(t,a);if(typeof t=="number"){if(t===0)return 1/0/t>0?"0":"-0";var s=String(t);return r?qq(t,s):s}if(typeof t=="bigint"){var g=String(t)+"n";return r?qq(t,g):g}var c=typeof a.depth>"u"?5:a.depth;if(typeof i>"u"&&(i=0),i>=c&&c>0&&typeof t=="object")return M0(t)?"[Array]":"[Object]";var I=awe(a,i);if(typeof e>"u")e=[];else if(r4(e,t)>=0)return"[Circular]";function d(U,N,k){if(N&&(e=LSe.call(e),e.push(N)),k){var V={depth:a.depth};return gg(a,"quoteStyle")&&(V.quoteStyle=a.quoteStyle),n(U,V,i+1,e)}return n(U,a,i+1,e)}if(typeof t=="function"&&!Wq(t)){var B=VSe(t),f=by(t,d);return"[Function"+(B?": "+B:" (anonymous)")+"]"+(f.length>0?" { "+rs.call(f,", ")+" }":"")}if(t4(t)){var Q=id?lc.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):O0.call(t);return typeof t=="object"&&!id?OC(Q):Q}if(Awe(t)){for(var y="<"+xq.call(String(t.nodeName)),m=t.attributes||[],_=0;_",y}if(M0(t)){if(t.length===0)return"[]";var T=by(t,d);return I&&!rwe(T)?"["+_0(T,I)+"]":"[ "+rs.call(T,", ")+" ]"}if(xSe(t)){var R=by(t,d);return!("cause"in Error.prototype)&&"cause"in t&&!$q.call(t,"cause")?"{ ["+String(t)+"] "+rs.call(Yq.call("[cause]: "+d(t.cause),R),", ")+" }":R.length===0?"["+String(t)+"]":"{ ["+String(t)+"] "+rs.call(R,", ")+" }"}if(typeof t=="object"&&A){if(Vq&&typeof t[Vq]=="function"&&b0)return b0(t,{depth:c-i});if(A!=="symbol"&&typeof t.inspect=="function")return t.inspect()}if(WSe(t)){var F=[];return Uq&&Uq.call(t,function(U,N){F.push(d(N,t,!0)+" => "+d(U,t))}),Zq("Map",My.call(t),F,I)}if($Se(t)){var K=[];return Hq&&Hq.call(t,function(U){K.push(d(U,t))}),Zq("Set",_y.call(t),K,I)}if(ZSe(t))return w0("WeakMap");if(ewe(t))return w0("WeakSet");if(XSe(t))return w0("WeakRef");if(jSe(t))return OC(d(Number(t)));if(qSe(t))return OC(d(D0.call(t)));if(JSe(t))return OC(kSe.call(t));if(YSe(t))return OC(d(String(t)));if(typeof window<"u"&&t===window)return"{ [object Window] }";if(typeof globalThis<"u"&&t===globalThis||typeof global<"u"&&t===global)return"{ [object globalThis] }";if(!KSe(t)&&!Wq(t)){var L=by(t,d),q=Jq?Jq(t)===Object.prototype:t instanceof Object||t.constructor===Object,z=t instanceof Object?"":"null prototype",j=!q&&_C&&Object(t)===t&&_C in t?R0.call(pc(t),8,-1):z?"Object":"",P=q||typeof t.constructor!="function"?"":t.constructor.name?t.constructor.name+" ":"",J=P+(j||z?"["+rs.call(Yq.call([],j||[],z||[]),": ")+"] ":"");return L.length===0?J+"{}":I?J+"{"+_0(L,I)+"}":J+"{ "+rs.call(L,", ")+" }"}return String(t)};function A4(n,t,o){var i=o.quoteStyle||t,e=e4[i];return e+n+e}function HSe(n){return lc.call(String(n),/"/g,""")}function YI(n){return!_C||!(typeof n=="object"&&(_C in n||typeof n[_C]<"u"))}function M0(n){return pc(n)==="[object Array]"&&YI(n)}function KSe(n){return pc(n)==="[object Date]"&&YI(n)}function Wq(n){return pc(n)==="[object RegExp]"&&YI(n)}function xSe(n){return pc(n)==="[object Error]"&&YI(n)}function YSe(n){return pc(n)==="[object String]"&&YI(n)}function jSe(n){return pc(n)==="[object Number]"&&YI(n)}function JSe(n){return pc(n)==="[object Boolean]"&&YI(n)}function t4(n){if(id)return n&&typeof n=="object"&&n instanceof Symbol;if(typeof n=="symbol")return!0;if(!n||typeof n!="object"||!O0)return!1;try{return O0.call(n),!0}catch{}return!1}function qSe(n){if(!n||typeof n!="object"||!D0)return!1;try{return D0.call(n),!0}catch{}return!1}var zSe=Object.prototype.hasOwnProperty||function(n){return n in this};function gg(n,t){return zSe.call(n,t)}function pc(n){return vSe.call(n)}function VSe(n){if(n.name)return n.name;var t=GSe.call(PSe.call(n),/^function\s*([\w$]+)/);return t?t[1]:null}function r4(n,t){if(n.indexOf)return n.indexOf(t);for(var o=0,i=n.length;ot.maxStringLength){var o=n.length-t.maxStringLength,i="... "+o+" more character"+(o>1?"s":"");return a4(R0.call(n,0,t.maxStringLength),t)+i}var e=USe[t.quoteStyle||"single"];e.lastIndex=0;var a=lc.call(lc.call(n,e,"\\$1"),/[\x00-\x1f]/g,twe);return A4(a,"single",t)}function twe(n){var t=n.charCodeAt(0),o={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return o?"\\"+o:"\\x"+(t<16?"0":"")+FSe.call(t.toString(16))}function OC(n){return"Object("+n+")"}function w0(n){return n+" { ? }"}function Zq(n,t,o,i){var e=i?_0(o,i):rs.call(o,", ");return n+" ("+t+") {"+e+"}"}function rwe(n){for(var t=0;t{CC("replaying proxy buffer for failed request"),xye.default(y.listenerCount("data")>0),y.push(f),y.push(null)}),Q})}};LI.default=FT;function qye(n){n.resume()}function zye(n,t){return!!(!t&&n===80||t&&n===443)}function Vye(n){return typeof n=="string"?/^https:?$/i.test(n):!1}function Wye(n,...t){let o={},i;for(i in n)t.includes(i)||(o[i]=n[i]);return o}});var KT=$((HT,MJ)=>{"use strict";var Zye=HT&&HT.__importDefault||function(n){return n&&n.__esModule?n:{default:n}},LT=Zye(bJ());function UT(n){return new LT.default(n)}(function(n){n.HttpsProxyAgent=LT.default,n.prototype=LT.default.prototype})(UT||(UT={}));MJ.exports=UT});var TJ=$((SiA,_J)=>{var uC;_J.exports=function(){if(!uC){try{uC=ct()("follow-redirects")}catch{}typeof uC!="function"&&(uC=function(){})}uC.apply(null,arguments)}});var PJ=$((wiA,e0)=>{var fC=$e("url"),BC=fC.URL,Xye=$e("http"),$ye=$e("https"),qT=$e("stream").Writable,zT=$e("assert"),NJ=TJ();(function(){var t=typeof process<"u",o=typeof window<"u"&&typeof document<"u",i=HI(Error.captureStackTrace);!t&&(o||!i)&&console.warn("The follow-redirects package should be excluded from browser builds.")})();var VT=!1;try{zT(new BC(""))}catch(n){VT=n.code==="ERR_INVALID_URL"}var eme=["Authorization","Proxy-Authorization","Cookie"],Ame=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],WT=["abort","aborted","connect","error","socket","timeout"],ZT=Object.create(null);WT.forEach(function(n){ZT[n]=function(t,o,i){this._redirectable.emit(n,t,o,i)}});var YT=QC("ERR_INVALID_URL","Invalid URL",TypeError),jT=QC("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),tme=QC("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",jT),rme=QC("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),ame=QC("ERR_STREAM_WRITE_AFTER_END","write after end"),ime=qT.prototype.destroy||kJ;function Ni(n,t){qT.call(this),this._sanitizeOptions(n),this._options=n,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],t&&this.on("response",t);var o=this;this._onNativeResponse=function(i){try{o._processResponse(i)}catch(e){o.emit("error",e instanceof jT?e:new jT({cause:e}))}},this._headerFilter=new RegExp("^(?:"+eme.concat(n.sensitiveHeaders).map(Ime).join("|")+")$","i"),this._performRequest()}Ni.prototype=Object.create(qT.prototype);Ni.prototype.abort=function(){$T(this._currentRequest),this._currentRequest.abort(),this.emit("abort")};Ni.prototype.destroy=function(n){return $T(this._currentRequest,n),ime.call(this,n),this};Ni.prototype.write=function(n,t,o){if(this._ending)throw new ame;if(!UI(n)&&!gme(n))throw new TypeError("data should be a string, Buffer or Uint8Array");if(HI(t)&&(o=t,t=null),n.length===0){o&&o();return}this._requestBodyLength+n.length<=this._options.maxBodyLength?(this._requestBodyLength+=n.length,this._requestBodyBuffers.push({data:n,encoding:t}),this._currentRequest.write(n,t,o)):(this.emit("error",new rme),this.abort())};Ni.prototype.end=function(n,t,o){if(HI(n)?(o=n,n=t=null):HI(t)&&(o=t,t=null),!n)this._ended=this._ending=!0,this._currentRequest.end(null,null,o);else{var i=this,e=this._currentRequest;this.write(n,t,function(){i._ended=!0,e.end(null,null,o)}),this._ending=!0}};Ni.prototype.setHeader=function(n,t){this._options.headers[n]=t,this._currentRequest.setHeader(n,t)};Ni.prototype.removeHeader=function(n){delete this._options.headers[n],this._currentRequest.removeHeader(n)};Ni.prototype.setTimeout=function(n,t){var o=this;function i(A){A.setTimeout(n),A.removeListener("timeout",A.destroy),A.addListener("timeout",A.destroy)}function e(A){o._timeout&&clearTimeout(o._timeout),o._timeout=setTimeout(function(){o.emit("timeout"),a()},n),i(A)}function a(){o._timeout&&(clearTimeout(o._timeout),o._timeout=null),o.removeListener("abort",a),o.removeListener("error",a),o.removeListener("response",a),o.removeListener("close",a),t&&o.removeListener("timeout",t),o.socket||o._currentRequest.removeListener("socket",e)}return t&&this.on("timeout",t),this.socket?e(this.socket):this._currentRequest.once("socket",e),this.on("socket",i),this.on("abort",a),this.on("error",a),this.on("response",a),this.on("close",a),this};["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(n){Ni.prototype[n]=function(t,o){return this._currentRequest[n](t,o)}});["aborted","connection","socket"].forEach(function(n){Object.defineProperty(Ni.prototype,n,{get:function(){return this._currentRequest[n]}})});Ni.prototype._sanitizeOptions=function(n){if(n.headers||(n.headers={}),sme(n.sensitiveHeaders)||(n.sensitiveHeaders=[]),n.host&&(n.hostname||(n.hostname=n.host),delete n.host),!n.pathname&&n.path){var t=n.path.indexOf("?");t<0?n.pathname=n.path:(n.pathname=n.path.substring(0,t),n.search=n.path.substring(t))}};Ni.prototype._performRequest=function(){var n=this._options.protocol,t=this._options.nativeProtocols[n];if(!t)throw new TypeError("Unsupported protocol "+n);if(this._options.agents){var o=n.slice(0,-1);this._options.agent=this._options.agents[o]}var i=this._currentRequest=t.request(this._options,this._onNativeResponse);i._redirectable=this;for(var e of WT)i.on(e,ZT[e]);if(this._currentUrl=/^\//.test(this._options.path)?fC.format(this._options):this._options.path,this._isRedirect){var a=0,A=this,r=this._requestBodyBuffers;(function s(g){if(i===A._currentRequest)if(g)A.emit("error",g);else if(a=400){n.responseUrl=this._currentUrl,n.redirects=this._redirects,this.emit("response",n),this._requestBodyBuffers=[];return}if($T(this._currentRequest),n.destroy(),++this._redirectCount>this._options.maxRedirects)throw new tme;var i,e=this._options.beforeRedirect;e&&(i=Object.assign({Host:n.req.getHeader("host")},this._options.headers));var a=this._options.method;((t===301||t===302)&&this._options.method==="POST"||t===303&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],xT(/^content-/i,this._options.headers));var A=xT(/^host$/i,this._options.headers),r=XT(this._currentUrl),s=A||r.host,g=/^\w+:/.test(o)?this._currentUrl:fC.format(Object.assign(r,{host:s})),c=ome(o,g);if(NJ("redirecting to",c.href),this._isRedirect=!0,JT(c,this._options),(c.protocol!==r.protocol&&c.protocol!=="https:"||c.host!==s&&!nme(c.host,s))&&xT(this._headerFilter,this._options.headers),HI(e)){var I={headers:n.headers,statusCode:t},d={url:g,method:a,headers:i};e(this._options,I,d),this._sanitizeOptions(this._options)}this._performRequest()};function RJ(n){var t={maxRedirects:21,maxBodyLength:10485760},o={};return Object.keys(n).forEach(function(i){var e=i+":",a=o[e]=n[i],A=t[i]=Object.create(a);function r(g,c,I){return cme(g)?g=JT(g):UI(g)?g=JT(XT(g)):(I=c,c=vJ(g),g={protocol:e}),HI(c)&&(I=c,c=null),c=Object.assign({maxRedirects:t.maxRedirects,maxBodyLength:t.maxBodyLength},g,c),c.nativeProtocols=o,!UI(c.host)&&!UI(c.hostname)&&(c.hostname="::1"),zT.equal(c.protocol,e,"protocol mismatch"),NJ("options",c),new Ni(c,I)}function s(g,c,I){var d=A.request(g,c,I);return d.end(),d}Object.defineProperties(A,{request:{value:r,configurable:!0,enumerable:!0,writable:!0},get:{value:s,configurable:!0,enumerable:!0,writable:!0}})}),t}function kJ(){}function XT(n){var t;if(VT)t=new BC(n);else if(t=vJ(fC.parse(n)),!UI(t.protocol))throw new YT({input:n});return t}function ome(n,t){return VT?new BC(n,t):XT(fC.resolve(t,n))}function vJ(n){if(/^\[/.test(n.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(n.hostname))throw new YT({input:n.href||n});if(/^\[/.test(n.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(n.host))throw new YT({input:n.href||n});return n}function JT(n,t){var o=t||{};for(var i of Ame)o[i]=n[i];return o.hostname.startsWith("[")&&(o.hostname=o.hostname.slice(1,-1)),o.port!==""&&(o.port=Number(o.port)),o.path=o.search?o.pathname+o.search:o.pathname,o}function xT(n,t){var o;for(var i in t)n.test(i)&&(o=t[i],delete t[i]);return o===null||typeof o>"u"?void 0:String(o).trim()}function QC(n,t,o){function i(e){HI(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,e||{}),this.code=n,this.message=this.cause?t+": "+this.cause.message:t}return i.prototype=new(o||Error),Object.defineProperties(i.prototype,{constructor:{value:i,enumerable:!1},name:{value:"Error ["+n+"]",enumerable:!1}}),i}function $T(n,t){for(var o of WT)n.removeListener(o,ZT[o]);n.on("error",kJ),n.destroy(t)}function nme(n,t){zT(UI(n)&&UI(t));var o=n.length-t.length-1;return o>0&&n[o]==="."&&n.endsWith(t)}function sme(n){return n instanceof Array}function UI(n){return typeof n=="string"||n instanceof String}function HI(n){return typeof n=="function"}function gme(n){return typeof n=="object"&&"length"in n}function cme(n){return BC&&n instanceof BC}function Ime(n){return n.replace(/[\]\\/()*+?.$]/g,"\\$&")}e0.exports=RJ({http:Xye,https:$ye});e0.exports.wrap=RJ});var Lq=$((qsA,Fq)=>{Fq.exports=$e("util").inspect});var TC=$((zsA,i4)=>{var T0=typeof Map=="function"&&Map.prototype,y0=Object.getOwnPropertyDescriptor&&T0?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,My=T0&&y0&&typeof y0.get=="function"?y0.get:null,Uq=T0&&Map.prototype.forEach,N0=typeof Set=="function"&&Set.prototype,m0=Object.getOwnPropertyDescriptor&&N0?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,_y=N0&&m0&&typeof m0.get=="function"?m0.get:null,Hq=N0&&Set.prototype.forEach,TSe=typeof WeakMap=="function"&&WeakMap.prototype,bC=TSe?WeakMap.prototype.has:null,NSe=typeof WeakSet=="function"&&WeakSet.prototype,MC=NSe?WeakSet.prototype.has:null,RSe=typeof WeakRef=="function"&&WeakRef.prototype,Kq=RSe?WeakRef.prototype.deref:null,kSe=Boolean.prototype.valueOf,vSe=Object.prototype.toString,PSe=Function.prototype.toString,GSe=String.prototype.match,R0=String.prototype.slice,lc=String.prototype.replace,FSe=String.prototype.toUpperCase,xq=String.prototype.toLowerCase,Xq=RegExp.prototype.test,Yq=Array.prototype.concat,rs=Array.prototype.join,LSe=Array.prototype.slice,jq=Math.floor,D0=typeof BigInt=="function"?BigInt.prototype.valueOf:null,S0=Object.getOwnPropertySymbols,O0=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,id=typeof Symbol=="function"&&typeof Symbol.iterator=="object",_C=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===id||!0)?Symbol.toStringTag:null,$q=Object.prototype.propertyIsEnumerable,Jq=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(n){return n.__proto__}:null);function qq(n,t){if(n===1/0||n===-1/0||n!==n||n&&n>-1e3&&n<1e3||Xq.call(/e/,t))return t;var o=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof n=="number"){var i=n<0?-jq(-n):jq(n);if(i!==n){var e=String(i),a=R0.call(t,e.length+1);return lc.call(e,o,"$&_")+"."+lc.call(lc.call(a,/([0-9]{3})/g,"$&_"),/_$/,"")}}return lc.call(t,o,"$&_")}var b0=Lq(),zq=b0.custom,Vq=t4(zq)?zq:null,e4={__proto__:null,double:'"',single:"'"},USe={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};i4.exports=function n(t,o,i,e){var a=o||{};if(gg(a,"quoteStyle")&&!gg(e4,a.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(gg(a,"maxStringLength")&&(typeof a.maxStringLength=="number"?a.maxStringLength<0&&a.maxStringLength!==1/0:a.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var A=gg(a,"customInspect")?a.customInspect:!0;if(typeof A!="boolean"&&A!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(gg(a,"indent")&&a.indent!==null&&a.indent!==" "&&!(parseInt(a.indent,10)===a.indent&&a.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(gg(a,"numericSeparator")&&typeof a.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var r=a.numericSeparator;if(typeof t>"u")return"undefined";if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="string")return a4(t,a);if(typeof t=="number"){if(t===0)return 1/0/t>0?"0":"-0";var s=String(t);return r?qq(t,s):s}if(typeof t=="bigint"){var g=String(t)+"n";return r?qq(t,g):g}var c=typeof a.depth>"u"?5:a.depth;if(typeof i>"u"&&(i=0),i>=c&&c>0&&typeof t=="object")return M0(t)?"[Array]":"[Object]";var I=awe(a,i);if(typeof e>"u")e=[];else if(r4(e,t)>=0)return"[Circular]";function d(H,N,k){if(N&&(e=LSe.call(e),e.push(N)),k){var V={depth:a.depth};return gg(a,"quoteStyle")&&(V.quoteStyle=a.quoteStyle),n(H,V,i+1,e)}return n(H,a,i+1,e)}if(typeof t=="function"&&!Wq(t)){var B=VSe(t),f=by(t,d);return"[Function"+(B?": "+B:" (anonymous)")+"]"+(f.length>0?" { "+rs.call(f,", ")+" }":"")}if(t4(t)){var Q=id?lc.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):O0.call(t);return typeof t=="object"&&!id?OC(Q):Q}if(Awe(t)){for(var y="<"+xq.call(String(t.nodeName)),m=t.attributes||[],_=0;_",y}if(M0(t)){if(t.length===0)return"[]";var T=by(t,d);return I&&!rwe(T)?"["+_0(T,I)+"]":"[ "+rs.call(T,", ")+" ]"}if(xSe(t)){var R=by(t,d);return!("cause"in Error.prototype)&&"cause"in t&&!$q.call(t,"cause")?"{ ["+String(t)+"] "+rs.call(Yq.call("[cause]: "+d(t.cause),R),", ")+" }":R.length===0?"["+String(t)+"]":"{ ["+String(t)+"] "+rs.call(R,", ")+" }"}if(typeof t=="object"&&A){if(Vq&&typeof t[Vq]=="function"&&b0)return b0(t,{depth:c-i});if(A!=="symbol"&&typeof t.inspect=="function")return t.inspect()}if(WSe(t)){var L=[];return Uq&&Uq.call(t,function(H,N){L.push(d(N,t,!0)+" => "+d(H,t))}),Zq("Map",My.call(t),L,I)}if($Se(t)){var U=[];return Hq&&Hq.call(t,function(H){U.push(d(H,t))}),Zq("Set",_y.call(t),U,I)}if(ZSe(t))return w0("WeakMap");if(ewe(t))return w0("WeakSet");if(XSe(t))return w0("WeakRef");if(jSe(t))return OC(d(Number(t)));if(qSe(t))return OC(d(D0.call(t)));if(JSe(t))return OC(kSe.call(t));if(YSe(t))return OC(d(String(t)));if(typeof window<"u"&&t===window)return"{ [object Window] }";if(typeof globalThis<"u"&&t===globalThis||typeof global<"u"&&t===global)return"{ [object globalThis] }";if(!KSe(t)&&!Wq(t)){var F=by(t,d),q=Jq?Jq(t)===Object.prototype:t instanceof Object||t.constructor===Object,z=t instanceof Object?"":"null prototype",j=!q&&_C&&Object(t)===t&&_C in t?R0.call(pc(t),8,-1):z?"Object":"",P=q||typeof t.constructor!="function"?"":t.constructor.name?t.constructor.name+" ":"",J=P+(j||z?"["+rs.call(Yq.call([],j||[],z||[]),": ")+"] ":"");return F.length===0?J+"{}":I?J+"{"+_0(F,I)+"}":J+"{ "+rs.call(F,", ")+" }"}return String(t)};function A4(n,t,o){var i=o.quoteStyle||t,e=e4[i];return e+n+e}function HSe(n){return lc.call(String(n),/"/g,""")}function YI(n){return!_C||!(typeof n=="object"&&(_C in n||typeof n[_C]<"u"))}function M0(n){return pc(n)==="[object Array]"&&YI(n)}function KSe(n){return pc(n)==="[object Date]"&&YI(n)}function Wq(n){return pc(n)==="[object RegExp]"&&YI(n)}function xSe(n){return pc(n)==="[object Error]"&&YI(n)}function YSe(n){return pc(n)==="[object String]"&&YI(n)}function jSe(n){return pc(n)==="[object Number]"&&YI(n)}function JSe(n){return pc(n)==="[object Boolean]"&&YI(n)}function t4(n){if(id)return n&&typeof n=="object"&&n instanceof Symbol;if(typeof n=="symbol")return!0;if(!n||typeof n!="object"||!O0)return!1;try{return O0.call(n),!0}catch{}return!1}function qSe(n){if(!n||typeof n!="object"||!D0)return!1;try{return D0.call(n),!0}catch{}return!1}var zSe=Object.prototype.hasOwnProperty||function(n){return n in this};function gg(n,t){return zSe.call(n,t)}function pc(n){return vSe.call(n)}function VSe(n){if(n.name)return n.name;var t=GSe.call(PSe.call(n),/^function\s*([\w$]+)/);return t?t[1]:null}function r4(n,t){if(n.indexOf)return n.indexOf(t);for(var o=0,i=n.length;ot.maxStringLength){var o=n.length-t.maxStringLength,i="... "+o+" more character"+(o>1?"s":"");return a4(R0.call(n,0,t.maxStringLength),t)+i}var e=USe[t.quoteStyle||"single"];e.lastIndex=0;var a=lc.call(lc.call(n,e,"\\$1"),/[\x00-\x1f]/g,twe);return A4(a,"single",t)}function twe(n){var t=n.charCodeAt(0),o={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return o?"\\"+o:"\\x"+(t<16?"0":"")+FSe.call(t.toString(16))}function OC(n){return"Object("+n+")"}function w0(n){return n+" { ? }"}function Zq(n,t,o,i){var e=i?_0(o,i):rs.call(o,", ");return n+" ("+t+") {"+e+"}"}function rwe(n){for(var t=0;t=0)return!1;return!0}function awe(n,t){var o;if(n.indent===" ")o=" ";else if(typeof n.indent=="number"&&n.indent>0)o=rs.call(Array(n.indent+1)," ");else return null;return{base:o,prev:rs.call(Array(t+1),o)}}function _0(n,t){if(n.length===0)return"";var o=` `+t.prev+t.base;return o+rs.call(n,","+o)+` -`+t.prev}function by(n,t){var o=M0(n),i=[];if(o){i.length=n.length;for(var e=0;e{"use strict";var iwe=TC(),owe=sc(),Ty=function(n,t,o){for(var i=n,e;(e=i.next)!=null;i=e)if(e.key===t)return i.next=e.next,o||(e.next=n.next,n.next=e),e},nwe=function(n,t){if(n){var o=Ty(n,t);return o&&o.value}},swe=function(n,t,o){var i=Ty(n,t);i?i.value=o:n.next={key:t,next:n.next,value:o}},gwe=function(n,t){return n?!!Ty(n,t):!1},cwe=function(n,t){if(n)return Ty(n,t,!0)};o4.exports=function(){var t,o={assert:function(i){if(!o.has(i))throw new owe("Side channel does not contain "+iwe(i))},delete:function(i){var e=cwe(t,i);return e&&t&&!t.next&&(t=void 0),!!e},get:function(i){return nwe(t,i)},has:function(i){return gwe(t,i)},set:function(i,e){t||(t={next:void 0}),swe(t,i,e)}};return o}});var k0=$((WsA,c4)=>{"use strict";var s4=sC(),g4=cT(),Iwe=g4([s4("%String.prototype.indexOf%")]);c4.exports=function(t,o){var i=s4(t,!!o);return typeof i=="function"&&Iwe(t,".prototype.")>-1?g4([i]):i}});var v0=$((ZsA,l4)=>{"use strict";var lwe=sC(),NC=k0(),pwe=TC(),dwe=sc(),I4=lwe("%Map%",!0),hwe=NC("Map.prototype.get",!0),Ewe=NC("Map.prototype.set",!0),Cwe=NC("Map.prototype.has",!0),uwe=NC("Map.prototype.delete",!0),Bwe=NC("Map.prototype.size",!0);l4.exports=!!I4&&function(){var t,o={assert:function(i){if(!o.has(i))throw new dwe("Side channel does not contain "+pwe(i))},delete:function(i){if(t){var e=uwe(t,i);return Bwe(t)===0&&(t=void 0),e}return!1},get:function(i){if(t)return hwe(t,i)},has:function(i){return t?Cwe(t,i):!1},set:function(i,e){t||(t=new I4),Ewe(t,i,e)}};return o}});var d4=$((XsA,p4)=>{"use strict";var fwe=sC(),Ry=k0(),Qwe=TC(),Ny=v0(),ywe=sc(),od=fwe("%WeakMap%",!0),mwe=Ry("WeakMap.prototype.get",!0),Swe=Ry("WeakMap.prototype.set",!0),wwe=Ry("WeakMap.prototype.has",!0),Dwe=Ry("WeakMap.prototype.delete",!0);p4.exports=od?function(){var t,o,i={assert:function(e){if(!i.has(e))throw new ywe("Side channel does not contain "+Qwe(e))},delete:function(e){if(od&&e&&(typeof e=="object"||typeof e=="function")){if(t)return Dwe(t,e)}else if(Ny&&o)return o.delete(e);return!1},get:function(e){return od&&e&&(typeof e=="object"||typeof e=="function")&&t?mwe(t,e):o&&o.get(e)},has:function(e){return od&&e&&(typeof e=="object"||typeof e=="function")&&t?wwe(t,e):!!o&&o.has(e)},set:function(e,a){od&&e&&(typeof e=="object"||typeof e=="function")?(t||(t=new od),Swe(t,e,a)):Ny&&(o||(o=Ny()),o.set(e,a))}};return i}:Ny});var P0=$(($sA,h4)=>{"use strict";var Owe=sc(),bwe=TC(),Mwe=n4(),_we=v0(),Twe=d4(),Nwe=Twe||_we||Mwe;h4.exports=function(){var t,o={assert:function(i){if(!o.has(i)){var e=i&&Object(i)===i?"the given object key":bwe(i);throw new Owe("Side channel does not contain "+e)}},delete:function(i){return!!t&&t.delete(i)},get:function(i){return t&&t.get(i)},has:function(i){return!!t&&t.has(i)},set:function(i,e){t||(t=Nwe()),t.set(i,e)}};return o}});var ky=$((egA,E4)=>{"use strict";var Rwe=String.prototype.replace,kwe=/%20/g,G0={RFC1738:"RFC1738",RFC3986:"RFC3986"};E4.exports={default:G0.RFC3986,formatters:{RFC1738:function(n){return Rwe.call(n,kwe,"+")},RFC3986:function(n){return String(n)}},RFC1738:G0.RFC1738,RFC3986:G0.RFC3986}});var H0=$((AgA,B4)=>{"use strict";var vwe=ky(),u4=P0(),C4=iT(),F0=Object.prototype.hasOwnProperty,dc=Array.isArray,Py=u4(),jI=function(t,o){return Py.set(t,o),t},JI=function(t){return Py.has(t)},RC=function(t){return Py.get(t)},L0=function(t,o){Py.set(t,o)},as=(function(){for(var n=[],t=0;t<256;++t)n[n.length]="%"+((t<16?"0":"")+t.toString(16)).toUpperCase();return n})(),Pwe=function(t){for(;t.length>1;){var o=t.pop(),i=o.obj[o.prop];if(dc(i)){for(var e=[],a=0;a=i.arrayLimit){if(i.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+i.arrayLimit+" element"+(i.arrayLimit===1?"":"s")+" allowed in an array.");return jI(nd(t.concat(o),i),e)}t[e]=o}else if(t&&typeof t=="object")if(JI(t)){var a=RC(t)+1;t[a]=o,L0(t,a)}else{if(i&&i.strictMerge)return[t,o];(i&&(i.plainObjects||i.allowPrototypes)||!F0.call(Object.prototype,o))&&(t[o]=!0)}else return[t,o];return t}if(!t||typeof t!="object"){if(JI(o)){for(var A=Object.keys(o),r=i&&i.plainObjects?{__proto__:null,0:t}:{0:t},s=0;si.arrayLimit){if(i.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+i.arrayLimit+" element"+(i.arrayLimit===1?"":"s")+" allowed in an array.");return jI(nd(c,i),c.length-1)}return c}var I=t;if(dc(t)&&!dc(o)&&(I=nd(t,i)),dc(t)&&dc(o)){if(o.forEach(function(d,B){if(F0.call(t,B)){var f=t[B];f&&typeof f=="object"&&d&&typeof d=="object"?t[B]=n(f,d,i):t[t.length]=d}else t[B]=d}),i&&typeof i.arrayLimit=="number"&&t.length>i.arrayLimit){if(i.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+i.arrayLimit+" element"+(i.arrayLimit===1?"":"s")+" allowed in an array.");return jI(nd(t,i),t.length-1)}return t}return Object.keys(o).reduce(function(d,B){var f=o[B];if(F0.call(d,B)?U0(d,B,n(d[B],f,i)):U0(d,B,f),JI(o)&&!JI(d)&&jI(d,RC(o)),JI(d)){var Q=parseInt(B,10);String(Q)===B&&Q>=0&&Q>RC(d)&&L0(d,Q)}return d},I)},Fwe=function(t,o){return Object.keys(o).reduce(function(i,e){return U0(i,e,o[e]),i},t)},Lwe=function(n,t,o){var i=n.replace(/\+/g," ");if(o==="iso-8859-1")return i.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(i)}catch{return i}},vy=1024,Uwe=function(t,o,i,e,a){if(t.length===0)return t;var A=t;if(typeof t=="symbol"?A=Symbol.prototype.toString.call(t):typeof t!="string"&&(A=String(t)),i==="iso-8859-1")return escape(A).replace(/%u[0-9a-f]{4}/gi,function(f){return"%26%23"+parseInt(f.slice(2),16)+"%3B"});for(var r="",s=0;s=vy?A.slice(s,s+vy):A;if(s+vy=55296&&c<=56319&&(g=g.slice(0,-1),s-=1)}for(var I=[],d=0;d=48&&B<=57||B>=65&&B<=90||B>=97&&B<=122||a===vwe.RFC1738&&(B===40||B===41)){I[I.length]=g.charAt(d);continue}if(B<128){I[I.length]=as[B];continue}if(B<2048){I[I.length]=as[192|B>>6]+as[128|B&63];continue}if(B<55296||B>=57344){I[I.length]=as[224|B>>12]+as[128|B>>6&63]+as[128|B&63];continue}d+=1,B=65536+((B&1023)<<10|g.charCodeAt(d)&1023),I[I.length]=as[240|B>>18]+as[128|B>>12&63]+as[128|B>>6&63]+as[128|B&63]}r+=I.join("")}return r},Hwe=function(t){for(var o=[{obj:{o:t},prop:"o"}],i=u4(),e=0;ei){if(a)throw new RangeError("Array limit exceeded. Only "+i+" element"+(i===1?"":"s")+" allowed in an array.");return jI(nd(g,{plainObjects:e}),g.length-1)}return g},jwe=function(t,o){if(dc(t)){for(var i=[],e=0;e{"use strict";var Q4=P0(),Gy=H0(),kC=ky(),Jwe=Object.prototype.hasOwnProperty,y4={brackets:function(t){return t+"[]"},comma:"comma",indices:function(t,o){return t+"["+o+"]"},repeat:function(t){return t}},is=Array.isArray,qwe=Array.prototype.push,m4=function(n,t){qwe.apply(n,is(t)?t:[t])},zwe=Date.prototype.toISOString,f4=kC.default,_r={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",depth:1/0,encode:!0,encodeDotInKeys:!1,encoder:Gy.encode,encodeValuesOnly:!1,filter:void 0,format:f4,formatter:kC.formatters[f4],indices:!1,serializeDate:function(t){return zwe.call(t)},skipNulls:!1,strictNullHandling:!1},Vwe=function(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"},K0={},Wwe=function n(t,o,i,e,a,A,r,s,g,c,I,d,B,f,Q,y,m,_,T,R){var F=t;if(R>T)throw new RangeError("Input depth exceeded depth option of "+T);for(var K=_,L=0,q=!1;(K=K.get(K0))!==void 0&&!q;){var z=K.get(t);if(L+=1,typeof z<"u"){if(z===L)throw new RangeError("Cyclic object value");q=!0}typeof K.get(K0)>"u"&&(L=0)}if(F=typeof c=="function"?c(o,F):F,F instanceof Date?F=B(F):i==="comma"&&is(F)&&(F=Gy.maybeMap(F,function(Ee){return Ee instanceof Date?B(Ee):Ee})),F===null){if(A)return Q(g&&!y?g(o,_r.encoder,m,"key",f):o);F=""}if(Vwe(F)||Gy.isBuffer(F)){if(g){var j=y?o:g(o,_r.encoder,m,"key",f);return[Q(j)+"="+Q(g(F,_r.encoder,m,"value",f))]}return[Q(o)+"="+Q(String(F))]}var P=[];if(typeof F>"u")return P;var J;if(i==="comma"&&is(F))y&&g&&(F=Gy.maybeMap(F,function(Ee){return Ee==null?Ee:g(Ee)})),J=[{value:F.length>0?F.join(",")||null:void 0}];else if(is(c))J=c;else{var U=Object.keys(F);J=I?U.sort(I):U}var N=s?String(o).replace(/\./g,"%2E"):String(o),k=e&&is(F)&&F.length===1?N+"[]":N;if(a&&is(F)&&F.length===0&&Object.keys(F).length===0)return k+"[]";for(var V=0;V"u"?t.encodeDotInKeys===!0?!0:_r.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:_r.addQueryPrefix,allowDots:r,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:_r.allowEmptyArrays,arrayFormat:A,charset:o,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:_r.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?_r.delimiter:t.delimiter,depth:typeof t.depth=="number"?t.depth:_r.depth,encode:typeof t.encode=="boolean"?t.encode:_r.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:_r.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:_r.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:_r.encodeValuesOnly,filter:a,format:i,formatter:e,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:_r.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:_r.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:_r.strictNullHandling}};S4.exports=function(n,t){var o=n,i=Zwe(t),e,a;typeof i.filter=="function"?(a=i.filter,o=a("",o)):is(i.filter)&&(a=i.filter,e=a);var A=[];if(typeof o!="object"||o===null)return"";var r=y4[i.arrayFormat],s=r==="comma"&&i.commaRoundTrip;e||(e=Object.keys(o)),i.sort&&e.sort(i.sort);for(var g=Q4(),c=0;c"u"||I===null)){var d=o[I];if(!(i.skipNulls&&d===null)){var B=i.encodeDotInKeys?String(I).replace(/\./g,"%2E"):String(I);m4(A,Wwe(d,B,r,s,i.allowEmptyArrays,i.strictNullHandling,i.skipNulls,i.encodeDotInKeys,i.encode?i.encoder:null,i.filter,i.sort,i.allowDots,i.serializeDate,i.format,i.formatter,i.encodeValuesOnly,i.charset,g,i.depth,0))}}}var f=A.join(i.delimiter),Q=i.addQueryPrefix===!0?"?":"";return i.charsetSentinel&&(i.charset==="iso-8859-1"?Q+="utf8=%26%2310003%3B"+i.delimiter:Q+="utf8=%E2%9C%93"+i.delimiter),f.length>0?Q+f:""}});var b4=$((rgA,O4)=>{"use strict";var os=H0(),Fy=Object.prototype.hasOwnProperty,x0=Array.isArray,or={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:os.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictMerge:!0,strictNullHandling:!1,throwOnLimitExceeded:!1},Xwe=function(n){return n.replace(/&#(\d+);/g,function(t,o){return String.fromCharCode(parseInt(o,10))})},D4=function(n,t,o){if(n&&typeof n=="string"&&t.comma&&n.indexOf(",")>-1){if(t.throwOnLimitExceeded)for(var i=0,e=n.indexOf(",");e>-1;){if(i+=1,i>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(t.arrayLimit===1?"":"s")+" allowed in an array.");e=n.indexOf(",",e+1)}return n.split(",")}if(t.throwOnLimitExceeded&&o>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(t.arrayLimit===1?"":"s")+" allowed in an array.");return n},$we="utf8=%26%2310003%3B",eDe="utf8=%E2%9C%93",ADe=function(t,o){var i={__proto__:null},e=o.ignoreQueryPrefix?t.replace(/^\?/,""):t;e=e.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var a=o.parameterLimit===1/0?void 0:o.parameterLimit,A=e.split(o.delimiter,o.throwOnLimitExceeded&&typeof a<"u"?a+1:a);if(o.throwOnLimitExceeded&&typeof a<"u"&&A.length>a)throw new RangeError("Parameter limit exceeded. Only "+a+" parameter"+(a===1?"":"s")+" allowed.");var r=-1,s,g=o.charset;if(o.charsetSentinel)for(s=0;s-1&&(f=x0(f)?[f]:f),o.comma&&x0(f)&&f.length>o.arrayLimit&&(f=os.combine([],f,o.arrayLimit,o.plainObjects,o.throwOnLimitExceeded)),B!==null){var Q=Fy.call(i,B);Q&&(o.duplicates==="combine"||c.indexOf("[]=")>-1)?i[B]=os.combine(i[B],f,o.arrayLimit,o.plainObjects,o.throwOnLimitExceeded):(!Q||o.duplicates==="last")&&(i[B]=f)}}return i},tDe=function(n,t,o,i){var e=0;if(n.length>0&&n[n.length-1]==="[]"){var a=n.slice(0,-1).join("");e=Array.isArray(t)&&t[a]?t[a].length:0}for(var A=i?t:D4(t,o,e),r=n.length-1;r>=0;--r){var s,g=n[r];if(g==="[]"&&o.parseArrays)os.isOverflow(A)?s=A:s=o.allowEmptyArrays&&(A===""||o.strictNullHandling&&A===null)?[]:os.combine([],A,o.arrayLimit,o.plainObjects,o.throwOnLimitExceeded);else{s=o.plainObjects?{__proto__:null}:{};var c=g.charAt(0)==="["&&g.charAt(g.length-1)==="]"?g.slice(1,-1):g,I=o.decodeDotInKeys?c.replace(/%2E/g,"."):c,d=parseInt(I,10),B=!isNaN(d)&&g!==I&&String(d)===I&&d>=0&&o.parseArrays;if(!o.parseArrays&&I==="")s={0:A};else if(B&&d=0?i.slice(0,a):i;if(A){if(!o.plainObjects&&Fy.call(Object.prototype,A)&&!o.allowPrototypes)return;e[e.length]=A}for(var r=i.length,s=a,g=0;s>=0&&g=0){if(o.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+o.depth+" and strictDepth is true");e[e.length]="["+i.slice(s)+"]"}return e},aDe=function(t,o,i,e){if(t){var a=rDe(t,i);if(a)return tDe(a,o,i,e)}},iDe=function(t){if(!t)return or;if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.decodeDotInKeys<"u"&&typeof t.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(t.decoder!==null&&typeof t.decoder<"u"&&typeof t.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(typeof t.throwOnLimitExceeded<"u"&&typeof t.throwOnLimitExceeded!="boolean")throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var o=typeof t.charset>"u"?or.charset:t.charset,i=typeof t.duplicates>"u"?or.duplicates:t.duplicates;if(i!=="combine"&&i!=="first"&&i!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var e=typeof t.allowDots>"u"?t.decodeDotInKeys===!0?!0:or.allowDots:!!t.allowDots;return{allowDots:e,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:or.allowEmptyArrays,allowPrototypes:typeof t.allowPrototypes=="boolean"?t.allowPrototypes:or.allowPrototypes,allowSparse:typeof t.allowSparse=="boolean"?t.allowSparse:or.allowSparse,arrayLimit:typeof t.arrayLimit=="number"?t.arrayLimit:or.arrayLimit,charset:o,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:or.charsetSentinel,comma:typeof t.comma=="boolean"?t.comma:or.comma,decodeDotInKeys:typeof t.decodeDotInKeys=="boolean"?t.decodeDotInKeys:or.decodeDotInKeys,decoder:typeof t.decoder=="function"?t.decoder:or.decoder,delimiter:typeof t.delimiter=="string"||os.isRegExp(t.delimiter)?t.delimiter:or.delimiter,depth:typeof t.depth=="number"||t.depth===!1?+t.depth:or.depth,duplicates:i,ignoreQueryPrefix:t.ignoreQueryPrefix===!0,interpretNumericEntities:typeof t.interpretNumericEntities=="boolean"?t.interpretNumericEntities:or.interpretNumericEntities,parameterLimit:typeof t.parameterLimit=="number"?t.parameterLimit:or.parameterLimit,parseArrays:t.parseArrays!==!1,plainObjects:typeof t.plainObjects=="boolean"?t.plainObjects:or.plainObjects,strictDepth:typeof t.strictDepth=="boolean"?!!t.strictDepth:or.strictDepth,strictMerge:typeof t.strictMerge=="boolean"?!!t.strictMerge:or.strictMerge,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:or.strictNullHandling,throwOnLimitExceeded:typeof t.throwOnLimitExceeded=="boolean"?t.throwOnLimitExceeded:!1}};O4.exports=function(n,t){var o=iDe(t);if(n===""||n===null||typeof n>"u")return o.plainObjects?{__proto__:null}:{};for(var i=typeof n=="string"?ADe(n,o):n,e=o.plainObjects?{__proto__:null}:{},a=Object.keys(i),A=0;A{"use strict";var oDe=w4(),nDe=b4(),sDe=ky();M4.exports={formats:sDe,parse:nDe,stringify:oDe}});var N4=$((igA,T4)=>{function gDe(n){return n}T4.exports=gDe});var h8=$((vC,gd)=>{var cDe=200,IDe="Expected a function",AN="__lodash_hash_undefined__",jy=1,cd=2,K4=1/0,x4=9007199254740991,Ly="[object Arguments]",J0="[object Array]",Y4="[object Boolean]",j4="[object Date]",J4="[object Error]",q4="[object Function]",lDe="[object GeneratorFunction]",Uy="[object Map]",z4="[object Number]",sd="[object Object]",R4="[object Promise]",V4="[object RegExp]",Hy="[object Set]",W4="[object String]",Z4="[object Symbol]",q0="[object WeakMap]",X4="[object ArrayBuffer]",Ky="[object DataView]",pDe="[object Float32Array]",dDe="[object Float64Array]",hDe="[object Int8Array]",EDe="[object Int16Array]",CDe="[object Int32Array]",uDe="[object Uint8Array]",BDe="[object Uint8ClampedArray]",fDe="[object Uint16Array]",QDe="[object Uint32Array]",yDe=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,mDe=/^\w*$/,SDe=/^\./,wDe=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,DDe=/[\\^$.*+?()[\]{}|]/g,ODe=/\\(\\)?/g,bDe=/^\[object .+?Constructor\]$/,MDe=/^(?:0|[1-9]\d*)$/,xt={};xt[pDe]=xt[dDe]=xt[hDe]=xt[EDe]=xt[CDe]=xt[uDe]=xt[BDe]=xt[fDe]=xt[QDe]=!0;xt[Ly]=xt[J0]=xt[X4]=xt[Y4]=xt[Ky]=xt[j4]=xt[J4]=xt[q4]=xt[Uy]=xt[z4]=xt[sd]=xt[V4]=xt[Hy]=xt[W4]=xt[q0]=!1;var $4=typeof global=="object"&&global&&global.Object===Object&&global,_De=typeof self=="object"&&self&&self.Object===Object&&self,Cc=$4||_De||Function("return this")(),e8=typeof vC=="object"&&vC&&!vC.nodeType&&vC,k4=e8&&typeof gd=="object"&&gd&&!gd.nodeType&&gd,TDe=k4&&k4.exports===e8,v4=TDe&&$4.process,P4=(function(){try{return v4&&v4.binding("util")}catch{}})(),G4=P4&&P4.isTypedArray;function A8(n,t){for(var o=-1,i=t.length,e=n.length;++o-1}function oOe(n,t){var o=this.__data__,i=qy(o,n);return i<0?o.push([n,t]):o[i][1]=t,this}Ig.prototype.clear=tOe;Ig.prototype.delete=rOe;Ig.prototype.get=aOe;Ig.prototype.has=iOe;Ig.prototype.set=oOe;function lg(n){var t=-1,o=n?n.length:0;for(this.clear();++tr))return!1;var g=a.get(n);if(g&&a.get(t))return g==t;var c=-1,I=!0,d=e&jy?new Yy:void 0;for(a.set(n,t),a.set(t,n);++c-1&&n%1==0&&n-1&&n%1==0&&n<=x4}function FC(n){var t=typeof n;return!!n&&(t=="object"||t=="function")}function Zy(n){return!!n&&typeof n=="object"}function nN(n){return typeof n=="symbol"||Zy(n)&&Id.call(n)==Z4}var JOe=G4?vDe(G4):wOe;function qOe(n){return n==null?"":ROe(n)}function zOe(n,t,o){var i=n==null?void 0:a8(n,t);return i===void 0?o:i}function VOe(n,t){return n!=null&&UOe(n,t,QOe)}function eN(n){return iN(n)?r8(n):OOe(n)}function WOe(n){return iN(n)?r8(n,!0):bOe(n)}function ZOe(n,t){return n==null?{}:TOe(n,POe(n),DOe(t))}function XOe(n){return n}function $Oe(n){return Vy(n)?RDe(Wy(n)):NOe(n)}function d8(){return[]}gd.exports=ZOe});var Y8=$((LC,pd)=>{var ebe=200,w8="__lodash_hash_undefined__",Abe=800,tbe=16,D8=9007199254740991,O8="[object Arguments]",rbe="[object Array]",abe="[object AsyncFunction]",ibe="[object Boolean]",obe="[object Date]",nbe="[object Error]",b8="[object Function]",sbe="[object GeneratorFunction]",gbe="[object Map]",cbe="[object Number]",Ibe="[object Null]",M8="[object Object]",lbe="[object Proxy]",pbe="[object RegExp]",dbe="[object Set]",hbe="[object String]",Ebe="[object Undefined]",Cbe="[object WeakMap]",ube="[object ArrayBuffer]",Bbe="[object DataView]",fbe="[object Float32Array]",Qbe="[object Float64Array]",ybe="[object Int8Array]",mbe="[object Int16Array]",Sbe="[object Int32Array]",wbe="[object Uint8Array]",Dbe="[object Uint8ClampedArray]",Obe="[object Uint16Array]",bbe="[object Uint32Array]",Mbe=/[\\^$.*+?()[\]{}|]/g,_be=/^\[object .+?Constructor\]$/,Tbe=/^(?:0|[1-9]\d*)$/,Yt={};Yt[fbe]=Yt[Qbe]=Yt[ybe]=Yt[mbe]=Yt[Sbe]=Yt[wbe]=Yt[Dbe]=Yt[Obe]=Yt[bbe]=!0;Yt[O8]=Yt[rbe]=Yt[ube]=Yt[ibe]=Yt[Bbe]=Yt[obe]=Yt[nbe]=Yt[b8]=Yt[gbe]=Yt[cbe]=Yt[M8]=Yt[pbe]=Yt[dbe]=Yt[hbe]=Yt[Cbe]=!1;var _8=typeof global=="object"&&global&&global.Object===Object&&global,Nbe=typeof self=="object"&&self&&self.Object===Object&&self,KC=_8||Nbe||Function("return this")(),T8=typeof LC=="object"&&LC&&!LC.nodeType&&LC,UC=T8&&typeof pd=="object"&&pd&&!pd.nodeType&&pd,N8=UC&&UC.exports===T8,sN=N8&&_8.process,E8=(function(){try{var n=UC&&UC.require&&UC.require("util").types;return n||sN&&sN.binding&&sN.binding("util")}catch{}})(),C8=E8&&E8.isTypedArray;function Rbe(n,t,o){switch(o.length){case 0:return n.call(t);case 1:return n.call(t,o[0]);case 2:return n.call(t,o[0],o[1]);case 3:return n.call(t,o[0],o[1],o[2])}return n.apply(t,o)}function kbe(n,t){for(var o=-1,i=Array(n);++o-1}function tMe(n,t){var o=this.__data__,i=tm(o,n);return i<0?(++this.size,o.push([n,t])):o[i][1]=t,this}dg.prototype.clear=Xbe;dg.prototype.delete=$be;dg.prototype.get=eMe;dg.prototype.has=AMe;dg.prototype.set=tMe;function dd(n){var t=-1,o=n==null?0:n.length;for(this.clear();++t1?o[e-1]:void 0,A=e>2?o[2]:void 0;for(a=n.length>3&&typeof a=="function"?(e--,a):void 0,A&&TMe(o[0],o[1],A)&&(a=e<3?void 0:a,e=1),t=Object(t);++i-1&&n%1==0&&n0){if(++t>=Abe)return arguments[0]}else t=0;return n.apply(void 0,arguments)}}function LMe(n){if(n!=null){try{return Am.call(n)}catch{}try{return n+""}catch{}}return""}function im(n,t){return n===t||n!==n&&t!==t}var lN=S8((function(){return arguments})())?S8:function(n){return xC(n)&&pg.call(n,"callee")&&!Kbe.call(n,"callee")},pN=Array.isArray;function EN(n){return n!=null&&U8(n.length)&&!CN(n)}function UMe(n){return xC(n)&&EN(n)}var L8=Ybe||jMe;function CN(n){if(!ZI(n))return!1;var t=rm(n);return t==b8||t==sbe||t==abe||t==lbe}function U8(n){return typeof n=="number"&&n>-1&&n%1==0&&n<=D8}function ZI(n){var t=typeof n;return n!=null&&(t=="object"||t=="function")}function xC(n){return n!=null&&typeof n=="object"}function HMe(n){if(!xC(n)||rm(n)!=M8)return!1;var t=k8(n);if(t===null)return!0;var o=pg.call(t,"constructor")&&t.constructor;return typeof o=="function"&&o instanceof o&&Am.call(o)==Ube}var H8=C8?vbe(C8):CMe;function KMe(n){return DMe(n,K8(n))}function K8(n){return EN(n)?pMe(n,!0):uMe(n)}var xMe=OMe(function(n,t,o){P8(n,t,o)});function YMe(n){return function(){return n}}function x8(n){return n}function jMe(){return!1}pd.exports=xMe});var hg=$((ogA,q8)=>{"use strict";var j8=["nodebuffer","arraybuffer","fragments"],J8=typeof Blob<"u";J8&&j8.push("blob");q8.exports={BINARY_TYPES:j8,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:J8,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var YC=$((ngA,om)=>{"use strict";var{EMPTY_BUFFER:JMe}=hg(),uN=Buffer[Symbol.species];function qMe(n,t){if(n.length===0)return JMe;if(n.length===1)return n[0];let o=Buffer.allocUnsafe(t),i=0;for(let e=0;e{"use strict";var W8=Symbol("kDone"),fN=Symbol("kRun"),QN=class{constructor(t){this[W8]=()=>{this.pending--,this[fN]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[fN]()}[fN](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[W8])}}};Z8.exports=QN});var ud=$((ggA,tz)=>{"use strict";var jC=$e("zlib"),$8=YC(),VMe=X8(),{kStatusCode:ez}=hg(),WMe=Buffer[Symbol.species],ZMe=Buffer.from([0,0,255,255]),sm=Symbol("permessage-deflate"),Eg=Symbol("total-length"),Ed=Symbol("callback"),uc=Symbol("buffers"),Cd=Symbol("error"),nm,yN=class{constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!nm){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;nm=new VMe(o)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[Ed];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let o=this._options,i=t.find(e=>!(o.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(o.serverMaxWindowBits===!1||typeof o.serverMaxWindowBits=="number"&&o.serverMaxWindowBits>e.server_max_window_bits)||typeof o.clientMaxWindowBits=="number"&&(typeof e.client_max_window_bits=="number"?o.clientMaxWindowBits>e.client_max_window_bits:!e.client_max_window_bits)));if(!i)throw new Error("None of the extension offers can be accepted");return o.serverNoContextTakeover&&(i.server_no_context_takeover=!0),o.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof o.serverMaxWindowBits=="number"&&(i.server_max_window_bits=o.serverMaxWindowBits),typeof o.clientMaxWindowBits=="number"?i.client_max_window_bits=o.clientMaxWindowBits:(i.client_max_window_bits===!0||o.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(t){let o=t[0];if(this._options.clientNoContextTakeover===!1&&o.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!o.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(o.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&o.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return o}normalizeParams(t){return t.forEach(o=>{Object.keys(o).forEach(i=>{let e=o[i];if(e.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(e=e[0],i==="client_max_window_bits"){if(e!==!0){let a=+e;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${e}`);e=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${e}`)}else if(i==="server_max_window_bits"){let a=+e;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${e}`);e=a}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(e!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${e}`)}else throw new Error(`Unknown parameter "${i}"`);o[i]=e})}),t}decompress(t,o,i){nm.add(e=>{this._decompress(t,o,(a,A)=>{e(),i(a,A)})})}compress(t,o,i){nm.add(e=>{this._compress(t,o,(a,A)=>{e(),i(a,A)})})}_decompress(t,o,i){let e=this._isServer?"client":"server";if(!this._inflate){let a=`${e}_max_window_bits`,A=typeof this.params[a]!="number"?jC.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=jC.createInflateRaw({...this._options.zlibInflateOptions,windowBits:A}),this._inflate[sm]=this,this._inflate[Eg]=0,this._inflate[uc]=[],this._inflate.on("error",$Me),this._inflate.on("data",Az)}this._inflate[Ed]=i,this._inflate.write(t),o&&this._inflate.write(ZMe),this._inflate.flush(()=>{let a=this._inflate[Cd];if(a){this._inflate.close(),this._inflate=null,i(a);return}let A=$8.concat(this._inflate[uc],this._inflate[Eg]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Eg]=0,this._inflate[uc]=[],o&&this.params[`${e}_no_context_takeover`]&&this._inflate.reset()),i(null,A)})}_compress(t,o,i){let e=this._isServer?"server":"client";if(!this._deflate){let a=`${e}_max_window_bits`,A=typeof this.params[a]!="number"?jC.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=jC.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:A}),this._deflate[Eg]=0,this._deflate[uc]=[],this._deflate.on("data",XMe)}this._deflate[Ed]=i,this._deflate.write(t),this._deflate.flush(jC.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=$8.concat(this._deflate[uc],this._deflate[Eg]);o&&(a=new WMe(a.buffer,a.byteOffset,a.length-4)),this._deflate[Ed]=null,this._deflate[Eg]=0,this._deflate[uc]=[],o&&this.params[`${e}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};tz.exports=yN;function XMe(n){this[uc].push(n),this[Eg]+=n.length}function Az(n){if(this[Eg]+=n.length,this[sm]._maxPayload<1||this[Eg]<=this[sm]._maxPayload){this[uc].push(n);return}this[Cd]=new RangeError("Max payload size exceeded"),this[Cd].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Cd][ez]=1009,this.removeListener("data",Az),this.reset()}function $Me(n){if(this[sm]._inflate=null,this[Cd]){this[Ed](this[Cd]);return}n[ez]=1007,this[Ed](n)}});var Bd=$((cgA,gm)=>{"use strict";var{isUtf8:rz}=$e("buffer"),{hasBlob:e_e}=hg(),A_e=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function t_e(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function mN(n){let t=n.length,o=0;for(;o=t||(n[o+1]&192)!==128||(n[o+2]&192)!==128||n[o]===224&&(n[o+1]&224)===128||n[o]===237&&(n[o+1]&224)===160)return!1;o+=3}else if((n[o]&248)===240){if(o+3>=t||(n[o+1]&192)!==128||(n[o+2]&192)!==128||(n[o+3]&192)!==128||n[o]===240&&(n[o+1]&240)===128||n[o]===244&&n[o+1]>143||n[o]>244)return!1;o+=4}else return!1;return!0}function r_e(n){return e_e&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}gm.exports={isBlob:r_e,isValidStatusCode:t_e,isValidUTF8:mN,tokenChars:A_e};if(rz)gm.exports.isValidUTF8=function(n){return n.length<24?mN(n):rz(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=$e("utf-8-validate");gm.exports.isValidUTF8=function(t){return t.length<32?mN(t):n(t)}}catch{}});var bN=$((IgA,cz)=>{"use strict";var{Writable:a_e}=$e("stream"),az=ud(),{BINARY_TYPES:i_e,EMPTY_BUFFER:iz,kStatusCode:o_e,kWebSocket:n_e}=hg(),{concat:SN,toArrayBuffer:s_e,unmask:g_e}=YC(),{isValidStatusCode:c_e,isValidUTF8:oz}=Bd(),cm=Buffer[Symbol.species],To=0,nz=1,sz=2,gz=3,wN=4,DN=5,Im=6,ON=class extends a_e{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||i_e[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[n_e]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=To}_write(t,o,i){if(this._opcode===8&&this._state==To)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(i)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t=i.length?o.set(this._buffers.shift(),e):(o.set(new Uint8Array(i.buffer,i.byteOffset,t),e),this._buffers[0]=new cm(i.buffer,i.byteOffset+t,i.length-t)),t-=i.length}while(t>0);return o}startLoop(t){this._loop=!0;do switch(this._state){case To:this.getInfo(t);break;case nz:this.getPayloadLength16(t);break;case sz:this.getPayloadLength64(t);break;case gz:this.getMask();break;case wN:this.getData(t);break;case DN:case Im:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let o=this.consume(2);if((o[0]&48)!==0){let e=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(e);return}let i=(o[0]&64)===64;if(i&&!this._extensions[az.extensionName]){let e=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(e);return}if(this._fin=(o[0]&128)===128,this._opcode=o[0]&15,this._payloadLength=o[1]&127,this._opcode===0){if(i){let e=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(e);return}if(!this._fragmented){let e=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(e);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let e=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(e);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let e=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(e);return}if(i){let e=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(e);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let e=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(e);return}}else{let e=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(e);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(o[1]&128)===128,this._isServer){if(!this._masked){let e=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(e);return}}else if(this._masked){let e=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(e);return}this._payloadLength===126?this._state=nz:this._payloadLength===127?this._state=sz:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let o=this.consume(8),i=o.readUInt32BE(0);if(i>Math.pow(2,21)-1){let e=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(e);return}this._payloadLength=i*Math.pow(2,32)+o.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._masked?this._state=gz:this._state=wN}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=wN}getData(t){let o=iz;if(this._payloadLength){if(this._bufferedBytes7){this.controlMessage(o,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(i);return}if(this._compressed){this._state=DN,this.decompress(o,t);return}o.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(o)),this.dataMessage(t)}decompress(t,o){this._extensions[az.extensionName].decompress(t,this._fin,(e,a)=>{if(e)return o(e);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let A=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");o(A);return}this._fragments.push(a)}this.dataMessage(o),this._state===To&&this.startLoop(o)})}dataMessage(t){if(!this._fin){this._state=To;return}let o=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let e;this._binaryType==="nodebuffer"?e=SN(i,o):this._binaryType==="arraybuffer"?e=s_e(SN(i,o)):this._binaryType==="blob"?e=new Blob(i):e=i,this._allowSynchronousEvents?(this.emit("message",e,!0),this._state=To):(this._state=Im,setImmediate(()=>{this.emit("message",e,!0),this._state=To,this.startLoop(t)}))}else{let e=SN(i,o);if(!this._skipUTF8Validation&&!oz(e)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(a);return}this._state===DN||this._allowSynchronousEvents?(this.emit("message",e,!1),this._state=To):(this._state=Im,setImmediate(()=>{this.emit("message",e,!1),this._state=To,this.startLoop(t)}))}}controlMessage(t,o){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,iz),this.end();else{let i=t.readUInt16BE(0);if(!c_e(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");o(a);return}let e=new cm(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!oz(e)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");o(a);return}this._loop=!1,this.emit("conclude",i,e),this.end()}this._state=To;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=To):(this._state=Im,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=To,this.startLoop(o)}))}createError(t,o,i,e,a){this._loop=!1,this._errored=!0;let A=new t(i?`Invalid WebSocket frame: ${o}`:o);return Error.captureStackTrace(A,this.createError),A.code=a,A[o_e]=e,A}};cz.exports=ON});var TN=$((pgA,pz)=>{"use strict";var{Duplex:lgA}=$e("stream"),{randomFillSync:I_e}=$e("crypto"),{types:{isUint8Array:l_e}}=$e("util"),Iz=ud(),{EMPTY_BUFFER:p_e,kWebSocket:d_e,NOOP:h_e}=hg(),{isBlob:fd,isValidStatusCode:E_e}=Bd(),{mask:lz,toBuffer:XI}=YC(),No=Symbol("kByteLength"),C_e=Buffer.alloc(4),lm=8*1024,$I,Qd=lm,Bn=0,u_e=1,B_e=2,MN=class n{constructor(t,o,i){this._extensions=o||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Bn,this.onerror=h_e,this[d_e]=void 0}static frame(t,o){let i,e=!1,a=2,A=!1;o.mask&&(i=o.maskBuffer||C_e,o.generateMask?o.generateMask(i):(Qd===lm&&($I===void 0&&($I=Buffer.alloc(lm)),I_e($I,0,lm),Qd=0),i[0]=$I[Qd++],i[1]=$I[Qd++],i[2]=$I[Qd++],i[3]=$I[Qd++]),A=(i[0]|i[1]|i[2]|i[3])===0,a=6);let r;typeof t=="string"?(!o.mask||A)&&o[No]!==void 0?r=o[No]:(t=Buffer.from(t),r=t.length):(r=t.length,e=o.mask&&o.readOnly&&!A);let s=r;r>=65536?(a+=8,s=127):r>125&&(a+=2,s=126);let g=Buffer.allocUnsafe(e?r+a:a);return g[0]=o.fin?o.opcode|128:o.opcode,o.rsv1&&(g[0]|=64),g[1]=s,s===126?g.writeUInt16BE(r,2):s===127&&(g[2]=g[3]=0,g.writeUIntBE(r,4,6)),o.mask?(g[1]|=128,g[a-4]=i[0],g[a-3]=i[1],g[a-2]=i[2],g[a-1]=i[3],A?[g,t]:e?(lz(t,i,g,a,r),[g]):(lz(t,i,t,0,r),[g,t])):[g,t]}close(t,o,i,e){let a;if(t===void 0)a=p_e;else{if(typeof t!="number"||!E_e(t))throw new TypeError("First argument must be a valid error code number");if(o===void 0||!o.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let r=Buffer.byteLength(o);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");if(a=Buffer.allocUnsafe(2+r),a.writeUInt16BE(t,0),typeof o=="string")a.write(o,2);else if(l_e(o))a.set(o,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let A={[No]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Bn?this.enqueue([this.dispatch,a,!1,A,e]):this.sendFrame(n.frame(a,A),e)}ping(t,o,i){let e,a;if(typeof t=="string"?(e=Buffer.byteLength(t),a=!1):fd(t)?(e=t.size,a=!1):(t=XI(t),e=t.length,a=XI.readOnly),e>125)throw new RangeError("The data size must not be greater than 125 bytes");let A={[No]:e,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};fd(t)?this._state!==Bn?this.enqueue([this.getBlobData,t,!1,A,i]):this.getBlobData(t,!1,A,i):this._state!==Bn?this.enqueue([this.dispatch,t,!1,A,i]):this.sendFrame(n.frame(t,A),i)}pong(t,o,i){let e,a;if(typeof t=="string"?(e=Buffer.byteLength(t),a=!1):fd(t)?(e=t.size,a=!1):(t=XI(t),e=t.length,a=XI.readOnly),e>125)throw new RangeError("The data size must not be greater than 125 bytes");let A={[No]:e,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};fd(t)?this._state!==Bn?this.enqueue([this.getBlobData,t,!1,A,i]):this.getBlobData(t,!1,A,i):this._state!==Bn?this.enqueue([this.dispatch,t,!1,A,i]):this.sendFrame(n.frame(t,A),i)}send(t,o,i){let e=this._extensions[Iz.extensionName],a=o.binary?2:1,A=o.compress,r,s;typeof t=="string"?(r=Buffer.byteLength(t),s=!1):fd(t)?(r=t.size,s=!1):(t=XI(t),r=t.length,s=XI.readOnly),this._firstFragment?(this._firstFragment=!1,A&&e&&e.params[e._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(A=r>=e._threshold),this._compress=A):(A=!1,a=0),o.fin&&(this._firstFragment=!0);let g={[No]:r,fin:o.fin,generateMask:this._generateMask,mask:o.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:s,rsv1:A};fd(t)?this._state!==Bn?this.enqueue([this.getBlobData,t,this._compress,g,i]):this.getBlobData(t,this._compress,g,i):this._state!==Bn?this.enqueue([this.dispatch,t,this._compress,g,i]):this.dispatch(t,this._compress,g,i)}getBlobData(t,o,i,e){this._bufferedBytes+=i[No],this._state=B_e,t.arrayBuffer().then(a=>{if(this._socket.destroyed){let r=new Error("The socket was closed while the blob was being read");process.nextTick(_N,this,r,e);return}this._bufferedBytes-=i[No];let A=XI(a);o?this.dispatch(A,o,i,e):(this._state=Bn,this.sendFrame(n.frame(A,i),e),this.dequeue())}).catch(a=>{process.nextTick(f_e,this,a,e)})}dispatch(t,o,i,e){if(!o){this.sendFrame(n.frame(t,i),e);return}let a=this._extensions[Iz.extensionName];this._bufferedBytes+=i[No],this._state=u_e,a.compress(t,i.fin,(A,r)=>{if(this._socket.destroyed){let s=new Error("The socket was closed while data was being compressed");_N(this,s,e);return}this._bufferedBytes-=i[No],this._state=Bn,i.readOnly=!1,this.sendFrame(n.frame(r,i),e),this.dequeue()})}dequeue(){for(;this._state===Bn&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][No],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][No],this._queue.push(t)}sendFrame(t,o){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],o),this._socket.uncork()):this._socket.write(t[0],o)}};pz.exports=MN;function _N(n,t,o){typeof o=="function"&&o(t);for(let i=0;i{"use strict";var{kForOnEventAttribute:JC,kListener:NN}=hg(),dz=Symbol("kCode"),hz=Symbol("kData"),Ez=Symbol("kError"),Cz=Symbol("kMessage"),uz=Symbol("kReason"),yd=Symbol("kTarget"),Bz=Symbol("kType"),fz=Symbol("kWasClean"),Cg=class{constructor(t){this[yd]=null,this[Bz]=t}get target(){return this[yd]}get type(){return this[Bz]}};Object.defineProperty(Cg.prototype,"target",{enumerable:!0});Object.defineProperty(Cg.prototype,"type",{enumerable:!0});var el=class extends Cg{constructor(t,o={}){super(t),this[dz]=o.code===void 0?0:o.code,this[uz]=o.reason===void 0?"":o.reason,this[fz]=o.wasClean===void 0?!1:o.wasClean}get code(){return this[dz]}get reason(){return this[uz]}get wasClean(){return this[fz]}};Object.defineProperty(el.prototype,"code",{enumerable:!0});Object.defineProperty(el.prototype,"reason",{enumerable:!0});Object.defineProperty(el.prototype,"wasClean",{enumerable:!0});var md=class extends Cg{constructor(t,o={}){super(t),this[Ez]=o.error===void 0?null:o.error,this[Cz]=o.message===void 0?"":o.message}get error(){return this[Ez]}get message(){return this[Cz]}};Object.defineProperty(md.prototype,"error",{enumerable:!0});Object.defineProperty(md.prototype,"message",{enumerable:!0});var qC=class extends Cg{constructor(t,o={}){super(t),this[hz]=o.data===void 0?null:o.data}get data(){return this[hz]}};Object.defineProperty(qC.prototype,"data",{enumerable:!0});var Q_e={addEventListener(n,t,o={}){for(let e of this.listeners(n))if(!o[JC]&&e[NN]===t&&!e[JC])return;let i;if(n==="message")i=function(a,A){let r=new qC("message",{data:A?a:a.toString()});r[yd]=this,pm(t,this,r)};else if(n==="close")i=function(a,A){let r=new el("close",{code:a,reason:A.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[yd]=this,pm(t,this,r)};else if(n==="error")i=function(a){let A=new md("error",{error:a,message:a.message});A[yd]=this,pm(t,this,A)};else if(n==="open")i=function(){let a=new Cg("open");a[yd]=this,pm(t,this,a)};else return;i[JC]=!!o[JC],i[NN]=t,o.once?this.once(n,i):this.on(n,i)},removeEventListener(n,t){for(let o of this.listeners(n))if(o[NN]===t&&!o[JC]){this.removeListener(n,o);break}}};Qz.exports={CloseEvent:el,ErrorEvent:md,Event:Cg,EventTarget:Q_e,MessageEvent:qC};function pm(n,t,o){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,o):n.call(t,o)}});var dm=$((hgA,mz)=>{"use strict";var{tokenChars:zC}=Bd();function ss(n,t,o){n[t]===void 0?n[t]=[o]:n[t].push(o)}function y_e(n){let t=Object.create(null),o=Object.create(null),i=!1,e=!1,a=!1,A,r,s=-1,g=-1,c=-1,I=0;for(;I{let o=n[t];return Array.isArray(o)||(o=[o]),o.map(i=>[t].concat(Object.keys(i).map(e=>{let a=i[e];return Array.isArray(a)||(a=[a]),a.map(A=>A===!0?e:`${e}=${A}`).join("; ")})).join("; ")).join(", ")}).join(", ")}mz.exports={format:m_e,parse:y_e}});var um=$((ugA,vz)=>{"use strict";var S_e=$e("events"),w_e=$e("https"),D_e=$e("http"),Dz=$e("net"),O_e=$e("tls"),{randomBytes:b_e,createHash:M_e}=$e("crypto"),{Duplex:EgA,Readable:CgA}=$e("stream"),{URL:RN}=$e("url"),Bc=ud(),__e=bN(),T_e=TN(),{isBlob:N_e}=Bd(),{BINARY_TYPES:Sz,CLOSE_TIMEOUT:R_e,EMPTY_BUFFER:hm,GUID:k_e,kForOnEventAttribute:kN,kListener:v_e,kStatusCode:P_e,kWebSocket:ia,NOOP:Oz}=hg(),{EventTarget:{addEventListener:G_e,removeEventListener:F_e}}=yz(),{format:L_e,parse:U_e}=dm(),{toBuffer:H_e}=YC(),bz=Symbol("kAborted"),vN=[8,13],ug=["CONNECTING","OPEN","CLOSING","CLOSED"],K_e=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Xt=class n extends S_e{constructor(t,o,i){super(),this._binaryType=Sz[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=hm,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,o===void 0?o=[]:Array.isArray(o)||(typeof o=="object"&&o!==null?(i=o,o=[]):o=[o]),Mz(this,t,o,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){Sz.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,o,i){let e=new __e({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new T_e(t,this._extensions,i.generateMask);this._receiver=e,this._sender=a,this._socket=t,e[ia]=this,a[ia]=this,t[ia]=this,e.on("conclude",j_e),e.on("drain",J_e),e.on("error",q_e),e.on("message",z_e),e.on("ping",V_e),e.on("pong",W_e),a.onerror=Z_e,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),o.length>0&&t.unshift(o),t.on("close",Nz),t.on("data",Cm),t.on("end",Rz),t.on("error",kz),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Bc.extensionName]&&this._extensions[Bc.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,o){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){eo(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(t,o,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Tz(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,o,i){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(i=t,t=o=void 0):typeof o=="function"&&(i=o,o=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){PN(this,t,i);return}o===void 0&&(o=!this._isServer),this._sender.ping(t||hm,o,i)}pong(t,o,i){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(i=t,t=o=void 0):typeof o=="function"&&(i=o,o=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){PN(this,t,i);return}o===void 0&&(o=!this._isServer),this._sender.pong(t||hm,o,i)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,o,i){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof o=="function"&&(i=o,o={}),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){PN(this,t,i);return}let e={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...o};this._extensions[Bc.extensionName]||(e.compress=!1),this._sender.send(t||hm,e,i)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){eo(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(Xt,"CONNECTING",{enumerable:!0,value:ug.indexOf("CONNECTING")});Object.defineProperty(Xt.prototype,"CONNECTING",{enumerable:!0,value:ug.indexOf("CONNECTING")});Object.defineProperty(Xt,"OPEN",{enumerable:!0,value:ug.indexOf("OPEN")});Object.defineProperty(Xt.prototype,"OPEN",{enumerable:!0,value:ug.indexOf("OPEN")});Object.defineProperty(Xt,"CLOSING",{enumerable:!0,value:ug.indexOf("CLOSING")});Object.defineProperty(Xt.prototype,"CLOSING",{enumerable:!0,value:ug.indexOf("CLOSING")});Object.defineProperty(Xt,"CLOSED",{enumerable:!0,value:ug.indexOf("CLOSED")});Object.defineProperty(Xt.prototype,"CLOSED",{enumerable:!0,value:ug.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(Xt.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(Xt.prototype,`on${n}`,{enumerable:!0,get(){for(let t of this.listeners(n))if(t[kN])return t[v_e];return null},set(t){for(let o of this.listeners(n))if(o[kN]){this.removeListener(n,o);break}typeof t=="function"&&this.addEventListener(n,t,{[kN]:!0})}})});Xt.prototype.addEventListener=G_e;Xt.prototype.removeEventListener=F_e;vz.exports=Xt;function Mz(n,t,o,i){let e={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:R_e,protocolVersion:vN[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=e.autoPong,n._closeTimeout=e.closeTimeout,!vN.includes(e.protocolVersion))throw new RangeError(`Unsupported protocol version: ${e.protocolVersion} (supported versions: ${vN.join(", ")})`);let a;if(t instanceof RN)a=t;else try{a=new RN(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),n._url=a.href;let A=a.protocol==="wss:",r=a.protocol==="ws+unix:",s;if(a.protocol!=="ws:"&&!A&&!r?s=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:r&&!a.pathname?s="The URL's pathname is empty":a.hash&&(s="The URL contains a fragment identifier"),s){let Q=new SyntaxError(s);if(n._redirects===0)throw Q;Em(n,Q);return}let g=A?443:80,c=b_e(16).toString("base64"),I=A?w_e.request:D_e.request,d=new Set,B;if(e.createConnection=e.createConnection||(A?Y_e:x_e),e.defaultPort=e.defaultPort||g,e.port=a.port||g,e.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,e.headers={...e.headers,"Sec-WebSocket-Version":e.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},e.path=a.pathname+a.search,e.timeout=e.handshakeTimeout,e.perMessageDeflate&&(B=new Bc({...e.perMessageDeflate,isServer:!1,maxPayload:e.maxPayload}),e.headers["Sec-WebSocket-Extensions"]=L_e({[Bc.extensionName]:B.offer()})),o.length){for(let Q of o){if(typeof Q!="string"||!K_e.test(Q)||d.has(Q))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(Q)}e.headers["Sec-WebSocket-Protocol"]=o.join(",")}if(e.origin&&(e.protocolVersion<13?e.headers["Sec-WebSocket-Origin"]=e.origin:e.headers.Origin=e.origin),(a.username||a.password)&&(e.auth=`${a.username}:${a.password}`),r){let Q=e.path.split(":");e.socketPath=Q[0],e.path=Q[1]}let f;if(e.followRedirects){if(n._redirects===0){n._originalIpc=r,n._originalSecure=A,n._originalHostOrSocketPath=r?e.socketPath:a.host;let Q=i&&i.headers;if(i={...i,headers:{}},Q)for(let[y,m]of Object.entries(Q))i.headers[y.toLowerCase()]=m}else if(n.listenerCount("redirect")===0){let Q=r?n._originalIpc?e.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:a.host===n._originalHostOrSocketPath;(!Q||n._originalSecure&&!A)&&(delete e.headers.authorization,delete e.headers.cookie,Q||delete e.headers.host,e.auth=void 0)}e.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(e.auth).toString("base64")),f=n._req=I(e),n._redirects&&n.emit("redirect",n.url,f)}else f=n._req=I(e);e.timeout&&f.on("timeout",()=>{eo(n,f,"Opening handshake has timed out")}),f.on("error",Q=>{f===null||f[bz]||(f=n._req=null,Em(n,Q))}),f.on("response",Q=>{let y=Q.headers.location,m=Q.statusCode;if(y&&e.followRedirects&&m>=300&&m<400){if(++n._redirects>e.maxRedirects){eo(n,f,"Maximum redirects exceeded");return}f.abort();let _;try{_=new RN(y,t)}catch{let R=new SyntaxError(`Invalid URL: ${y}`);Em(n,R);return}Mz(n,_,o,i)}else n.emit("unexpected-response",f,Q)||eo(n,f,`Unexpected server response: ${Q.statusCode}`)}),f.on("upgrade",(Q,y,m)=>{if(n.emit("upgrade",Q),n.readyState!==Xt.CONNECTING)return;f=n._req=null;let _=Q.headers.upgrade;if(_===void 0||_.toLowerCase()!=="websocket"){eo(n,y,"Invalid Upgrade header");return}let T=M_e("sha1").update(c+k_e).digest("base64");if(Q.headers["sec-websocket-accept"]!==T){eo(n,y,"Invalid Sec-WebSocket-Accept header");return}let R=Q.headers["sec-websocket-protocol"],F;if(R!==void 0?d.size?d.has(R)||(F="Server sent an invalid subprotocol"):F="Server sent a subprotocol but none was requested":d.size&&(F="Server sent no subprotocol"),F){eo(n,y,F);return}R&&(n._protocol=R);let K=Q.headers["sec-websocket-extensions"];if(K!==void 0){if(!B){eo(n,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let L;try{L=U_e(K)}catch{eo(n,y,"Invalid Sec-WebSocket-Extensions header");return}let q=Object.keys(L);if(q.length!==1||q[0]!==Bc.extensionName){eo(n,y,"Server indicated an extension that was not requested");return}try{B.accept(L[Bc.extensionName])}catch{eo(n,y,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[Bc.extensionName]=B}n.setSocket(y,m,{allowSynchronousEvents:e.allowSynchronousEvents,generateMask:e.generateMask,maxBufferedChunks:e.maxBufferedChunks,maxFragments:e.maxFragments,maxPayload:e.maxPayload,skipUTF8Validation:e.skipUTF8Validation})}),e.finishRequest?e.finishRequest(f,n):f.end()}function Em(n,t){n._readyState=Xt.CLOSING,n._errorEmitted=!0,n.emit("error",t),n.emitClose()}function x_e(n){return n.path=n.socketPath,Dz.connect(n)}function Y_e(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=Dz.isIP(n.host)?"":n.host),O_e.connect(n)}function eo(n,t,o){n._readyState=Xt.CLOSING;let i=new Error(o);Error.captureStackTrace(i,eo),t.setHeader?(t[bz]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Em,n,i)):(t.destroy(i),t.once("error",n.emit.bind(n,"error")),t.once("close",n.emitClose.bind(n)))}function PN(n,t,o){if(t){let i=N_e(t)?t.size:H_e(t).length;n._socket?n._sender._bufferedBytes+=i:n._bufferedAmount+=i}if(o){let i=new Error(`WebSocket is not open: readyState ${n.readyState} (${ug[n.readyState]})`);process.nextTick(o,i)}}function j_e(n,t){let o=this[ia];o._closeFrameReceived=!0,o._closeMessage=t,o._closeCode=n,o._socket[ia]!==void 0&&(o._socket.removeListener("data",Cm),process.nextTick(_z,o._socket),n===1005?o.close():o.close(n,t))}function J_e(){let n=this[ia];n.isPaused||n._socket.resume()}function q_e(n){let t=this[ia];t._socket[ia]!==void 0&&(t._socket.removeListener("data",Cm),process.nextTick(_z,t._socket),t.close(n[P_e])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",n))}function wz(){this[ia].emitClose()}function z_e(n,t){this[ia].emit("message",n,t)}function V_e(n){let t=this[ia];t._autoPong&&t.pong(n,!this._isServer,Oz),t.emit("ping",n)}function W_e(n){this[ia].emit("pong",n)}function _z(n){n.resume()}function Z_e(n){let t=this[ia];t.readyState!==Xt.CLOSED&&(t.readyState===Xt.OPEN&&(t._readyState=Xt.CLOSING,Tz(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",n)))}function Tz(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function Nz(){let n=this[ia];if(this.removeListener("close",Nz),this.removeListener("data",Cm),this.removeListener("end",Rz),n._readyState=Xt.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);n._receiver.write(t)}n._receiver.end(),this[ia]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",wz),n._receiver.on("finish",wz))}function Cm(n){this[ia]._receiver.write(n)||this.pause()}function Rz(){let n=this[ia];n._readyState=Xt.CLOSING,n._receiver.end(),this.end()}function kz(){let n=this[ia];this.removeListener("error",kz),this.on("error",Oz),n&&(n._readyState=Xt.CLOSING,this.destroy())}});var Lz=$((fgA,Fz)=>{"use strict";var BgA=um(),{Duplex:X_e}=$e("stream");function Pz(n){n.emit("close")}function $_e(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Gz(n){this.removeListener("error",Gz),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function eTe(n,t){let o=!0,i=new X_e({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(a,A){let r=!A&&i._readableState.objectMode?a.toString():a;i.push(r)||n.pause()}),n.once("error",function(a){i.destroyed||(o=!1,i.destroy(a))}),n.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(e,a){if(n.readyState===n.CLOSED){a(e),process.nextTick(Pz,i);return}let A=!1;n.once("error",function(s){A=!0,a(s)}),n.once("close",function(){A||a(e),process.nextTick(Pz,i)}),o&&n.terminate()},i._final=function(e){if(n.readyState===n.CONNECTING){n.once("open",function(){i._final(e)});return}n._socket!==null&&(n._socket._writableState.finished?(e(),i._readableState.endEmitted&&i.destroy()):(n._socket.once("finish",function(){e()}),n.close()))},i._read=function(){n.isPaused&&n.resume()},i._write=function(e,a,A){if(n.readyState===n.CONNECTING){n.once("open",function(){i._write(e,a,A)});return}n.send(e,A)},i.on("end",$_e),i.on("error",Gz),i}Fz.exports=eTe});var GN=$((QgA,Uz)=>{"use strict";var{tokenChars:ATe}=Bd();function tTe(n){let t=new Set,o=-1,i=-1,e=0;for(e;e{"use strict";var rTe=$e("events"),Bm=$e("http"),{Duplex:ygA}=$e("stream"),{createHash:aTe}=$e("crypto"),Hz=dm(),Al=ud(),iTe=GN(),oTe=um(),{CLOSE_TIMEOUT:nTe,GUID:sTe,kWebSocket:gTe}=hg(),cTe=/^[+/0-9A-Za-z]{22}==$/,Kz=0,xz=1,jz=2,FN=class extends rTe{constructor(t,o){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:nTe,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:oTe,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=Bm.createServer((i,e)=>{let a=Bm.STATUS_CODES[426];e.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),e.end(a)}),this._server.listen(t.port,t.host,t.backlog,o)):t.server&&(this._server=t.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=ITe(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(e,a,A)=>{this.handleUpgrade(e,a,A,i)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=Kz}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===jz){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(VC,this);return}if(t&&this.once("close",t),this._state!==xz)if(this._state=xz,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(VC,this):process.nextTick(VC,this);else{let o=this._server;this._removeListeners(),this._removeListeners=this._server=null,o.close(()=>{VC(this)})}}shouldHandle(t){if(this.options.path){let o=t.url.indexOf("?");if((o!==-1?t.url.slice(0,o):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,o,i,e){o.on("error",Yz);let a=t.headers["sec-websocket-key"],A=t.headers.upgrade,r=+t.headers["sec-websocket-version"];if(t.method!=="GET"){tl(this,t,o,405,"Invalid HTTP method");return}if(A===void 0||A.toLowerCase()!=="websocket"){tl(this,t,o,400,"Invalid Upgrade header");return}if(a===void 0||!cTe.test(a)){tl(this,t,o,400,"Missing or invalid Sec-WebSocket-Key header");return}if(r!==13&&r!==8){tl(this,t,o,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){WC(o,400);return}let s=t.headers["sec-websocket-protocol"],g=new Set;if(s!==void 0)try{g=iTe.parse(s)}catch{tl(this,t,o,400,"Invalid Sec-WebSocket-Protocol header");return}let c=t.headers["sec-websocket-extensions"],I={};if(this.options.perMessageDeflate&&c!==void 0){let d=new Al({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let B=Hz.parse(c);B[Al.extensionName]&&(d.accept(B[Al.extensionName]),I[Al.extensionName]=d)}catch{tl(this,t,o,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let d={origin:t.headers[`${r===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(d,(B,f,Q,y)=>{if(!B)return WC(o,f||401,Q,y);this.completeUpgrade(I,a,g,t,o,i,e)});return}if(!this.options.verifyClient(d))return WC(o,401)}this.completeUpgrade(I,a,g,t,o,i,e)}completeUpgrade(t,o,i,e,a,A,r){if(!a.readable||!a.writable)return a.destroy();if(a[gTe])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Kz)return WC(a,503);let g=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${aTe("sha1").update(o+sTe).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(i.size){let I=this.options.handleProtocols?this.options.handleProtocols(i,e):i.values().next().value;I&&(g.push(`Sec-WebSocket-Protocol: ${I}`),c._protocol=I)}if(t[Al.extensionName]){let I=t[Al.extensionName].params,d=Hz.format({[Al.extensionName]:[I]});g.push(`Sec-WebSocket-Extensions: ${d}`),c._extensions=t}this.emit("headers",g,e),a.write(g.concat(`\r +`+t.prev}function by(n,t){var o=M0(n),i=[];if(o){i.length=n.length;for(var e=0;e{"use strict";var iwe=TC(),owe=sc(),Ty=function(n,t,o){for(var i=n,e;(e=i.next)!=null;i=e)if(e.key===t)return i.next=e.next,o||(e.next=n.next,n.next=e),e},nwe=function(n,t){if(n){var o=Ty(n,t);return o&&o.value}},swe=function(n,t,o){var i=Ty(n,t);i?i.value=o:n.next={key:t,next:n.next,value:o}},gwe=function(n,t){return n?!!Ty(n,t):!1},cwe=function(n,t){if(n)return Ty(n,t,!0)};o4.exports=function(){var t,o={assert:function(i){if(!o.has(i))throw new owe("Side channel does not contain "+iwe(i))},delete:function(i){var e=cwe(t,i);return e&&t&&!t.next&&(t=void 0),!!e},get:function(i){return nwe(t,i)},has:function(i){return gwe(t,i)},set:function(i,e){t||(t={next:void 0}),swe(t,i,e)}};return o}});var k0=$((WsA,c4)=>{"use strict";var s4=sC(),g4=cT(),Iwe=g4([s4("%String.prototype.indexOf%")]);c4.exports=function(t,o){var i=s4(t,!!o);return typeof i=="function"&&Iwe(t,".prototype.")>-1?g4([i]):i}});var v0=$((ZsA,l4)=>{"use strict";var lwe=sC(),NC=k0(),pwe=TC(),dwe=sc(),I4=lwe("%Map%",!0),hwe=NC("Map.prototype.get",!0),Ewe=NC("Map.prototype.set",!0),Cwe=NC("Map.prototype.has",!0),uwe=NC("Map.prototype.delete",!0),Bwe=NC("Map.prototype.size",!0);l4.exports=!!I4&&function(){var t,o={assert:function(i){if(!o.has(i))throw new dwe("Side channel does not contain "+pwe(i))},delete:function(i){if(t){var e=uwe(t,i);return Bwe(t)===0&&(t=void 0),e}return!1},get:function(i){if(t)return hwe(t,i)},has:function(i){return t?Cwe(t,i):!1},set:function(i,e){t||(t=new I4),Ewe(t,i,e)}};return o}});var d4=$((XsA,p4)=>{"use strict";var fwe=sC(),Ry=k0(),Qwe=TC(),Ny=v0(),ywe=sc(),od=fwe("%WeakMap%",!0),mwe=Ry("WeakMap.prototype.get",!0),Swe=Ry("WeakMap.prototype.set",!0),wwe=Ry("WeakMap.prototype.has",!0),Dwe=Ry("WeakMap.prototype.delete",!0);p4.exports=od?function(){var t,o,i={assert:function(e){if(!i.has(e))throw new ywe("Side channel does not contain "+Qwe(e))},delete:function(e){if(od&&e&&(typeof e=="object"||typeof e=="function")){if(t)return Dwe(t,e)}else if(Ny&&o)return o.delete(e);return!1},get:function(e){return od&&e&&(typeof e=="object"||typeof e=="function")&&t?mwe(t,e):o&&o.get(e)},has:function(e){return od&&e&&(typeof e=="object"||typeof e=="function")&&t?wwe(t,e):!!o&&o.has(e)},set:function(e,a){od&&e&&(typeof e=="object"||typeof e=="function")?(t||(t=new od),Swe(t,e,a)):Ny&&(o||(o=Ny()),o.set(e,a))}};return i}:Ny});var P0=$(($sA,h4)=>{"use strict";var Owe=sc(),bwe=TC(),Mwe=n4(),_we=v0(),Twe=d4(),Nwe=Twe||_we||Mwe;h4.exports=function(){var t,o={assert:function(i){if(!o.has(i)){var e=i&&Object(i)===i?"the given object key":bwe(i);throw new Owe("Side channel does not contain "+e)}},delete:function(i){return!!t&&t.delete(i)},get:function(i){return t&&t.get(i)},has:function(i){return!!t&&t.has(i)},set:function(i,e){t||(t=Nwe()),t.set(i,e)}};return o}});var ky=$((egA,E4)=>{"use strict";var Rwe=String.prototype.replace,kwe=/%20/g,G0={RFC1738:"RFC1738",RFC3986:"RFC3986"};E4.exports={default:G0.RFC3986,formatters:{RFC1738:function(n){return Rwe.call(n,kwe,"+")},RFC3986:function(n){return String(n)}},RFC1738:G0.RFC1738,RFC3986:G0.RFC3986}});var H0=$((AgA,B4)=>{"use strict";var vwe=ky(),u4=P0(),C4=iT(),F0=Object.prototype.hasOwnProperty,dc=Array.isArray,Py=u4(),jI=function(t,o){return Py.set(t,o),t},JI=function(t){return Py.has(t)},RC=function(t){return Py.get(t)},L0=function(t,o){Py.set(t,o)},as=(function(){for(var n=[],t=0;t<256;++t)n[n.length]="%"+((t<16?"0":"")+t.toString(16)).toUpperCase();return n})(),Pwe=function(t){for(;t.length>1;){var o=t.pop(),i=o.obj[o.prop];if(dc(i)){for(var e=[],a=0;a=i.arrayLimit){if(i.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+i.arrayLimit+" element"+(i.arrayLimit===1?"":"s")+" allowed in an array.");return jI(nd(t.concat(o),i),e)}t[e]=o}else if(t&&typeof t=="object")if(JI(t)){var a=RC(t)+1;t[a]=o,L0(t,a)}else{if(i&&i.strictMerge)return[t,o];(i&&(i.plainObjects||i.allowPrototypes)||!F0.call(Object.prototype,o))&&(t[o]=!0)}else return[t,o];return t}if(!t||typeof t!="object"){if(JI(o)){for(var A=Object.keys(o),r=i&&i.plainObjects?{__proto__:null,0:t}:{0:t},s=0;si.arrayLimit){if(i.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+i.arrayLimit+" element"+(i.arrayLimit===1?"":"s")+" allowed in an array.");return jI(nd(c,i),c.length-1)}return c}var I=t;if(dc(t)&&!dc(o)&&(I=nd(t,i)),dc(t)&&dc(o)){if(o.forEach(function(d,B){if(F0.call(t,B)){var f=t[B];f&&typeof f=="object"&&d&&typeof d=="object"?t[B]=n(f,d,i):t[t.length]=d}else t[B]=d}),i&&typeof i.arrayLimit=="number"&&t.length>i.arrayLimit){if(i.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+i.arrayLimit+" element"+(i.arrayLimit===1?"":"s")+" allowed in an array.");return jI(nd(t,i),t.length-1)}return t}return Object.keys(o).reduce(function(d,B){var f=o[B];if(F0.call(d,B)?U0(d,B,n(d[B],f,i)):U0(d,B,f),JI(o)&&!JI(d)&&jI(d,RC(o)),JI(d)){var Q=parseInt(B,10);String(Q)===B&&Q>=0&&Q>RC(d)&&L0(d,Q)}return d},I)},Fwe=function(t,o){return Object.keys(o).reduce(function(i,e){return U0(i,e,o[e]),i},t)},Lwe=function(n,t,o){var i=n.replace(/\+/g," ");if(o==="iso-8859-1")return i.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(i)}catch{return i}},vy=1024,Uwe=function(t,o,i,e,a){if(t.length===0)return t;var A=t;if(typeof t=="symbol"?A=Symbol.prototype.toString.call(t):typeof t!="string"&&(A=String(t)),i==="iso-8859-1")return escape(A).replace(/%u[0-9a-f]{4}/gi,function(f){return"%26%23"+parseInt(f.slice(2),16)+"%3B"});for(var r="",s=0;s=vy?A.slice(s,s+vy):A;if(s+vy=55296&&c<=56319&&(g=g.slice(0,-1),s-=1)}for(var I=[],d=0;d=48&&B<=57||B>=65&&B<=90||B>=97&&B<=122||a===vwe.RFC1738&&(B===40||B===41)){I[I.length]=g.charAt(d);continue}if(B<128){I[I.length]=as[B];continue}if(B<2048){I[I.length]=as[192|B>>6]+as[128|B&63];continue}if(B<55296||B>=57344){I[I.length]=as[224|B>>12]+as[128|B>>6&63]+as[128|B&63];continue}d+=1,B=65536+((B&1023)<<10|g.charCodeAt(d)&1023),I[I.length]=as[240|B>>18]+as[128|B>>12&63]+as[128|B>>6&63]+as[128|B&63]}r+=I.join("")}return r},Hwe=function(t){for(var o=[{obj:{o:t},prop:"o"}],i=u4(),e=0;ei){if(a)throw new RangeError("Array limit exceeded. Only "+i+" element"+(i===1?"":"s")+" allowed in an array.");return jI(nd(g,{plainObjects:e}),g.length-1)}return g},jwe=function(t,o){if(dc(t)){for(var i=[],e=0;e{"use strict";var Q4=P0(),Gy=H0(),kC=ky(),Jwe=Object.prototype.hasOwnProperty,y4={brackets:function(t){return t+"[]"},comma:"comma",indices:function(t,o){return t+"["+o+"]"},repeat:function(t){return t}},is=Array.isArray,qwe=Array.prototype.push,m4=function(n,t){qwe.apply(n,is(t)?t:[t])},zwe=Date.prototype.toISOString,f4=kC.default,_r={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",depth:1/0,encode:!0,encodeDotInKeys:!1,encoder:Gy.encode,encodeValuesOnly:!1,filter:void 0,format:f4,formatter:kC.formatters[f4],indices:!1,serializeDate:function(t){return zwe.call(t)},skipNulls:!1,strictNullHandling:!1},Vwe=function(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"},K0={},Wwe=function n(t,o,i,e,a,A,r,s,g,c,I,d,B,f,Q,y,m,_,T,R){var L=t;if(R>T)throw new RangeError("Input depth exceeded depth option of "+T);for(var U=_,F=0,q=!1;(U=U.get(K0))!==void 0&&!q;){var z=U.get(t);if(F+=1,typeof z<"u"){if(z===F)throw new RangeError("Cyclic object value");q=!0}typeof U.get(K0)>"u"&&(F=0)}if(L=typeof c=="function"?c(o,L):L,L instanceof Date?L=B(L):i==="comma"&&is(L)&&(L=Gy.maybeMap(L,function(Ee){return Ee instanceof Date?B(Ee):Ee})),L===null){if(A)return Q(g&&!y?g(o,_r.encoder,m,"key",f):o);L=""}if(Vwe(L)||Gy.isBuffer(L)){if(g){var j=y?o:g(o,_r.encoder,m,"key",f);return[Q(j)+"="+Q(g(L,_r.encoder,m,"value",f))]}return[Q(o)+"="+Q(String(L))]}var P=[];if(typeof L>"u")return P;var J;if(i==="comma"&&is(L))y&&g&&(L=Gy.maybeMap(L,function(Ee){return Ee==null?Ee:g(Ee)})),J=[{value:L.length>0?L.join(",")||null:void 0}];else if(is(c))J=c;else{var H=Object.keys(L);J=I?H.sort(I):H}var N=s?String(o).replace(/\./g,"%2E"):String(o),k=e&&is(L)&&L.length===1?N+"[]":N;if(a&&is(L)&&L.length===0&&Object.keys(L).length===0)return k+"[]";for(var V=0;V"u"?t.encodeDotInKeys===!0?!0:_r.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:_r.addQueryPrefix,allowDots:r,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:_r.allowEmptyArrays,arrayFormat:A,charset:o,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:_r.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?_r.delimiter:t.delimiter,depth:typeof t.depth=="number"?t.depth:_r.depth,encode:typeof t.encode=="boolean"?t.encode:_r.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:_r.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:_r.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:_r.encodeValuesOnly,filter:a,format:i,formatter:e,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:_r.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:_r.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:_r.strictNullHandling}};S4.exports=function(n,t){var o=n,i=Zwe(t),e,a;typeof i.filter=="function"?(a=i.filter,o=a("",o)):is(i.filter)&&(a=i.filter,e=a);var A=[];if(typeof o!="object"||o===null)return"";var r=y4[i.arrayFormat],s=r==="comma"&&i.commaRoundTrip;e||(e=Object.keys(o)),i.sort&&e.sort(i.sort);for(var g=Q4(),c=0;c"u"||I===null)){var d=o[I];if(!(i.skipNulls&&d===null)){var B=i.encodeDotInKeys?String(I).replace(/\./g,"%2E"):String(I);m4(A,Wwe(d,B,r,s,i.allowEmptyArrays,i.strictNullHandling,i.skipNulls,i.encodeDotInKeys,i.encode?i.encoder:null,i.filter,i.sort,i.allowDots,i.serializeDate,i.format,i.formatter,i.encodeValuesOnly,i.charset,g,i.depth,0))}}}var f=A.join(i.delimiter),Q=i.addQueryPrefix===!0?"?":"";return i.charsetSentinel&&(i.charset==="iso-8859-1"?Q+="utf8=%26%2310003%3B"+i.delimiter:Q+="utf8=%E2%9C%93"+i.delimiter),f.length>0?Q+f:""}});var b4=$((rgA,O4)=>{"use strict";var os=H0(),Fy=Object.prototype.hasOwnProperty,x0=Array.isArray,or={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:os.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictMerge:!0,strictNullHandling:!1,throwOnLimitExceeded:!1},Xwe=function(n){return n.replace(/&#(\d+);/g,function(t,o){return String.fromCharCode(parseInt(o,10))})},D4=function(n,t,o){if(n&&typeof n=="string"&&t.comma&&n.indexOf(",")>-1){if(t.throwOnLimitExceeded)for(var i=0,e=n.indexOf(",");e>-1;){if(i+=1,i>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(t.arrayLimit===1?"":"s")+" allowed in an array.");e=n.indexOf(",",e+1)}return n.split(",")}if(t.throwOnLimitExceeded&&o>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(t.arrayLimit===1?"":"s")+" allowed in an array.");return n},$we="utf8=%26%2310003%3B",eDe="utf8=%E2%9C%93",ADe=function(t,o){var i={__proto__:null},e=o.ignoreQueryPrefix?t.replace(/^\?/,""):t;e=e.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var a=o.parameterLimit===1/0?void 0:o.parameterLimit,A=e.split(o.delimiter,o.throwOnLimitExceeded&&typeof a<"u"?a+1:a);if(o.throwOnLimitExceeded&&typeof a<"u"&&A.length>a)throw new RangeError("Parameter limit exceeded. Only "+a+" parameter"+(a===1?"":"s")+" allowed.");var r=-1,s,g=o.charset;if(o.charsetSentinel)for(s=0;s-1&&(f=x0(f)?[f]:f),o.comma&&x0(f)&&f.length>o.arrayLimit&&(f=os.combine([],f,o.arrayLimit,o.plainObjects,o.throwOnLimitExceeded)),B!==null){var Q=Fy.call(i,B);Q&&(o.duplicates==="combine"||c.indexOf("[]=")>-1)?i[B]=os.combine(i[B],f,o.arrayLimit,o.plainObjects,o.throwOnLimitExceeded):(!Q||o.duplicates==="last")&&(i[B]=f)}}return i},tDe=function(n,t,o,i){var e=0;if(n.length>0&&n[n.length-1]==="[]"){var a=n.slice(0,-1).join("");e=Array.isArray(t)&&t[a]?t[a].length:0}for(var A=i?t:D4(t,o,e),r=n.length-1;r>=0;--r){var s,g=n[r];if(g==="[]"&&o.parseArrays)os.isOverflow(A)?s=A:s=o.allowEmptyArrays&&(A===""||o.strictNullHandling&&A===null)?[]:os.combine([],A,o.arrayLimit,o.plainObjects,o.throwOnLimitExceeded);else{s=o.plainObjects?{__proto__:null}:{};var c=g.charAt(0)==="["&&g.charAt(g.length-1)==="]"?g.slice(1,-1):g,I=o.decodeDotInKeys?c.replace(/%2E/g,"."):c,d=parseInt(I,10),B=!isNaN(d)&&g!==I&&String(d)===I&&d>=0&&o.parseArrays;if(!o.parseArrays&&I==="")s={0:A};else if(B&&d=0?i.slice(0,a):i;if(A){if(!o.plainObjects&&Fy.call(Object.prototype,A)&&!o.allowPrototypes)return;e[e.length]=A}for(var r=i.length,s=a,g=0;s>=0&&g=0){if(o.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+o.depth+" and strictDepth is true");e[e.length]="["+i.slice(s)+"]"}return e},aDe=function(t,o,i,e){if(t){var a=rDe(t,i);if(a)return tDe(a,o,i,e)}},iDe=function(t){if(!t)return or;if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.decodeDotInKeys<"u"&&typeof t.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(t.decoder!==null&&typeof t.decoder<"u"&&typeof t.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(typeof t.throwOnLimitExceeded<"u"&&typeof t.throwOnLimitExceeded!="boolean")throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var o=typeof t.charset>"u"?or.charset:t.charset,i=typeof t.duplicates>"u"?or.duplicates:t.duplicates;if(i!=="combine"&&i!=="first"&&i!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var e=typeof t.allowDots>"u"?t.decodeDotInKeys===!0?!0:or.allowDots:!!t.allowDots;return{allowDots:e,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:or.allowEmptyArrays,allowPrototypes:typeof t.allowPrototypes=="boolean"?t.allowPrototypes:or.allowPrototypes,allowSparse:typeof t.allowSparse=="boolean"?t.allowSparse:or.allowSparse,arrayLimit:typeof t.arrayLimit=="number"?t.arrayLimit:or.arrayLimit,charset:o,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:or.charsetSentinel,comma:typeof t.comma=="boolean"?t.comma:or.comma,decodeDotInKeys:typeof t.decodeDotInKeys=="boolean"?t.decodeDotInKeys:or.decodeDotInKeys,decoder:typeof t.decoder=="function"?t.decoder:or.decoder,delimiter:typeof t.delimiter=="string"||os.isRegExp(t.delimiter)?t.delimiter:or.delimiter,depth:typeof t.depth=="number"||t.depth===!1?+t.depth:or.depth,duplicates:i,ignoreQueryPrefix:t.ignoreQueryPrefix===!0,interpretNumericEntities:typeof t.interpretNumericEntities=="boolean"?t.interpretNumericEntities:or.interpretNumericEntities,parameterLimit:typeof t.parameterLimit=="number"?t.parameterLimit:or.parameterLimit,parseArrays:t.parseArrays!==!1,plainObjects:typeof t.plainObjects=="boolean"?t.plainObjects:or.plainObjects,strictDepth:typeof t.strictDepth=="boolean"?!!t.strictDepth:or.strictDepth,strictMerge:typeof t.strictMerge=="boolean"?!!t.strictMerge:or.strictMerge,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:or.strictNullHandling,throwOnLimitExceeded:typeof t.throwOnLimitExceeded=="boolean"?t.throwOnLimitExceeded:!1}};O4.exports=function(n,t){var o=iDe(t);if(n===""||n===null||typeof n>"u")return o.plainObjects?{__proto__:null}:{};for(var i=typeof n=="string"?ADe(n,o):n,e=o.plainObjects?{__proto__:null}:{},a=Object.keys(i),A=0;A{"use strict";var oDe=w4(),nDe=b4(),sDe=ky();M4.exports={formats:sDe,parse:nDe,stringify:oDe}});var N4=$((igA,T4)=>{function gDe(n){return n}T4.exports=gDe});var h8=$((vC,gd)=>{var cDe=200,IDe="Expected a function",AN="__lodash_hash_undefined__",jy=1,cd=2,K4=1/0,x4=9007199254740991,Ly="[object Arguments]",J0="[object Array]",Y4="[object Boolean]",j4="[object Date]",J4="[object Error]",q4="[object Function]",lDe="[object GeneratorFunction]",Uy="[object Map]",z4="[object Number]",sd="[object Object]",R4="[object Promise]",V4="[object RegExp]",Hy="[object Set]",W4="[object String]",Z4="[object Symbol]",q0="[object WeakMap]",X4="[object ArrayBuffer]",Ky="[object DataView]",pDe="[object Float32Array]",dDe="[object Float64Array]",hDe="[object Int8Array]",EDe="[object Int16Array]",CDe="[object Int32Array]",uDe="[object Uint8Array]",BDe="[object Uint8ClampedArray]",fDe="[object Uint16Array]",QDe="[object Uint32Array]",yDe=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,mDe=/^\w*$/,SDe=/^\./,wDe=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,DDe=/[\\^$.*+?()[\]{}|]/g,ODe=/\\(\\)?/g,bDe=/^\[object .+?Constructor\]$/,MDe=/^(?:0|[1-9]\d*)$/,xt={};xt[pDe]=xt[dDe]=xt[hDe]=xt[EDe]=xt[CDe]=xt[uDe]=xt[BDe]=xt[fDe]=xt[QDe]=!0;xt[Ly]=xt[J0]=xt[X4]=xt[Y4]=xt[Ky]=xt[j4]=xt[J4]=xt[q4]=xt[Uy]=xt[z4]=xt[sd]=xt[V4]=xt[Hy]=xt[W4]=xt[q0]=!1;var $4=typeof global=="object"&&global&&global.Object===Object&&global,_De=typeof self=="object"&&self&&self.Object===Object&&self,Cc=$4||_De||Function("return this")(),e8=typeof vC=="object"&&vC&&!vC.nodeType&&vC,k4=e8&&typeof gd=="object"&&gd&&!gd.nodeType&&gd,TDe=k4&&k4.exports===e8,v4=TDe&&$4.process,P4=(function(){try{return v4&&v4.binding("util")}catch{}})(),G4=P4&&P4.isTypedArray;function A8(n,t){for(var o=-1,i=t.length,e=n.length;++o-1}function oOe(n,t){var o=this.__data__,i=qy(o,n);return i<0?o.push([n,t]):o[i][1]=t,this}Ig.prototype.clear=tOe;Ig.prototype.delete=rOe;Ig.prototype.get=aOe;Ig.prototype.has=iOe;Ig.prototype.set=oOe;function lg(n){var t=-1,o=n?n.length:0;for(this.clear();++tr))return!1;var g=a.get(n);if(g&&a.get(t))return g==t;var c=-1,I=!0,d=e&jy?new Yy:void 0;for(a.set(n,t),a.set(t,n);++c-1&&n%1==0&&n-1&&n%1==0&&n<=x4}function FC(n){var t=typeof n;return!!n&&(t=="object"||t=="function")}function Zy(n){return!!n&&typeof n=="object"}function nN(n){return typeof n=="symbol"||Zy(n)&&Id.call(n)==Z4}var JOe=G4?vDe(G4):wOe;function qOe(n){return n==null?"":ROe(n)}function zOe(n,t,o){var i=n==null?void 0:a8(n,t);return i===void 0?o:i}function VOe(n,t){return n!=null&&UOe(n,t,QOe)}function eN(n){return iN(n)?r8(n):OOe(n)}function WOe(n){return iN(n)?r8(n,!0):bOe(n)}function ZOe(n,t){return n==null?{}:TOe(n,POe(n),DOe(t))}function XOe(n){return n}function $Oe(n){return Vy(n)?RDe(Wy(n)):NOe(n)}function d8(){return[]}gd.exports=ZOe});var Y8=$((LC,pd)=>{var ebe=200,w8="__lodash_hash_undefined__",Abe=800,tbe=16,D8=9007199254740991,O8="[object Arguments]",rbe="[object Array]",abe="[object AsyncFunction]",ibe="[object Boolean]",obe="[object Date]",nbe="[object Error]",b8="[object Function]",sbe="[object GeneratorFunction]",gbe="[object Map]",cbe="[object Number]",Ibe="[object Null]",M8="[object Object]",lbe="[object Proxy]",pbe="[object RegExp]",dbe="[object Set]",hbe="[object String]",Ebe="[object Undefined]",Cbe="[object WeakMap]",ube="[object ArrayBuffer]",Bbe="[object DataView]",fbe="[object Float32Array]",Qbe="[object Float64Array]",ybe="[object Int8Array]",mbe="[object Int16Array]",Sbe="[object Int32Array]",wbe="[object Uint8Array]",Dbe="[object Uint8ClampedArray]",Obe="[object Uint16Array]",bbe="[object Uint32Array]",Mbe=/[\\^$.*+?()[\]{}|]/g,_be=/^\[object .+?Constructor\]$/,Tbe=/^(?:0|[1-9]\d*)$/,Yt={};Yt[fbe]=Yt[Qbe]=Yt[ybe]=Yt[mbe]=Yt[Sbe]=Yt[wbe]=Yt[Dbe]=Yt[Obe]=Yt[bbe]=!0;Yt[O8]=Yt[rbe]=Yt[ube]=Yt[ibe]=Yt[Bbe]=Yt[obe]=Yt[nbe]=Yt[b8]=Yt[gbe]=Yt[cbe]=Yt[M8]=Yt[pbe]=Yt[dbe]=Yt[hbe]=Yt[Cbe]=!1;var _8=typeof global=="object"&&global&&global.Object===Object&&global,Nbe=typeof self=="object"&&self&&self.Object===Object&&self,KC=_8||Nbe||Function("return this")(),T8=typeof LC=="object"&&LC&&!LC.nodeType&&LC,UC=T8&&typeof pd=="object"&&pd&&!pd.nodeType&&pd,N8=UC&&UC.exports===T8,sN=N8&&_8.process,E8=(function(){try{var n=UC&&UC.require&&UC.require("util").types;return n||sN&&sN.binding&&sN.binding("util")}catch{}})(),C8=E8&&E8.isTypedArray;function Rbe(n,t,o){switch(o.length){case 0:return n.call(t);case 1:return n.call(t,o[0]);case 2:return n.call(t,o[0],o[1]);case 3:return n.call(t,o[0],o[1],o[2])}return n.apply(t,o)}function kbe(n,t){for(var o=-1,i=Array(n);++o-1}function tMe(n,t){var o=this.__data__,i=tm(o,n);return i<0?(++this.size,o.push([n,t])):o[i][1]=t,this}dg.prototype.clear=Xbe;dg.prototype.delete=$be;dg.prototype.get=eMe;dg.prototype.has=AMe;dg.prototype.set=tMe;function dd(n){var t=-1,o=n==null?0:n.length;for(this.clear();++t1?o[e-1]:void 0,A=e>2?o[2]:void 0;for(a=n.length>3&&typeof a=="function"?(e--,a):void 0,A&&TMe(o[0],o[1],A)&&(a=e<3?void 0:a,e=1),t=Object(t);++i-1&&n%1==0&&n0){if(++t>=Abe)return arguments[0]}else t=0;return n.apply(void 0,arguments)}}function LMe(n){if(n!=null){try{return Am.call(n)}catch{}try{return n+""}catch{}}return""}function im(n,t){return n===t||n!==n&&t!==t}var lN=S8((function(){return arguments})())?S8:function(n){return xC(n)&&pg.call(n,"callee")&&!Kbe.call(n,"callee")},pN=Array.isArray;function EN(n){return n!=null&&U8(n.length)&&!CN(n)}function UMe(n){return xC(n)&&EN(n)}var L8=Ybe||jMe;function CN(n){if(!ZI(n))return!1;var t=rm(n);return t==b8||t==sbe||t==abe||t==lbe}function U8(n){return typeof n=="number"&&n>-1&&n%1==0&&n<=D8}function ZI(n){var t=typeof n;return n!=null&&(t=="object"||t=="function")}function xC(n){return n!=null&&typeof n=="object"}function HMe(n){if(!xC(n)||rm(n)!=M8)return!1;var t=k8(n);if(t===null)return!0;var o=pg.call(t,"constructor")&&t.constructor;return typeof o=="function"&&o instanceof o&&Am.call(o)==Ube}var H8=C8?vbe(C8):CMe;function KMe(n){return DMe(n,K8(n))}function K8(n){return EN(n)?pMe(n,!0):uMe(n)}var xMe=OMe(function(n,t,o){P8(n,t,o)});function YMe(n){return function(){return n}}function x8(n){return n}function jMe(){return!1}pd.exports=xMe});var hg=$((ogA,q8)=>{"use strict";var j8=["nodebuffer","arraybuffer","fragments"],J8=typeof Blob<"u";J8&&j8.push("blob");q8.exports={BINARY_TYPES:j8,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:J8,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var YC=$((ngA,om)=>{"use strict";var{EMPTY_BUFFER:JMe}=hg(),uN=Buffer[Symbol.species];function qMe(n,t){if(n.length===0)return JMe;if(n.length===1)return n[0];let o=Buffer.allocUnsafe(t),i=0;for(let e=0;e{"use strict";var W8=Symbol("kDone"),fN=Symbol("kRun"),QN=class{constructor(t){this[W8]=()=>{this.pending--,this[fN]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[fN]()}[fN](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[W8])}}};Z8.exports=QN});var ud=$((ggA,tz)=>{"use strict";var jC=$e("zlib"),$8=YC(),VMe=X8(),{kStatusCode:ez}=hg(),WMe=Buffer[Symbol.species],ZMe=Buffer.from([0,0,255,255]),sm=Symbol("permessage-deflate"),Eg=Symbol("total-length"),Ed=Symbol("callback"),uc=Symbol("buffers"),Cd=Symbol("error"),nm,yN=class{constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!nm){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;nm=new VMe(o)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[Ed];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let o=this._options,i=t.find(e=>!(o.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(o.serverMaxWindowBits===!1||typeof o.serverMaxWindowBits=="number"&&o.serverMaxWindowBits>e.server_max_window_bits)||typeof o.clientMaxWindowBits=="number"&&(typeof e.client_max_window_bits=="number"?o.clientMaxWindowBits>e.client_max_window_bits:!e.client_max_window_bits)));if(!i)throw new Error("None of the extension offers can be accepted");return o.serverNoContextTakeover&&(i.server_no_context_takeover=!0),o.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof o.serverMaxWindowBits=="number"&&(i.server_max_window_bits=o.serverMaxWindowBits),typeof o.clientMaxWindowBits=="number"?i.client_max_window_bits=o.clientMaxWindowBits:(i.client_max_window_bits===!0||o.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(t){let o=t[0];if(this._options.clientNoContextTakeover===!1&&o.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!o.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(o.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&o.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return o}normalizeParams(t){return t.forEach(o=>{Object.keys(o).forEach(i=>{let e=o[i];if(e.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(e=e[0],i==="client_max_window_bits"){if(e!==!0){let a=+e;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${e}`);e=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${e}`)}else if(i==="server_max_window_bits"){let a=+e;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${e}`);e=a}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(e!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${e}`)}else throw new Error(`Unknown parameter "${i}"`);o[i]=e})}),t}decompress(t,o,i){nm.add(e=>{this._decompress(t,o,(a,A)=>{e(),i(a,A)})})}compress(t,o,i){nm.add(e=>{this._compress(t,o,(a,A)=>{e(),i(a,A)})})}_decompress(t,o,i){let e=this._isServer?"client":"server";if(!this._inflate){let a=`${e}_max_window_bits`,A=typeof this.params[a]!="number"?jC.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=jC.createInflateRaw({...this._options.zlibInflateOptions,windowBits:A}),this._inflate[sm]=this,this._inflate[Eg]=0,this._inflate[uc]=[],this._inflate.on("error",$Me),this._inflate.on("data",Az)}this._inflate[Ed]=i,this._inflate.write(t),o&&this._inflate.write(ZMe),this._inflate.flush(()=>{let a=this._inflate[Cd];if(a){this._inflate.close(),this._inflate=null,i(a);return}let A=$8.concat(this._inflate[uc],this._inflate[Eg]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Eg]=0,this._inflate[uc]=[],o&&this.params[`${e}_no_context_takeover`]&&this._inflate.reset()),i(null,A)})}_compress(t,o,i){let e=this._isServer?"server":"client";if(!this._deflate){let a=`${e}_max_window_bits`,A=typeof this.params[a]!="number"?jC.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=jC.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:A}),this._deflate[Eg]=0,this._deflate[uc]=[],this._deflate.on("data",XMe)}this._deflate[Ed]=i,this._deflate.write(t),this._deflate.flush(jC.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=$8.concat(this._deflate[uc],this._deflate[Eg]);o&&(a=new WMe(a.buffer,a.byteOffset,a.length-4)),this._deflate[Ed]=null,this._deflate[Eg]=0,this._deflate[uc]=[],o&&this.params[`${e}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};tz.exports=yN;function XMe(n){this[uc].push(n),this[Eg]+=n.length}function Az(n){if(this[Eg]+=n.length,this[sm]._maxPayload<1||this[Eg]<=this[sm]._maxPayload){this[uc].push(n);return}this[Cd]=new RangeError("Max payload size exceeded"),this[Cd].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Cd][ez]=1009,this.removeListener("data",Az),this.reset()}function $Me(n){if(this[sm]._inflate=null,this[Cd]){this[Ed](this[Cd]);return}n[ez]=1007,this[Ed](n)}});var Bd=$((cgA,gm)=>{"use strict";var{isUtf8:rz}=$e("buffer"),{hasBlob:e_e}=hg(),A_e=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function t_e(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function mN(n){let t=n.length,o=0;for(;o=t||(n[o+1]&192)!==128||(n[o+2]&192)!==128||n[o]===224&&(n[o+1]&224)===128||n[o]===237&&(n[o+1]&224)===160)return!1;o+=3}else if((n[o]&248)===240){if(o+3>=t||(n[o+1]&192)!==128||(n[o+2]&192)!==128||(n[o+3]&192)!==128||n[o]===240&&(n[o+1]&240)===128||n[o]===244&&n[o+1]>143||n[o]>244)return!1;o+=4}else return!1;return!0}function r_e(n){return e_e&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}gm.exports={isBlob:r_e,isValidStatusCode:t_e,isValidUTF8:mN,tokenChars:A_e};if(rz)gm.exports.isValidUTF8=function(n){return n.length<24?mN(n):rz(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=$e("utf-8-validate");gm.exports.isValidUTF8=function(t){return t.length<32?mN(t):n(t)}}catch{}});var bN=$((IgA,cz)=>{"use strict";var{Writable:a_e}=$e("stream"),az=ud(),{BINARY_TYPES:i_e,EMPTY_BUFFER:iz,kStatusCode:o_e,kWebSocket:n_e}=hg(),{concat:SN,toArrayBuffer:s_e,unmask:g_e}=YC(),{isValidStatusCode:c_e,isValidUTF8:oz}=Bd(),cm=Buffer[Symbol.species],To=0,nz=1,sz=2,gz=3,wN=4,DN=5,Im=6,ON=class extends a_e{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||i_e[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[n_e]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=To}_write(t,o,i){if(this._opcode===8&&this._state==To)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(i)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t=i.length?o.set(this._buffers.shift(),e):(o.set(new Uint8Array(i.buffer,i.byteOffset,t),e),this._buffers[0]=new cm(i.buffer,i.byteOffset+t,i.length-t)),t-=i.length}while(t>0);return o}startLoop(t){this._loop=!0;do switch(this._state){case To:this.getInfo(t);break;case nz:this.getPayloadLength16(t);break;case sz:this.getPayloadLength64(t);break;case gz:this.getMask();break;case wN:this.getData(t);break;case DN:case Im:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let o=this.consume(2);if((o[0]&48)!==0){let e=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(e);return}let i=(o[0]&64)===64;if(i&&!this._extensions[az.extensionName]){let e=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(e);return}if(this._fin=(o[0]&128)===128,this._opcode=o[0]&15,this._payloadLength=o[1]&127,this._opcode===0){if(i){let e=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(e);return}if(!this._fragmented){let e=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(e);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let e=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(e);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let e=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(e);return}if(i){let e=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(e);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let e=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(e);return}}else{let e=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(e);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(o[1]&128)===128,this._isServer){if(!this._masked){let e=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(e);return}}else if(this._masked){let e=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(e);return}this._payloadLength===126?this._state=nz:this._payloadLength===127?this._state=sz:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let o=this.consume(8),i=o.readUInt32BE(0);if(i>Math.pow(2,21)-1){let e=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(e);return}this._payloadLength=i*Math.pow(2,32)+o.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._masked?this._state=gz:this._state=wN}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=wN}getData(t){let o=iz;if(this._payloadLength){if(this._bufferedBytes7){this.controlMessage(o,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(i);return}if(this._compressed){this._state=DN,this.decompress(o,t);return}o.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(o)),this.dataMessage(t)}decompress(t,o){this._extensions[az.extensionName].decompress(t,this._fin,(e,a)=>{if(e)return o(e);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let A=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");o(A);return}this._fragments.push(a)}this.dataMessage(o),this._state===To&&this.startLoop(o)})}dataMessage(t){if(!this._fin){this._state=To;return}let o=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let e;this._binaryType==="nodebuffer"?e=SN(i,o):this._binaryType==="arraybuffer"?e=s_e(SN(i,o)):this._binaryType==="blob"?e=new Blob(i):e=i,this._allowSynchronousEvents?(this.emit("message",e,!0),this._state=To):(this._state=Im,setImmediate(()=>{this.emit("message",e,!0),this._state=To,this.startLoop(t)}))}else{let e=SN(i,o);if(!this._skipUTF8Validation&&!oz(e)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(a);return}this._state===DN||this._allowSynchronousEvents?(this.emit("message",e,!1),this._state=To):(this._state=Im,setImmediate(()=>{this.emit("message",e,!1),this._state=To,this.startLoop(t)}))}}controlMessage(t,o){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,iz),this.end();else{let i=t.readUInt16BE(0);if(!c_e(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");o(a);return}let e=new cm(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!oz(e)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");o(a);return}this._loop=!1,this.emit("conclude",i,e),this.end()}this._state=To;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=To):(this._state=Im,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=To,this.startLoop(o)}))}createError(t,o,i,e,a){this._loop=!1,this._errored=!0;let A=new t(i?`Invalid WebSocket frame: ${o}`:o);return Error.captureStackTrace(A,this.createError),A.code=a,A[o_e]=e,A}};cz.exports=ON});var TN=$((pgA,pz)=>{"use strict";var{Duplex:lgA}=$e("stream"),{randomFillSync:I_e}=$e("crypto"),{types:{isUint8Array:l_e}}=$e("util"),Iz=ud(),{EMPTY_BUFFER:p_e,kWebSocket:d_e,NOOP:h_e}=hg(),{isBlob:fd,isValidStatusCode:E_e}=Bd(),{mask:lz,toBuffer:XI}=YC(),No=Symbol("kByteLength"),C_e=Buffer.alloc(4),lm=8*1024,$I,Qd=lm,Bn=0,u_e=1,B_e=2,MN=class n{constructor(t,o,i){this._extensions=o||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Bn,this.onerror=h_e,this[d_e]=void 0}static frame(t,o){let i,e=!1,a=2,A=!1;o.mask&&(i=o.maskBuffer||C_e,o.generateMask?o.generateMask(i):(Qd===lm&&($I===void 0&&($I=Buffer.alloc(lm)),I_e($I,0,lm),Qd=0),i[0]=$I[Qd++],i[1]=$I[Qd++],i[2]=$I[Qd++],i[3]=$I[Qd++]),A=(i[0]|i[1]|i[2]|i[3])===0,a=6);let r;typeof t=="string"?(!o.mask||A)&&o[No]!==void 0?r=o[No]:(t=Buffer.from(t),r=t.length):(r=t.length,e=o.mask&&o.readOnly&&!A);let s=r;r>=65536?(a+=8,s=127):r>125&&(a+=2,s=126);let g=Buffer.allocUnsafe(e?r+a:a);return g[0]=o.fin?o.opcode|128:o.opcode,o.rsv1&&(g[0]|=64),g[1]=s,s===126?g.writeUInt16BE(r,2):s===127&&(g[2]=g[3]=0,g.writeUIntBE(r,4,6)),o.mask?(g[1]|=128,g[a-4]=i[0],g[a-3]=i[1],g[a-2]=i[2],g[a-1]=i[3],A?[g,t]:e?(lz(t,i,g,a,r),[g]):(lz(t,i,t,0,r),[g,t])):[g,t]}close(t,o,i,e){let a;if(t===void 0)a=p_e;else{if(typeof t!="number"||!E_e(t))throw new TypeError("First argument must be a valid error code number");if(o===void 0||!o.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let r=Buffer.byteLength(o);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");if(a=Buffer.allocUnsafe(2+r),a.writeUInt16BE(t,0),typeof o=="string")a.write(o,2);else if(l_e(o))a.set(o,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let A={[No]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Bn?this.enqueue([this.dispatch,a,!1,A,e]):this.sendFrame(n.frame(a,A),e)}ping(t,o,i){let e,a;if(typeof t=="string"?(e=Buffer.byteLength(t),a=!1):fd(t)?(e=t.size,a=!1):(t=XI(t),e=t.length,a=XI.readOnly),e>125)throw new RangeError("The data size must not be greater than 125 bytes");let A={[No]:e,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};fd(t)?this._state!==Bn?this.enqueue([this.getBlobData,t,!1,A,i]):this.getBlobData(t,!1,A,i):this._state!==Bn?this.enqueue([this.dispatch,t,!1,A,i]):this.sendFrame(n.frame(t,A),i)}pong(t,o,i){let e,a;if(typeof t=="string"?(e=Buffer.byteLength(t),a=!1):fd(t)?(e=t.size,a=!1):(t=XI(t),e=t.length,a=XI.readOnly),e>125)throw new RangeError("The data size must not be greater than 125 bytes");let A={[No]:e,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};fd(t)?this._state!==Bn?this.enqueue([this.getBlobData,t,!1,A,i]):this.getBlobData(t,!1,A,i):this._state!==Bn?this.enqueue([this.dispatch,t,!1,A,i]):this.sendFrame(n.frame(t,A),i)}send(t,o,i){let e=this._extensions[Iz.extensionName],a=o.binary?2:1,A=o.compress,r,s;typeof t=="string"?(r=Buffer.byteLength(t),s=!1):fd(t)?(r=t.size,s=!1):(t=XI(t),r=t.length,s=XI.readOnly),this._firstFragment?(this._firstFragment=!1,A&&e&&e.params[e._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(A=r>=e._threshold),this._compress=A):(A=!1,a=0),o.fin&&(this._firstFragment=!0);let g={[No]:r,fin:o.fin,generateMask:this._generateMask,mask:o.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:s,rsv1:A};fd(t)?this._state!==Bn?this.enqueue([this.getBlobData,t,this._compress,g,i]):this.getBlobData(t,this._compress,g,i):this._state!==Bn?this.enqueue([this.dispatch,t,this._compress,g,i]):this.dispatch(t,this._compress,g,i)}getBlobData(t,o,i,e){this._bufferedBytes+=i[No],this._state=B_e,t.arrayBuffer().then(a=>{if(this._socket.destroyed){let r=new Error("The socket was closed while the blob was being read");process.nextTick(_N,this,r,e);return}this._bufferedBytes-=i[No];let A=XI(a);o?this.dispatch(A,o,i,e):(this._state=Bn,this.sendFrame(n.frame(A,i),e),this.dequeue())}).catch(a=>{process.nextTick(f_e,this,a,e)})}dispatch(t,o,i,e){if(!o){this.sendFrame(n.frame(t,i),e);return}let a=this._extensions[Iz.extensionName];this._bufferedBytes+=i[No],this._state=u_e,a.compress(t,i.fin,(A,r)=>{if(this._socket.destroyed){let s=new Error("The socket was closed while data was being compressed");_N(this,s,e);return}this._bufferedBytes-=i[No],this._state=Bn,i.readOnly=!1,this.sendFrame(n.frame(r,i),e),this.dequeue()})}dequeue(){for(;this._state===Bn&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][No],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][No],this._queue.push(t)}sendFrame(t,o){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],o),this._socket.uncork()):this._socket.write(t[0],o)}};pz.exports=MN;function _N(n,t,o){typeof o=="function"&&o(t);for(let i=0;i{"use strict";var{kForOnEventAttribute:JC,kListener:NN}=hg(),dz=Symbol("kCode"),hz=Symbol("kData"),Ez=Symbol("kError"),Cz=Symbol("kMessage"),uz=Symbol("kReason"),yd=Symbol("kTarget"),Bz=Symbol("kType"),fz=Symbol("kWasClean"),Cg=class{constructor(t){this[yd]=null,this[Bz]=t}get target(){return this[yd]}get type(){return this[Bz]}};Object.defineProperty(Cg.prototype,"target",{enumerable:!0});Object.defineProperty(Cg.prototype,"type",{enumerable:!0});var el=class extends Cg{constructor(t,o={}){super(t),this[dz]=o.code===void 0?0:o.code,this[uz]=o.reason===void 0?"":o.reason,this[fz]=o.wasClean===void 0?!1:o.wasClean}get code(){return this[dz]}get reason(){return this[uz]}get wasClean(){return this[fz]}};Object.defineProperty(el.prototype,"code",{enumerable:!0});Object.defineProperty(el.prototype,"reason",{enumerable:!0});Object.defineProperty(el.prototype,"wasClean",{enumerable:!0});var md=class extends Cg{constructor(t,o={}){super(t),this[Ez]=o.error===void 0?null:o.error,this[Cz]=o.message===void 0?"":o.message}get error(){return this[Ez]}get message(){return this[Cz]}};Object.defineProperty(md.prototype,"error",{enumerable:!0});Object.defineProperty(md.prototype,"message",{enumerable:!0});var qC=class extends Cg{constructor(t,o={}){super(t),this[hz]=o.data===void 0?null:o.data}get data(){return this[hz]}};Object.defineProperty(qC.prototype,"data",{enumerable:!0});var Q_e={addEventListener(n,t,o={}){for(let e of this.listeners(n))if(!o[JC]&&e[NN]===t&&!e[JC])return;let i;if(n==="message")i=function(a,A){let r=new qC("message",{data:A?a:a.toString()});r[yd]=this,pm(t,this,r)};else if(n==="close")i=function(a,A){let r=new el("close",{code:a,reason:A.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[yd]=this,pm(t,this,r)};else if(n==="error")i=function(a){let A=new md("error",{error:a,message:a.message});A[yd]=this,pm(t,this,A)};else if(n==="open")i=function(){let a=new Cg("open");a[yd]=this,pm(t,this,a)};else return;i[JC]=!!o[JC],i[NN]=t,o.once?this.once(n,i):this.on(n,i)},removeEventListener(n,t){for(let o of this.listeners(n))if(o[NN]===t&&!o[JC]){this.removeListener(n,o);break}}};Qz.exports={CloseEvent:el,ErrorEvent:md,Event:Cg,EventTarget:Q_e,MessageEvent:qC};function pm(n,t,o){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,o):n.call(t,o)}});var dm=$((hgA,mz)=>{"use strict";var{tokenChars:zC}=Bd();function ss(n,t,o){n[t]===void 0?n[t]=[o]:n[t].push(o)}function y_e(n){let t=Object.create(null),o=Object.create(null),i=!1,e=!1,a=!1,A,r,s=-1,g=-1,c=-1,I=0;for(;I{let o=n[t];return Array.isArray(o)||(o=[o]),o.map(i=>[t].concat(Object.keys(i).map(e=>{let a=i[e];return Array.isArray(a)||(a=[a]),a.map(A=>A===!0?e:`${e}=${A}`).join("; ")})).join("; ")).join(", ")}).join(", ")}mz.exports={format:m_e,parse:y_e}});var um=$((ugA,vz)=>{"use strict";var S_e=$e("events"),w_e=$e("https"),D_e=$e("http"),Dz=$e("net"),O_e=$e("tls"),{randomBytes:b_e,createHash:M_e}=$e("crypto"),{Duplex:EgA,Readable:CgA}=$e("stream"),{URL:RN}=$e("url"),Bc=ud(),__e=bN(),T_e=TN(),{isBlob:N_e}=Bd(),{BINARY_TYPES:Sz,CLOSE_TIMEOUT:R_e,EMPTY_BUFFER:hm,GUID:k_e,kForOnEventAttribute:kN,kListener:v_e,kStatusCode:P_e,kWebSocket:ia,NOOP:Oz}=hg(),{EventTarget:{addEventListener:G_e,removeEventListener:F_e}}=yz(),{format:L_e,parse:U_e}=dm(),{toBuffer:H_e}=YC(),bz=Symbol("kAborted"),vN=[8,13],ug=["CONNECTING","OPEN","CLOSING","CLOSED"],K_e=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Xt=class n extends S_e{constructor(t,o,i){super(),this._binaryType=Sz[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=hm,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,o===void 0?o=[]:Array.isArray(o)||(typeof o=="object"&&o!==null?(i=o,o=[]):o=[o]),Mz(this,t,o,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){Sz.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,o,i){let e=new __e({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new T_e(t,this._extensions,i.generateMask);this._receiver=e,this._sender=a,this._socket=t,e[ia]=this,a[ia]=this,t[ia]=this,e.on("conclude",j_e),e.on("drain",J_e),e.on("error",q_e),e.on("message",z_e),e.on("ping",V_e),e.on("pong",W_e),a.onerror=Z_e,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),o.length>0&&t.unshift(o),t.on("close",Nz),t.on("data",Cm),t.on("end",Rz),t.on("error",kz),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Bc.extensionName]&&this._extensions[Bc.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,o){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){eo(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(t,o,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Tz(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,o,i){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(i=t,t=o=void 0):typeof o=="function"&&(i=o,o=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){PN(this,t,i);return}o===void 0&&(o=!this._isServer),this._sender.ping(t||hm,o,i)}pong(t,o,i){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(i=t,t=o=void 0):typeof o=="function"&&(i=o,o=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){PN(this,t,i);return}o===void 0&&(o=!this._isServer),this._sender.pong(t||hm,o,i)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,o,i){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof o=="function"&&(i=o,o={}),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){PN(this,t,i);return}let e={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...o};this._extensions[Bc.extensionName]||(e.compress=!1),this._sender.send(t||hm,e,i)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){eo(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(Xt,"CONNECTING",{enumerable:!0,value:ug.indexOf("CONNECTING")});Object.defineProperty(Xt.prototype,"CONNECTING",{enumerable:!0,value:ug.indexOf("CONNECTING")});Object.defineProperty(Xt,"OPEN",{enumerable:!0,value:ug.indexOf("OPEN")});Object.defineProperty(Xt.prototype,"OPEN",{enumerable:!0,value:ug.indexOf("OPEN")});Object.defineProperty(Xt,"CLOSING",{enumerable:!0,value:ug.indexOf("CLOSING")});Object.defineProperty(Xt.prototype,"CLOSING",{enumerable:!0,value:ug.indexOf("CLOSING")});Object.defineProperty(Xt,"CLOSED",{enumerable:!0,value:ug.indexOf("CLOSED")});Object.defineProperty(Xt.prototype,"CLOSED",{enumerable:!0,value:ug.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(Xt.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(Xt.prototype,`on${n}`,{enumerable:!0,get(){for(let t of this.listeners(n))if(t[kN])return t[v_e];return null},set(t){for(let o of this.listeners(n))if(o[kN]){this.removeListener(n,o);break}typeof t=="function"&&this.addEventListener(n,t,{[kN]:!0})}})});Xt.prototype.addEventListener=G_e;Xt.prototype.removeEventListener=F_e;vz.exports=Xt;function Mz(n,t,o,i){let e={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:R_e,protocolVersion:vN[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=e.autoPong,n._closeTimeout=e.closeTimeout,!vN.includes(e.protocolVersion))throw new RangeError(`Unsupported protocol version: ${e.protocolVersion} (supported versions: ${vN.join(", ")})`);let a;if(t instanceof RN)a=t;else try{a=new RN(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),n._url=a.href;let A=a.protocol==="wss:",r=a.protocol==="ws+unix:",s;if(a.protocol!=="ws:"&&!A&&!r?s=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:r&&!a.pathname?s="The URL's pathname is empty":a.hash&&(s="The URL contains a fragment identifier"),s){let Q=new SyntaxError(s);if(n._redirects===0)throw Q;Em(n,Q);return}let g=A?443:80,c=b_e(16).toString("base64"),I=A?w_e.request:D_e.request,d=new Set,B;if(e.createConnection=e.createConnection||(A?Y_e:x_e),e.defaultPort=e.defaultPort||g,e.port=a.port||g,e.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,e.headers={...e.headers,"Sec-WebSocket-Version":e.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},e.path=a.pathname+a.search,e.timeout=e.handshakeTimeout,e.perMessageDeflate&&(B=new Bc({...e.perMessageDeflate,isServer:!1,maxPayload:e.maxPayload}),e.headers["Sec-WebSocket-Extensions"]=L_e({[Bc.extensionName]:B.offer()})),o.length){for(let Q of o){if(typeof Q!="string"||!K_e.test(Q)||d.has(Q))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(Q)}e.headers["Sec-WebSocket-Protocol"]=o.join(",")}if(e.origin&&(e.protocolVersion<13?e.headers["Sec-WebSocket-Origin"]=e.origin:e.headers.Origin=e.origin),(a.username||a.password)&&(e.auth=`${a.username}:${a.password}`),r){let Q=e.path.split(":");e.socketPath=Q[0],e.path=Q[1]}let f;if(e.followRedirects){if(n._redirects===0){n._originalIpc=r,n._originalSecure=A,n._originalHostOrSocketPath=r?e.socketPath:a.host;let Q=i&&i.headers;if(i={...i,headers:{}},Q)for(let[y,m]of Object.entries(Q))i.headers[y.toLowerCase()]=m}else if(n.listenerCount("redirect")===0){let Q=r?n._originalIpc?e.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:a.host===n._originalHostOrSocketPath;(!Q||n._originalSecure&&!A)&&(delete e.headers.authorization,delete e.headers.cookie,Q||delete e.headers.host,e.auth=void 0)}e.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(e.auth).toString("base64")),f=n._req=I(e),n._redirects&&n.emit("redirect",n.url,f)}else f=n._req=I(e);e.timeout&&f.on("timeout",()=>{eo(n,f,"Opening handshake has timed out")}),f.on("error",Q=>{f===null||f[bz]||(f=n._req=null,Em(n,Q))}),f.on("response",Q=>{let y=Q.headers.location,m=Q.statusCode;if(y&&e.followRedirects&&m>=300&&m<400){if(++n._redirects>e.maxRedirects){eo(n,f,"Maximum redirects exceeded");return}f.abort();let _;try{_=new RN(y,t)}catch{let R=new SyntaxError(`Invalid URL: ${y}`);Em(n,R);return}Mz(n,_,o,i)}else n.emit("unexpected-response",f,Q)||eo(n,f,`Unexpected server response: ${Q.statusCode}`)}),f.on("upgrade",(Q,y,m)=>{if(n.emit("upgrade",Q),n.readyState!==Xt.CONNECTING)return;f=n._req=null;let _=Q.headers.upgrade;if(_===void 0||_.toLowerCase()!=="websocket"){eo(n,y,"Invalid Upgrade header");return}let T=M_e("sha1").update(c+k_e).digest("base64");if(Q.headers["sec-websocket-accept"]!==T){eo(n,y,"Invalid Sec-WebSocket-Accept header");return}let R=Q.headers["sec-websocket-protocol"],L;if(R!==void 0?d.size?d.has(R)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":d.size&&(L="Server sent no subprotocol"),L){eo(n,y,L);return}R&&(n._protocol=R);let U=Q.headers["sec-websocket-extensions"];if(U!==void 0){if(!B){eo(n,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let F;try{F=U_e(U)}catch{eo(n,y,"Invalid Sec-WebSocket-Extensions header");return}let q=Object.keys(F);if(q.length!==1||q[0]!==Bc.extensionName){eo(n,y,"Server indicated an extension that was not requested");return}try{B.accept(F[Bc.extensionName])}catch{eo(n,y,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[Bc.extensionName]=B}n.setSocket(y,m,{allowSynchronousEvents:e.allowSynchronousEvents,generateMask:e.generateMask,maxBufferedChunks:e.maxBufferedChunks,maxFragments:e.maxFragments,maxPayload:e.maxPayload,skipUTF8Validation:e.skipUTF8Validation})}),e.finishRequest?e.finishRequest(f,n):f.end()}function Em(n,t){n._readyState=Xt.CLOSING,n._errorEmitted=!0,n.emit("error",t),n.emitClose()}function x_e(n){return n.path=n.socketPath,Dz.connect(n)}function Y_e(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=Dz.isIP(n.host)?"":n.host),O_e.connect(n)}function eo(n,t,o){n._readyState=Xt.CLOSING;let i=new Error(o);Error.captureStackTrace(i,eo),t.setHeader?(t[bz]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Em,n,i)):(t.destroy(i),t.once("error",n.emit.bind(n,"error")),t.once("close",n.emitClose.bind(n)))}function PN(n,t,o){if(t){let i=N_e(t)?t.size:H_e(t).length;n._socket?n._sender._bufferedBytes+=i:n._bufferedAmount+=i}if(o){let i=new Error(`WebSocket is not open: readyState ${n.readyState} (${ug[n.readyState]})`);process.nextTick(o,i)}}function j_e(n,t){let o=this[ia];o._closeFrameReceived=!0,o._closeMessage=t,o._closeCode=n,o._socket[ia]!==void 0&&(o._socket.removeListener("data",Cm),process.nextTick(_z,o._socket),n===1005?o.close():o.close(n,t))}function J_e(){let n=this[ia];n.isPaused||n._socket.resume()}function q_e(n){let t=this[ia];t._socket[ia]!==void 0&&(t._socket.removeListener("data",Cm),process.nextTick(_z,t._socket),t.close(n[P_e])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",n))}function wz(){this[ia].emitClose()}function z_e(n,t){this[ia].emit("message",n,t)}function V_e(n){let t=this[ia];t._autoPong&&t.pong(n,!this._isServer,Oz),t.emit("ping",n)}function W_e(n){this[ia].emit("pong",n)}function _z(n){n.resume()}function Z_e(n){let t=this[ia];t.readyState!==Xt.CLOSED&&(t.readyState===Xt.OPEN&&(t._readyState=Xt.CLOSING,Tz(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",n)))}function Tz(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function Nz(){let n=this[ia];if(this.removeListener("close",Nz),this.removeListener("data",Cm),this.removeListener("end",Rz),n._readyState=Xt.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);n._receiver.write(t)}n._receiver.end(),this[ia]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",wz),n._receiver.on("finish",wz))}function Cm(n){this[ia]._receiver.write(n)||this.pause()}function Rz(){let n=this[ia];n._readyState=Xt.CLOSING,n._receiver.end(),this.end()}function kz(){let n=this[ia];this.removeListener("error",kz),this.on("error",Oz),n&&(n._readyState=Xt.CLOSING,this.destroy())}});var Lz=$((fgA,Fz)=>{"use strict";var BgA=um(),{Duplex:X_e}=$e("stream");function Pz(n){n.emit("close")}function $_e(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Gz(n){this.removeListener("error",Gz),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function eTe(n,t){let o=!0,i=new X_e({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(a,A){let r=!A&&i._readableState.objectMode?a.toString():a;i.push(r)||n.pause()}),n.once("error",function(a){i.destroyed||(o=!1,i.destroy(a))}),n.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(e,a){if(n.readyState===n.CLOSED){a(e),process.nextTick(Pz,i);return}let A=!1;n.once("error",function(s){A=!0,a(s)}),n.once("close",function(){A||a(e),process.nextTick(Pz,i)}),o&&n.terminate()},i._final=function(e){if(n.readyState===n.CONNECTING){n.once("open",function(){i._final(e)});return}n._socket!==null&&(n._socket._writableState.finished?(e(),i._readableState.endEmitted&&i.destroy()):(n._socket.once("finish",function(){e()}),n.close()))},i._read=function(){n.isPaused&&n.resume()},i._write=function(e,a,A){if(n.readyState===n.CONNECTING){n.once("open",function(){i._write(e,a,A)});return}n.send(e,A)},i.on("end",$_e),i.on("error",Gz),i}Fz.exports=eTe});var GN=$((QgA,Uz)=>{"use strict";var{tokenChars:ATe}=Bd();function tTe(n){let t=new Set,o=-1,i=-1,e=0;for(e;e{"use strict";var rTe=$e("events"),Bm=$e("http"),{Duplex:ygA}=$e("stream"),{createHash:aTe}=$e("crypto"),Hz=dm(),Al=ud(),iTe=GN(),oTe=um(),{CLOSE_TIMEOUT:nTe,GUID:sTe,kWebSocket:gTe}=hg(),cTe=/^[+/0-9A-Za-z]{22}==$/,Kz=0,xz=1,jz=2,FN=class extends rTe{constructor(t,o){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:nTe,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:oTe,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=Bm.createServer((i,e)=>{let a=Bm.STATUS_CODES[426];e.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),e.end(a)}),this._server.listen(t.port,t.host,t.backlog,o)):t.server&&(this._server=t.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=ITe(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(e,a,A)=>{this.handleUpgrade(e,a,A,i)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=Kz}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===jz){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(VC,this);return}if(t&&this.once("close",t),this._state!==xz)if(this._state=xz,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(VC,this):process.nextTick(VC,this);else{let o=this._server;this._removeListeners(),this._removeListeners=this._server=null,o.close(()=>{VC(this)})}}shouldHandle(t){if(this.options.path){let o=t.url.indexOf("?");if((o!==-1?t.url.slice(0,o):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,o,i,e){o.on("error",Yz);let a=t.headers["sec-websocket-key"],A=t.headers.upgrade,r=+t.headers["sec-websocket-version"];if(t.method!=="GET"){tl(this,t,o,405,"Invalid HTTP method");return}if(A===void 0||A.toLowerCase()!=="websocket"){tl(this,t,o,400,"Invalid Upgrade header");return}if(a===void 0||!cTe.test(a)){tl(this,t,o,400,"Missing or invalid Sec-WebSocket-Key header");return}if(r!==13&&r!==8){tl(this,t,o,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){WC(o,400);return}let s=t.headers["sec-websocket-protocol"],g=new Set;if(s!==void 0)try{g=iTe.parse(s)}catch{tl(this,t,o,400,"Invalid Sec-WebSocket-Protocol header");return}let c=t.headers["sec-websocket-extensions"],I={};if(this.options.perMessageDeflate&&c!==void 0){let d=new Al({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let B=Hz.parse(c);B[Al.extensionName]&&(d.accept(B[Al.extensionName]),I[Al.extensionName]=d)}catch{tl(this,t,o,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let d={origin:t.headers[`${r===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(d,(B,f,Q,y)=>{if(!B)return WC(o,f||401,Q,y);this.completeUpgrade(I,a,g,t,o,i,e)});return}if(!this.options.verifyClient(d))return WC(o,401)}this.completeUpgrade(I,a,g,t,o,i,e)}completeUpgrade(t,o,i,e,a,A,r){if(!a.readable||!a.writable)return a.destroy();if(a[gTe])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Kz)return WC(a,503);let g=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${aTe("sha1").update(o+sTe).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(i.size){let I=this.options.handleProtocols?this.options.handleProtocols(i,e):i.values().next().value;I&&(g.push(`Sec-WebSocket-Protocol: ${I}`),c._protocol=I)}if(t[Al.extensionName]){let I=t[Al.extensionName].params,d=Hz.format({[Al.extensionName]:[I]});g.push(`Sec-WebSocket-Extensions: ${d}`),c._extensions=t}this.emit("headers",g,e),a.write(g.concat(`\r `).join(`\r `)),a.removeListener("error",Yz),c.setSocket(a,A,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(VC,this)})),r(c,e)}};Jz.exports=FN;function ITe(n,t){for(let o of Object.keys(t))n.on(o,t[o]);return function(){for(let i of Object.keys(t))n.removeListener(i,t[i])}}function VC(n){n._state=jz,n.emit("close")}function Yz(){this.destroy()}function WC(n,t,o,i){o=o||Bm.STATUS_CODES[t],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(o),...i},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${t} ${Bm.STATUS_CODES[t]}\r `+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r `)+`\r \r -`+o)}function tl(n,t,o,i,e,a){if(n.listenerCount("wsClientError")){let A=new Error(e);Error.captureStackTrace(A,tl),n.emit("wsClientError",A,o,t)}else WC(o,i,e,a)}});var Wz=$((wgA,Vz)=>{"use strict";Vz.exports=BTe;function BTe(n,t){for(var o=new Array(arguments.length-1),i=0,e=2,a=!0;e{"use strict";var fm=$z;fm.length=function(t){var o=t.length;if(!o)return 0;for(var i=0;--o%4>1&&t.charAt(o)==="=";)++i;return Math.ceil(t.length*3)/4-i};var Sd=new Array(64),Xz=new Array(123);for(fn=0;fn<64;)Xz[Sd[fn]=fn<26?fn+65:fn<52?fn+71:fn<62?fn-4:fn-59|43]=fn++;var fn;fm.encode=function(t,o,i){for(var e=null,a=[],A=0,r=0,s;o>2],s=(g&3)<<4,r=1;break;case 1:a[A++]=Sd[s|g>>4],s=(g&15)<<2,r=2;break;case 2:a[A++]=Sd[s|g>>6],a[A++]=Sd[g&63],r=0;break}A>8191&&((e||(e=[])).push(String.fromCharCode.apply(String,a)),A=0)}return r&&(a[A++]=Sd[s],a[A++]=61,r===1&&(a[A++]=61)),e?(A&&e.push(String.fromCharCode.apply(String,a.slice(0,A))),e.join("")):String.fromCharCode.apply(String,a.slice(0,A))};var Zz="invalid encoding";fm.decode=function(t,o,i){for(var e=i,a=0,A,r=0;r1)break;if((s=Xz[s])===void 0)throw Error(Zz);switch(a){case 0:A=s,a=1;break;case 1:o[i++]=A<<2|(s&48)>>4,A=s,a=2;break;case 2:o[i++]=(A&15)<<4|(s&60)>>2,A=s,a=3;break;case 3:o[i++]=(A&3)<<6|s,a=0;break}}if(a===1)throw Error(Zz);return i-e};fm.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}});var tV=$((OgA,AV)=>{"use strict";AV.exports=Qm;function Qm(){this._listeners=Object.create(null)}Qm.prototype.on=function(t,o,i){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:o,ctx:i||this}),this};Qm.prototype.off=function(t,o){if(t===void 0)this._listeners=Object.create(null);else if(o===void 0)this._listeners[t]=[];else{var i=this._listeners[t];if(!i)return this;for(var e=0;e{"use strict";sV.exports=rV(rV);function rV(n){return typeof Float32Array<"u"?(function(){var t=new Float32Array([-0]),o=new Uint8Array(t.buffer),i=o[3]===128;function e(s,g,c){t[0]=s,g[c]=o[0],g[c+1]=o[1],g[c+2]=o[2],g[c+3]=o[3]}function a(s,g,c){t[0]=s,g[c]=o[3],g[c+1]=o[2],g[c+2]=o[1],g[c+3]=o[0]}n.writeFloatLE=i?e:a,n.writeFloatBE=i?a:e;function A(s,g){return o[0]=s[g],o[1]=s[g+1],o[2]=s[g+2],o[3]=s[g+3],t[0]}function r(s,g){return o[3]=s[g],o[2]=s[g+1],o[1]=s[g+2],o[0]=s[g+3],t[0]}n.readFloatLE=i?A:r,n.readFloatBE=i?r:A})():(function(){function t(i,e,a,A){var r=e<0?1:0;if(r&&(e=-e),e===0)i(1/e>0?0:2147483648,a,A);else if(isNaN(e))i(2143289344,a,A);else if(e>34028234663852886e22)i((r<<31|2139095040)>>>0,a,A);else if(e<11754943508222875e-54)i((r<<31|Math.round(e/1401298464324817e-60))>>>0,a,A);else{var s=Math.floor(Math.log(e)/Math.LN2),g=Math.round(e*Math.pow(2,-s)*8388608)&8388607;i((r<<31|s+127<<23|g)>>>0,a,A)}}n.writeFloatLE=t.bind(null,aV),n.writeFloatBE=t.bind(null,iV);function o(i,e,a){var A=i(e,a),r=(A>>31)*2+1,s=A>>>23&255,g=A&8388607;return s===255?g?NaN:r*(1/0):s===0?r*1401298464324817e-60*g:r*Math.pow(2,s-150)*(g+8388608)}n.readFloatLE=o.bind(null,oV),n.readFloatBE=o.bind(null,nV)})(),typeof Float64Array<"u"?(function(){var t=new Float64Array([-0]),o=new Uint8Array(t.buffer),i=o[7]===128;function e(s,g,c){t[0]=s,g[c]=o[0],g[c+1]=o[1],g[c+2]=o[2],g[c+3]=o[3],g[c+4]=o[4],g[c+5]=o[5],g[c+6]=o[6],g[c+7]=o[7]}function a(s,g,c){t[0]=s,g[c]=o[7],g[c+1]=o[6],g[c+2]=o[5],g[c+3]=o[4],g[c+4]=o[3],g[c+5]=o[2],g[c+6]=o[1],g[c+7]=o[0]}n.writeDoubleLE=i?e:a,n.writeDoubleBE=i?a:e;function A(s,g){return o[0]=s[g],o[1]=s[g+1],o[2]=s[g+2],o[3]=s[g+3],o[4]=s[g+4],o[5]=s[g+5],o[6]=s[g+6],o[7]=s[g+7],t[0]}function r(s,g){return o[7]=s[g],o[6]=s[g+1],o[5]=s[g+2],o[4]=s[g+3],o[3]=s[g+4],o[2]=s[g+5],o[1]=s[g+6],o[0]=s[g+7],t[0]}n.readDoubleLE=i?A:r,n.readDoubleBE=i?r:A})():(function(){function t(i,e,a,A,r,s){var g=A<0?1:0;if(g&&(A=-A),A===0)i(0,r,s+e),i(1/A>0?0:2147483648,r,s+a);else if(isNaN(A))i(0,r,s+e),i(2146959360,r,s+a);else if(A>17976931348623157e292)i(0,r,s+e),i((g<<31|2146435072)>>>0,r,s+a);else{var c;if(A<22250738585072014e-324)c=A/5e-324,i(c>>>0,r,s+e),i((g<<31|c/4294967296)>>>0,r,s+a);else{var I=Math.floor(Math.log(A)/Math.LN2);I===1024&&(I=1023),c=A*Math.pow(2,-I),i(c*4503599627370496>>>0,r,s+e),i((g<<31|I+1023<<20|c*1048576&1048575)>>>0,r,s+a)}}}n.writeDoubleLE=t.bind(null,aV,0,4),n.writeDoubleBE=t.bind(null,iV,4,0);function o(i,e,a,A,r){var s=i(A,r+e),g=i(A,r+a),c=(g>>31)*2+1,I=g>>>20&2047,d=4294967296*(g&1048575)+s;return I===2047?d?NaN:c*(1/0):I===0?c*5e-324*d:c*Math.pow(2,I-1075)*(d+4503599627370496)}n.readDoubleLE=o.bind(null,oV,0,4),n.readDoubleBE=o.bind(null,nV,4,0)})(),n}function aV(n,t,o){t[o]=n&255,t[o+1]=n>>>8&255,t[o+2]=n>>>16&255,t[o+3]=n>>>24}function iV(n,t,o){t[o]=n>>>24,t[o+1]=n>>>16&255,t[o+2]=n>>>8&255,t[o+3]=n&255}function oV(n,t){return(n[t]|n[t+1]<<8|n[t+2]<<16|n[t+3]<<24)>>>0}function nV(n,t){return(n[t]<<24|n[t+1]<<16|n[t+2]<<8|n[t+3])>>>0}});var IV=$(cV=>{"use strict";var UN=cV,LN=65533;UN.length=function(t){for(var o=0,i=0,e=0;e=192&&r<224?(g=(r&31)<<6|t[o++]&63,a[A++]=g>=128?g:LN):r>=224&&r<240?(c=(r&15)<<12|(t[o++]&63)<<6|t[o++]&63,a[A++]=c>=2048?c:LN):r>=240&&(s=(r&7)<<18|(t[o++]&63)<<12|(t[o++]&63)<<6|t[o++]&63,s<65536||s>1114111?a[A++]=LN:(s-=65536,a[A++]=55296+(s>>10),a[A++]=56320+(s&1023))),A>8191&&((e||(e=[])).push(String.fromCharCode.apply(String,a.slice(0,A))),A=0);return e?(A&&e.push(String.fromCharCode.apply(String,a.slice(0,A))),e.join("")):String.fromCharCode.apply(String,a.slice(0,A))};UN.write=function(t,o,i){for(var e=i,a,A,r=0;r>6|192,o[i++]=a&63|128):(a&64512)===55296&&((A=t.charCodeAt(r+1))&64512)===56320?(a=65536+((a&1023)<<10)+(A&1023),++r,o[i++]=a>>18|240,o[i++]=a>>12&63|128,o[i++]=a>>6&63|128,o[i++]=a&63|128):(o[i++]=a>>12|224,o[i++]=a>>6&63|128,o[i++]=a&63|128);return i-e}});var pV=$((_gA,lV)=>{"use strict";lV.exports=fTe;function fTe(n,t,o){var i=o||8192,e=i>>>1,a=null,A=i;return function(s){if(s<1||s>e)return n(s);A+s>i&&(a=n(i),A=0);var g=t.call(a,A,A+=s);return A&7&&(A=(A|7)+1),g}}});var hV=$((TgA,dV)=>{"use strict";dV.exports=oa;var ZC=Qc();function oa(n,t){this.lo=n>>>0,this.hi=t>>>0}var rl=oa.zero=new oa(0,0);rl.toNumber=function(){return 0};rl.zzEncode=rl.zzDecode=function(){return this};rl.length=function(){return 1};var QTe=oa.zeroHash="\0\0\0\0\0\0\0\0";oa.fromNumber=function(t){if(t===0)return rl;var o=t<0;o&&(t=-t);var i=t>>>0,e=(t-i)/4294967296>>>0;return o&&(e=~e>>>0,i=~i>>>0,++i>4294967295&&(i=0,++e>4294967295&&(e=0))),new oa(i,e)};oa.from=function(t){if(typeof t=="number")return oa.fromNumber(t);if(ZC.isString(t))if(ZC.Long)t=ZC.Long.fromString(t);else return oa.fromNumber(parseInt(t,10));return t.low||t.high?new oa(t.low>>>0,t.high>>>0):rl};oa.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var o=~this.lo+1>>>0,i=~this.hi>>>0;return o||(i=i+1>>>0),-(o+i*4294967296)}return this.lo+this.hi*4294967296};oa.prototype.toLong=function(t){return ZC.Long?new ZC.Long(this.lo|0,this.hi|0,!!t):{low:this.lo|0,high:this.hi|0,unsigned:!!t}};var fc=String.prototype.charCodeAt;oa.fromHash=function(t){return t===QTe?rl:new oa((fc.call(t,0)|fc.call(t,1)<<8|fc.call(t,2)<<16|fc.call(t,3)<<24)>>>0,(fc.call(t,4)|fc.call(t,5)<<8|fc.call(t,6)<<16|fc.call(t,7)<<24)>>>0)};oa.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};oa.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this};oa.prototype.zzDecode=function(){var t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this};oa.prototype.length=function(){var t=this.lo,o=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return i===0?o===0?t<16384?t<128?1:2:t<2097152?3:4:o<16384?o<128?5:6:o<2097152?7:8:i<128?9:10}});var EV=$((XC,HN)=>{(function(n,t){function o(i){return i.default||i}typeof define=="function"&&define.amd?define([],function(){var i={};return t(i),o(i)}):typeof XC=="object"?(t(XC),typeof HN=="object"&&(HN.exports=o(XC))):(function(){var i={};t(i),n.Long=o(i)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:XC,function(n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function o(U,N,k){this.low=U|0,this.high=N|0,this.unsigned=!!k}o.prototype.__isLong__,Object.defineProperty(o.prototype,"__isLong__",{value:!0});function i(U){return(U&&U.__isLong__)===!0}function e(U){var N=Math.clz32(U&-U);return U?31-N:N}o.isLong=i;var a={},A={};function r(U,N){var k,V,Ae;return N?(U>>>=0,(Ae=0<=U&&U<256)&&(V=A[U],V)?V:(k=g(U,0,!0),Ae&&(A[U]=k),k)):(U|=0,(Ae=-128<=U&&U<128)&&(V=a[U],V)?V:(k=g(U,U<0?-1:0,!1),Ae&&(a[U]=k),k))}o.fromInt=r;function s(U,N){if(isNaN(U))return N?R:T;if(N){if(U<0)return R;if(U>=y)return z}else{if(U<=-m)return j;if(U+1>=m)return q}return U<0?s(-U,N).neg():g(U%Q|0,U/Q|0,N)}o.fromNumber=s;function g(U,N,k){return new o(U,N,k)}o.fromBits=g;var c=Math.pow;function I(U,N,k){if(U.length===0)throw Error("empty string");if(typeof N=="number"?(k=N,N=!1):N=!!N,U==="NaN"||U==="Infinity"||U==="+Infinity"||U==="-Infinity")return N?R:T;if(k=k||10,k<2||360)throw Error("interior hyphen");if(V===0)return I(U.substring(1),N,k).neg();for(var Ae=s(c(k,8)),ie=T,De=0;De>>0:this.low},P.toNumber=function(){return this.unsigned?(this.high>>>0)*Q+(this.low>>>0):this.high*Q+(this.low>>>0)},P.toString=function(N){if(N=N||10,N<2||36>>0,Qe=Ee.toString(N);if(De=_e,De.isZero())return Qe+fe;for(;Qe.length<6;)Qe="0"+Qe;fe=""+Qe+fe}},P.getHighBits=function(){return this.high},P.getHighBitsUnsigned=function(){return this.high>>>0},P.getLowBits=function(){return this.low},P.getLowBitsUnsigned=function(){return this.low>>>0},P.getNumBitsAbs=function(){if(this.isNegative())return this.eq(j)?64:this.neg().getNumBitsAbs();for(var N=this.high!=0?this.high:this.low,k=31;k>0&&(N&1<>21;return N?this.unsigned?!1:N===-1&&!(this.low===0&&this.high===-2097152):!0},P.isZero=function(){return this.high===0&&this.low===0},P.eqz=P.isZero,P.isNegative=function(){return!this.unsigned&&this.high<0},P.isPositive=function(){return this.unsigned||this.high>=0},P.isOdd=function(){return(this.low&1)===1},P.isEven=function(){return(this.low&1)===0},P.equals=function(N){return i(N)||(N=d(N)),this.unsigned!==N.unsigned&&this.high>>>31===1&&N.high>>>31===1?!1:this.high===N.high&&this.low===N.low},P.eq=P.equals,P.notEquals=function(N){return!this.eq(N)},P.neq=P.notEquals,P.ne=P.notEquals,P.lessThan=function(N){return this.comp(N)<0},P.lt=P.lessThan,P.lessThanOrEqual=function(N){return this.comp(N)<=0},P.lte=P.lessThanOrEqual,P.le=P.lessThanOrEqual,P.greaterThan=function(N){return this.comp(N)>0},P.gt=P.greaterThan,P.greaterThanOrEqual=function(N){return this.comp(N)>=0},P.gte=P.greaterThanOrEqual,P.ge=P.greaterThanOrEqual,P.compare=function(N){if(i(N)||(N=d(N)),this.eq(N))return 0;var k=this.isNegative(),V=N.isNegative();return k&&!V?-1:!k&&V?1:this.unsigned?N.high>>>0>this.high>>>0||N.high===this.high&&N.low>>>0>this.low>>>0?-1:1:this.sub(N).isNegative()?-1:1},P.comp=P.compare,P.negate=function(){return!this.unsigned&&this.eq(j)?j:this.not().add(F)},P.neg=P.negate,P.add=function(N){i(N)||(N=d(N));var k=this.high>>>16,V=this.high&65535,Ae=this.low>>>16,ie=this.low&65535,De=N.high>>>16,fe=N.high&65535,_e=N.low>>>16,Ee=N.low&65535,Qe=0,Le=0,AA=0,aA=0;return aA+=ie+Ee,AA+=aA>>>16,aA&=65535,AA+=Ae+_e,Le+=AA>>>16,AA&=65535,Le+=V+fe,Qe+=Le>>>16,Le&=65535,Qe+=k+De,Qe&=65535,g(AA<<16|aA,Qe<<16|Le,this.unsigned)},P.subtract=function(N){return i(N)||(N=d(N)),this.add(N.neg())},P.sub=P.subtract,P.multiply=function(N){if(this.isZero())return this;if(i(N)||(N=d(N)),t){var k=t.mul(this.low,this.high,N.low,N.high);return g(k,t.get_high(),this.unsigned)}if(N.isZero())return this.unsigned?R:T;if(this.eq(j))return N.isOdd()?j:T;if(N.eq(j))return this.isOdd()?j:T;if(this.isNegative())return N.isNegative()?this.neg().mul(N.neg()):this.neg().mul(N).neg();if(N.isNegative())return this.mul(N.neg()).neg();if(this.lt(_)&&N.lt(_))return s(this.toNumber()*N.toNumber(),this.unsigned);var V=this.high>>>16,Ae=this.high&65535,ie=this.low>>>16,De=this.low&65535,fe=N.high>>>16,_e=N.high&65535,Ee=N.low>>>16,Qe=N.low&65535,Le=0,AA=0,aA=0,He=0;return He+=De*Qe,aA+=He>>>16,He&=65535,aA+=ie*Qe,AA+=aA>>>16,aA&=65535,aA+=De*Ee,AA+=aA>>>16,aA&=65535,AA+=Ae*Qe,Le+=AA>>>16,AA&=65535,AA+=ie*Ee,Le+=AA>>>16,AA&=65535,AA+=De*_e,Le+=AA>>>16,AA&=65535,Le+=V*Qe+Ae*Ee+ie*_e+De*fe,Le&=65535,g(aA<<16|He,Le<<16|AA,this.unsigned)},P.mul=P.multiply,P.divide=function(N){if(i(N)||(N=d(N)),N.isZero())throw Error("division by zero");if(t){if(!this.unsigned&&this.high===-2147483648&&N.low===-1&&N.high===-1)return this;var k=(this.unsigned?t.div_u:t.div_s)(this.low,this.high,N.low,N.high);return g(k,t.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?R:T;var V,Ae,ie;if(this.unsigned){if(N.unsigned||(N=N.toUnsigned()),N.gt(this))return R;if(N.gt(this.shru(1)))return K;ie=R}else{if(this.eq(j)){if(N.eq(F)||N.eq(L))return j;if(N.eq(j))return F;var De=this.shr(1);return V=De.div(N).shl(1),V.eq(T)?N.isNegative()?F:L:(Ae=this.sub(N.mul(V)),ie=V.add(Ae.div(N)),ie)}else if(N.eq(j))return this.unsigned?R:T;if(this.isNegative())return N.isNegative()?this.neg().div(N.neg()):this.neg().div(N).neg();if(N.isNegative())return this.div(N.neg()).neg();ie=T}for(Ae=this;Ae.gte(N);){V=Math.max(1,Math.floor(Ae.toNumber()/N.toNumber()));for(var fe=Math.ceil(Math.log(V)/Math.LN2),_e=fe<=48?1:c(2,fe-48),Ee=s(V),Qe=Ee.mul(N);Qe.isNegative()||Qe.gt(Ae);)V-=_e,Ee=s(V,this.unsigned),Qe=Ee.mul(N);Ee.isZero()&&(Ee=F),ie=ie.add(Ee),Ae=Ae.sub(Qe)}return ie},P.div=P.divide,P.modulo=function(N){if(i(N)||(N=d(N)),t){var k=(this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,N.low,N.high);return g(k,t.get_high(),this.unsigned)}return this.sub(this.div(N).mul(N))},P.mod=P.modulo,P.rem=P.modulo,P.not=function(){return g(~this.low,~this.high,this.unsigned)},P.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},P.clz=P.countLeadingZeros,P.countTrailingZeros=function(){return this.low?e(this.low):e(this.high)+32},P.ctz=P.countTrailingZeros,P.and=function(N){return i(N)||(N=d(N)),g(this.low&N.low,this.high&N.high,this.unsigned)},P.or=function(N){return i(N)||(N=d(N)),g(this.low|N.low,this.high|N.high,this.unsigned)},P.xor=function(N){return i(N)||(N=d(N)),g(this.low^N.low,this.high^N.high,this.unsigned)},P.shiftLeft=function(N){return i(N)&&(N=N.toInt()),(N&=63)===0?this:N<32?g(this.low<>>32-N,this.unsigned):g(0,this.low<>>N|this.high<<32-N,this.high>>N,this.unsigned):g(this.high>>N-32,this.high>=0?0:-1,this.unsigned)},P.shr=P.shiftRight,P.shiftRightUnsigned=function(N){return i(N)&&(N=N.toInt()),(N&=63)===0?this:N<32?g(this.low>>>N|this.high<<32-N,this.high>>>N,this.unsigned):N===32?g(this.high,0,this.unsigned):g(this.high>>>N-32,0,this.unsigned)},P.shru=P.shiftRightUnsigned,P.shr_u=P.shiftRightUnsigned,P.rotateLeft=function(N){var k;return i(N)&&(N=N.toInt()),(N&=63)===0?this:N===32?g(this.high,this.low,this.unsigned):N<32?(k=32-N,g(this.low<>>k,this.high<>>k,this.unsigned)):(N-=32,k=32-N,g(this.high<>>k,this.low<>>k,this.unsigned))},P.rotl=P.rotateLeft,P.rotateRight=function(N){var k;return i(N)&&(N=N.toInt()),(N&=63)===0?this:N===32?g(this.high,this.low,this.unsigned):N<32?(k=32-N,g(this.high<>>N,this.low<>>N,this.unsigned)):(N-=32,k=32-N,g(this.low<>>N,this.high<>>N,this.unsigned))},P.rotr=P.rotateRight,P.toSigned=function(){return this.unsigned?g(this.low,this.high,!1):this},P.toUnsigned=function(){return this.unsigned?this:g(this.low,this.high,!0)},P.toBytes=function(N){return N?this.toBytesLE():this.toBytesBE()},P.toBytesLE=function(){var N=this.high,k=this.low;return[k&255,k>>>8&255,k>>>16&255,k>>>24,N&255,N>>>8&255,N>>>16&255,N>>>24]},P.toBytesBE=function(){var N=this.high,k=this.low;return[N>>>24,N>>>16&255,N>>>8&255,N&255,k>>>24,k>>>16&255,k>>>8&255,k&255]},o.fromBytes=function(N,k,V){return V?o.fromBytesLE(N,k):o.fromBytesBE(N,k)},o.fromBytesLE=function(N,k){return new o(N[0]|N[1]<<8|N[2]<<16|N[3]<<24,N[4]|N[5]<<8|N[6]<<16|N[7]<<24,k)},o.fromBytesBE=function(N,k){return new o(N[4]<<24|N[5]<<16|N[6]<<8|N[7],N[0]<<24|N[1]<<16|N[2]<<8|N[3],k)},typeof BigInt=="function"&&(o.fromBigInt=function(N,k){var V=Number(BigInt.asIntN(32,N)),Ae=Number(BigInt.asIntN(32,N>>BigInt(32)));return g(V,Ae,k)},o.fromValue=function(N,k){return typeof N=="bigint"?o.fromBigInt(N,k):d(N,k)},P.toBigInt=function(){var N=BigInt(this.low>>>0),k=BigInt(this.unsigned?this.high>>>0:this.high);return k<{"use strict";var BA=KN;BA.asPromise=Wz();BA.base64=eV();BA.EventEmitter=tV();BA.float=gV();BA.utf8=IV();BA.pool=pV();BA.LongBits=hV();function CV(n){return n==="__proto__"||n==="prototype"||n==="constructor"}BA.isUnsafeProperty=CV;BA.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);BA.global=BA.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||KN;BA.emptyArray=Object.freeze?Object.freeze([]):[];BA.emptyObject=Object.freeze?Object.freeze({}):{};BA.isInteger=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t};BA.isString=function(t){return typeof t=="string"||t instanceof String};BA.isObject=function(t){return t&&typeof t=="object"};BA.isset=BA.isSet=function(t,o){var i=t[o];return i!=null&&Object.hasOwnProperty.call(t,o)?typeof i!="object"||(Array.isArray(i)?i.length:Object.keys(i).length)>0:!1};BA.Buffer=(function(){try{var n=BA.global.Buffer;return n.prototype.utf8Write?n:null}catch{return null}})();BA._Buffer_from=null;BA._Buffer_allocUnsafe=null;BA.newBuffer=function(t){return typeof t=="number"?BA.Buffer?BA._Buffer_allocUnsafe(t):new BA.Array(t):BA.Buffer?BA._Buffer_from(t):typeof Uint8Array>"u"?t:new Uint8Array(t)};BA.Array=typeof Uint8Array<"u"?Uint8Array:Array;BA.Long=BA.global.dcodeIO&&BA.global.dcodeIO.Long||BA.global.Long||(function(){try{var n=EV();return n&&n.isLong?n:null}catch{return null}})();BA.key2Re=/^true|false|0|1$/;BA.key32Re=/^-?(?:0|[1-9][0-9]*)$/;BA.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;BA.longToHash=function(t){return t?BA.LongBits.from(t).toHash():BA.LongBits.zeroHash};BA.longFromHash=function(t,o){var i=BA.LongBits.fromHash(t);return BA.Long?BA.Long.fromBits(i.lo,i.hi,o):i.toNumber(!!o)};function uV(n){var t=typeof arguments[arguments.length-1]=="boolean",o=t?arguments.length-1:arguments.length;t=t&&arguments[arguments.length-1];for(var i=1;i-1;--a)if(o[e[a]]===1&&this[e[a]]!==void 0&&this[e[a]]!==null)return e[a]}};BA.oneOfSetter=function(t){return function(o){for(var i=0;i{"use strict";mV.exports=ft;var ko=Qc(),xN,ym=ko.LongBits,fV=ko.base64,QV=ko.utf8;function $C(n,t,o){this.fn=n,this.len=t,this.next=void 0,this.val=o}function jN(){}function yTe(n){this.head=n.head,this.tail=n.tail,this.len=n.len,this.next=n.states}function ft(){this.len=0,this.head=new $C(jN,0,0),this.tail=this.head,this.states=null}var yV=function(){return ko.Buffer?function(){return(ft.create=function(){return new xN})()}:function(){return new ft}};ft.create=yV();ft.alloc=function(t){return new ko.Array(t)};ko.Array!==Array&&(ft.alloc=ko.pool(ft.alloc,ko.Array.prototype.subarray));ft.prototype._push=function(t,o,i){return this.tail=this.tail.next=new $C(t,o,i),this.len+=o,this};function JN(n,t,o){t[o]=n&255}function mTe(n,t,o){for(;n>127;)t[o++]=n&127|128,n>>>=7;t[o]=n}function qN(n,t){this.len=n,this.next=void 0,this.val=t}qN.prototype=Object.create($C.prototype);qN.prototype.fn=mTe;ft.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new qN((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this};ft.prototype.int32=function(t){return(t|=0)<0?this._push(zN,10,ym.fromNumber(t)):this.uint32(t)};ft.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)};function zN(n,t,o){for(var i=n.lo,e=n.hi;e;)t[o++]=i&127|128,i=(i>>>7|e<<25)>>>0,e>>>=7;for(;i>127;)t[o++]=i&127|128,i=i>>>7;t[o++]=i}ft.prototype.uint64=function(t){var o=ym.from(t);return this._push(zN,o.length(),o)};ft.prototype.int64=ft.prototype.uint64;ft.prototype.sint64=function(t){var o=ym.from(t).zzEncode();return this._push(zN,o.length(),o)};ft.prototype.bool=function(t){return this._push(JN,1,t?1:0)};function YN(n,t,o){t[o]=n&255,t[o+1]=n>>>8&255,t[o+2]=n>>>16&255,t[o+3]=n>>>24}ft.prototype.fixed32=function(t){return this._push(YN,4,t>>>0)};ft.prototype.sfixed32=ft.prototype.fixed32;ft.prototype.fixed64=function(t){var o=ym.from(t);return this._push(YN,4,o.lo)._push(YN,4,o.hi)};ft.prototype.sfixed64=ft.prototype.fixed64;ft.prototype.float=function(t){return this._push(ko.float.writeFloatLE,4,t)};ft.prototype.double=function(t){return this._push(ko.float.writeDoubleLE,8,t)};var STe=ko.Array.prototype.set?function(t,o,i){o.set(t,i)}:function(t,o,i){for(var e=0;e>>0;if(!o)return this._push(JN,1,0);if(ko.isString(t)){var i=ft.alloc(o=fV.length(t));fV.decode(t,i,0),t=i}return this.uint32(o)._push(STe,o,t)};ft.prototype.string=function(t){var o=QV.length(t);return o?this.uint32(o)._push(QV.write,o,t):this._push(JN,1,0)};ft.prototype.fork=function(){return this.states=new yTe(this),this.head=this.tail=new $C(jN,0,0),this.len=0,this};ft.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new $C(jN,0,0),this.len=0),this};ft.prototype.ldelim=function(){var t=this.head,o=this.tail,i=this.len;return this.reset().uint32(i),i&&(this.tail.next=t.next,this.tail=o,this.len+=i),this};ft.prototype.finish=function(){for(var t=this.head.next,o=this.constructor.alloc(this.len),i=0;t;)t.fn(t.val,o,i),i+=t.len,t=t.next;return o};ft._configure=function(n){xN=n,ft.create=yV(),xN._configure()}});var DV=$((kgA,wV)=>{"use strict";wV.exports=gs;var SV=VN();(gs.prototype=Object.create(SV.prototype)).constructor=gs;var yc=Qc();function gs(){SV.call(this)}gs._configure=function(){gs.alloc=yc._Buffer_allocUnsafe,gs.writeBytesBuffer=yc.Buffer&&yc.Buffer.prototype instanceof Uint8Array&&yc.Buffer.prototype.set.name==="set"?function(t,o,i){o.set(t,i)}:function(t,o,i){if(t.copy)t.copy(o,i,0,t.length);else for(var e=0;e>>0;return this.uint32(o),o&&this._push(gs.writeBytesBuffer,o,t),this};function wTe(n,t,o){n.length<40?yc.utf8.write(n,t,o):t.utf8Write?t.utf8Write(n,o):t.write(n,o)}gs.prototype.string=function(t){var o=yc.Buffer.byteLength(t);return this.uint32(o),o&&this._push(wTe,o,t),this};gs._configure()});var XN=$((vgA,TV)=>{"use strict";TV.exports=nr;var vo=Qc(),ZN,MV=vo.LongBits,DTe=vo.utf8;function Ri(n,t){return RangeError("index out of range: "+n.pos+" + "+(t||1)+" > "+n.len)}function nr(n){this.buf=n,this.pos=0,this.len=n.length}var OV=typeof Uint8Array<"u"?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new nr(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new nr(t);throw Error("illegal buffer")},_V=function(){return vo.Buffer?function(o){return(nr.create=function(e){return vo.Buffer.isBuffer(e)?new ZN(e):OV(e)})(o)}:OV};nr.create=_V();nr.prototype._slice=vo.Array.prototype.subarray||vo.Array.prototype.slice;function OTe(n){for(var t=0,o=0;o<4;++o){if(n.pos>=n.len)throw Ri(n);var i=n.buf[n.pos++];if(t=(t|(i&127)<>>0,i<128)return t}throw Ri(n)}nr.prototype.uint32=(function(){var t=4294967295;return function(){if(this.len-this.pos<5){if(this.pos>=this.len)throw Ri(this);if(this.buf[this.pos]>=128)return OTe(this)}if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Ri(this,10);return t}})();nr.prototype.int32=function(){return this.uint32()|0};nr.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(t&1)|0};function WN(){var n=new MV(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(n.lo=(n.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n;if(n.lo=(n.lo|(this.buf[this.pos]&127)<<28)>>>0,n.hi=(n.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return n;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ri(this);if(n.lo=(n.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n}return n.lo=(n.lo|(this.buf[this.pos++]&127)<>>0,n}if(this.len-this.pos>4){for(;t<5;++t)if(n.hi=(n.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n}else for(;t<5;++t){if(this.pos>=this.len)throw Ri(this);if(n.hi=(n.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n}throw Error("invalid varint encoding")}nr.prototype.bool=function(){return this.uint32()!==0};function mm(n,t){return(n[t-4]|n[t-3]<<8|n[t-2]<<16|n[t-1]<<24)>>>0}nr.prototype.fixed32=function(){if(this.pos+4>this.len)throw Ri(this,4);return mm(this.buf,this.pos+=4)};nr.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Ri(this,4);return mm(this.buf,this.pos+=4)|0};function bV(){if(this.pos+8>this.len)throw Ri(this,8);return new MV(mm(this.buf,this.pos+=4),mm(this.buf,this.pos+=4))}nr.prototype.float=function(){if(this.pos+4>this.len)throw Ri(this,4);var t=vo.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t};nr.prototype.double=function(){if(this.pos+8>this.len)throw Ri(this,4);var t=vo.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t};nr.prototype.bytes=function(){var t=this.uint32(),o=this.pos,i=this.pos+t;if(i>this.len)throw Ri(this,t);if(this.pos+=t,Array.isArray(this.buf))return this.buf.slice(o,i);if(o===i){var e=vo.Buffer;return e?e.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,o,i)};nr.prototype.string=function(){var t=this.bytes();return DTe.read(t,0,t.length)};nr.prototype.skip=function(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Ri(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Ri(this);while(this.buf[this.pos++]&128);return this};nr.recursionLimit=vo.recursionLimit;nr.prototype.skipType=function(n,t){if(t===void 0&&(t=0),t>nr.recursionLimit)throw Error("maximum nesting depth exceeded");switch(n){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(n=this.uint32()&7)!==4;)this.skipType(n,t+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+n+" at offset "+this.pos)}return this};nr._configure=function(n){ZN=n,nr.create=_V(),ZN._configure();var t=vo.Long?"toLong":"toNumber";vo.merge(nr.prototype,{int64:function(){return WN.call(this)[t](!1)},uint64:function(){return WN.call(this)[t](!0)},sint64:function(){return WN.call(this).zzDecode()[t](!1)},fixed64:function(){return bV.call(this)[t](!0)},sfixed64:function(){return bV.call(this)[t](!1)}})}});var vV=$((PgA,kV)=>{"use strict";kV.exports=al;var RV=XN();(al.prototype=Object.create(RV.prototype)).constructor=al;var NV=Qc();function al(n){RV.call(this,n)}al._configure=function(){NV.Buffer&&(al.prototype._slice=NV.Buffer.prototype.slice)};al.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))};al._configure()});var GV=$((GgA,PV)=>{"use strict";PV.exports=eu;var $N=Qc();(eu.prototype=Object.create($N.EventEmitter.prototype)).constructor=eu;function eu(n,t,o){if(typeof n!="function")throw TypeError("rpcImpl must be a function");$N.EventEmitter.call(this),this.rpcImpl=n,this.requestDelimited=!!t,this.responseDelimited=!!o}eu.prototype.rpcCall=function n(t,o,i,e,a){if(!e)throw TypeError("request must be specified");var A=this;if(!a)return $N.asPromise(n,A,t,o,i,e);if(!A.rpcImpl){setTimeout(function(){a(Error("already ended"))},0);return}try{return A.rpcImpl(t,o[A.requestDelimited?"encodeDelimited":"encode"](e).finish(),function(s,g){if(s)return A.emit("error",s,t),a(s);if(g===null){A.end(!0);return}if(!(g instanceof i))try{g=i[A.responseDelimited?"decodeDelimited":"decode"](g)}catch(c){return A.emit("error",c,t),a(c)}return A.emit("data",g,t),a(null,g)})}catch(r){A.emit("error",r,t),setTimeout(function(){a(r)},0);return}};eu.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var LV=$(FV=>{"use strict";var bTe=FV;bTe.Service=GV()});var HV=$((LgA,UV)=>{"use strict";UV.exports=Object.create(null)});var YV=$(xV=>{"use strict";var ki=xV;ki.build="minimal";ki.Writer=VN();ki.BufferWriter=DV();ki.Reader=XN();ki.BufferReader=vV();ki.util=Qc();ki.rpc=LV();ki.roots=HV();ki.configure=KV;function KV(){ki.util._configure(),ki.Writer._configure(ki.BufferWriter),ki.Reader._configure(ki.BufferReader)}KV()});var Sm=$((HgA,jV)=>{"use strict";jV.exports=YV()});var K6=$(ot=>{"use strict";var bu=Symbol.for("react.element"),Kke=Symbol.for("react.portal"),xke=Symbol.for("react.fragment"),Yke=Symbol.for("react.strict_mode"),jke=Symbol.for("react.profiler"),Jke=Symbol.for("react.provider"),qke=Symbol.for("react.context"),zke=Symbol.for("react.forward_ref"),Vke=Symbol.for("react.suspense"),Wke=Symbol.for("react.memo"),Zke=Symbol.for("react.lazy"),T6=Symbol.iterator;function Xke(n){return n===null||typeof n!="object"?null:(n=T6&&n[T6]||n["@@iterator"],typeof n=="function"?n:null)}var k6={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v6=Object.assign,P6={};function kd(n,t,o){this.props=n,this.context=t,this.refs=P6,this.updater=o||k6}kd.prototype.isReactComponent={};kd.prototype.setState=function(n,t){if(typeof n!="object"&&typeof n!="function"&&n!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,n,t,"setState")};kd.prototype.forceUpdate=function(n){this.updater.enqueueForceUpdate(this,n,"forceUpdate")};function G6(){}G6.prototype=kd.prototype;function sP(n,t,o){this.props=n,this.context=t,this.refs=P6,this.updater=o||k6}var gP=sP.prototype=new G6;gP.constructor=sP;v6(gP,kd.prototype);gP.isPureReactComponent=!0;var N6=Array.isArray,F6=Object.prototype.hasOwnProperty,cP={current:null},L6={key:!0,ref:!0,__self:!0,__source:!0};function U6(n,t,o){var i,e={},a=null,A=null;if(t!=null)for(i in t.ref!==void 0&&(A=t.ref),t.key!==void 0&&(a=""+t.key),t)F6.call(t,i)&&!L6.hasOwnProperty(i)&&(e[i]=t[i]);var r=arguments.length-2;if(r===1)e.children=o;else if(1{"use strict";process.env.NODE_ENV!=="production"&&(function(){"use strict";typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var n="18.3.1",t=Symbol.for("react.element"),o=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),e=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),A=Symbol.for("react.provider"),r=Symbol.for("react.context"),s=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),c=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),B=Symbol.for("react.offscreen"),f=Symbol.iterator,Q="@@iterator";function y(H){if(H===null||typeof H!="object")return null;var te=f&&H[f]||H[Q];return typeof te=="function"?te:null}var m={current:null},_={transition:null},T={current:null,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1},R={current:null},F={},K=null;function L(H){K=H}F.setExtraStackFrame=function(H){K=H},F.getCurrentStack=null,F.getStackAddendum=function(){var H="";K&&(H+=K);var te=F.getCurrentStack;return te&&(H+=te()||""),H};var q=!1,z=!1,j=!1,P=!1,J=!1,U={ReactCurrentDispatcher:m,ReactCurrentBatchConfig:_,ReactCurrentOwner:R};U.ReactDebugCurrentFrame=F,U.ReactCurrentActQueue=T;function N(H){{for(var te=arguments.length,de=new Array(te>1?te-1:0),Se=1;Se1?te-1:0),Se=1;Se1){for(var zt=Array(vt),Vt=0;Vt1){for(var ar=Array(Vt),br=0;br is not supported and will be removed in a future major release. Did you mean to render instead?")),te.Provider},set:function(EA){te.Provider=EA}},_currentValue:{get:function(){return te._currentValue},set:function(EA){te._currentValue=EA}},_currentValue2:{get:function(){return te._currentValue2},set:function(EA){te._currentValue2=EA}},_threadCount:{get:function(){return te._threadCount},set:function(EA){te._threadCount=EA}},Consumer:{get:function(){return de||(de=!0,k("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?")),te.Consumer}},displayName:{get:function(){return te.displayName},set:function(EA){qe||(N("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.",EA),qe=!0)}}}),te.Consumer=MA}return te._currentRenderer=null,te._currentRenderer2=null,te}var he=-1,me=0,je=1,lA=2;function QA(H){if(H._status===he){var te=H._result,de=te();if(de.then(function(MA){if(H._status===me||H._status===he){var EA=H;EA._status=je,EA._result=MA}},function(MA){if(H._status===me||H._status===he){var EA=H;EA._status=lA,EA._result=MA}}),H._status===he){var Se=H;Se._status=me,Se._result=de}}if(H._status===je){var qe=H._result;return qe===void 0&&k(`lazy: Expected the result of a dynamic import() call. Instead received: %s +`+o)}function tl(n,t,o,i,e,a){if(n.listenerCount("wsClientError")){let A=new Error(e);Error.captureStackTrace(A,tl),n.emit("wsClientError",A,o,t)}else WC(o,i,e,a)}});var Wz=$((wgA,Vz)=>{"use strict";Vz.exports=BTe;function BTe(n,t){for(var o=new Array(arguments.length-1),i=0,e=2,a=!0;e{"use strict";var fm=$z;fm.length=function(t){var o=t.length;if(!o)return 0;for(var i=0;--o%4>1&&t.charAt(o)==="=";)++i;return Math.ceil(t.length*3)/4-i};var Sd=new Array(64),Xz=new Array(123);for(fn=0;fn<64;)Xz[Sd[fn]=fn<26?fn+65:fn<52?fn+71:fn<62?fn-4:fn-59|43]=fn++;var fn;fm.encode=function(t,o,i){for(var e=null,a=[],A=0,r=0,s;o>2],s=(g&3)<<4,r=1;break;case 1:a[A++]=Sd[s|g>>4],s=(g&15)<<2,r=2;break;case 2:a[A++]=Sd[s|g>>6],a[A++]=Sd[g&63],r=0;break}A>8191&&((e||(e=[])).push(String.fromCharCode.apply(String,a)),A=0)}return r&&(a[A++]=Sd[s],a[A++]=61,r===1&&(a[A++]=61)),e?(A&&e.push(String.fromCharCode.apply(String,a.slice(0,A))),e.join("")):String.fromCharCode.apply(String,a.slice(0,A))};var Zz="invalid encoding";fm.decode=function(t,o,i){for(var e=i,a=0,A,r=0;r1)break;if((s=Xz[s])===void 0)throw Error(Zz);switch(a){case 0:A=s,a=1;break;case 1:o[i++]=A<<2|(s&48)>>4,A=s,a=2;break;case 2:o[i++]=(A&15)<<4|(s&60)>>2,A=s,a=3;break;case 3:o[i++]=(A&3)<<6|s,a=0;break}}if(a===1)throw Error(Zz);return i-e};fm.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}});var tV=$((OgA,AV)=>{"use strict";AV.exports=Qm;function Qm(){this._listeners=Object.create(null)}Qm.prototype.on=function(t,o,i){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:o,ctx:i||this}),this};Qm.prototype.off=function(t,o){if(t===void 0)this._listeners=Object.create(null);else if(o===void 0)this._listeners[t]=[];else{var i=this._listeners[t];if(!i)return this;for(var e=0;e{"use strict";sV.exports=rV(rV);function rV(n){return typeof Float32Array<"u"?(function(){var t=new Float32Array([-0]),o=new Uint8Array(t.buffer),i=o[3]===128;function e(s,g,c){t[0]=s,g[c]=o[0],g[c+1]=o[1],g[c+2]=o[2],g[c+3]=o[3]}function a(s,g,c){t[0]=s,g[c]=o[3],g[c+1]=o[2],g[c+2]=o[1],g[c+3]=o[0]}n.writeFloatLE=i?e:a,n.writeFloatBE=i?a:e;function A(s,g){return o[0]=s[g],o[1]=s[g+1],o[2]=s[g+2],o[3]=s[g+3],t[0]}function r(s,g){return o[3]=s[g],o[2]=s[g+1],o[1]=s[g+2],o[0]=s[g+3],t[0]}n.readFloatLE=i?A:r,n.readFloatBE=i?r:A})():(function(){function t(i,e,a,A){var r=e<0?1:0;if(r&&(e=-e),e===0)i(1/e>0?0:2147483648,a,A);else if(isNaN(e))i(2143289344,a,A);else if(e>34028234663852886e22)i((r<<31|2139095040)>>>0,a,A);else if(e<11754943508222875e-54)i((r<<31|Math.round(e/1401298464324817e-60))>>>0,a,A);else{var s=Math.floor(Math.log(e)/Math.LN2),g=Math.round(e*Math.pow(2,-s)*8388608)&8388607;i((r<<31|s+127<<23|g)>>>0,a,A)}}n.writeFloatLE=t.bind(null,aV),n.writeFloatBE=t.bind(null,iV);function o(i,e,a){var A=i(e,a),r=(A>>31)*2+1,s=A>>>23&255,g=A&8388607;return s===255?g?NaN:r*(1/0):s===0?r*1401298464324817e-60*g:r*Math.pow(2,s-150)*(g+8388608)}n.readFloatLE=o.bind(null,oV),n.readFloatBE=o.bind(null,nV)})(),typeof Float64Array<"u"?(function(){var t=new Float64Array([-0]),o=new Uint8Array(t.buffer),i=o[7]===128;function e(s,g,c){t[0]=s,g[c]=o[0],g[c+1]=o[1],g[c+2]=o[2],g[c+3]=o[3],g[c+4]=o[4],g[c+5]=o[5],g[c+6]=o[6],g[c+7]=o[7]}function a(s,g,c){t[0]=s,g[c]=o[7],g[c+1]=o[6],g[c+2]=o[5],g[c+3]=o[4],g[c+4]=o[3],g[c+5]=o[2],g[c+6]=o[1],g[c+7]=o[0]}n.writeDoubleLE=i?e:a,n.writeDoubleBE=i?a:e;function A(s,g){return o[0]=s[g],o[1]=s[g+1],o[2]=s[g+2],o[3]=s[g+3],o[4]=s[g+4],o[5]=s[g+5],o[6]=s[g+6],o[7]=s[g+7],t[0]}function r(s,g){return o[7]=s[g],o[6]=s[g+1],o[5]=s[g+2],o[4]=s[g+3],o[3]=s[g+4],o[2]=s[g+5],o[1]=s[g+6],o[0]=s[g+7],t[0]}n.readDoubleLE=i?A:r,n.readDoubleBE=i?r:A})():(function(){function t(i,e,a,A,r,s){var g=A<0?1:0;if(g&&(A=-A),A===0)i(0,r,s+e),i(1/A>0?0:2147483648,r,s+a);else if(isNaN(A))i(0,r,s+e),i(2146959360,r,s+a);else if(A>17976931348623157e292)i(0,r,s+e),i((g<<31|2146435072)>>>0,r,s+a);else{var c;if(A<22250738585072014e-324)c=A/5e-324,i(c>>>0,r,s+e),i((g<<31|c/4294967296)>>>0,r,s+a);else{var I=Math.floor(Math.log(A)/Math.LN2);I===1024&&(I=1023),c=A*Math.pow(2,-I),i(c*4503599627370496>>>0,r,s+e),i((g<<31|I+1023<<20|c*1048576&1048575)>>>0,r,s+a)}}}n.writeDoubleLE=t.bind(null,aV,0,4),n.writeDoubleBE=t.bind(null,iV,4,0);function o(i,e,a,A,r){var s=i(A,r+e),g=i(A,r+a),c=(g>>31)*2+1,I=g>>>20&2047,d=4294967296*(g&1048575)+s;return I===2047?d?NaN:c*(1/0):I===0?c*5e-324*d:c*Math.pow(2,I-1075)*(d+4503599627370496)}n.readDoubleLE=o.bind(null,oV,0,4),n.readDoubleBE=o.bind(null,nV,4,0)})(),n}function aV(n,t,o){t[o]=n&255,t[o+1]=n>>>8&255,t[o+2]=n>>>16&255,t[o+3]=n>>>24}function iV(n,t,o){t[o]=n>>>24,t[o+1]=n>>>16&255,t[o+2]=n>>>8&255,t[o+3]=n&255}function oV(n,t){return(n[t]|n[t+1]<<8|n[t+2]<<16|n[t+3]<<24)>>>0}function nV(n,t){return(n[t]<<24|n[t+1]<<16|n[t+2]<<8|n[t+3])>>>0}});var IV=$(cV=>{"use strict";var UN=cV,LN=65533;UN.length=function(t){for(var o=0,i=0,e=0;e=192&&r<224?(g=(r&31)<<6|t[o++]&63,a[A++]=g>=128?g:LN):r>=224&&r<240?(c=(r&15)<<12|(t[o++]&63)<<6|t[o++]&63,a[A++]=c>=2048?c:LN):r>=240&&(s=(r&7)<<18|(t[o++]&63)<<12|(t[o++]&63)<<6|t[o++]&63,s<65536||s>1114111?a[A++]=LN:(s-=65536,a[A++]=55296+(s>>10),a[A++]=56320+(s&1023))),A>8191&&((e||(e=[])).push(String.fromCharCode.apply(String,a.slice(0,A))),A=0);return e?(A&&e.push(String.fromCharCode.apply(String,a.slice(0,A))),e.join("")):String.fromCharCode.apply(String,a.slice(0,A))};UN.write=function(t,o,i){for(var e=i,a,A,r=0;r>6|192,o[i++]=a&63|128):(a&64512)===55296&&((A=t.charCodeAt(r+1))&64512)===56320?(a=65536+((a&1023)<<10)+(A&1023),++r,o[i++]=a>>18|240,o[i++]=a>>12&63|128,o[i++]=a>>6&63|128,o[i++]=a&63|128):(o[i++]=a>>12|224,o[i++]=a>>6&63|128,o[i++]=a&63|128);return i-e}});var pV=$((_gA,lV)=>{"use strict";lV.exports=fTe;function fTe(n,t,o){var i=o||8192,e=i>>>1,a=null,A=i;return function(s){if(s<1||s>e)return n(s);A+s>i&&(a=n(i),A=0);var g=t.call(a,A,A+=s);return A&7&&(A=(A|7)+1),g}}});var hV=$((TgA,dV)=>{"use strict";dV.exports=oa;var ZC=Qc();function oa(n,t){this.lo=n>>>0,this.hi=t>>>0}var rl=oa.zero=new oa(0,0);rl.toNumber=function(){return 0};rl.zzEncode=rl.zzDecode=function(){return this};rl.length=function(){return 1};var QTe=oa.zeroHash="\0\0\0\0\0\0\0\0";oa.fromNumber=function(t){if(t===0)return rl;var o=t<0;o&&(t=-t);var i=t>>>0,e=(t-i)/4294967296>>>0;return o&&(e=~e>>>0,i=~i>>>0,++i>4294967295&&(i=0,++e>4294967295&&(e=0))),new oa(i,e)};oa.from=function(t){if(typeof t=="number")return oa.fromNumber(t);if(ZC.isString(t))if(ZC.Long)t=ZC.Long.fromString(t);else return oa.fromNumber(parseInt(t,10));return t.low||t.high?new oa(t.low>>>0,t.high>>>0):rl};oa.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var o=~this.lo+1>>>0,i=~this.hi>>>0;return o||(i=i+1>>>0),-(o+i*4294967296)}return this.lo+this.hi*4294967296};oa.prototype.toLong=function(t){return ZC.Long?new ZC.Long(this.lo|0,this.hi|0,!!t):{low:this.lo|0,high:this.hi|0,unsigned:!!t}};var fc=String.prototype.charCodeAt;oa.fromHash=function(t){return t===QTe?rl:new oa((fc.call(t,0)|fc.call(t,1)<<8|fc.call(t,2)<<16|fc.call(t,3)<<24)>>>0,(fc.call(t,4)|fc.call(t,5)<<8|fc.call(t,6)<<16|fc.call(t,7)<<24)>>>0)};oa.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};oa.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this};oa.prototype.zzDecode=function(){var t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this};oa.prototype.length=function(){var t=this.lo,o=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return i===0?o===0?t<16384?t<128?1:2:t<2097152?3:4:o<16384?o<128?5:6:o<2097152?7:8:i<128?9:10}});var EV=$((XC,HN)=>{(function(n,t){function o(i){return i.default||i}typeof define=="function"&&define.amd?define([],function(){var i={};return t(i),o(i)}):typeof XC=="object"?(t(XC),typeof HN=="object"&&(HN.exports=o(XC))):(function(){var i={};t(i),n.Long=o(i)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:XC,function(n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function o(H,N,k){this.low=H|0,this.high=N|0,this.unsigned=!!k}o.prototype.__isLong__,Object.defineProperty(o.prototype,"__isLong__",{value:!0});function i(H){return(H&&H.__isLong__)===!0}function e(H){var N=Math.clz32(H&-H);return H?31-N:N}o.isLong=i;var a={},A={};function r(H,N){var k,V,Ae;return N?(H>>>=0,(Ae=0<=H&&H<256)&&(V=A[H],V)?V:(k=g(H,0,!0),Ae&&(A[H]=k),k)):(H|=0,(Ae=-128<=H&&H<128)&&(V=a[H],V)?V:(k=g(H,H<0?-1:0,!1),Ae&&(a[H]=k),k))}o.fromInt=r;function s(H,N){if(isNaN(H))return N?R:T;if(N){if(H<0)return R;if(H>=y)return z}else{if(H<=-m)return j;if(H+1>=m)return q}return H<0?s(-H,N).neg():g(H%Q|0,H/Q|0,N)}o.fromNumber=s;function g(H,N,k){return new o(H,N,k)}o.fromBits=g;var c=Math.pow;function I(H,N,k){if(H.length===0)throw Error("empty string");if(typeof N=="number"?(k=N,N=!1):N=!!N,H==="NaN"||H==="Infinity"||H==="+Infinity"||H==="-Infinity")return N?R:T;if(k=k||10,k<2||360)throw Error("interior hyphen");if(V===0)return I(H.substring(1),N,k).neg();for(var Ae=s(c(k,8)),ie=T,De=0;De>>0:this.low},P.toNumber=function(){return this.unsigned?(this.high>>>0)*Q+(this.low>>>0):this.high*Q+(this.low>>>0)},P.toString=function(N){if(N=N||10,N<2||36>>0,Qe=Ee.toString(N);if(De=_e,De.isZero())return Qe+fe;for(;Qe.length<6;)Qe="0"+Qe;fe=""+Qe+fe}},P.getHighBits=function(){return this.high},P.getHighBitsUnsigned=function(){return this.high>>>0},P.getLowBits=function(){return this.low},P.getLowBitsUnsigned=function(){return this.low>>>0},P.getNumBitsAbs=function(){if(this.isNegative())return this.eq(j)?64:this.neg().getNumBitsAbs();for(var N=this.high!=0?this.high:this.low,k=31;k>0&&(N&1<>21;return N?this.unsigned?!1:N===-1&&!(this.low===0&&this.high===-2097152):!0},P.isZero=function(){return this.high===0&&this.low===0},P.eqz=P.isZero,P.isNegative=function(){return!this.unsigned&&this.high<0},P.isPositive=function(){return this.unsigned||this.high>=0},P.isOdd=function(){return(this.low&1)===1},P.isEven=function(){return(this.low&1)===0},P.equals=function(N){return i(N)||(N=d(N)),this.unsigned!==N.unsigned&&this.high>>>31===1&&N.high>>>31===1?!1:this.high===N.high&&this.low===N.low},P.eq=P.equals,P.notEquals=function(N){return!this.eq(N)},P.neq=P.notEquals,P.ne=P.notEquals,P.lessThan=function(N){return this.comp(N)<0},P.lt=P.lessThan,P.lessThanOrEqual=function(N){return this.comp(N)<=0},P.lte=P.lessThanOrEqual,P.le=P.lessThanOrEqual,P.greaterThan=function(N){return this.comp(N)>0},P.gt=P.greaterThan,P.greaterThanOrEqual=function(N){return this.comp(N)>=0},P.gte=P.greaterThanOrEqual,P.ge=P.greaterThanOrEqual,P.compare=function(N){if(i(N)||(N=d(N)),this.eq(N))return 0;var k=this.isNegative(),V=N.isNegative();return k&&!V?-1:!k&&V?1:this.unsigned?N.high>>>0>this.high>>>0||N.high===this.high&&N.low>>>0>this.low>>>0?-1:1:this.sub(N).isNegative()?-1:1},P.comp=P.compare,P.negate=function(){return!this.unsigned&&this.eq(j)?j:this.not().add(L)},P.neg=P.negate,P.add=function(N){i(N)||(N=d(N));var k=this.high>>>16,V=this.high&65535,Ae=this.low>>>16,ie=this.low&65535,De=N.high>>>16,fe=N.high&65535,_e=N.low>>>16,Ee=N.low&65535,Qe=0,Le=0,AA=0,aA=0;return aA+=ie+Ee,AA+=aA>>>16,aA&=65535,AA+=Ae+_e,Le+=AA>>>16,AA&=65535,Le+=V+fe,Qe+=Le>>>16,Le&=65535,Qe+=k+De,Qe&=65535,g(AA<<16|aA,Qe<<16|Le,this.unsigned)},P.subtract=function(N){return i(N)||(N=d(N)),this.add(N.neg())},P.sub=P.subtract,P.multiply=function(N){if(this.isZero())return this;if(i(N)||(N=d(N)),t){var k=t.mul(this.low,this.high,N.low,N.high);return g(k,t.get_high(),this.unsigned)}if(N.isZero())return this.unsigned?R:T;if(this.eq(j))return N.isOdd()?j:T;if(N.eq(j))return this.isOdd()?j:T;if(this.isNegative())return N.isNegative()?this.neg().mul(N.neg()):this.neg().mul(N).neg();if(N.isNegative())return this.mul(N.neg()).neg();if(this.lt(_)&&N.lt(_))return s(this.toNumber()*N.toNumber(),this.unsigned);var V=this.high>>>16,Ae=this.high&65535,ie=this.low>>>16,De=this.low&65535,fe=N.high>>>16,_e=N.high&65535,Ee=N.low>>>16,Qe=N.low&65535,Le=0,AA=0,aA=0,He=0;return He+=De*Qe,aA+=He>>>16,He&=65535,aA+=ie*Qe,AA+=aA>>>16,aA&=65535,aA+=De*Ee,AA+=aA>>>16,aA&=65535,AA+=Ae*Qe,Le+=AA>>>16,AA&=65535,AA+=ie*Ee,Le+=AA>>>16,AA&=65535,AA+=De*_e,Le+=AA>>>16,AA&=65535,Le+=V*Qe+Ae*Ee+ie*_e+De*fe,Le&=65535,g(aA<<16|He,Le<<16|AA,this.unsigned)},P.mul=P.multiply,P.divide=function(N){if(i(N)||(N=d(N)),N.isZero())throw Error("division by zero");if(t){if(!this.unsigned&&this.high===-2147483648&&N.low===-1&&N.high===-1)return this;var k=(this.unsigned?t.div_u:t.div_s)(this.low,this.high,N.low,N.high);return g(k,t.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?R:T;var V,Ae,ie;if(this.unsigned){if(N.unsigned||(N=N.toUnsigned()),N.gt(this))return R;if(N.gt(this.shru(1)))return U;ie=R}else{if(this.eq(j)){if(N.eq(L)||N.eq(F))return j;if(N.eq(j))return L;var De=this.shr(1);return V=De.div(N).shl(1),V.eq(T)?N.isNegative()?L:F:(Ae=this.sub(N.mul(V)),ie=V.add(Ae.div(N)),ie)}else if(N.eq(j))return this.unsigned?R:T;if(this.isNegative())return N.isNegative()?this.neg().div(N.neg()):this.neg().div(N).neg();if(N.isNegative())return this.div(N.neg()).neg();ie=T}for(Ae=this;Ae.gte(N);){V=Math.max(1,Math.floor(Ae.toNumber()/N.toNumber()));for(var fe=Math.ceil(Math.log(V)/Math.LN2),_e=fe<=48?1:c(2,fe-48),Ee=s(V),Qe=Ee.mul(N);Qe.isNegative()||Qe.gt(Ae);)V-=_e,Ee=s(V,this.unsigned),Qe=Ee.mul(N);Ee.isZero()&&(Ee=L),ie=ie.add(Ee),Ae=Ae.sub(Qe)}return ie},P.div=P.divide,P.modulo=function(N){if(i(N)||(N=d(N)),t){var k=(this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,N.low,N.high);return g(k,t.get_high(),this.unsigned)}return this.sub(this.div(N).mul(N))},P.mod=P.modulo,P.rem=P.modulo,P.not=function(){return g(~this.low,~this.high,this.unsigned)},P.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},P.clz=P.countLeadingZeros,P.countTrailingZeros=function(){return this.low?e(this.low):e(this.high)+32},P.ctz=P.countTrailingZeros,P.and=function(N){return i(N)||(N=d(N)),g(this.low&N.low,this.high&N.high,this.unsigned)},P.or=function(N){return i(N)||(N=d(N)),g(this.low|N.low,this.high|N.high,this.unsigned)},P.xor=function(N){return i(N)||(N=d(N)),g(this.low^N.low,this.high^N.high,this.unsigned)},P.shiftLeft=function(N){return i(N)&&(N=N.toInt()),(N&=63)===0?this:N<32?g(this.low<>>32-N,this.unsigned):g(0,this.low<>>N|this.high<<32-N,this.high>>N,this.unsigned):g(this.high>>N-32,this.high>=0?0:-1,this.unsigned)},P.shr=P.shiftRight,P.shiftRightUnsigned=function(N){return i(N)&&(N=N.toInt()),(N&=63)===0?this:N<32?g(this.low>>>N|this.high<<32-N,this.high>>>N,this.unsigned):N===32?g(this.high,0,this.unsigned):g(this.high>>>N-32,0,this.unsigned)},P.shru=P.shiftRightUnsigned,P.shr_u=P.shiftRightUnsigned,P.rotateLeft=function(N){var k;return i(N)&&(N=N.toInt()),(N&=63)===0?this:N===32?g(this.high,this.low,this.unsigned):N<32?(k=32-N,g(this.low<>>k,this.high<>>k,this.unsigned)):(N-=32,k=32-N,g(this.high<>>k,this.low<>>k,this.unsigned))},P.rotl=P.rotateLeft,P.rotateRight=function(N){var k;return i(N)&&(N=N.toInt()),(N&=63)===0?this:N===32?g(this.high,this.low,this.unsigned):N<32?(k=32-N,g(this.high<>>N,this.low<>>N,this.unsigned)):(N-=32,k=32-N,g(this.low<>>N,this.high<>>N,this.unsigned))},P.rotr=P.rotateRight,P.toSigned=function(){return this.unsigned?g(this.low,this.high,!1):this},P.toUnsigned=function(){return this.unsigned?this:g(this.low,this.high,!0)},P.toBytes=function(N){return N?this.toBytesLE():this.toBytesBE()},P.toBytesLE=function(){var N=this.high,k=this.low;return[k&255,k>>>8&255,k>>>16&255,k>>>24,N&255,N>>>8&255,N>>>16&255,N>>>24]},P.toBytesBE=function(){var N=this.high,k=this.low;return[N>>>24,N>>>16&255,N>>>8&255,N&255,k>>>24,k>>>16&255,k>>>8&255,k&255]},o.fromBytes=function(N,k,V){return V?o.fromBytesLE(N,k):o.fromBytesBE(N,k)},o.fromBytesLE=function(N,k){return new o(N[0]|N[1]<<8|N[2]<<16|N[3]<<24,N[4]|N[5]<<8|N[6]<<16|N[7]<<24,k)},o.fromBytesBE=function(N,k){return new o(N[4]<<24|N[5]<<16|N[6]<<8|N[7],N[0]<<24|N[1]<<16|N[2]<<8|N[3],k)},typeof BigInt=="function"&&(o.fromBigInt=function(N,k){var V=Number(BigInt.asIntN(32,N)),Ae=Number(BigInt.asIntN(32,N>>BigInt(32)));return g(V,Ae,k)},o.fromValue=function(N,k){return typeof N=="bigint"?o.fromBigInt(N,k):d(N,k)},P.toBigInt=function(){var N=BigInt(this.low>>>0),k=BigInt(this.unsigned?this.high>>>0:this.high);return k<{"use strict";var BA=KN;BA.asPromise=Wz();BA.base64=eV();BA.EventEmitter=tV();BA.float=gV();BA.utf8=IV();BA.pool=pV();BA.LongBits=hV();function CV(n){return n==="__proto__"||n==="prototype"||n==="constructor"}BA.isUnsafeProperty=CV;BA.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);BA.global=BA.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||KN;BA.emptyArray=Object.freeze?Object.freeze([]):[];BA.emptyObject=Object.freeze?Object.freeze({}):{};BA.isInteger=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t};BA.isString=function(t){return typeof t=="string"||t instanceof String};BA.isObject=function(t){return t&&typeof t=="object"};BA.isset=BA.isSet=function(t,o){var i=t[o];return i!=null&&Object.hasOwnProperty.call(t,o)?typeof i!="object"||(Array.isArray(i)?i.length:Object.keys(i).length)>0:!1};BA.Buffer=(function(){try{var n=BA.global.Buffer;return n.prototype.utf8Write?n:null}catch{return null}})();BA._Buffer_from=null;BA._Buffer_allocUnsafe=null;BA.newBuffer=function(t){return typeof t=="number"?BA.Buffer?BA._Buffer_allocUnsafe(t):new BA.Array(t):BA.Buffer?BA._Buffer_from(t):typeof Uint8Array>"u"?t:new Uint8Array(t)};BA.Array=typeof Uint8Array<"u"?Uint8Array:Array;BA.Long=BA.global.dcodeIO&&BA.global.dcodeIO.Long||BA.global.Long||(function(){try{var n=EV();return n&&n.isLong?n:null}catch{return null}})();BA.key2Re=/^true|false|0|1$/;BA.key32Re=/^-?(?:0|[1-9][0-9]*)$/;BA.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;BA.longToHash=function(t){return t?BA.LongBits.from(t).toHash():BA.LongBits.zeroHash};BA.longFromHash=function(t,o){var i=BA.LongBits.fromHash(t);return BA.Long?BA.Long.fromBits(i.lo,i.hi,o):i.toNumber(!!o)};function uV(n){var t=typeof arguments[arguments.length-1]=="boolean",o=t?arguments.length-1:arguments.length;t=t&&arguments[arguments.length-1];for(var i=1;i-1;--a)if(o[e[a]]===1&&this[e[a]]!==void 0&&this[e[a]]!==null)return e[a]}};BA.oneOfSetter=function(t){return function(o){for(var i=0;i{"use strict";mV.exports=ft;var ko=Qc(),xN,ym=ko.LongBits,fV=ko.base64,QV=ko.utf8;function $C(n,t,o){this.fn=n,this.len=t,this.next=void 0,this.val=o}function jN(){}function yTe(n){this.head=n.head,this.tail=n.tail,this.len=n.len,this.next=n.states}function ft(){this.len=0,this.head=new $C(jN,0,0),this.tail=this.head,this.states=null}var yV=function(){return ko.Buffer?function(){return(ft.create=function(){return new xN})()}:function(){return new ft}};ft.create=yV();ft.alloc=function(t){return new ko.Array(t)};ko.Array!==Array&&(ft.alloc=ko.pool(ft.alloc,ko.Array.prototype.subarray));ft.prototype._push=function(t,o,i){return this.tail=this.tail.next=new $C(t,o,i),this.len+=o,this};function JN(n,t,o){t[o]=n&255}function mTe(n,t,o){for(;n>127;)t[o++]=n&127|128,n>>>=7;t[o]=n}function qN(n,t){this.len=n,this.next=void 0,this.val=t}qN.prototype=Object.create($C.prototype);qN.prototype.fn=mTe;ft.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new qN((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this};ft.prototype.int32=function(t){return(t|=0)<0?this._push(zN,10,ym.fromNumber(t)):this.uint32(t)};ft.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)};function zN(n,t,o){for(var i=n.lo,e=n.hi;e;)t[o++]=i&127|128,i=(i>>>7|e<<25)>>>0,e>>>=7;for(;i>127;)t[o++]=i&127|128,i=i>>>7;t[o++]=i}ft.prototype.uint64=function(t){var o=ym.from(t);return this._push(zN,o.length(),o)};ft.prototype.int64=ft.prototype.uint64;ft.prototype.sint64=function(t){var o=ym.from(t).zzEncode();return this._push(zN,o.length(),o)};ft.prototype.bool=function(t){return this._push(JN,1,t?1:0)};function YN(n,t,o){t[o]=n&255,t[o+1]=n>>>8&255,t[o+2]=n>>>16&255,t[o+3]=n>>>24}ft.prototype.fixed32=function(t){return this._push(YN,4,t>>>0)};ft.prototype.sfixed32=ft.prototype.fixed32;ft.prototype.fixed64=function(t){var o=ym.from(t);return this._push(YN,4,o.lo)._push(YN,4,o.hi)};ft.prototype.sfixed64=ft.prototype.fixed64;ft.prototype.float=function(t){return this._push(ko.float.writeFloatLE,4,t)};ft.prototype.double=function(t){return this._push(ko.float.writeDoubleLE,8,t)};var STe=ko.Array.prototype.set?function(t,o,i){o.set(t,i)}:function(t,o,i){for(var e=0;e>>0;if(!o)return this._push(JN,1,0);if(ko.isString(t)){var i=ft.alloc(o=fV.length(t));fV.decode(t,i,0),t=i}return this.uint32(o)._push(STe,o,t)};ft.prototype.string=function(t){var o=QV.length(t);return o?this.uint32(o)._push(QV.write,o,t):this._push(JN,1,0)};ft.prototype.fork=function(){return this.states=new yTe(this),this.head=this.tail=new $C(jN,0,0),this.len=0,this};ft.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new $C(jN,0,0),this.len=0),this};ft.prototype.ldelim=function(){var t=this.head,o=this.tail,i=this.len;return this.reset().uint32(i),i&&(this.tail.next=t.next,this.tail=o,this.len+=i),this};ft.prototype.finish=function(){for(var t=this.head.next,o=this.constructor.alloc(this.len),i=0;t;)t.fn(t.val,o,i),i+=t.len,t=t.next;return o};ft._configure=function(n){xN=n,ft.create=yV(),xN._configure()}});var DV=$((kgA,wV)=>{"use strict";wV.exports=gs;var SV=VN();(gs.prototype=Object.create(SV.prototype)).constructor=gs;var yc=Qc();function gs(){SV.call(this)}gs._configure=function(){gs.alloc=yc._Buffer_allocUnsafe,gs.writeBytesBuffer=yc.Buffer&&yc.Buffer.prototype instanceof Uint8Array&&yc.Buffer.prototype.set.name==="set"?function(t,o,i){o.set(t,i)}:function(t,o,i){if(t.copy)t.copy(o,i,0,t.length);else for(var e=0;e>>0;return this.uint32(o),o&&this._push(gs.writeBytesBuffer,o,t),this};function wTe(n,t,o){n.length<40?yc.utf8.write(n,t,o):t.utf8Write?t.utf8Write(n,o):t.write(n,o)}gs.prototype.string=function(t){var o=yc.Buffer.byteLength(t);return this.uint32(o),o&&this._push(wTe,o,t),this};gs._configure()});var XN=$((vgA,TV)=>{"use strict";TV.exports=nr;var vo=Qc(),ZN,MV=vo.LongBits,DTe=vo.utf8;function Ri(n,t){return RangeError("index out of range: "+n.pos+" + "+(t||1)+" > "+n.len)}function nr(n){this.buf=n,this.pos=0,this.len=n.length}var OV=typeof Uint8Array<"u"?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new nr(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new nr(t);throw Error("illegal buffer")},_V=function(){return vo.Buffer?function(o){return(nr.create=function(e){return vo.Buffer.isBuffer(e)?new ZN(e):OV(e)})(o)}:OV};nr.create=_V();nr.prototype._slice=vo.Array.prototype.subarray||vo.Array.prototype.slice;function OTe(n){for(var t=0,o=0;o<4;++o){if(n.pos>=n.len)throw Ri(n);var i=n.buf[n.pos++];if(t=(t|(i&127)<>>0,i<128)return t}throw Ri(n)}nr.prototype.uint32=(function(){var t=4294967295;return function(){if(this.len-this.pos<5){if(this.pos>=this.len)throw Ri(this);if(this.buf[this.pos]>=128)return OTe(this)}if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Ri(this,10);return t}})();nr.prototype.int32=function(){return this.uint32()|0};nr.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(t&1)|0};function WN(){var n=new MV(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(n.lo=(n.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n;if(n.lo=(n.lo|(this.buf[this.pos]&127)<<28)>>>0,n.hi=(n.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return n;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ri(this);if(n.lo=(n.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n}return n.lo=(n.lo|(this.buf[this.pos++]&127)<>>0,n}if(this.len-this.pos>4){for(;t<5;++t)if(n.hi=(n.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n}else for(;t<5;++t){if(this.pos>=this.len)throw Ri(this);if(n.hi=(n.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n}throw Error("invalid varint encoding")}nr.prototype.bool=function(){return this.uint32()!==0};function mm(n,t){return(n[t-4]|n[t-3]<<8|n[t-2]<<16|n[t-1]<<24)>>>0}nr.prototype.fixed32=function(){if(this.pos+4>this.len)throw Ri(this,4);return mm(this.buf,this.pos+=4)};nr.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Ri(this,4);return mm(this.buf,this.pos+=4)|0};function bV(){if(this.pos+8>this.len)throw Ri(this,8);return new MV(mm(this.buf,this.pos+=4),mm(this.buf,this.pos+=4))}nr.prototype.float=function(){if(this.pos+4>this.len)throw Ri(this,4);var t=vo.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t};nr.prototype.double=function(){if(this.pos+8>this.len)throw Ri(this,4);var t=vo.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t};nr.prototype.bytes=function(){var t=this.uint32(),o=this.pos,i=this.pos+t;if(i>this.len)throw Ri(this,t);if(this.pos+=t,Array.isArray(this.buf))return this.buf.slice(o,i);if(o===i){var e=vo.Buffer;return e?e.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,o,i)};nr.prototype.string=function(){var t=this.bytes();return DTe.read(t,0,t.length)};nr.prototype.skip=function(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Ri(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Ri(this);while(this.buf[this.pos++]&128);return this};nr.recursionLimit=vo.recursionLimit;nr.prototype.skipType=function(n,t){if(t===void 0&&(t=0),t>nr.recursionLimit)throw Error("maximum nesting depth exceeded");switch(n){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(n=this.uint32()&7)!==4;)this.skipType(n,t+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+n+" at offset "+this.pos)}return this};nr._configure=function(n){ZN=n,nr.create=_V(),ZN._configure();var t=vo.Long?"toLong":"toNumber";vo.merge(nr.prototype,{int64:function(){return WN.call(this)[t](!1)},uint64:function(){return WN.call(this)[t](!0)},sint64:function(){return WN.call(this).zzDecode()[t](!1)},fixed64:function(){return bV.call(this)[t](!0)},sfixed64:function(){return bV.call(this)[t](!1)}})}});var vV=$((PgA,kV)=>{"use strict";kV.exports=al;var RV=XN();(al.prototype=Object.create(RV.prototype)).constructor=al;var NV=Qc();function al(n){RV.call(this,n)}al._configure=function(){NV.Buffer&&(al.prototype._slice=NV.Buffer.prototype.slice)};al.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))};al._configure()});var GV=$((GgA,PV)=>{"use strict";PV.exports=eu;var $N=Qc();(eu.prototype=Object.create($N.EventEmitter.prototype)).constructor=eu;function eu(n,t,o){if(typeof n!="function")throw TypeError("rpcImpl must be a function");$N.EventEmitter.call(this),this.rpcImpl=n,this.requestDelimited=!!t,this.responseDelimited=!!o}eu.prototype.rpcCall=function n(t,o,i,e,a){if(!e)throw TypeError("request must be specified");var A=this;if(!a)return $N.asPromise(n,A,t,o,i,e);if(!A.rpcImpl){setTimeout(function(){a(Error("already ended"))},0);return}try{return A.rpcImpl(t,o[A.requestDelimited?"encodeDelimited":"encode"](e).finish(),function(s,g){if(s)return A.emit("error",s,t),a(s);if(g===null){A.end(!0);return}if(!(g instanceof i))try{g=i[A.responseDelimited?"decodeDelimited":"decode"](g)}catch(c){return A.emit("error",c,t),a(c)}return A.emit("data",g,t),a(null,g)})}catch(r){A.emit("error",r,t),setTimeout(function(){a(r)},0);return}};eu.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var LV=$(FV=>{"use strict";var bTe=FV;bTe.Service=GV()});var HV=$((LgA,UV)=>{"use strict";UV.exports=Object.create(null)});var YV=$(xV=>{"use strict";var ki=xV;ki.build="minimal";ki.Writer=VN();ki.BufferWriter=DV();ki.Reader=XN();ki.BufferReader=vV();ki.util=Qc();ki.rpc=LV();ki.roots=HV();ki.configure=KV;function KV(){ki.util._configure(),ki.Writer._configure(ki.BufferWriter),ki.Reader._configure(ki.BufferReader)}KV()});var Sm=$((HgA,jV)=>{"use strict";jV.exports=YV()});var K6=$(ot=>{"use strict";var bu=Symbol.for("react.element"),Kke=Symbol.for("react.portal"),xke=Symbol.for("react.fragment"),Yke=Symbol.for("react.strict_mode"),jke=Symbol.for("react.profiler"),Jke=Symbol.for("react.provider"),qke=Symbol.for("react.context"),zke=Symbol.for("react.forward_ref"),Vke=Symbol.for("react.suspense"),Wke=Symbol.for("react.memo"),Zke=Symbol.for("react.lazy"),T6=Symbol.iterator;function Xke(n){return n===null||typeof n!="object"?null:(n=T6&&n[T6]||n["@@iterator"],typeof n=="function"?n:null)}var k6={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v6=Object.assign,P6={};function kd(n,t,o){this.props=n,this.context=t,this.refs=P6,this.updater=o||k6}kd.prototype.isReactComponent={};kd.prototype.setState=function(n,t){if(typeof n!="object"&&typeof n!="function"&&n!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,n,t,"setState")};kd.prototype.forceUpdate=function(n){this.updater.enqueueForceUpdate(this,n,"forceUpdate")};function G6(){}G6.prototype=kd.prototype;function sP(n,t,o){this.props=n,this.context=t,this.refs=P6,this.updater=o||k6}var gP=sP.prototype=new G6;gP.constructor=sP;v6(gP,kd.prototype);gP.isPureReactComponent=!0;var N6=Array.isArray,F6=Object.prototype.hasOwnProperty,cP={current:null},L6={key:!0,ref:!0,__self:!0,__source:!0};function U6(n,t,o){var i,e={},a=null,A=null;if(t!=null)for(i in t.ref!==void 0&&(A=t.ref),t.key!==void 0&&(a=""+t.key),t)F6.call(t,i)&&!L6.hasOwnProperty(i)&&(e[i]=t[i]);var r=arguments.length-2;if(r===1)e.children=o;else if(1{"use strict";process.env.NODE_ENV!=="production"&&(function(){"use strict";typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var n="18.3.1",t=Symbol.for("react.element"),o=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),e=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),A=Symbol.for("react.provider"),r=Symbol.for("react.context"),s=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),c=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),B=Symbol.for("react.offscreen"),f=Symbol.iterator,Q="@@iterator";function y(K){if(K===null||typeof K!="object")return null;var te=f&&K[f]||K[Q];return typeof te=="function"?te:null}var m={current:null},_={transition:null},T={current:null,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1},R={current:null},L={},U=null;function F(K){U=K}L.setExtraStackFrame=function(K){U=K},L.getCurrentStack=null,L.getStackAddendum=function(){var K="";U&&(K+=U);var te=L.getCurrentStack;return te&&(K+=te()||""),K};var q=!1,z=!1,j=!1,P=!1,J=!1,H={ReactCurrentDispatcher:m,ReactCurrentBatchConfig:_,ReactCurrentOwner:R};H.ReactDebugCurrentFrame=L,H.ReactCurrentActQueue=T;function N(K){{for(var te=arguments.length,de=new Array(te>1?te-1:0),Se=1;Se1?te-1:0),Se=1;Se1){for(var zt=Array(vt),Vt=0;Vt1){for(var ar=Array(Vt),br=0;br is not supported and will be removed in a future major release. Did you mean to render instead?")),te.Provider},set:function(EA){te.Provider=EA}},_currentValue:{get:function(){return te._currentValue},set:function(EA){te._currentValue=EA}},_currentValue2:{get:function(){return te._currentValue2},set:function(EA){te._currentValue2=EA}},_threadCount:{get:function(){return te._threadCount},set:function(EA){te._threadCount=EA}},Consumer:{get:function(){return de||(de=!0,k("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?")),te.Consumer}},displayName:{get:function(){return te.displayName},set:function(EA){qe||(N("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.",EA),qe=!0)}}}),te.Consumer=MA}return te._currentRenderer=null,te._currentRenderer2=null,te}var he=-1,me=0,je=1,lA=2;function QA(K){if(K._status===he){var te=K._result,de=te();if(de.then(function(MA){if(K._status===me||K._status===he){var EA=K;EA._status=je,EA._result=MA}},function(MA){if(K._status===me||K._status===he){var EA=K;EA._status=lA,EA._result=MA}}),K._status===he){var Se=K;Se._status=me,Se._result=de}}if(K._status===je){var qe=K._result;return qe===void 0&&k(`lazy: Expected the result of a dynamic import() call. Instead received: %s Your code should look like: const MyComponent = lazy(() => import('./MyComponent')) @@ -33,27 +33,27 @@ Your code should look like: Did you accidentally put curly braces around the import?`,qe),"default"in qe||k(`lazy: Expected the result of a dynamic import() call. Instead received: %s Your code should look like: - const MyComponent = lazy(() => import('./MyComponent'))`,qe),qe.default}else throw H._result}function $A(H){var te={_status:he,_result:H},de={$$typeof:d,_payload:te,_init:QA};{var Se,qe;Object.defineProperties(de,{defaultProps:{configurable:!0,get:function(){return Se},set:function(MA){k("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),Se=MA,Object.defineProperty(de,"defaultProps",{enumerable:!0})}},propTypes:{configurable:!0,get:function(){return qe},set:function(MA){k("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),qe=MA,Object.defineProperty(de,"propTypes",{enumerable:!0})}}})}return de}function RA(H){H!=null&&H.$$typeof===I?k("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof H!="function"?k("forwardRef requires a render function but was given %s.",H===null?"null":typeof H):H.length!==0&&H.length!==2&&k("forwardRef render functions accept exactly two parameters: props and ref. %s",H.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),H!=null&&(H.defaultProps!=null||H.propTypes!=null)&&k("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");var te={$$typeof:s,render:H};{var de;Object.defineProperty(te,"displayName",{enumerable:!1,configurable:!0,get:function(){return de},set:function(Se){de=Se,!H.name&&!H.displayName&&(H.displayName=Se)}})}return te}var xA;xA=Symbol.for("react.module.reference");function et(H){return!!(typeof H=="string"||typeof H=="function"||H===i||H===a||J||H===e||H===g||H===c||P||H===B||q||z||j||typeof H=="object"&&H!==null&&(H.$$typeof===d||H.$$typeof===I||H.$$typeof===A||H.$$typeof===r||H.$$typeof===s||H.$$typeof===xA||H.getModuleId!==void 0))}function ve(H,te){et(H)||k("memo: The first argument must be a component. Instead received: %s",H===null?"null":typeof H);var de={$$typeof:I,type:H,compare:te===void 0?null:te};{var Se;Object.defineProperty(de,"displayName",{enumerable:!1,configurable:!0,get:function(){return Se},set:function(qe){Se=qe,!H.name&&!H.displayName&&(H.displayName=qe)}})}return de}function tA(){var H=m.current;return H===null&&k(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: + const MyComponent = lazy(() => import('./MyComponent'))`,qe),qe.default}else throw K._result}function $A(K){var te={_status:he,_result:K},de={$$typeof:d,_payload:te,_init:QA};{var Se,qe;Object.defineProperties(de,{defaultProps:{configurable:!0,get:function(){return Se},set:function(MA){k("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),Se=MA,Object.defineProperty(de,"defaultProps",{enumerable:!0})}},propTypes:{configurable:!0,get:function(){return qe},set:function(MA){k("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),qe=MA,Object.defineProperty(de,"propTypes",{enumerable:!0})}}})}return de}function RA(K){K!=null&&K.$$typeof===I?k("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof K!="function"?k("forwardRef requires a render function but was given %s.",K===null?"null":typeof K):K.length!==0&&K.length!==2&&k("forwardRef render functions accept exactly two parameters: props and ref. %s",K.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),K!=null&&(K.defaultProps!=null||K.propTypes!=null)&&k("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");var te={$$typeof:s,render:K};{var de;Object.defineProperty(te,"displayName",{enumerable:!1,configurable:!0,get:function(){return de},set:function(Se){de=Se,!K.name&&!K.displayName&&(K.displayName=Se)}})}return te}var xA;xA=Symbol.for("react.module.reference");function et(K){return!!(typeof K=="string"||typeof K=="function"||K===i||K===a||J||K===e||K===g||K===c||P||K===B||q||z||j||typeof K=="object"&&K!==null&&(K.$$typeof===d||K.$$typeof===I||K.$$typeof===A||K.$$typeof===r||K.$$typeof===s||K.$$typeof===xA||K.getModuleId!==void 0))}function ve(K,te){et(K)||k("memo: The first argument must be a component. Instead received: %s",K===null?"null":typeof K);var de={$$typeof:I,type:K,compare:te===void 0?null:te};{var Se;Object.defineProperty(de,"displayName",{enumerable:!1,configurable:!0,get:function(){return Se},set:function(qe){Se=qe,!K.name&&!K.displayName&&(K.displayName=qe)}})}return de}function tA(){var K=m.current;return K===null&&k(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app -See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.`),H}function At(H){var te=tA();if(H._context!==void 0){var de=H._context;de.Consumer===H?k("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"):de.Provider===H&&k("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?")}return te.useContext(H)}function zr(H){var te=tA();return te.useState(H)}function rr(H,te,de){var Se=tA();return Se.useReducer(H,te,de)}function po(H){var te=tA();return te.useRef(H)}function dM(H,te){var de=tA();return de.useEffect(H,te)}function hM(H,te){var de=tA();return de.useInsertionEffect(H,te)}function ho(H,te){var de=tA();return de.useLayoutEffect(H,te)}function dp(H,te){var de=tA();return de.useCallback(H,te)}function EM(H,te){var de=tA();return de.useMemo(H,te)}function CM(H,te,de){var Se=tA();return Se.useImperativeHandle(H,te,de)}function pIe(H,te){{var de=tA();return de.useDebugValue(H,te)}}function dIe(){var H=tA();return H.useTransition()}function hIe(H){var te=tA();return te.useDeferredValue(H)}function EIe(){var H=tA();return H.useId()}function CIe(H,te,de){var Se=tA();return Se.useSyncExternalStore(H,te,de)}var mE=0,rK,aK,iK,oK,nK,sK,gK;function cK(){}cK.__reactDisabledLog=!0;function uIe(){{if(mE===0){rK=console.log,aK=console.info,iK=console.warn,oK=console.error,nK=console.group,sK=console.groupCollapsed,gK=console.groupEnd;var H={configurable:!0,enumerable:!0,value:cK,writable:!0};Object.defineProperties(console,{info:H,log:H,warn:H,error:H,group:H,groupCollapsed:H,groupEnd:H})}mE++}}function BIe(){{if(mE--,mE===0){var H={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:fe({},H,{value:rK}),info:fe({},H,{value:aK}),warn:fe({},H,{value:iK}),error:fe({},H,{value:oK}),group:fe({},H,{value:nK}),groupCollapsed:fe({},H,{value:sK}),groupEnd:fe({},H,{value:gK})})}mE<0&&k("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var uM=U.ReactCurrentDispatcher,BM;function Wf(H,te,de){{if(BM===void 0)try{throw Error()}catch(qe){var Se=qe.stack.trim().match(/\n( *(at )?)/);BM=Se&&Se[1]||""}return` -`+BM+H}}var fM=!1,Zf;{var fIe=typeof WeakMap=="function"?WeakMap:Map;Zf=new fIe}function IK(H,te){if(!H||fM)return"";{var de=Zf.get(H);if(de!==void 0)return de}var Se;fM=!0;var qe=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var MA;MA=uM.current,uM.current=null,uIe();try{if(te){var EA=function(){throw Error()};if(Object.defineProperty(EA.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(EA,[])}catch(ha){Se=ha}Reflect.construct(H,[],EA)}else{try{EA.call()}catch(ha){Se=ha}H.call(EA.prototype)}}else{try{throw Error()}catch(ha){Se=ha}H()}}catch(ha){if(ha&&Se&&typeof ha.stack=="string"){for(var KA=ha.stack.split(` +See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.`),K}function At(K){var te=tA();if(K._context!==void 0){var de=K._context;de.Consumer===K?k("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"):de.Provider===K&&k("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?")}return te.useContext(K)}function zr(K){var te=tA();return te.useState(K)}function rr(K,te,de){var Se=tA();return Se.useReducer(K,te,de)}function po(K){var te=tA();return te.useRef(K)}function dM(K,te){var de=tA();return de.useEffect(K,te)}function hM(K,te){var de=tA();return de.useInsertionEffect(K,te)}function ho(K,te){var de=tA();return de.useLayoutEffect(K,te)}function dp(K,te){var de=tA();return de.useCallback(K,te)}function EM(K,te){var de=tA();return de.useMemo(K,te)}function CM(K,te,de){var Se=tA();return Se.useImperativeHandle(K,te,de)}function pIe(K,te){{var de=tA();return de.useDebugValue(K,te)}}function dIe(){var K=tA();return K.useTransition()}function hIe(K){var te=tA();return te.useDeferredValue(K)}function EIe(){var K=tA();return K.useId()}function CIe(K,te,de){var Se=tA();return Se.useSyncExternalStore(K,te,de)}var mE=0,rK,aK,iK,oK,nK,sK,gK;function cK(){}cK.__reactDisabledLog=!0;function uIe(){{if(mE===0){rK=console.log,aK=console.info,iK=console.warn,oK=console.error,nK=console.group,sK=console.groupCollapsed,gK=console.groupEnd;var K={configurable:!0,enumerable:!0,value:cK,writable:!0};Object.defineProperties(console,{info:K,log:K,warn:K,error:K,group:K,groupCollapsed:K,groupEnd:K})}mE++}}function BIe(){{if(mE--,mE===0){var K={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:fe({},K,{value:rK}),info:fe({},K,{value:aK}),warn:fe({},K,{value:iK}),error:fe({},K,{value:oK}),group:fe({},K,{value:nK}),groupCollapsed:fe({},K,{value:sK}),groupEnd:fe({},K,{value:gK})})}mE<0&&k("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var uM=H.ReactCurrentDispatcher,BM;function Wf(K,te,de){{if(BM===void 0)try{throw Error()}catch(qe){var Se=qe.stack.trim().match(/\n( *(at )?)/);BM=Se&&Se[1]||""}return` +`+BM+K}}var fM=!1,Zf;{var fIe=typeof WeakMap=="function"?WeakMap:Map;Zf=new fIe}function IK(K,te){if(!K||fM)return"";{var de=Zf.get(K);if(de!==void 0)return de}var Se;fM=!0;var qe=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var MA;MA=uM.current,uM.current=null,uIe();try{if(te){var EA=function(){throw Error()};if(Object.defineProperty(EA.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(EA,[])}catch(ha){Se=ha}Reflect.construct(K,[],EA)}else{try{EA.call()}catch(ha){Se=ha}K.call(EA.prototype)}}else{try{throw Error()}catch(ha){Se=ha}K()}}catch(ha){if(ha&&Se&&typeof ha.stack=="string"){for(var KA=ha.stack.split(` `),pt=Se.stack.split(` `),vt=KA.length-1,zt=pt.length-1;vt>=1&&zt>=0&&KA[vt]!==pt[zt];)zt--;for(;vt>=1&&zt>=0;vt--,zt--)if(KA[vt]!==pt[zt]){if(vt!==1||zt!==1)do if(vt--,zt--,zt<0||KA[vt]!==pt[zt]){var Vt=` -`+KA[vt].replace(" at new "," at ");return H.displayName&&Vt.includes("")&&(Vt=Vt.replace("",H.displayName)),typeof H=="function"&&Zf.set(H,Vt),Vt}while(vt>=1&&zt>=0);break}}}finally{fM=!1,uM.current=MA,BIe(),Error.prepareStackTrace=qe}var ar=H?H.displayName||H.name:"",br=ar?Wf(ar):"";return typeof H=="function"&&Zf.set(H,br),br}function QIe(H,te,de){return IK(H,!1)}function yIe(H){var te=H.prototype;return!!(te&&te.isReactComponent)}function Xf(H,te,de){if(H==null)return"";if(typeof H=="function")return IK(H,yIe(H));if(typeof H=="string")return Wf(H);switch(H){case g:return Wf("Suspense");case c:return Wf("SuspenseList")}if(typeof H=="object")switch(H.$$typeof){case s:return QIe(H.render);case I:return Xf(H.type,te,de);case d:{var Se=H,qe=Se._payload,MA=Se._init;try{return Xf(MA(qe),te,de)}catch{}}}return""}var lK={},pK=U.ReactDebugCurrentFrame;function $f(H){if(H){var te=H._owner,de=Xf(H.type,H._source,te?te.type:null);pK.setExtraStackFrame(de)}else pK.setExtraStackFrame(null)}function mIe(H,te,de,Se,qe){{var MA=Function.call.bind(CA);for(var EA in H)if(MA(H,EA)){var KA=void 0;try{if(typeof H[EA]!="function"){var pt=Error((Se||"React class")+": "+de+" type `"+EA+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof H[EA]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw pt.name="Invariant Violation",pt}KA=H[EA](te,EA,Se,de,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(vt){KA=vt}KA&&!(KA instanceof Error)&&($f(qe),k("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",Se||"React class",de,EA,typeof KA),$f(null)),KA instanceof Error&&!(KA.message in lK)&&(lK[KA.message]=!0,$f(qe),k("Failed %s type: %s",de,KA.message),$f(null))}}}function hp(H){if(H){var te=H._owner,de=Xf(H.type,H._source,te?te.type:null);L(de)}else L(null)}var QM;QM=!1;function dK(){if(R.current){var H=Me(R.current.type);if(H)return` +`+KA[vt].replace(" at new "," at ");return K.displayName&&Vt.includes("")&&(Vt=Vt.replace("",K.displayName)),typeof K=="function"&&Zf.set(K,Vt),Vt}while(vt>=1&&zt>=0);break}}}finally{fM=!1,uM.current=MA,BIe(),Error.prepareStackTrace=qe}var ar=K?K.displayName||K.name:"",br=ar?Wf(ar):"";return typeof K=="function"&&Zf.set(K,br),br}function QIe(K,te,de){return IK(K,!1)}function yIe(K){var te=K.prototype;return!!(te&&te.isReactComponent)}function Xf(K,te,de){if(K==null)return"";if(typeof K=="function")return IK(K,yIe(K));if(typeof K=="string")return Wf(K);switch(K){case g:return Wf("Suspense");case c:return Wf("SuspenseList")}if(typeof K=="object")switch(K.$$typeof){case s:return QIe(K.render);case I:return Xf(K.type,te,de);case d:{var Se=K,qe=Se._payload,MA=Se._init;try{return Xf(MA(qe),te,de)}catch{}}}return""}var lK={},pK=H.ReactDebugCurrentFrame;function $f(K){if(K){var te=K._owner,de=Xf(K.type,K._source,te?te.type:null);pK.setExtraStackFrame(de)}else pK.setExtraStackFrame(null)}function mIe(K,te,de,Se,qe){{var MA=Function.call.bind(CA);for(var EA in K)if(MA(K,EA)){var KA=void 0;try{if(typeof K[EA]!="function"){var pt=Error((Se||"React class")+": "+de+" type `"+EA+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof K[EA]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw pt.name="Invariant Violation",pt}KA=K[EA](te,EA,Se,de,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(vt){KA=vt}KA&&!(KA instanceof Error)&&($f(qe),k("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",Se||"React class",de,EA,typeof KA),$f(null)),KA instanceof Error&&!(KA.message in lK)&&(lK[KA.message]=!0,$f(qe),k("Failed %s type: %s",de,KA.message),$f(null))}}}function hp(K){if(K){var te=K._owner,de=Xf(K.type,K._source,te?te.type:null);F(de)}else F(null)}var QM;QM=!1;function dK(){if(R.current){var K=Me(R.current.type);if(K)return` -Check the render method of \``+H+"`."}return""}function SIe(H){if(H!==void 0){var te=H.fileName.replace(/^.*[\\\/]/,""),de=H.lineNumber;return` +Check the render method of \``+K+"`."}return""}function SIe(K){if(K!==void 0){var te=K.fileName.replace(/^.*[\\\/]/,""),de=K.lineNumber;return` -Check your code at `+te+":"+de+"."}return""}function wIe(H){return H!=null?SIe(H.__source):""}var hK={};function DIe(H){var te=dK();if(!te){var de=typeof H=="string"?H:H.displayName||H.name;de&&(te=` +Check your code at `+te+":"+de+"."}return""}function wIe(K){return K!=null?SIe(K.__source):""}var hK={};function DIe(K){var te=dK();if(!te){var de=typeof K=="string"?K:K.displayName||K.name;de&&(te=` -Check the top-level render call using <`+de+">.")}return te}function EK(H,te){if(!(!H._store||H._store.validated||H.key!=null)){H._store.validated=!0;var de=DIe(te);if(!hK[de]){hK[de]=!0;var Se="";H&&H._owner&&H._owner!==R.current&&(Se=" It was passed a child from "+Me(H._owner.type)+"."),hp(H),k('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',de,Se),hp(null)}}}function CK(H,te){if(typeof H=="object"){if(Ye(H))for(var de=0;de",qe=" Did you accidentally export a JSX literal instead of a component?"):EA=typeof H,k("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",EA,qe)}var KA=Ie.apply(this,arguments);if(KA==null)return KA;if(Se)for(var pt=2;pt10&&N("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),Se._updatedFibers.clear()}}}var QK=!1,eQ=null;function TIe(H){if(eQ===null)try{var te=("require"+Math.random()).slice(0,7),de=yS&&yS[te];eQ=de.call(yS,"timers").setImmediate}catch{eQ=function(qe){QK===!1&&(QK=!0,typeof MessageChannel>"u"&&k("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var MA=new MessageChannel;MA.port1.onmessage=qe,MA.port2.postMessage(void 0)}}return eQ(H)}var Ep=0,yK=!1;function mK(H){{var te=Ep;Ep++,T.current===null&&(T.current=[]);var de=T.isBatchingLegacy,Se;try{if(T.isBatchingLegacy=!0,Se=H(),!de&&T.didScheduleLegacyUpdate){var qe=T.current;qe!==null&&(T.didScheduleLegacyUpdate=!1,SM(qe))}}catch(ar){throw AQ(te),ar}finally{T.isBatchingLegacy=de}if(Se!==null&&typeof Se=="object"&&typeof Se.then=="function"){var MA=Se,EA=!1,KA={then:function(ar,br){EA=!0,MA.then(function(ha){AQ(te),Ep===0?yM(ha,ar,br):ar(ha)},function(ha){AQ(te),br(ha)})}};return!yK&&typeof Promise<"u"&&Promise.resolve().then(function(){}).then(function(){EA||(yK=!0,k("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),KA}else{var pt=Se;if(AQ(te),Ep===0){var vt=T.current;vt!==null&&(SM(vt),T.current=null);var zt={then:function(ar,br){T.current===null?(T.current=[],yM(pt,ar,br)):ar(pt)}};return zt}else{var Vt={then:function(ar,br){ar(pt)}};return Vt}}}}function AQ(H){H!==Ep-1&&k("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),Ep=H}function yM(H,te,de){{var Se=T.current;if(Se!==null)try{SM(Se),TIe(function(){Se.length===0?(T.current=null,te(H)):yM(H,te,de)})}catch(qe){de(qe)}else te(H)}}var mM=!1;function SM(H){if(!mM){mM=!0;var te=0;try{for(;te{"use strict";process.env.NODE_ENV==="production"?lP.exports=K6():lP.exports=x6()});var yl=$((lBA,VZ)=>{"use strict";var _w=$e("crypto"),n2e=$e("assert");function Uo(n){if(!(n instanceof Buffer))throw TypeError(`Expected Buffer instead of: ${n.constructor.name}`);return n}function s2e(n,t,o){Uo(n),Uo(t),Uo(o);let i=_w.createCipheriv("aes-256-cbc",n,o);return Buffer.concat([i.update(t),i.final()])}function g2e(n,t,o){Uo(n),Uo(t),Uo(o);let i=_w.createDecipheriv("aes-256-cbc",n,o);return Buffer.concat([i.update(t),i.final()])}function Vd(n,t){Uo(n),Uo(t);let o=_w.createHmac("sha256",n);return o.update(t),Buffer.from(o.digest())}function c2e(n){Uo(n);let t=_w.createHash("sha512");return t.update(n),t.digest()}function I2e(n,t,o,i){if(Uo(n),Uo(t),Uo(o),t.byteLength!=32)throw new Error("Got salt of incorrect length");i=i||3,n2e(i>=1&&i<=3);let e=Vd(t,n),a=new Uint8Array(o.byteLength+1+32);a.set(o,32),a[a.length-1]=1;let A=[Vd(e,Buffer.from(a.slice(32)))];return i>1&&(a.set(A[A.length-1]),a[a.length-1]=2,A.push(Vd(e,Buffer.from(a)))),i>2&&(a.set(A[A.length-1]),a[a.length-1]=3,A.push(Vd(e,Buffer.from(a)))),A}function l2e(n,t,o,i){let e=Vd(t,n).slice(0,i);if(o.length!==i||e.length!==i)throw new Error("Bad MAC length");if(!o.equals(e))throw new Error("Bad MAC")}VZ.exports={deriveSecrets:I2e,decrypt:g2e,encrypt:s2e,hash:c2e,calculateMAC:Vd,verifyMAC:l2e}});var g9=$(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var pBA=new Uint8Array(16),r9=new Uint8Array(32);r9[0]=9;function dA(n){var t,o=new Float64Array(16);if(n)for(t=0;t>24&255,n[t+1]=o>>16&255,n[t+2]=o>>8&255,n[t+3]=o&255,n[t+4]=i>>24&255,n[t+5]=i>>16&255,n[t+6]=i>>8&255,n[t+7]=i&255}function C2e(n,t,o,i,e){var a,A=0;for(a=0;a>>8)-1}function a9(n,t,o,i){return C2e(n,t,o,i,32)}function Rc(n,t){var o;for(o=0;o<16;o++)n[o]=t[o]|0}function UG(n){var t,o,i=1;for(t=0;t<16;t++)o=n[t]+i+65535,i=Math.floor(o/65536),n[t]=o-i*65536;n[0]+=i-1+37*(i-1)}function Wd(n,t,o){for(var i,e=~(o-1),a=0;a<16;a++)i=e&(n[a]^t[a]),n[a]^=i,t[a]^=i}function Xd(n,t){var o,i,e,a=dA(),A=dA();for(o=0;o<16;o++)A[o]=t[o];for(UG(A),UG(A),UG(A),i=0;i<2;i++){for(a[0]=A[0]-65517,o=1;o<15;o++)a[o]=A[o]-65535-(a[o-1]>>16&1),a[o-1]&=65535;a[15]=A[15]-32767-(a[14]>>16&1),e=a[15]>>16&1,a[14]&=65535,Wd(A,a,1-e)}for(o=0;o<16;o++)n[2*o]=A[o]&255,n[2*o+1]=A[o]>>8}function $Z(n,t){var o=new Uint8Array(32),i=new Uint8Array(32);return Xd(o,n),Xd(i,t),a9(o,0,i,0)}function i9(n){var t=new Uint8Array(32);return Xd(t,n),t[0]&1}function jG(n,t){var o;for(o=0;o<16;o++)n[o]=t[2*o]+(t[2*o+1]<<8);n[15]&=32767}function Dn(n,t,o){for(var i=0;i<16;i++)n[i]=t[i]+o[i]}function bn(n,t,o){for(var i=0;i<16;i++)n[i]=t[i]-o[i]}function It(n,t,o){var i,e,a=0,A=0,r=0,s=0,g=0,c=0,I=0,d=0,B=0,f=0,Q=0,y=0,m=0,_=0,T=0,R=0,F=0,K=0,L=0,q=0,z=0,j=0,P=0,J=0,U=0,N=0,k=0,V=0,Ae=0,ie=0,De=0,fe=o[0],_e=o[1],Ee=o[2],Qe=o[3],Le=o[4],AA=o[5],aA=o[6],He=o[7],ce=o[8],Be=o[9],We=o[10],Ye=o[11],Re=o[12],Ze=o[13],iA=o[14],gA=o[15];i=t[0],a+=i*fe,A+=i*_e,r+=i*Ee,s+=i*Qe,g+=i*Le,c+=i*AA,I+=i*aA,d+=i*He,B+=i*ce,f+=i*Be,Q+=i*We,y+=i*Ye,m+=i*Re,_+=i*Ze,T+=i*iA,R+=i*gA,i=t[1],A+=i*fe,r+=i*_e,s+=i*Ee,g+=i*Qe,c+=i*Le,I+=i*AA,d+=i*aA,B+=i*He,f+=i*ce,Q+=i*Be,y+=i*We,m+=i*Ye,_+=i*Re,T+=i*Ze,R+=i*iA,F+=i*gA,i=t[2],r+=i*fe,s+=i*_e,g+=i*Ee,c+=i*Qe,I+=i*Le,d+=i*AA,B+=i*aA,f+=i*He,Q+=i*ce,y+=i*Be,m+=i*We,_+=i*Ye,T+=i*Re,R+=i*Ze,F+=i*iA,K+=i*gA,i=t[3],s+=i*fe,g+=i*_e,c+=i*Ee,I+=i*Qe,d+=i*Le,B+=i*AA,f+=i*aA,Q+=i*He,y+=i*ce,m+=i*Be,_+=i*We,T+=i*Ye,R+=i*Re,F+=i*Ze,K+=i*iA,L+=i*gA,i=t[4],g+=i*fe,c+=i*_e,I+=i*Ee,d+=i*Qe,B+=i*Le,f+=i*AA,Q+=i*aA,y+=i*He,m+=i*ce,_+=i*Be,T+=i*We,R+=i*Ye,F+=i*Re,K+=i*Ze,L+=i*iA,q+=i*gA,i=t[5],c+=i*fe,I+=i*_e,d+=i*Ee,B+=i*Qe,f+=i*Le,Q+=i*AA,y+=i*aA,m+=i*He,_+=i*ce,T+=i*Be,R+=i*We,F+=i*Ye,K+=i*Re,L+=i*Ze,q+=i*iA,z+=i*gA,i=t[6],I+=i*fe,d+=i*_e,B+=i*Ee,f+=i*Qe,Q+=i*Le,y+=i*AA,m+=i*aA,_+=i*He,T+=i*ce,R+=i*Be,F+=i*We,K+=i*Ye,L+=i*Re,q+=i*Ze,z+=i*iA,j+=i*gA,i=t[7],d+=i*fe,B+=i*_e,f+=i*Ee,Q+=i*Qe,y+=i*Le,m+=i*AA,_+=i*aA,T+=i*He,R+=i*ce,F+=i*Be,K+=i*We,L+=i*Ye,q+=i*Re,z+=i*Ze,j+=i*iA,P+=i*gA,i=t[8],B+=i*fe,f+=i*_e,Q+=i*Ee,y+=i*Qe,m+=i*Le,_+=i*AA,T+=i*aA,R+=i*He,F+=i*ce,K+=i*Be,L+=i*We,q+=i*Ye,z+=i*Re,j+=i*Ze,P+=i*iA,J+=i*gA,i=t[9],f+=i*fe,Q+=i*_e,y+=i*Ee,m+=i*Qe,_+=i*Le,T+=i*AA,R+=i*aA,F+=i*He,K+=i*ce,L+=i*Be,q+=i*We,z+=i*Ye,j+=i*Re,P+=i*Ze,J+=i*iA,U+=i*gA,i=t[10],Q+=i*fe,y+=i*_e,m+=i*Ee,_+=i*Qe,T+=i*Le,R+=i*AA,F+=i*aA,K+=i*He,L+=i*ce,q+=i*Be,z+=i*We,j+=i*Ye,P+=i*Re,J+=i*Ze,U+=i*iA,N+=i*gA,i=t[11],y+=i*fe,m+=i*_e,_+=i*Ee,T+=i*Qe,R+=i*Le,F+=i*AA,K+=i*aA,L+=i*He,q+=i*ce,z+=i*Be,j+=i*We,P+=i*Ye,J+=i*Re,U+=i*Ze,N+=i*iA,k+=i*gA,i=t[12],m+=i*fe,_+=i*_e,T+=i*Ee,R+=i*Qe,F+=i*Le,K+=i*AA,L+=i*aA,q+=i*He,z+=i*ce,j+=i*Be,P+=i*We,J+=i*Ye,U+=i*Re,N+=i*Ze,k+=i*iA,V+=i*gA,i=t[13],_+=i*fe,T+=i*_e,R+=i*Ee,F+=i*Qe,K+=i*Le,L+=i*AA,q+=i*aA,z+=i*He,j+=i*ce,P+=i*Be,J+=i*We,U+=i*Ye,N+=i*Re,k+=i*Ze,V+=i*iA,Ae+=i*gA,i=t[14],T+=i*fe,R+=i*_e,F+=i*Ee,K+=i*Qe,L+=i*Le,q+=i*AA,z+=i*aA,j+=i*He,P+=i*ce,J+=i*Be,U+=i*We,N+=i*Ye,k+=i*Re,V+=i*Ze,Ae+=i*iA,ie+=i*gA,i=t[15],R+=i*fe,F+=i*_e,K+=i*Ee,L+=i*Qe,q+=i*Le,z+=i*AA,j+=i*aA,P+=i*He,J+=i*ce,U+=i*Be,N+=i*We,k+=i*Ye,V+=i*Re,Ae+=i*Ze,ie+=i*iA,De+=i*gA,a+=38*F,A+=38*K,r+=38*L,s+=38*q,g+=38*z,c+=38*j,I+=38*P,d+=38*J,B+=38*U,f+=38*N,Q+=38*k,y+=38*V,m+=38*Ae,_+=38*ie,T+=38*De,e=1,i=a+e+65535,e=Math.floor(i/65536),a=i-e*65536,i=A+e+65535,e=Math.floor(i/65536),A=i-e*65536,i=r+e+65535,e=Math.floor(i/65536),r=i-e*65536,i=s+e+65535,e=Math.floor(i/65536),s=i-e*65536,i=g+e+65535,e=Math.floor(i/65536),g=i-e*65536,i=c+e+65535,e=Math.floor(i/65536),c=i-e*65536,i=I+e+65535,e=Math.floor(i/65536),I=i-e*65536,i=d+e+65535,e=Math.floor(i/65536),d=i-e*65536,i=B+e+65535,e=Math.floor(i/65536),B=i-e*65536,i=f+e+65535,e=Math.floor(i/65536),f=i-e*65536,i=Q+e+65535,e=Math.floor(i/65536),Q=i-e*65536,i=y+e+65535,e=Math.floor(i/65536),y=i-e*65536,i=m+e+65535,e=Math.floor(i/65536),m=i-e*65536,i=_+e+65535,e=Math.floor(i/65536),_=i-e*65536,i=T+e+65535,e=Math.floor(i/65536),T=i-e*65536,i=R+e+65535,e=Math.floor(i/65536),R=i-e*65536,a+=e-1+37*(e-1),e=1,i=a+e+65535,e=Math.floor(i/65536),a=i-e*65536,i=A+e+65535,e=Math.floor(i/65536),A=i-e*65536,i=r+e+65535,e=Math.floor(i/65536),r=i-e*65536,i=s+e+65535,e=Math.floor(i/65536),s=i-e*65536,i=g+e+65535,e=Math.floor(i/65536),g=i-e*65536,i=c+e+65535,e=Math.floor(i/65536),c=i-e*65536,i=I+e+65535,e=Math.floor(i/65536),I=i-e*65536,i=d+e+65535,e=Math.floor(i/65536),d=i-e*65536,i=B+e+65535,e=Math.floor(i/65536),B=i-e*65536,i=f+e+65535,e=Math.floor(i/65536),f=i-e*65536,i=Q+e+65535,e=Math.floor(i/65536),Q=i-e*65536,i=y+e+65535,e=Math.floor(i/65536),y=i-e*65536,i=m+e+65535,e=Math.floor(i/65536),m=i-e*65536,i=_+e+65535,e=Math.floor(i/65536),_=i-e*65536,i=T+e+65535,e=Math.floor(i/65536),T=i-e*65536,i=R+e+65535,e=Math.floor(i/65536),R=i-e*65536,a+=e-1+37*(e-1),n[0]=a,n[1]=A,n[2]=r,n[3]=s,n[4]=g,n[5]=c,n[6]=I,n[7]=d,n[8]=B,n[9]=f,n[10]=Q,n[11]=y,n[12]=m,n[13]=_,n[14]=T,n[15]=R}function On(n,t){It(n,t,t)}function JG(n,t){var o=dA(),i;for(i=0;i<16;i++)o[i]=t[i];for(i=253;i>=0;i--)On(o,o),i!==2&&i!==4&&It(o,o,t);for(i=0;i<16;i++)n[i]=o[i]}function u2e(n,t){var o=dA(),i;for(i=0;i<16;i++)o[i]=t[i];for(i=250;i>=0;i--)On(o,o),i!==1&&It(o,o,t);for(i=0;i<16;i++)n[i]=o[i]}function o9(n,t,o){var i=new Uint8Array(32),e=new Float64Array(80),a,A,r=dA(),s=dA(),g=dA(),c=dA(),I=dA(),d=dA();for(A=0;A<31;A++)i[A]=t[A];for(i[31]=t[31]&127|64,i[0]&=248,jG(e,o),A=0;A<16;A++)s[A]=e[A],c[A]=r[A]=g[A]=0;for(r[0]=c[0]=1,A=254;A>=0;--A)a=i[A>>>3]>>>(A&7)&1,Wd(r,s,a),Wd(g,c,a),Dn(I,r,g),bn(r,r,g),Dn(g,s,c),bn(s,s,c),On(c,I),On(d,r),It(r,g,r),It(g,s,I),Dn(I,r,g),bn(r,r,g),On(s,r),bn(g,c,d),It(r,g,p2e),Dn(r,r,c),It(g,g,r),It(r,c,d),It(c,s,e),On(s,I),Wd(r,s,a),Wd(g,c,a);for(A=0;A<16;A++)e[A+16]=r[A],e[A+32]=g[A],e[A+48]=s[A],e[A+64]=c[A];var B=e.subarray(32),f=e.subarray(16);return JG(B,B),It(f,f,B),Xd(n,f),0}function B2e(n,t){return o9(n,t,r9)}var e9=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function A9(n,t,o,i){for(var e=new Int32Array(16),a=new Int32Array(16),A,r,s,g,c,I,d,B,f,Q,y,m,_,T,R,F,K,L,q,z,j,P,J,U,N,k,V=n[0],Ae=n[1],ie=n[2],De=n[3],fe=n[4],_e=n[5],Ee=n[6],Qe=n[7],Le=t[0],AA=t[1],aA=t[2],He=t[3],ce=t[4],Be=t[5],We=t[6],Ye=t[7],Re=0;i>=128;){for(q=0;q<16;q++)z=8*q+Re,e[q]=o[z+0]<<24|o[z+1]<<16|o[z+2]<<8|o[z+3],a[q]=o[z+4]<<24|o[z+5]<<16|o[z+6]<<8|o[z+7];for(q=0;q<80;q++)if(A=V,r=Ae,s=ie,g=De,c=fe,I=_e,d=Ee,B=Qe,f=Le,Q=AA,y=aA,m=He,_=ce,T=Be,R=We,F=Ye,j=Qe,P=Ye,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=(fe>>>14|ce<<18)^(fe>>>18|ce<<14)^(ce>>>9|fe<<23),P=(ce>>>14|fe<<18)^(ce>>>18|fe<<14)^(fe>>>9|ce<<23),J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,j=fe&_e^~fe&Ee,P=ce&Be^~ce&We,J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,j=e9[q*2],P=e9[q*2+1],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,j=e[q%16],P=a[q%16],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,K=N&65535|k<<16,L=J&65535|U<<16,j=K,P=L,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=(V>>>28|Le<<4)^(Le>>>2|V<<30)^(Le>>>7|V<<25),P=(Le>>>28|V<<4)^(V>>>2|Le<<30)^(V>>>7|Le<<25),J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,j=V&Ae^V&ie^Ae&ie,P=Le&AA^Le&aA^AA&aA,J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,B=N&65535|k<<16,F=J&65535|U<<16,j=g,P=m,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=K,P=L,J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,g=N&65535|k<<16,m=J&65535|U<<16,Ae=A,ie=r,De=s,fe=g,_e=c,Ee=I,Qe=d,V=B,AA=f,aA=Q,He=y,ce=m,Be=_,We=T,Ye=R,Le=F,q%16===15)for(z=0;z<16;z++)j=e[z],P=a[z],J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=e[(z+9)%16],P=a[(z+9)%16],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,K=e[(z+1)%16],L=a[(z+1)%16],j=(K>>>1|L<<31)^(K>>>8|L<<24)^K>>>7,P=(L>>>1|K<<31)^(L>>>8|K<<24)^(L>>>7|K<<25),J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,K=e[(z+14)%16],L=a[(z+14)%16],j=(K>>>19|L<<13)^(L>>>29|K<<3)^K>>>6,P=(L>>>19|K<<13)^(K>>>29|L<<3)^(L>>>6|K<<26),J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,e[z]=N&65535|k<<16,a[z]=J&65535|U<<16;j=V,P=Le,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=n[0],P=t[0],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,n[0]=V=N&65535|k<<16,t[0]=Le=J&65535|U<<16,j=Ae,P=AA,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=n[1],P=t[1],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,n[1]=Ae=N&65535|k<<16,t[1]=AA=J&65535|U<<16,j=ie,P=aA,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=n[2],P=t[2],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,n[2]=ie=N&65535|k<<16,t[2]=aA=J&65535|U<<16,j=De,P=He,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=n[3],P=t[3],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,n[3]=De=N&65535|k<<16,t[3]=He=J&65535|U<<16,j=fe,P=ce,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=n[4],P=t[4],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,n[4]=fe=N&65535|k<<16,t[4]=ce=J&65535|U<<16,j=_e,P=Be,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=n[5],P=t[5],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,n[5]=_e=N&65535|k<<16,t[5]=Be=J&65535|U<<16,j=Ee,P=We,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=n[6],P=t[6],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,n[6]=Ee=N&65535|k<<16,t[6]=We=J&65535|U<<16,j=Qe,P=Ye,J=P&65535,U=P>>>16,N=j&65535,k=j>>>16,j=n[7],P=t[7],J+=P&65535,U+=P>>>16,N+=j&65535,k+=j>>>16,U+=J>>>16,N+=U>>>16,k+=N>>>16,n[7]=Qe=N&65535|k<<16,t[7]=Ye=J&65535|U<<16,Re+=128,i-=128}return i}function nB(n,t,o){var i=new Int32Array(8),e=new Int32Array(8),a=new Uint8Array(256),A,r=o;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,e[0]=4089235720,e[1]=2227873595,e[2]=4271175723,e[3]=1595750129,e[4]=2917565137,e[5]=725511199,e[6]=4215389547,e[7]=327033209,A9(i,e,t,o),o%=128,A=0;A=0;--e)i=o[e/8|0]>>(e&7)&1,t9(n,t,i),xG(t,n),xG(n,n),t9(n,t,i)}function Nw(n,t){var o=[dA(),dA(),dA(),dA()];Rc(o[0],WZ),Rc(o[1],ZZ),Rc(o[2],Zd),It(o[3],WZ,ZZ),n9(n,o,t)}var HG=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function qG(n,t){var o,i,e,a;for(i=63;i>=32;--i){for(o=0,e=i-32,a=i-12;e>8,t[e]-=o*256;t[e]+=o,t[i]=0}for(o=0,e=0;e<32;e++)t[e]+=o-(t[31]>>4)*HG[e],o=t[e]>>8,t[e]&=255;for(e=0;e<32;e++)t[e]-=o*HG[e];for(i=0;i<32;i++)t[i+1]+=t[i]>>8,n[i]=t[i]&255}function sB(n){var t=new Float64Array(64),o;for(o=0;o<64;o++)t[o]=n[o];for(o=0;o<64;o++)n[o]=0;qG(n,t)}function f2e(n,t,o,i){var e=new Uint8Array(64),a=new Uint8Array(64),A,r,s=new Float64Array(64),g=[dA(),dA(),dA(),dA()];for(A=0;A>7&&bn(n[0],KG,n[0]),It(n[3],n[0],n[1]),0)}function m2e(n,t,o,i){var e,a,A=new Uint8Array(32),r=new Uint8Array(64),s=[dA(),dA(),dA(),dA()],g=[dA(),dA(),dA(),dA()];if(a=-1,o<64||y2e(g,i))return-1;for(e=0;e=0}Dg.verify=M2e;function _2e(n){if(kc(n),n.length!==32)throw new Error("wrong seed length");for(var t=new Uint8Array(32),o=new Uint8Array(32),i=0;i<32;i++)t[i]=n[i];return B2e(o,t),t[0]&=248,t[31]&=127,t[31]|=64,o[31]&=127,{public:o,private:t}}Dg.generateKeyPair=_2e;Dg.default={}});var vc=$(eh=>{"use strict";var gB=g9(),$d=$e("crypto"),zG=Buffer.from([48,42,48,5,6,3,43,101,110,3,33,0]),VG=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),T2e=Buffer.from([5]),WG=function(n){return Buffer.concat([T2e,n])};function c9(n){if(n===void 0)throw new Error("Undefined private key");if(!(n instanceof Buffer))throw new Error(`Invalid private key type: ${n.constructor.name}`);if(n.byteLength!=32)throw new Error(`Incorrect private key length: ${n.byteLength}`)}function I9(n){if(!(n instanceof Buffer))throw new Error(`Invalid public key type: ${n.constructor.name}`);if(n===void 0||(n.byteLength!=33||n[0]!=5)&&n.byteLength!=32)throw new Error("Invalid public key");return n.byteLength==33?n.slice(1):(console.error("WARNING: Expected pubkey of length 33, please report the ST and client that generated the pubkey"),n)}function N2e(n){let t=new Uint8Array(n);return t[0]|=6,t[31]|=128,t[31]&=-65,t}eh.getPublicFromPrivateKey=function(n){let t=N2e(n),o=gB.generateKeyPair(t);return WG(Buffer.from(o.public))};eh.generateKeyPair=function(){try{let{publicKey:n,privateKey:t}=$d.generateKeyPairSync("x25519",{publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}}),o=n.slice(zG.length,zG.length+32),i=t.slice(VG.length,VG.length+32);return{pubKey:WG(o),privKey:i}}catch{let t=gB.generateKeyPair($d.randomBytes(32));return{privKey:Buffer.from(t.private),pubKey:WG(Buffer.from(t.public))}}};eh.calculateAgreement=function(n,t){if(n=I9(n),c9(t),!n||n.byteLength!=32)throw new Error("Invalid public key");if(typeof $d.diffieHellman=="function"){let o=$d.createPrivateKey({key:Buffer.concat([VG,t]),format:"der",type:"pkcs8"}),i=$d.createPublicKey({key:Buffer.concat([zG,n]),format:"der",type:"spki"});return $d.diffieHellman({privateKey:o,publicKey:i})}else{let o=gB.sharedKey(t,n);return Buffer.from(o)}};eh.calculateSignature=function(n,t){if(c9(n),!t)throw new Error("Invalid message");return Buffer.from(gB.sign(n,t))};eh.verifySignature=function(n,t,o,i){if(n=I9(n),!n||n.byteLength!=32)throw new Error("Invalid public key");if(!t)throw new Error("Invalid message");if(!o||o.byteLength!=64)throw new Error("Invalid signature");return i?!0:gB.verify(n,t,o)}});var p9=$(cB=>{var Rw=vc(),R2e=$e("crypto");function l9(n){return typeof n=="number"&&n%1===0&&n>=0}cB.generateIdentityKeyPair=Rw.generateKeyPair;cB.generateRegistrationId=function(){var n=Uint16Array.from(R2e.randomBytes(2))[0];return n&16383};cB.generateSignedPreKey=function(n,t){if(!(n.privKey instanceof Buffer)||n.privKey.byteLength!=32||!(n.pubKey instanceof Buffer)||n.pubKey.byteLength!=33)throw new TypeError("Invalid argument for identityKeyPair");if(!l9(t))throw new TypeError("Invalid argument for signedKeyId: "+t);let o=Rw.generateKeyPair(),i=Rw.calculateSignature(n.privKey,o.pubKey);return{keyId:t,keyPair:o,signature:i}};cB.generatePreKey=function(n){if(!l9(n))throw new TypeError("Invalid argument for keyId: "+n);let t=Rw.generateKeyPair();return{keyId:n,keyPair:t}}});var XG=$((CBA,d9)=>{var ZG=class n{static from(t){if(typeof t!="string"||!t.match(/.*\.\d+/))throw new Error("Invalid address encoding");let o=t.split(".");return new this(o[0],parseInt(o[1]))}constructor(t,o){if(typeof t!="string")throw new TypeError("id required for addr");if(t.indexOf(".")!==-1)throw new TypeError("encoded addr detected");if(this.id=t,typeof o!="number")throw new TypeError("number required for deviceId");this.deviceId=o}toString(){return`${this.id}.${this.deviceId}`}is(t){return t instanceof n?t.id===this.id&&t.deviceId===this.deviceId:!1}};d9.exports=ZG});var $G=$((uBA,h9)=>{var k2e={OURS:1,THEIRS:2};h9.exports=k2e});var eF=$((BBA,E9)=>{var v2e={SENDING:1,RECEIVING:2};E9.exports=v2e});var Gw=$((fBA,u9)=>{var P2e=$G(),G2e=40,C9="v1";function vw(n){if(!Buffer.isBuffer(n))throw new TypeError("Buffer required")}var Pw=class{constructor(){this._chains={}}toString(){return``}inspect(){return this.toString()}addChain(t,o){vw(t);let i=t.toString("base64");if(this._chains.hasOwnProperty(i))throw new Error("Overwrite attempt");this._chains[i]=o}getChain(t){return vw(t),this._chains[t.toString("base64")]}deleteChain(t){vw(t);let o=t.toString("base64");if(!this._chains.hasOwnProperty(o))throw new ReferenceError("Not Found");delete this._chains[o]}*chains(){for(let[t,o]of Object.entries(this._chains))yield[Buffer.from(t,"base64"),o]}serialize(){let t={registrationId:this.registrationId,currentRatchet:{ephemeralKeyPair:{pubKey:this.currentRatchet.ephemeralKeyPair.pubKey.toString("base64"),privKey:this.currentRatchet.ephemeralKeyPair.privKey.toString("base64")},lastRemoteEphemeralKey:this.currentRatchet.lastRemoteEphemeralKey.toString("base64"),previousCounter:this.currentRatchet.previousCounter,rootKey:this.currentRatchet.rootKey.toString("base64")},indexInfo:{baseKey:this.indexInfo.baseKey.toString("base64"),baseKeyType:this.indexInfo.baseKeyType,closed:this.indexInfo.closed,used:this.indexInfo.used,created:this.indexInfo.created,remoteIdentityKey:this.indexInfo.remoteIdentityKey.toString("base64")},_chains:this._serialize_chains(this._chains)};return this.pendingPreKey&&(t.pendingPreKey=Object.assign({},this.pendingPreKey),t.pendingPreKey.baseKey=this.pendingPreKey.baseKey.toString("base64")),t}static deserialize(t){let o=new this;return o.registrationId=t.registrationId,o.currentRatchet={ephemeralKeyPair:{pubKey:Buffer.from(t.currentRatchet.ephemeralKeyPair.pubKey,"base64"),privKey:Buffer.from(t.currentRatchet.ephemeralKeyPair.privKey,"base64")},lastRemoteEphemeralKey:Buffer.from(t.currentRatchet.lastRemoteEphemeralKey,"base64"),previousCounter:t.currentRatchet.previousCounter,rootKey:Buffer.from(t.currentRatchet.rootKey,"base64")},o.indexInfo={baseKey:Buffer.from(t.indexInfo.baseKey,"base64"),baseKeyType:t.indexInfo.baseKeyType,closed:t.indexInfo.closed,used:t.indexInfo.used,created:t.indexInfo.created,remoteIdentityKey:Buffer.from(t.indexInfo.remoteIdentityKey,"base64")},o._chains=this._deserialize_chains(t._chains),t.pendingPreKey&&(o.pendingPreKey=Object.assign({},t.pendingPreKey),o.pendingPreKey.baseKey=Buffer.from(t.pendingPreKey.baseKey,"base64")),o}_serialize_chains(t){let o={};for(let i of Object.keys(t)){let e=t[i],a={};for(let[A,r]of Object.entries(e.messageKeys))a[A]=r.toString("base64");o[i]={chainKey:{counter:e.chainKey.counter,key:e.chainKey.key&&e.chainKey.key.toString("base64")},chainType:e.chainType,messageKeys:a}}return o}static _deserialize_chains(t){let o={};for(let i of Object.keys(t)){let e=t[i],a={};for(let[A,r]of Object.entries(e.messageKeys))a[A]=Buffer.from(r,"base64");o[i]={chainKey:{counter:e.chainKey.counter,key:e.chainKey.key&&Buffer.from(e.chainKey.key,"base64")},chainType:e.chainType,messageKeys:a}}return o}},kw=[{version:"v1",migrate:function(t){let o=t._sessions;if(t.registrationId)for(let i in o)o[i].registrationId||(o[i].registrationId=t.registrationId);else for(let i in o)o[i].indexInfo.closed===-1&&console.error("V1 session storage migration error: registrationId",t.registrationId,"for open session version",t.version)}}],AF=class{static createEntry(){return new Pw}static migrate(t){let o=t.version===void 0;for(let i=0;i{let i=t.indexInfo.used||0,e=o.indexInfo.used||0;return i===e?0:iG2e;){let t,o;for(let[i,e]of Object.entries(this.sessions))e.indexInfo.closed!==-1&&(!o||e.indexInfo.closed{Bs.SignalError=class extends Error{};Bs.UntrustedIdentityKeyError=class extends Bs.SignalError{constructor(t,o){super(),this.name="UntrustedIdentityKeyError",this.addr=t,this.identityKey=o}};Bs.SessionError=class extends Bs.SignalError{constructor(t){super(t),this.name="SessionError"}};Bs.MessageCounterError=class extends Bs.SessionError{constructor(t){super(t),this.name="MessageCounterError"}};Bs.PreKeyError=class extends Bs.SessionError{constructor(t){super(t),this.name="PreKeyError"}}});var tF=$((OBA,f9)=>{"use strict";var Lw=new Map,B9=1e4;async function F2e(n,t){let o=0;for(;;){let i=Math.min(n.length,B9);for(let e=o;e=B9?(n.splice(0,i),o=0):o=i;else break}t()}f9.exports=function(n,t){t.name||(Object.defineProperty(t,"name",{writable:!0}),typeof n=="string"?t.name=n:console.warn("Unhandled bucket type (for naming):",typeof n,n));let o;Lw.has(n)||(Lw.set(n,[]),o=!0);let i=Lw.get(n),e=new Promise((a,A)=>i.push({awaitable:t,resolve:a,reject:A}));return o&&F2e(i,()=>Lw.delete(n)),e}});var aF=$((bBA,S9)=>{"use strict";var Q9=$G(),L2e=eF(),y9=Gw(),m9=yl(),Pc=vc(),Uw=Fw(),U2e=tF(),rF=class{constructor(t,o){this.addr=o,this.storage=t}async initOutgoing(t){let o=this.addr.toString();return await U2e(o,async()=>{if(!await this.storage.isTrustedIdentity(this.addr.id,t.identityKey))throw new Uw.UntrustedIdentityKeyError(this.addr.id,t.identityKey);Pc.verifySignature(t.identityKey,t.signedPreKey.publicKey,t.signedPreKey.signature,!0);let i=Pc.generateKeyPair(),e=t.preKey&&t.preKey.publicKey,a=await this.initSession(!0,i,void 0,t.identityKey,e,t.signedPreKey.publicKey,t.registrationId);a.pendingPreKey={signedKeyId:t.signedPreKey.keyId,baseKey:i.pubKey},t.preKey&&(a.pendingPreKey.preKeyId=t.preKey.keyId);let A=await this.storage.loadSession(o);if(!A)A=new y9;else{let r=A.getOpenSession();r&&A.closeSession(r)}A.setSession(a),await this.storage.storeSession(o,A)})}async initIncoming(t,o){let i=this.addr.toString();if(!await this.storage.isTrustedIdentity(i,o.identityKey))throw new Uw.UntrustedIdentityKeyError(this.addr.id,o.identityKey);if(t.getSession(o.baseKey))return;let e=await this.storage.loadPreKey(o.preKeyId);if(o.preKeyId&&!e)throw new Uw.PreKeyError("Invalid PreKey ID");let a=await this.storage.loadSignedPreKey(o.signedPreKeyId);if(!a)throw new Uw.PreKeyError("Missing SignedPreKey");let A=t.getOpenSession();return A&&(console.warn("Closing open session in favor of incoming prekey bundle"),t.closeSession(A)),t.setSession(await this.initSession(!1,e,a,o.identityKey,o.baseKey,void 0,o.registrationId)),o.preKeyId}async initSession(t,o,i,e,a,A,r){if(t){if(i)throw new Error("Invalid call to initSession");i=o}else{if(A)throw new Error("Invalid call to initSession");A=a}let s;!o||!a?s=new Uint8Array(128):s=new Uint8Array(160);for(var g=0;g<32;g++)s[g]=255;let c=await this.storage.getOurIdentity(),I=Pc.calculateAgreement(A,c.privKey),d=Pc.calculateAgreement(e,i.privKey),B=Pc.calculateAgreement(A,i.privKey);if(t?(s.set(new Uint8Array(I),32),s.set(new Uint8Array(d),64)):(s.set(new Uint8Array(I),64),s.set(new Uint8Array(d),32)),s.set(new Uint8Array(B),96),o&&a){let y=Pc.calculateAgreement(a,o.privKey);s.set(new Uint8Array(y),128)}let f=m9.deriveSecrets(Buffer.from(s),Buffer.alloc(32),Buffer.from("WhisperText")),Q=y9.createEntry();return Q.registrationId=r,Q.currentRatchet={rootKey:f[0],ephemeralKeyPair:t?Pc.generateKeyPair():i,lastRemoteEphemeralKey:A,previousCounter:0},Q.indexInfo={created:Date.now(),used:Date.now(),remoteIdentityKey:e,baseKey:t?o.pubKey:a,baseKeyType:t?Q9.OURS:Q9.THEIRS,closed:-1},t&&this.calculateSendingRatchet(Q,A),Q}calculateSendingRatchet(t,o){let i=t.currentRatchet,e=Pc.calculateAgreement(o,i.ephemeralKeyPair.privKey),a=m9.deriveSecrets(e,i.rootKey,Buffer.from("WhisperRatchet"));t.addChain(i.ephemeralKeyPair.pubKey,{messageKeys:{},chainKey:{counter:-1,key:a[1]},chainType:L2e.SENDING}),i.rootKey=a[0]}};S9.exports=rF});var D9=$((MBA,w9)=>{"use strict";var Gc=Sm(),Ho=Gc.Reader,iF=Gc.Writer,nA=Gc.util,Mn=Gc.roots.default||(Gc.roots.default={});Mn.textsecure=(function(){var n={};return n.WhisperMessage=(function(){function t(o){if(o)for(var i=Object.keys(o),e=0;e>>3){case 1:A.ephemeralKey=i.bytes();break;case 2:A.counter=i.uint32();break;case 3:A.previousCounter=i.uint32();break;case 4:A.ciphertext=i.bytes();break;default:i.skipType(r&7);break}}return A},t.decodeDelimited=function(i){return i instanceof Ho||(i=new Ho(i)),this.decode(i,i.uint32())},t.verify=function(i){return typeof i!="object"||i===null?"object expected":i.ephemeralKey!=null&&i.hasOwnProperty("ephemeralKey")&&!(i.ephemeralKey&&typeof i.ephemeralKey.length=="number"||nA.isString(i.ephemeralKey))?"ephemeralKey: buffer expected":i.counter!=null&&i.hasOwnProperty("counter")&&!nA.isInteger(i.counter)?"counter: integer expected":i.previousCounter!=null&&i.hasOwnProperty("previousCounter")&&!nA.isInteger(i.previousCounter)?"previousCounter: integer expected":i.ciphertext!=null&&i.hasOwnProperty("ciphertext")&&!(i.ciphertext&&typeof i.ciphertext.length=="number"||nA.isString(i.ciphertext))?"ciphertext: buffer expected":null},t.fromObject=function(i){if(i instanceof Mn.textsecure.WhisperMessage)return i;var e=new Mn.textsecure.WhisperMessage;return i.ephemeralKey!=null&&(typeof i.ephemeralKey=="string"?nA.base64.decode(i.ephemeralKey,e.ephemeralKey=nA.newBuffer(nA.base64.length(i.ephemeralKey)),0):i.ephemeralKey.length&&(e.ephemeralKey=i.ephemeralKey)),i.counter!=null&&(e.counter=i.counter>>>0),i.previousCounter!=null&&(e.previousCounter=i.previousCounter>>>0),i.ciphertext!=null&&(typeof i.ciphertext=="string"?nA.base64.decode(i.ciphertext,e.ciphertext=nA.newBuffer(nA.base64.length(i.ciphertext)),0):i.ciphertext.length&&(e.ciphertext=i.ciphertext)),e},t.toObject=function(i,e){e||(e={});var a={};return e.defaults&&(e.bytes===String?a.ephemeralKey="":(a.ephemeralKey=[],e.bytes!==Array&&(a.ephemeralKey=nA.newBuffer(a.ephemeralKey))),a.counter=0,a.previousCounter=0,e.bytes===String?a.ciphertext="":(a.ciphertext=[],e.bytes!==Array&&(a.ciphertext=nA.newBuffer(a.ciphertext)))),i.ephemeralKey!=null&&i.hasOwnProperty("ephemeralKey")&&(a.ephemeralKey=e.bytes===String?nA.base64.encode(i.ephemeralKey,0,i.ephemeralKey.length):e.bytes===Array?Array.prototype.slice.call(i.ephemeralKey):i.ephemeralKey),i.counter!=null&&i.hasOwnProperty("counter")&&(a.counter=i.counter),i.previousCounter!=null&&i.hasOwnProperty("previousCounter")&&(a.previousCounter=i.previousCounter),i.ciphertext!=null&&i.hasOwnProperty("ciphertext")&&(a.ciphertext=e.bytes===String?nA.base64.encode(i.ciphertext,0,i.ciphertext.length):e.bytes===Array?Array.prototype.slice.call(i.ciphertext):i.ciphertext),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,Gc.util.toJSONOptions)},t})(),n.PreKeyWhisperMessage=(function(){function t(o){if(o)for(var i=Object.keys(o),e=0;e>>3){case 5:A.registrationId=i.uint32();break;case 1:A.preKeyId=i.uint32();break;case 6:A.signedPreKeyId=i.uint32();break;case 2:A.baseKey=i.bytes();break;case 3:A.identityKey=i.bytes();break;case 4:A.message=i.bytes();break;default:i.skipType(r&7);break}}return A},t.decodeDelimited=function(i){return i instanceof Ho||(i=new Ho(i)),this.decode(i,i.uint32())},t.verify=function(i){return typeof i!="object"||i===null?"object expected":i.registrationId!=null&&i.hasOwnProperty("registrationId")&&!nA.isInteger(i.registrationId)?"registrationId: integer expected":i.preKeyId!=null&&i.hasOwnProperty("preKeyId")&&!nA.isInteger(i.preKeyId)?"preKeyId: integer expected":i.signedPreKeyId!=null&&i.hasOwnProperty("signedPreKeyId")&&!nA.isInteger(i.signedPreKeyId)?"signedPreKeyId: integer expected":i.baseKey!=null&&i.hasOwnProperty("baseKey")&&!(i.baseKey&&typeof i.baseKey.length=="number"||nA.isString(i.baseKey))?"baseKey: buffer expected":i.identityKey!=null&&i.hasOwnProperty("identityKey")&&!(i.identityKey&&typeof i.identityKey.length=="number"||nA.isString(i.identityKey))?"identityKey: buffer expected":i.message!=null&&i.hasOwnProperty("message")&&!(i.message&&typeof i.message.length=="number"||nA.isString(i.message))?"message: buffer expected":null},t.fromObject=function(i){if(i instanceof Mn.textsecure.PreKeyWhisperMessage)return i;var e=new Mn.textsecure.PreKeyWhisperMessage;return i.registrationId!=null&&(e.registrationId=i.registrationId>>>0),i.preKeyId!=null&&(e.preKeyId=i.preKeyId>>>0),i.signedPreKeyId!=null&&(e.signedPreKeyId=i.signedPreKeyId>>>0),i.baseKey!=null&&(typeof i.baseKey=="string"?nA.base64.decode(i.baseKey,e.baseKey=nA.newBuffer(nA.base64.length(i.baseKey)),0):i.baseKey.length&&(e.baseKey=i.baseKey)),i.identityKey!=null&&(typeof i.identityKey=="string"?nA.base64.decode(i.identityKey,e.identityKey=nA.newBuffer(nA.base64.length(i.identityKey)),0):i.identityKey.length&&(e.identityKey=i.identityKey)),i.message!=null&&(typeof i.message=="string"?nA.base64.decode(i.message,e.message=nA.newBuffer(nA.base64.length(i.message)),0):i.message.length&&(e.message=i.message)),e},t.toObject=function(i,e){e||(e={});var a={};return e.defaults&&(a.preKeyId=0,e.bytes===String?a.baseKey="":(a.baseKey=[],e.bytes!==Array&&(a.baseKey=nA.newBuffer(a.baseKey))),e.bytes===String?a.identityKey="":(a.identityKey=[],e.bytes!==Array&&(a.identityKey=nA.newBuffer(a.identityKey))),e.bytes===String?a.message="":(a.message=[],e.bytes!==Array&&(a.message=nA.newBuffer(a.message))),a.registrationId=0,a.signedPreKeyId=0),i.preKeyId!=null&&i.hasOwnProperty("preKeyId")&&(a.preKeyId=i.preKeyId),i.baseKey!=null&&i.hasOwnProperty("baseKey")&&(a.baseKey=e.bytes===String?nA.base64.encode(i.baseKey,0,i.baseKey.length):e.bytes===Array?Array.prototype.slice.call(i.baseKey):i.baseKey),i.identityKey!=null&&i.hasOwnProperty("identityKey")&&(a.identityKey=e.bytes===String?nA.base64.encode(i.identityKey,0,i.identityKey.length):e.bytes===Array?Array.prototype.slice.call(i.identityKey):i.identityKey),i.message!=null&&i.hasOwnProperty("message")&&(a.message=e.bytes===String?nA.base64.encode(i.message,0,i.message.length):e.bytes===Array?Array.prototype.slice.call(i.message):i.message),i.registrationId!=null&&i.hasOwnProperty("registrationId")&&(a.registrationId=i.registrationId),i.signedPreKeyId!=null&&i.hasOwnProperty("signedPreKeyId")&&(a.signedPreKeyId=i.signedPreKeyId),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,Gc.util.toJSONOptions)},t})(),n.KeyExchangeMessage=(function(){function t(o){if(o)for(var i=Object.keys(o),e=0;e>>3){case 1:A.id=i.uint32();break;case 2:A.baseKey=i.bytes();break;case 3:A.ephemeralKey=i.bytes();break;case 4:A.identityKey=i.bytes();break;case 5:A.baseKeySignature=i.bytes();break;default:i.skipType(r&7);break}}return A},t.decodeDelimited=function(i){return i instanceof Ho||(i=new Ho(i)),this.decode(i,i.uint32())},t.verify=function(i){return typeof i!="object"||i===null?"object expected":i.id!=null&&i.hasOwnProperty("id")&&!nA.isInteger(i.id)?"id: integer expected":i.baseKey!=null&&i.hasOwnProperty("baseKey")&&!(i.baseKey&&typeof i.baseKey.length=="number"||nA.isString(i.baseKey))?"baseKey: buffer expected":i.ephemeralKey!=null&&i.hasOwnProperty("ephemeralKey")&&!(i.ephemeralKey&&typeof i.ephemeralKey.length=="number"||nA.isString(i.ephemeralKey))?"ephemeralKey: buffer expected":i.identityKey!=null&&i.hasOwnProperty("identityKey")&&!(i.identityKey&&typeof i.identityKey.length=="number"||nA.isString(i.identityKey))?"identityKey: buffer expected":i.baseKeySignature!=null&&i.hasOwnProperty("baseKeySignature")&&!(i.baseKeySignature&&typeof i.baseKeySignature.length=="number"||nA.isString(i.baseKeySignature))?"baseKeySignature: buffer expected":null},t.fromObject=function(i){if(i instanceof Mn.textsecure.KeyExchangeMessage)return i;var e=new Mn.textsecure.KeyExchangeMessage;return i.id!=null&&(e.id=i.id>>>0),i.baseKey!=null&&(typeof i.baseKey=="string"?nA.base64.decode(i.baseKey,e.baseKey=nA.newBuffer(nA.base64.length(i.baseKey)),0):i.baseKey.length&&(e.baseKey=i.baseKey)),i.ephemeralKey!=null&&(typeof i.ephemeralKey=="string"?nA.base64.decode(i.ephemeralKey,e.ephemeralKey=nA.newBuffer(nA.base64.length(i.ephemeralKey)),0):i.ephemeralKey.length&&(e.ephemeralKey=i.ephemeralKey)),i.identityKey!=null&&(typeof i.identityKey=="string"?nA.base64.decode(i.identityKey,e.identityKey=nA.newBuffer(nA.base64.length(i.identityKey)),0):i.identityKey.length&&(e.identityKey=i.identityKey)),i.baseKeySignature!=null&&(typeof i.baseKeySignature=="string"?nA.base64.decode(i.baseKeySignature,e.baseKeySignature=nA.newBuffer(nA.base64.length(i.baseKeySignature)),0):i.baseKeySignature.length&&(e.baseKeySignature=i.baseKeySignature)),e},t.toObject=function(i,e){e||(e={});var a={};return e.defaults&&(a.id=0,e.bytes===String?a.baseKey="":(a.baseKey=[],e.bytes!==Array&&(a.baseKey=nA.newBuffer(a.baseKey))),e.bytes===String?a.ephemeralKey="":(a.ephemeralKey=[],e.bytes!==Array&&(a.ephemeralKey=nA.newBuffer(a.ephemeralKey))),e.bytes===String?a.identityKey="":(a.identityKey=[],e.bytes!==Array&&(a.identityKey=nA.newBuffer(a.identityKey))),e.bytes===String?a.baseKeySignature="":(a.baseKeySignature=[],e.bytes!==Array&&(a.baseKeySignature=nA.newBuffer(a.baseKeySignature)))),i.id!=null&&i.hasOwnProperty("id")&&(a.id=i.id),i.baseKey!=null&&i.hasOwnProperty("baseKey")&&(a.baseKey=e.bytes===String?nA.base64.encode(i.baseKey,0,i.baseKey.length):e.bytes===Array?Array.prototype.slice.call(i.baseKey):i.baseKey),i.ephemeralKey!=null&&i.hasOwnProperty("ephemeralKey")&&(a.ephemeralKey=e.bytes===String?nA.base64.encode(i.ephemeralKey,0,i.ephemeralKey.length):e.bytes===Array?Array.prototype.slice.call(i.ephemeralKey):i.ephemeralKey),i.identityKey!=null&&i.hasOwnProperty("identityKey")&&(a.identityKey=e.bytes===String?nA.base64.encode(i.identityKey,0,i.identityKey.length):e.bytes===Array?Array.prototype.slice.call(i.identityKey):i.identityKey),i.baseKeySignature!=null&&i.hasOwnProperty("baseKeySignature")&&(a.baseKeySignature=e.bytes===String?nA.base64.encode(i.baseKeySignature,0,i.baseKeySignature.length):e.bytes===Array?Array.prototype.slice.call(i.baseKeySignature):i.baseKeySignature),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,Gc.util.toJSONOptions)},t})(),n})();w9.exports=Mn});var oF=$((_BA,O9)=>{"use strict";var{textsecure:{WhisperMessage:H2e,PreKeyWhisperMessage:K2e}}=D9();O9.exports={WhisperMessage:H2e,PreKeyWhisperMessage:K2e}});var T9=$((TBA,_9)=>{var Hw=eF(),x2e=XG(),Y2e=aF(),b9=Gw(),Og=yl(),M9=vc(),fs=Fw(),Ah=oF(),j2e=tF(),Fc=3;function Kw(n){if(!(n instanceof Buffer))throw TypeError(`Expected Buffer instead of: ${n.constructor.name}`);return n}var nF=class{constructor(t,o){if(!(o instanceof x2e))throw new TypeError("protocolAddress must be a ProtocolAddress");this.addr=o,this.storage=t}_encodeTupleByte(t,o){if(t>15||o>15)throw TypeError("Numbers must be 4 bits or less");return t<<4|o}_decodeTupleByte(t){return[t>>4,t&15]}toString(){return``}async getRecord(){let t=await this.storage.loadSession(this.addr.toString());if(t&&!(t instanceof b9))throw new TypeError("SessionRecord type expected from loadSession");return t}async storeRecord(t){t.removeOldSessions(),await this.storage.storeSession(this.addr.toString(),t)}async queueJob(t){return await j2e(this.addr.toString(),t)}async encrypt(t){Kw(t);let o=await this.storage.getOurIdentity();return await this.queueJob(async()=>{let i=await this.getRecord();if(!i)throw new fs.SessionError("No sessions");let e=i.getOpenSession();if(!e)throw new fs.SessionError("No open session");let a=e.indexInfo.remoteIdentityKey;if(!await this.storage.isTrustedIdentity(this.addr.id,a))throw new fs.UntrustedIdentityKeyError(this.addr.id,a);let A=e.getChain(e.currentRatchet.ephemeralKeyPair.pubKey);if(A.chainType===Hw.RECEIVING)throw new Error("Tried to encrypt on a receiving chain");this.fillMessageKeys(A,A.chainKey.counter+1);let r=Og.deriveSecrets(A.messageKeys[A.chainKey.counter],Buffer.alloc(32),Buffer.from("WhisperMessageKeys"));delete A.messageKeys[A.chainKey.counter];let s=Ah.WhisperMessage.create();s.ephemeralKey=e.currentRatchet.ephemeralKeyPair.pubKey,s.counter=A.chainKey.counter,s.previousCounter=e.currentRatchet.previousCounter,s.ciphertext=Og.encrypt(r[0],t,r[2].slice(0,16));let g=Ah.WhisperMessage.encode(s).finish(),c=Buffer.alloc(g.byteLength+66+1);c.set(o.pubKey),c.set(e.indexInfo.remoteIdentityKey,33),c[66]=this._encodeTupleByte(Fc,Fc),c.set(g,67);let I=Og.calculateMAC(r[1],c),d=Buffer.alloc(g.byteLength+9);d[0]=this._encodeTupleByte(Fc,Fc),d.set(g,1),d.set(I.slice(0,8),g.byteLength+1),await this.storeRecord(i);let B,f;if(e.pendingPreKey){B=3;let Q=Ah.PreKeyWhisperMessage.create({identityKey:o.pubKey,registrationId:await this.storage.getOurRegistrationId(),baseKey:e.pendingPreKey.baseKey,signedPreKeyId:e.pendingPreKey.signedKeyId,message:d});e.pendingPreKey.preKeyId&&(Q.preKeyId=e.pendingPreKey.preKeyId),f=Buffer.concat([Buffer.from([this._encodeTupleByte(Fc,Fc)]),Buffer.from(Ah.PreKeyWhisperMessage.encode(Q).finish())])}else B=1,f=d;return{type:B,body:f,registrationId:e.registrationId}})}async decryptWithSessions(t,o){if(!o.length)throw new fs.SessionError("No sessions available");let i=[];for(let e of o){let a;try{return a=await this.doDecryptWhisperMessage(t,e),e.indexInfo.used=Date.now(),{session:e,plaintext:a}}catch(A){i.push(A)}}console.error("Failed to decrypt message with any known session...");for(let e of i)console.error("Session error:"+e,e.stack);throw new fs.SessionError("No matching sessions found for message")}async decryptWhisperMessage(t){return Kw(t),await this.queueJob(async()=>{let o=await this.getRecord();if(!o)throw new fs.SessionError("No session record");let i=await this.decryptWithSessions(t,o.getSessions()),e=i.session.indexInfo.remoteIdentityKey;if(!await this.storage.isTrustedIdentity(this.addr.id,e))throw new fs.UntrustedIdentityKeyError(this.addr.id,e);return o.isClosed(i.session)&&console.warn("Decrypted message with closed session."),await this.storeRecord(o),i.plaintext})}async decryptPreKeyWhisperMessage(t){Kw(t);let o=this._decodeTupleByte(t[0]);if(o[1]>3||o[0]<3)throw new Error("Incompatible version number on PreKeyWhisperMessage");return await this.queueJob(async()=>{let i=await this.getRecord(),e=Ah.PreKeyWhisperMessage.decode(t.slice(1));if(!i){if(e.registrationId==null)throw new Error("No registrationId");i=new b9}let A=await new Y2e(this.storage,this.addr).initIncoming(i,e),r=i.getSession(e.baseKey),s=await this.doDecryptWhisperMessage(e.message,r);return await this.storeRecord(i),A&&await this.storage.removePreKey(A),s})}async doDecryptWhisperMessage(t,o){if(Kw(t),!o)throw new TypeError("session required");let i=this._decodeTupleByte(t[0]);if(i[1]>3||i[0]<3)throw new Error("Incompatible version number on WhisperMessage");let e=t.slice(1,-8),a=Ah.WhisperMessage.decode(e);this.maybeStepRatchet(o,a.ephemeralKey,a.previousCounter);let A=o.getChain(a.ephemeralKey);if(A.chainType===Hw.SENDING)throw new Error("Tried to decrypt on a sending chain");if(this.fillMessageKeys(A,a.counter),!A.messageKeys.hasOwnProperty(a.counter))throw new fs.MessageCounterError("Key used already or never filled");let r=A.messageKeys[a.counter];delete A.messageKeys[a.counter];let s=Og.deriveSecrets(r,Buffer.alloc(32),Buffer.from("WhisperMessageKeys")),g=await this.storage.getOurIdentity(),c=Buffer.alloc(e.byteLength+66+1);c.set(o.indexInfo.remoteIdentityKey),c.set(g.pubKey,33),c[66]=this._encodeTupleByte(Fc,Fc),c.set(e,67),Og.verifyMAC(c,s[1],t.slice(-8),8);let I=Og.decrypt(s[0],a.ciphertext,s[2].slice(0,16));return delete o.pendingPreKey,I}fillMessageKeys(t,o){if(t.chainKey.counter>=o)return;if(o-t.chainKey.counter>2e3)throw new fs.SessionError("Over 2000 messages into the future!");if(t.chainKey.key===void 0)throw new fs.SessionError("Chain closed");let i=t.chainKey.key;return t.messageKeys[t.chainKey.counter+1]=Og.calculateMAC(i,Buffer.from([1])),t.chainKey.key=Og.calculateMAC(i,Buffer.from([2])),t.chainKey.counter+=1,this.fillMessageKeys(t,o)}maybeStepRatchet(t,o,i){if(t.getChain(o))return;let e=t.currentRatchet,a=t.getChain(e.lastRemoteEphemeralKey);a&&(this.fillMessageKeys(a,i),delete a.chainKey.key),this.calculateRatchet(t,o,!1);let A=t.getChain(e.ephemeralKeyPair.pubKey);A&&(e.previousCounter=A.chainKey.counter,t.deleteChain(e.ephemeralKeyPair.pubKey)),e.ephemeralKeyPair=M9.generateKeyPair(),this.calculateRatchet(t,o,!0),e.lastRemoteEphemeralKey=o}calculateRatchet(t,o,i){let e=t.currentRatchet,a=M9.calculateAgreement(o,e.ephemeralKeyPair.privKey),A=Og.deriveSecrets(a,e.rootKey,Buffer.from("WhisperRatchet"),2),r=i?e.ephemeralKeyPair.pubKey:o;t.addChain(r,{messageKeys:{},chainKey:{counter:-1,key:A[1]},chainType:i?Hw.SENDING:Hw.RECEIVING}),e.rootKey=A[0]}async hasOpenSession(){return await this.queueJob(async()=>{let t=await this.getRecord();return t?t.haveOpenSession():!1})}async closeOpenSession(){return await this.queueJob(async()=>{let t=await this.getRecord();if(t){let o=t.getOpenSession();o&&(t.closeSession(o),await this.storeRecord(t))}})}};_9.exports=nF});var N9=$(bg=>{"use strict";bg.crypto=yl();bg.curve=vc();bg.keyhelper=p9();bg.ProtocolAddress=XG();bg.SessionBuilder=aF();bg.SessionCipher=T9();bg.SessionRecord=Gw();Object.assign(bg,Fw())});var gF=$((PBA,G9)=>{"use strict";G9.exports=function(...n){try{return JSON.stringify.apply(null,n)}catch(t){return"[Cannot display object: "+t.message+"]"}}});var cF=$((F9,L9)=>{"use strict";var X2e=gF();L9.exports=class extends Error{constructor(n){let t=n.filter(o=>o!=="").map(o=>typeof o=="string"?o:o instanceof Error?o.message:X2e(o));super(t.join(" ")||"Unknown error"),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,F9.assert)}}});var ml=$((FBA,U9)=>{"use strict";var $2e=cF();U9.exports=function(n,...t){if(!n)throw t.length===1&&t[0]instanceof Error?t[0]:new $2e(t)}});var pB=$((LBA,K9)=>{"use strict";var IF=ml(),H9={};K9.exports=function(n,t,o){if(t===!1||t===null||t===void 0)return n;o=o||{},typeof o=="string"&&(o={separator:o});let i=Array.isArray(t);IF(!i||!o.separator,"Separator option no valid for array-based chain");let e=i?t:t.split(o.separator||"."),a=n;for(let A=0;A{"use strict";var x9={};ai=Y9.exports={array:Array.prototype,buffer:Buffer&&Buffer.prototype,date:Date.prototype,error:Error.prototype,generic:Object.prototype,map:Map.prototype,promise:Promise.prototype,regex:RegExp.prototype,set:Set.prototype,weakMap:WeakMap.prototype,weakSet:WeakSet.prototype};x9.typeMap=new Map([["[object Error]",ai.error],["[object Map]",ai.map],["[object Promise]",ai.promise],["[object Set]",ai.set],["[object WeakMap]",ai.weakMap],["[object WeakSet]",ai.weakSet]]);ai.getInternalProto=function(n){if(Array.isArray(n))return ai.array;if(Buffer&&n instanceof Buffer)return ai.buffer;if(n instanceof Date)return ai.date;if(n instanceof RegExp)return ai.regex;if(n instanceof Error)return ai.error;let t=Object.prototype.toString.call(n);return x9.typeMap.get(t)||ai.generic}});var Yw=$(j9=>{"use strict";j9.keys=function(n,t={}){return t.symbols!==!1?Reflect.ownKeys(n):Object.getOwnPropertyNames(n)}});var jw=$((HBA,J9)=>{"use strict";var eUe=pB(),Ko=lF(),AUe=Yw(),_g={needsProtoHack:new Set([Ko.set,Ko.map,Ko.weakSet,Ko.weakMap])};J9.exports=_g.clone=function(n,t={},o=null){if(typeof n!="object"||n===null)return n;let i=_g.clone,e=o;if(t.shallow){if(t.shallow!==!0)return _g.cloneWithShallow(n,t);i=s=>s}else{e=e||new Map;let s=e.get(n);if(s)return s}let a=Ko.getInternalProto(n);if(a===Ko.buffer)return Buffer&&Buffer.from(n);if(a===Ko.date)return new Date(n.getTime());if(a===Ko.regex)return new RegExp(n);let A=_g.base(n,a,t);if(A===n)return n;if(e&&e.set(n,A),a===Ko.set)for(let s of n)A.add(i(s,t,e));else if(a===Ko.map)for(let[s,g]of n)A.set(s,i(g,t,e));let r=AUe.keys(n,t);for(let s of r){if(a===Ko.array&&s==="length"){A.length=n.length;continue}let g=Object.getOwnPropertyDescriptor(n,s);g?g.get||g.set?Object.defineProperty(A,s,g):g.enumerable?A[s]=i(n[s],t,e):Object.defineProperty(A,s,{enumerable:!1,writable:!0,configurable:!0,value:i(n[s],t,e)}):Object.defineProperty(A,s,{enumerable:!0,writable:!0,configurable:!0,value:i(n[s],t,e)})}return A};_g.cloneWithShallow=function(n,t){let o=t.shallow;t=Object.assign({},t),t.shallow=!1;let i=new Map;for(let e of o){let a=eUe(n,e);(typeof a=="object"||typeof a=="function")&&i.set(a,a)}return _g.clone(n,t,i)};_g.base=function(n,t,o){if(t===Ko.array)return[];if(o.prototype===!1)return _g.needsProtoHack.has(t)?new t.constructor:{};let i=Object.getPrototypeOf(n);if(i&&i.isImmutable)return n;if(_g.needsProtoHack.has(t)){let e=new i.constructor;return i!==t&&Object.setPrototypeOf(e,i),e}return Object.create(i)}});var dF=$((KBA,V9)=>{"use strict";var pF=ml(),q9=jw(),tUe=Yw(),z9={};V9.exports=z9.merge=function(n,t,o){if(pF(n&&typeof n=="object","Invalid target value: must be an object"),pF(t==null||typeof t=="object","Invalid source value: must be null, undefined, or an object"),!t)return n;if(o=Object.assign({nullOverride:!0,mergeArrays:!0},o),Array.isArray(t)){pF(Array.isArray(n),"Cannot merge array onto an object"),o.mergeArrays||(n.length=0);for(let e=0;e{"use strict";var Jw=ml(),Z9=jw(),X9=dF(),W9=pB(),qw={};$9.exports=function(n,t,o={}){if(Jw(n&&typeof n=="object","Invalid defaults value: must be an object"),Jw(!t||t===!0||typeof t=="object","Invalid source value: must be true, falsy or an object"),Jw(typeof o=="object","Invalid options: must be an object"),!t)return null;if(o.shallow)return qw.applyToDefaultsWithShallow(n,t,o);let i=Z9(n);if(t===!0)return i;let e=o.nullOverride!==void 0?o.nullOverride:!1;return X9(i,t,{nullOverride:e,mergeArrays:!1})};qw.applyToDefaultsWithShallow=function(n,t,o){let i=o.shallow;Jw(Array.isArray(i),"Invalid keys");let e=new Map,a=t===!0?null:new Set;for(let r of i){r=Array.isArray(r)?r:r.split(".");let s=W9(n,r);s&&typeof s=="object"?e.set(s,a?W9(t,r):s):a&&a.add(r)}let A=Z9(n,{},e);if(!a)return A;for(let r of a)qw.reachCopy(A,t,r);return X9(A,t,{mergeArrays:!1,nullOverride:!1})};qw.reachCopy=function(n,t,o){for(let a of o){if(!(a in t))return;t=t[a]}let i=t,e=n;for(let a=0;a{"use strict";var hF={};AX.exports=hF.Bench=class{constructor(){this.ts=0,this.reset()}reset(){this.ts=hF.Bench.now()}elapsed(){return hF.Bench.now()-this.ts}static now(){let n=process.hrtime();return n[0]*1e3+n[1]/1e6}}});var EF=$((JBA,rX)=>{"use strict";rX.exports=function(){}});var iX=$((qBA,aX)=>{"use strict";var rUe=EF();aX.exports=function(){return new Promise(rUe)}});var CF=$((zBA,oX)=>{"use strict";var Qs=lF(),Za={mismatched:null};oX.exports=function(n,t,o){return o=Object.assign({prototype:!0},o),!!Za.isDeepEqual(n,t,o,[])};Za.isDeepEqual=function(n,t,o,i){if(n===t)return n!==0||1/n===1/t;let e=typeof n;if(e!==typeof t||n===null||t===null)return!1;if(e==="function"){if(!o.deepFunction||n.toString()!==t.toString())return!1}else if(e!=="object")return n!==n&&t!==t;let a=Za.getSharedType(n,t,!!o.prototype);switch(a){case Qs.buffer:return Buffer&&Buffer.prototype.equals.call(n,t);case Qs.promise:return n===t;case Qs.regex:return n.toString()===t.toString();case Za.mismatched:return!1}for(let A=i.length-1;A>=0;--A)if(i[A].isSame(n,t))return!0;i.push(new Za.SeenEntry(n,t));try{return!!Za.isDeepEqualObj(a,n,t,o,i)}finally{i.pop()}};Za.getSharedType=function(n,t,o){if(o)return Object.getPrototypeOf(n)!==Object.getPrototypeOf(t)?Za.mismatched:Qs.getInternalProto(n);let i=Qs.getInternalProto(n);return i!==Qs.getInternalProto(t)?Za.mismatched:i};Za.valueOf=function(n){let t=n.valueOf;if(t===void 0)return n;try{return t.call(n)}catch(o){return o}};Za.hasOwnEnumerableProperty=function(n,t){return Object.prototype.propertyIsEnumerable.call(n,t)};Za.isSetSimpleEqual=function(n,t){for(let o of n)if(!t.has(o))return!1;return!0};Za.isDeepEqualObj=function(n,t,o,i,e){let{isDeepEqual:a,valueOf:A,hasOwnEnumerableProperty:r}=Za,{keys:s,getOwnPropertySymbols:g}=Object;if(n===Qs.array)if(i.part){for(let f of t)for(let Q of o)if(a(f,Q,i,e))return!0}else{if(t.length!==o.length)return!1;for(let f=0;f{"use strict";nX.exports=function(n){return n.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g,"\\$&")}});var gX=$((ZBA,sX)=>{"use strict";var zw=ml(),aUe=CF(),iUe=uF(),oUe=Yw(),xo={};sX.exports=function(n,t,o={}){return typeof t!="object"&&(t=[t]),zw(!Array.isArray(t)||t.length,"Values array cannot be empty"),typeof n=="string"?xo.string(n,t,o):Array.isArray(n)?xo.array(n,t,o):(zw(typeof n=="object","Reference must be string or an object"),xo.object(n,t,o))};xo.array=function(n,t,o){if(Array.isArray(t)||(t=[t]),!n.length||o.only&&o.once&&n.length!==t.length)return!1;let i,e=new Map;for(let A of t)if(!o.deep||!A||typeof A!="object"){let r=e.get(A);r?++r.allowed:e.set(A,{allowed:1,hits:0})}else{i=i||xo.compare(o);let r=!1;for(let[s,g]of e.entries())if(i(s,A)){++g.allowed,r=!0;break}r||e.set(A,{allowed:1,hits:0})}let a=0;for(let A of n){let r;if(!o.deep||!A||typeof A!="object")r=e.get(A);else for(let[s,g]of e.entries())if(i(s,A)){r=g;break}if(r&&(++r.hits,++a,o.once&&r.hits>r.allowed))return!1}if(o.only&&a!==n.length)return!1;for(let A of e.values())if(A.hits!==A.allowed&&A.hitst.propertyIsEnumerable(s)),a=[...Object.keys(t),...e],A=xo.compare(o),r=new Set(a);for(let s of i){if(!r.has(s)){if(o.only)return!1;continue}if(!A(t[s],n[s]))return!1;r.delete(s)}return r.size?o.part?r.sizes!=="");let i=new Map,e=[];for(let s of t)if(zw(typeof s=="string","Cannot compare string reference to non-string value"),s){let g=i.get(s);g?++g.allowed:(i.set(s,{allowed:1,hits:0}),e.push(iUe(s)))}else if(o.once||o.only)return!1;if(!e.length)return!0;let a=new RegExp(`(${e.join("|")})`,"g"),A=n.replace(a,(s,g)=>(++i.get(g).hits,""));if(o.only&&A)return!1;let r=!1;for(let s of i.values())if(s.hits&&(r=!0),s.hits!==s.allowed&&(s.hitsaUe(e,a,i)};xo.shallow=function(n,t){return n===t}});var IX=$((XBA,cX)=>{"use strict";var nUe=ml();cX.exports=function(n){return nUe(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(n),"Bad attribute value ("+n+")"),n.replace(/\\/g,"\\\\").replace(/\"/g,'\\"')}});var pX=$(($BA,lX)=>{"use strict";var Uc={};lX.exports=function(n){if(!n)return"";let t="";for(let o=0;o=256?"&#"+n+";":`&#x${n.toString(16).padStart(2,"0")};`};Uc.isSafe=function(n){return typeof Uc.safeCharCodes[n]<"u"};Uc.namedHtml={38:"&",60:"<",62:">",34:""",160:" ",162:"¢",163:"£",164:"¤",169:"©",174:"®"};Uc.safeCharCodes=(function(){let n={};for(let t=32;t<123;++t)(t>=97||t>=65&&t<=90||t>=48&&t<=57||t===32||t===46||t===44||t===45||t===58||t===95)&&(n[t]=null);return n})()});var hX=$((efA,dX)=>{"use strict";dX.exports=function(n){if(!n)return"";let t=60,o=62,i=38,e=8232,a;return n.replace(/[<>&\u2028\u2029]/g,A=>(a=A.charCodeAt(0),a===t?"\\u003c":a===o?"\\u003e":a===i?"\\u0026":a===e?"\\u2028":"\\u2029"))}});var uX=$((AfA,CX)=>{"use strict";var EX={};CX.exports=EX.flatten=function(n,t){let o=t||[];for(let i=0;i{"use strict";var BX={};fX.exports=function(n,t,o={}){if(!n||!t)return o.first?null:[];let i=[],e=Array.isArray(n)?new Set(n):n,a=new Set;for(let A of t)if(BX.has(e,A)&&!a.has(A)){if(o.first)return A;i.push(A),a.add(A)}return o.first?null:i};BX.has=function(n,t){return typeof n.has=="function"?n.has(t):n[t]!==void 0}});var mX=$((rfA,yX)=>{"use strict";yX.exports=function(n){return!!n&&typeof n.then=="function"}});var wX=$((afA,SX)=>{"use strict";SX.exports=function(n){if(n._hoekOnce)return n;let t=!1,o=function(...i){t||(t=!0,n(...i))};return o._hoekOnce=!0,o}});var OX=$((ifA,DX)=>{"use strict";var sUe=pB();DX.exports=function(n,t,o){return t.replace(/{([^}]+)}/g,(i,e)=>{let a=sUe(n,e,o);return a??""})}});var MX=$((ofA,bX)=>{"use strict";bX.exports=function(n){return new Promise(t=>setTimeout(t,n))}});var TX=$((nfA,_X)=>{"use strict";_X.exports={applyToDefaults:eX(),assert:ml(),Bench:tX(),block:iX(),clone:jw(),contain:gX(),deepEqual:CF(),Error:cF(),escapeHeaderAttribute:IX(),escapeHtml:pX(),escapeJson:hX(),escapeRegex:uF(),flatten:uX(),ignore:EF(),intersect:QX(),isPromise:mX(),merge:dF(),once:wX(),reach:pB(),reachTemplate:OX(),stringify:gF(),wait:MX()}});var Lr=$(ke=>{"use strict";var Sl=TX(),Fi={codes:new Map([[100,"Continue"],[101,"Switching Protocols"],[102,"Processing"],[200,"OK"],[201,"Created"],[202,"Accepted"],[203,"Non-Authoritative Information"],[204,"No Content"],[205,"Reset Content"],[206,"Partial Content"],[207,"Multi-Status"],[300,"Multiple Choices"],[301,"Moved Permanently"],[302,"Moved Temporarily"],[303,"See Other"],[304,"Not Modified"],[305,"Use Proxy"],[307,"Temporary Redirect"],[400,"Bad Request"],[401,"Unauthorized"],[402,"Payment Required"],[403,"Forbidden"],[404,"Not Found"],[405,"Method Not Allowed"],[406,"Not Acceptable"],[407,"Proxy Authentication Required"],[408,"Request Time-out"],[409,"Conflict"],[410,"Gone"],[411,"Length Required"],[412,"Precondition Failed"],[413,"Request Entity Too Large"],[414,"Request-URI Too Large"],[415,"Unsupported Media Type"],[416,"Requested Range Not Satisfiable"],[417,"Expectation Failed"],[418,"I'm a teapot"],[422,"Unprocessable Entity"],[423,"Locked"],[424,"Failed Dependency"],[425,"Too Early"],[426,"Upgrade Required"],[428,"Precondition Required"],[429,"Too Many Requests"],[431,"Request Header Fields Too Large"],[451,"Unavailable For Legal Reasons"],[500,"Internal Server Error"],[501,"Not Implemented"],[502,"Bad Gateway"],[503,"Service Unavailable"],[504,"Gateway Time-out"],[505,"HTTP Version Not Supported"],[506,"Variant Also Negotiates"],[507,"Insufficient Storage"],[509,"Bandwidth Limit Exceeded"],[510,"Not Extended"],[511,"Network Authentication Required"]])};ke.Boom=class extends Error{constructor(n,t={}){if(n instanceof Error)return ke.boomify(Sl.clone(n),t);let{statusCode:o=500,data:i=null,ctor:e=ke.Boom}=t,a=new Error(n||void 0);Error.captureStackTrace(a,e),a.data=i;let A=Fi.initialize(a,o);return Object.defineProperty(A,"typeof",{value:e}),t.decorate&&Object.assign(A,t.decorate),A}static[Symbol.hasInstance](n){return this===ke.Boom?ke.isBoom(n):this.prototype.isPrototypeOf(n)}};ke.isBoom=function(n,t){return n instanceof Error&&!!n.isBoom&&(!t||n.output.statusCode===t)};ke.boomify=function(n,t){return Sl.assert(n instanceof Error,"Cannot wrap non-Error object"),t=t||{},t.data!==void 0&&(n.data=t.data),t.decorate&&Object.assign(n,t.decorate),n.isBoom?t.override===!1||!t.statusCode&&!t.message?n:Fi.initialize(n,t.statusCode||n.output.statusCode,t.message):Fi.initialize(n,t.statusCode||500,t.message)};ke.badRequest=function(n,t){return new ke.Boom(n,{statusCode:400,data:t,ctor:ke.badRequest})};ke.unauthorized=function(n,t,o){let i=new ke.Boom(n,{statusCode:401,ctor:ke.unauthorized});if(!t)return i;if(typeof t!="string")return i.output.headers["WWW-Authenticate"]=t.join(", "),i;let e=`${t}`;return(o||n)&&(i.output.payload.attributes={}),o&&(typeof o=="string"?(e+=" "+Sl.escapeHeaderAttribute(o),i.output.payload.attributes=o):e+=" "+Object.keys(o).map(a=>{let A=o[a];return A==null&&(A=""),i.output.payload.attributes[a]=A,`${a}="${Sl.escapeHeaderAttribute(A.toString())}"`}).join(", ")),n?(o&&(e+=","),e+=` error="${Sl.escapeHeaderAttribute(n)}"`,i.output.payload.attributes.error=n):i.isMissing=!0,i.output.headers["WWW-Authenticate"]=e,i};ke.paymentRequired=function(n,t){return new ke.Boom(n,{statusCode:402,data:t,ctor:ke.paymentRequired})};ke.forbidden=function(n,t){return new ke.Boom(n,{statusCode:403,data:t,ctor:ke.forbidden})};ke.notFound=function(n,t){return new ke.Boom(n,{statusCode:404,data:t,ctor:ke.notFound})};ke.methodNotAllowed=function(n,t,o){let i=new ke.Boom(n,{statusCode:405,data:t,ctor:ke.methodNotAllowed});return typeof o=="string"&&(o=[o]),Array.isArray(o)&&(i.output.headers.Allow=o.join(", ")),i};ke.notAcceptable=function(n,t){return new ke.Boom(n,{statusCode:406,data:t,ctor:ke.notAcceptable})};ke.proxyAuthRequired=function(n,t){return new ke.Boom(n,{statusCode:407,data:t,ctor:ke.proxyAuthRequired})};ke.clientTimeout=function(n,t){return new ke.Boom(n,{statusCode:408,data:t,ctor:ke.clientTimeout})};ke.conflict=function(n,t){return new ke.Boom(n,{statusCode:409,data:t,ctor:ke.conflict})};ke.resourceGone=function(n,t){return new ke.Boom(n,{statusCode:410,data:t,ctor:ke.resourceGone})};ke.lengthRequired=function(n,t){return new ke.Boom(n,{statusCode:411,data:t,ctor:ke.lengthRequired})};ke.preconditionFailed=function(n,t){return new ke.Boom(n,{statusCode:412,data:t,ctor:ke.preconditionFailed})};ke.entityTooLarge=function(n,t){return new ke.Boom(n,{statusCode:413,data:t,ctor:ke.entityTooLarge})};ke.uriTooLong=function(n,t){return new ke.Boom(n,{statusCode:414,data:t,ctor:ke.uriTooLong})};ke.unsupportedMediaType=function(n,t){return new ke.Boom(n,{statusCode:415,data:t,ctor:ke.unsupportedMediaType})};ke.rangeNotSatisfiable=function(n,t){return new ke.Boom(n,{statusCode:416,data:t,ctor:ke.rangeNotSatisfiable})};ke.expectationFailed=function(n,t){return new ke.Boom(n,{statusCode:417,data:t,ctor:ke.expectationFailed})};ke.teapot=function(n,t){return new ke.Boom(n,{statusCode:418,data:t,ctor:ke.teapot})};ke.badData=function(n,t){return new ke.Boom(n,{statusCode:422,data:t,ctor:ke.badData})};ke.locked=function(n,t){return new ke.Boom(n,{statusCode:423,data:t,ctor:ke.locked})};ke.failedDependency=function(n,t){return new ke.Boom(n,{statusCode:424,data:t,ctor:ke.failedDependency})};ke.tooEarly=function(n,t){return new ke.Boom(n,{statusCode:425,data:t,ctor:ke.tooEarly})};ke.preconditionRequired=function(n,t){return new ke.Boom(n,{statusCode:428,data:t,ctor:ke.preconditionRequired})};ke.tooManyRequests=function(n,t){return new ke.Boom(n,{statusCode:429,data:t,ctor:ke.tooManyRequests})};ke.illegal=function(n,t){return new ke.Boom(n,{statusCode:451,data:t,ctor:ke.illegal})};ke.internal=function(n,t,o=500){return Fi.serverError(n,t,o,ke.internal)};ke.notImplemented=function(n,t){return Fi.serverError(n,t,501,ke.notImplemented)};ke.badGateway=function(n,t){return Fi.serverError(n,t,502,ke.badGateway)};ke.serverUnavailable=function(n,t){return Fi.serverError(n,t,503,ke.serverUnavailable)};ke.gatewayTimeout=function(n,t){return Fi.serverError(n,t,504,ke.gatewayTimeout)};ke.badImplementation=function(n,t){let o=Fi.serverError(n,t,500,ke.badImplementation);return o.isDeveloperError=!0,o};Fi.initialize=function(n,t,o){let i=parseInt(t,10);if(Sl.assert(!isNaN(i)&&i>=400,"First argument must be a number (400+):",t),n.isBoom=!0,n.isServer=i>=500,n.hasOwnProperty("data")||(n.data=null),n.output={statusCode:i,payload:{},headers:{}},Object.defineProperty(n,"reformat",{value:Fi.reformat}),!o&&!n.message&&(n.reformat(),o=n.output.payload.error),o){let e=Object.getOwnPropertyDescriptor(n,"message")||Object.getOwnPropertyDescriptor(Object.getPrototypeOf(n),"message");Sl.assert(!e||e.configurable&&!e.get,"The error is not compatible with boom"),n.message=o+(n.message?": "+n.message:""),n.output.payload.message=n.message}return n.reformat(),n};Fi.reformat=function(n=!1){this.output.payload.statusCode=this.output.statusCode,this.output.payload.error=Fi.codes.get(this.output.statusCode)||"Unknown",this.output.statusCode===500&&n!==!0?this.output.payload.message="An internal server error occurred":this.message&&(this.output.payload.message=this.message)};Fi.serverError=function(n,t,o,i){return t instanceof Error&&!t.isBoom?ke.boomify(t,{statusCode:o,message:n}):new ke.Boom(n,{statusCode:o,data:t,ctor:i})}});var k7,KUe,xUe,YUe,jUe,JUe,qUe,zUe,VUe,WUe,ZUe,XUe,$Ue,eHe,AHe,O,ms=ue(()=>{k7=n=>typeof n<"u"&&n!==null,KUe=n=>typeof n=="object",xUe=n=>Object.prototype.toString.call(n)==="[object Object]",YUe=n=>typeof n=="function",jUe=n=>typeof n=="boolean",JUe=n=>n instanceof Buffer,qUe=n=>{if(k7(n))switch(n.constructor){case Uint8Array:case Uint8ClampedArray:case Int8Array:case Uint16Array:case Int16Array:case Uint32Array:case Int32Array:case Float32Array:case Float64Array:return!0}return!1},zUe=n=>n instanceof ArrayBuffer,VUe=n=>typeof n=="string"&&n.length>0,WUe=n=>typeof n=="number"&&Number.isFinite(n),ZUe=n=>Number.isInteger(n),XUe=(n,t,o)=>n>=t&&n<=o,$Ue=(n,t)=>t.includes(n),eHe=(n,t,o)=>new Error(`Expected ${t} for ${n} but received ${o} of type ${typeof o}`),AHe=(n,t)=>(t.message=n.message,t),O={defined:k7,object:KUe,plainObject:xUe,fn:YUe,bool:jUe,buffer:JUe,typedArray:qUe,arrayBuffer:zUe,string:VUe,number:WUe,integer:ZUe,inRange:XUe,inArray:$Ue,invalidParameterError:eHe,nativeError:AHe}});var G7=$((CQA,P7)=>{"use strict";var v7=()=>process.platform==="linux",cD=null,tHe=()=>{if(!cD)if(v7()&&process.report){let n=process.report.excludeNetwork;process.report.excludeNetwork=!0,cD=process.report.getReport(),process.report.excludeNetwork=n}else cD={};return cD};P7.exports={isLinux:v7,getReport:tHe}});var L7=$((uQA,F7)=>{"use strict";var lh=$e("fs"),rHe="/usr/bin/ldd",aHe="/proc/self/exe",ID=2048,iHe=n=>{let t=lh.openSync(n,"r"),o=Buffer.alloc(ID),i=lh.readSync(t,o,0,ID,0);return lh.close(t,()=>{}),o.subarray(0,i)},oHe=n=>new Promise((t,o)=>{lh.open(n,"r",(i,e)=>{if(i)o(i);else{let a=Buffer.alloc(ID);lh.read(e,a,0,ID,0,(A,r)=>{t(a.subarray(0,r)),lh.close(e,()=>{})})}})});F7.exports={LDD_PATH:rHe,SELF_PATH:aHe,readFileSync:iHe,readFile:oHe}});var H7=$((BQA,U7)=>{"use strict";var nHe=n=>{if(n.length<64||n.readUInt32BE(0)!==2135247942||n.readUInt8(4)!==2||n.readUInt8(5)!==1)return null;let t=n.readUInt32LE(32),o=n.readUInt16LE(54),i=n.readUInt16LE(56);for(let e=0;e{"use strict";var x7=$e("child_process"),{isLinux:ph,getReport:Y7}=G7(),{LDD_PATH:lD,SELF_PATH:j7,readFile:NF,readFileSync:RF}=L7(),{interpreterPath:J7}=H7(),Ss,ws,Ds,q7="getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",qc="",z7=()=>qc||new Promise(n=>{x7.exec(q7,(t,o)=>{qc=t?" ":o,n(qc)})}),V7=()=>{if(!qc)try{qc=x7.execSync(q7,{encoding:"utf8"})}catch{qc=" "}return qc},vg="glibc",W7=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,_l="musl",sHe=n=>n.includes("libc.musl-")||n.includes("ld-musl-"),Z7=()=>{let n=Y7();return n.header&&n.header.glibcVersionRuntime?vg:Array.isArray(n.sharedObjects)&&n.sharedObjects.some(sHe)?_l:null},X7=n=>{let[t,o]=n.split(/[\r\n]+/);return t&&t.includes(vg)?vg:o&&o.includes(_l)?_l:null},$7=n=>{if(n){if(n.includes("/ld-musl-"))return _l;if(n.includes("/ld-linux-"))return vg}return null},e$=n=>(n=n.toString(),n.includes("musl")?_l:n.includes("GNU C Library")?vg:null),gHe=async()=>{if(ws!==void 0)return ws;ws=null;try{let n=await NF(lD);ws=e$(n)}catch{}return ws},cHe=()=>{if(ws!==void 0)return ws;ws=null;try{let n=RF(lD);ws=e$(n)}catch{}return ws},IHe=async()=>{if(Ss!==void 0)return Ss;Ss=null;try{let n=await NF(j7),t=J7(n);Ss=$7(t)}catch{}return Ss},lHe=()=>{if(Ss!==void 0)return Ss;Ss=null;try{let n=RF(j7),t=J7(n);Ss=$7(t)}catch{}return Ss},A$=async()=>{let n=null;if(ph()&&(n=await IHe(),!n&&(n=await gHe(),n||(n=Z7()),!n))){let t=await z7();n=X7(t)}return n},t$=()=>{let n=null;if(ph()&&(n=lHe(),!n&&(n=cHe(),n||(n=Z7()),!n))){let t=V7();n=X7(t)}return n},pHe=async()=>ph()&&await A$()!==vg,dHe=()=>ph()&&t$()!==vg,hHe=async()=>{if(Ds!==void 0)return Ds;Ds=null;try{let t=(await NF(lD)).match(W7);t&&(Ds=t[1])}catch{}return Ds},EHe=()=>{if(Ds!==void 0)return Ds;Ds=null;try{let t=RF(lD).match(W7);t&&(Ds=t[1])}catch{}return Ds},r$=()=>{let n=Y7();return n.header&&n.header.glibcVersionRuntime?n.header.glibcVersionRuntime:null},K7=n=>n.trim().split(/\s+/)[1],a$=n=>{let[t,o,i]=n.split(/[\r\n]+/);return t&&t.includes(vg)?K7(t):o&&i&&o.includes(_l)?K7(i):null},CHe=async()=>{let n=null;if(ph()&&(n=await hHe(),n||(n=r$()),!n)){let t=await z7();n=a$(t)}return n},uHe=()=>{let n=null;if(ph()&&(n=EHe(),n||(n=r$()),!n)){let t=V7();n=a$(t)}return n};i$.exports={GLIBC:vg,MUSL:_l,family:A$,familySync:t$,isNonGlibcLinux:pHe,isNonGlibcLinuxSync:dHe,version:CHe,versionSync:uHe}});var dh=$((QQA,o$)=>{"use strict";var BHe="2.0.0",fHe=Number.MAX_SAFE_INTEGER||9007199254740991,QHe=16,yHe=250,mHe=["major","premajor","minor","preminor","patch","prepatch","prerelease"];o$.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:QHe,MAX_SAFE_BUILD_LENGTH:yHe,MAX_SAFE_INTEGER:fHe,RELEASE_TYPES:mHe,SEMVER_SPEC_VERSION:BHe,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var OB=$((yQA,n$)=>{"use strict";var SHe=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...n)=>console.error("SEMVER",...n):()=>{};n$.exports=SHe});var hh=$((Os,s$)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:kF,MAX_SAFE_BUILD_LENGTH:wHe,MAX_LENGTH:DHe}=dh(),OHe=OB();Os=s$.exports={};var bHe=Os.re=[],MHe=Os.safeRe=[],cA=Os.src=[],_He=Os.safeSrc=[],IA=Os.t={},THe=0,vF="[a-zA-Z0-9-]",NHe=[["\\s",1],["\\d",DHe],[vF,wHe]],RHe=n=>{for(let[t,o]of NHe)n=n.split(`${t}*`).join(`${t}{0,${o}}`).split(`${t}+`).join(`${t}{1,${o}}`);return n},jA=(n,t,o)=>{let i=RHe(t),e=THe++;OHe(n,e,t),IA[n]=e,cA[e]=t,_He[e]=i,bHe[e]=new RegExp(t,o?"g":void 0),MHe[e]=new RegExp(i,o?"g":void 0)};jA("NUMERICIDENTIFIER","0|[1-9]\\d*");jA("NUMERICIDENTIFIERLOOSE","\\d+");jA("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${vF}*`);jA("MAINVERSION",`(${cA[IA.NUMERICIDENTIFIER]})\\.(${cA[IA.NUMERICIDENTIFIER]})\\.(${cA[IA.NUMERICIDENTIFIER]})`);jA("MAINVERSIONLOOSE",`(${cA[IA.NUMERICIDENTIFIERLOOSE]})\\.(${cA[IA.NUMERICIDENTIFIERLOOSE]})\\.(${cA[IA.NUMERICIDENTIFIERLOOSE]})`);jA("PRERELEASEIDENTIFIER",`(?:${cA[IA.NONNUMERICIDENTIFIER]}|${cA[IA.NUMERICIDENTIFIER]})`);jA("PRERELEASEIDENTIFIERLOOSE",`(?:${cA[IA.NONNUMERICIDENTIFIER]}|${cA[IA.NUMERICIDENTIFIERLOOSE]})`);jA("PRERELEASE",`(?:-(${cA[IA.PRERELEASEIDENTIFIER]}(?:\\.${cA[IA.PRERELEASEIDENTIFIER]})*))`);jA("PRERELEASELOOSE",`(?:-?(${cA[IA.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${cA[IA.PRERELEASEIDENTIFIERLOOSE]})*))`);jA("BUILDIDENTIFIER",`${vF}+`);jA("BUILD",`(?:\\+(${cA[IA.BUILDIDENTIFIER]}(?:\\.${cA[IA.BUILDIDENTIFIER]})*))`);jA("FULLPLAIN",`v?${cA[IA.MAINVERSION]}${cA[IA.PRERELEASE]}?${cA[IA.BUILD]}?`);jA("FULL",`^${cA[IA.FULLPLAIN]}$`);jA("LOOSEPLAIN",`[v=\\s]*${cA[IA.MAINVERSIONLOOSE]}${cA[IA.PRERELEASELOOSE]}?${cA[IA.BUILD]}?`);jA("LOOSE",`^${cA[IA.LOOSEPLAIN]}$`);jA("GTLT","((?:<|>)?=?)");jA("XRANGEIDENTIFIERLOOSE",`${cA[IA.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);jA("XRANGEIDENTIFIER",`${cA[IA.NUMERICIDENTIFIER]}|x|X|\\*`);jA("XRANGEPLAIN",`[v=\\s]*(${cA[IA.XRANGEIDENTIFIER]})(?:\\.(${cA[IA.XRANGEIDENTIFIER]})(?:\\.(${cA[IA.XRANGEIDENTIFIER]})(?:${cA[IA.PRERELEASE]})?${cA[IA.BUILD]}?)?)?`);jA("XRANGEPLAINLOOSE",`[v=\\s]*(${cA[IA.XRANGEIDENTIFIERLOOSE]})(?:\\.(${cA[IA.XRANGEIDENTIFIERLOOSE]})(?:\\.(${cA[IA.XRANGEIDENTIFIERLOOSE]})(?:${cA[IA.PRERELEASELOOSE]})?${cA[IA.BUILD]}?)?)?`);jA("XRANGE",`^${cA[IA.GTLT]}\\s*${cA[IA.XRANGEPLAIN]}$`);jA("XRANGELOOSE",`^${cA[IA.GTLT]}\\s*${cA[IA.XRANGEPLAINLOOSE]}$`);jA("COERCEPLAIN",`(^|[^\\d])(\\d{1,${kF}})(?:\\.(\\d{1,${kF}}))?(?:\\.(\\d{1,${kF}}))?`);jA("COERCE",`${cA[IA.COERCEPLAIN]}(?:$|[^\\d])`);jA("COERCEFULL",cA[IA.COERCEPLAIN]+`(?:${cA[IA.PRERELEASE]})?(?:${cA[IA.BUILD]})?(?:$|[^\\d])`);jA("COERCERTL",cA[IA.COERCE],!0);jA("COERCERTLFULL",cA[IA.COERCEFULL],!0);jA("LONETILDE","(?:~>?)");jA("TILDETRIM",`(\\s*)${cA[IA.LONETILDE]}\\s+`,!0);Os.tildeTrimReplace="$1~";jA("TILDE",`^${cA[IA.LONETILDE]}${cA[IA.XRANGEPLAIN]}$`);jA("TILDELOOSE",`^${cA[IA.LONETILDE]}${cA[IA.XRANGEPLAINLOOSE]}$`);jA("LONECARET","(?:\\^)");jA("CARETTRIM",`(\\s*)${cA[IA.LONECARET]}\\s+`,!0);Os.caretTrimReplace="$1^";jA("CARET",`^${cA[IA.LONECARET]}${cA[IA.XRANGEPLAIN]}$`);jA("CARETLOOSE",`^${cA[IA.LONECARET]}${cA[IA.XRANGEPLAINLOOSE]}$`);jA("COMPARATORLOOSE",`^${cA[IA.GTLT]}\\s*(${cA[IA.LOOSEPLAIN]})$|^$`);jA("COMPARATOR",`^${cA[IA.GTLT]}\\s*(${cA[IA.FULLPLAIN]})$|^$`);jA("COMPARATORTRIM",`(\\s*)${cA[IA.GTLT]}\\s*(${cA[IA.LOOSEPLAIN]}|${cA[IA.XRANGEPLAIN]})`,!0);Os.comparatorTrimReplace="$1$2$3";jA("HYPHENRANGE",`^\\s*(${cA[IA.XRANGEPLAIN]})\\s+-\\s+(${cA[IA.XRANGEPLAIN]})\\s*$`);jA("HYPHENRANGELOOSE",`^\\s*(${cA[IA.XRANGEPLAINLOOSE]})\\s+-\\s+(${cA[IA.XRANGEPLAINLOOSE]})\\s*$`);jA("STAR","(<|>)?=?\\s*\\*");jA("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");jA("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var dD=$((mQA,g$)=>{"use strict";var kHe=Object.freeze({loose:!0}),vHe=Object.freeze({}),PHe=n=>n?typeof n!="object"?kHe:n:vHe;g$.exports=PHe});var PF=$((SQA,l$)=>{"use strict";var c$=/^[0-9]+$/,I$=(n,t)=>{if(typeof n=="number"&&typeof t=="number")return n===t?0:nI$(t,n);l$.exports={compareIdentifiers:I$,rcompareIdentifiers:GHe}});var ma=$((wQA,d$)=>{"use strict";var hD=OB(),{MAX_LENGTH:p$,MAX_SAFE_INTEGER:ED}=dh(),{safeRe:CD,t:uD}=hh(),FHe=dD(),{compareIdentifiers:GF}=PF(),LHe=(n,t)=>{let o=t.split(".");if(o.length>n.length)return!1;for(let i=0;ip$)throw new TypeError(`version is longer than ${p$} characters`);hD("SemVer",t,o),this.options=o,this.loose=!!o.loose,this.includePrerelease=!!o.includePrerelease;let i=t.trim().match(o.loose?CD[uD.LOOSE]:CD[uD.FULL]);if(!i)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>ED||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ED||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ED||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){let a=+e;if(a>=0&&at.major?1:this.minort.minor?1:this.patcht.patch?1:0}comparePre(t){if(t instanceof n||(t=new n(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let o=0;do{let i=this.prerelease[o],e=t.prerelease[o];if(hD("prerelease compare",o,i,e),i===void 0&&e===void 0)return 0;if(e===void 0)return 1;if(i===void 0)return-1;if(i===e)continue;return GF(i,e)}while(++o)}compareBuild(t){t instanceof n||(t=new n(t,this.options));let o=0;do{let i=this.build[o],e=t.build[o];if(hD("build compare",o,i,e),i===void 0&&e===void 0)return 0;if(e===void 0)return 1;if(i===void 0)return-1;if(i===e)continue;return GF(i,e)}while(++o)}inc(t,o,i){if(t.startsWith("pre")){if(!o&&i===!1)throw new Error("invalid increment argument: identifier is empty");if(o){let e=`-${o}`.match(this.options.loose?CD[uD.PRERELEASELOOSE]:CD[uD.PRERELEASE]);if(!e||e[1]!==o)throw new Error(`invalid identifier: ${o}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",o,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",o,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",o,i),this.inc("pre",o,i);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",o,i),this.inc("pre",o,i);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let e=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[e];else{let a=this.prerelease.length;for(;--a>=0;)typeof this.prerelease[a]=="number"&&(this.prerelease[a]++,a=-2);if(a===-1){if(o===this.prerelease.join(".")&&i===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(o){let a=[o,e];if(i===!1&&(a=[o]),LHe(this.prerelease,o)){let A=this.prerelease[o.split(".").length];isNaN(A)&&(this.prerelease=a)}else this.prerelease=a}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};d$.exports=FF});var zc=$((DQA,E$)=>{"use strict";var h$=ma(),UHe=(n,t,o=!1)=>{if(n instanceof h$)return n;try{return new h$(n,t)}catch(i){if(!o)return null;throw i}};E$.exports=UHe});var u$=$((OQA,C$)=>{"use strict";var HHe=zc(),KHe=(n,t)=>{let o=HHe(n,t);return o?o.version:null};C$.exports=KHe});var f$=$((bQA,B$)=>{"use strict";var xHe=zc(),YHe=(n,t)=>{let o=xHe(n.trim().replace(/^[=v]+/,""),t);return o?o.version:null};B$.exports=YHe});var m$=$((MQA,y$)=>{"use strict";var Q$=ma(),jHe=(n,t,o,i,e)=>{typeof o=="string"&&(e=i,i=o,o=void 0);try{return new Q$(n instanceof Q$?n.version:n,o).inc(t,i,e).version}catch{return null}};y$.exports=jHe});var D$=$((_QA,w$)=>{"use strict";var S$=zc(),JHe=(n,t)=>{let o=S$(n,null,!0),i=S$(t,null,!0),e=o.compare(i);if(e===0)return null;let a=e>0,A=a?o:i,r=a?i:o,s=!!A.prerelease.length;if(!!r.prerelease.length&&!s){if(!r.patch&&!r.minor)return"major";if(r.compareMain(A)===0)return r.minor&&!r.patch?"minor":"patch"}let c=s?"pre":"";return o.major!==i.major?c+"major":o.minor!==i.minor?c+"minor":o.patch!==i.patch?c+"patch":"prerelease"};w$.exports=JHe});var b$=$((TQA,O$)=>{"use strict";var qHe=ma(),zHe=(n,t)=>new qHe(n,t).major;O$.exports=zHe});var _$=$((NQA,M$)=>{"use strict";var VHe=ma(),WHe=(n,t)=>new VHe(n,t).minor;M$.exports=WHe});var N$=$((RQA,T$)=>{"use strict";var ZHe=ma(),XHe=(n,t)=>new ZHe(n,t).patch;T$.exports=XHe});var k$=$((kQA,R$)=>{"use strict";var $He=zc(),eKe=(n,t)=>{let o=$He(n,t);return o&&o.prerelease.length?o.prerelease:null};R$.exports=eKe});var jo=$((vQA,P$)=>{"use strict";var v$=ma(),AKe=(n,t,o)=>new v$(n,o).compare(new v$(t,o));P$.exports=AKe});var F$=$((PQA,G$)=>{"use strict";var tKe=jo(),rKe=(n,t,o)=>tKe(t,n,o);G$.exports=rKe});var U$=$((GQA,L$)=>{"use strict";var aKe=jo(),iKe=(n,t)=>aKe(n,t,!0);L$.exports=iKe});var BD=$((FQA,K$)=>{"use strict";var H$=ma(),oKe=(n,t,o)=>{let i=new H$(n,o),e=new H$(t,o);return i.compare(e)||i.compareBuild(e)};K$.exports=oKe});var Y$=$((LQA,x$)=>{"use strict";var nKe=BD(),sKe=(n,t)=>n.sort((o,i)=>nKe(o,i,t));x$.exports=sKe});var J$=$((UQA,j$)=>{"use strict";var gKe=BD(),cKe=(n,t)=>n.sort((o,i)=>gKe(i,o,t));j$.exports=cKe});var bB=$((HQA,q$)=>{"use strict";var IKe=jo(),lKe=(n,t,o)=>IKe(n,t,o)>0;q$.exports=lKe});var fD=$((KQA,z$)=>{"use strict";var pKe=jo(),dKe=(n,t,o)=>pKe(n,t,o)<0;z$.exports=dKe});var LF=$((xQA,V$)=>{"use strict";var hKe=jo(),EKe=(n,t,o)=>hKe(n,t,o)===0;V$.exports=EKe});var UF=$((YQA,W$)=>{"use strict";var CKe=jo(),uKe=(n,t,o)=>CKe(n,t,o)!==0;W$.exports=uKe});var QD=$((jQA,Z$)=>{"use strict";var BKe=jo(),fKe=(n,t,o)=>BKe(n,t,o)>=0;Z$.exports=fKe});var yD=$((JQA,X$)=>{"use strict";var QKe=jo(),yKe=(n,t,o)=>QKe(n,t,o)<=0;X$.exports=yKe});var HF=$((qQA,$$)=>{"use strict";var mKe=LF(),SKe=UF(),wKe=bB(),DKe=QD(),OKe=fD(),bKe=yD(),MKe=(n,t,o,i)=>{switch(t){case"===":return typeof n=="object"&&(n=n.version),typeof o=="object"&&(o=o.version),n===o;case"!==":return typeof n=="object"&&(n=n.version),typeof o=="object"&&(o=o.version),n!==o;case"":case"=":case"==":return mKe(n,o,i);case"!=":return SKe(n,o,i);case">":return wKe(n,o,i);case">=":return DKe(n,o,i);case"<":return OKe(n,o,i);case"<=":return bKe(n,o,i);default:throw new TypeError(`Invalid operator: ${t}`)}};$$.exports=MKe});var Aee=$((zQA,eee)=>{"use strict";var _Ke=ma(),TKe=zc(),{safeRe:mD,t:SD}=hh(),NKe=(n,t)=>{if(n instanceof _Ke)return n;if(typeof n=="number"&&(n=String(n)),typeof n!="string")return null;t=t||{};let o=null;if(!t.rtl)o=n.match(t.includePrerelease?mD[SD.COERCEFULL]:mD[SD.COERCE]);else{let s=t.includePrerelease?mD[SD.COERCERTLFULL]:mD[SD.COERCERTL],g;for(;(g=s.exec(n))&&(!o||o.index+o[0].length!==n.length);)(!o||g.index+g[0].length!==o.index+o[0].length)&&(o=g),s.lastIndex=g.index+g[1].length+g[2].length;s.lastIndex=-1}if(o===null)return null;let i=o[2],e=o[3]||"0",a=o[4]||"0",A=t.includePrerelease&&o[5]?`-${o[5]}`:"",r=t.includePrerelease&&o[6]?`+${o[6]}`:"";return TKe(`${i}.${e}.${a}${A}${r}`,t)};eee.exports=NKe});var ree=$((VQA,tee)=>{"use strict";var RKe=zc(),kKe=dh(),vKe=ma(),PKe=(n,t,o)=>{if(!kKe.RELEASE_TYPES.includes(t))return null;let i=GKe(n,o);return i&&FKe(i,t)},GKe=(n,t)=>{let o=n instanceof vKe?n.version:n;return RKe(o,t)},FKe=(n,t)=>{if(LKe(t))return n.version;switch(n.prerelease=[],t){case"major":n.minor=0,n.patch=0;break;case"minor":n.patch=0;break}return n.format()},LKe=n=>n.startsWith("pre");tee.exports=PKe});var iee=$((WQA,aee)=>{"use strict";var KF=class{constructor(){this.max=1e3,this.map=new Map}get(t){let o=this.map.get(t);if(o!==void 0)return this.map.delete(t),this.map.set(t,o),o}delete(t){return this.map.delete(t)}set(t,o){if(!this.delete(t)&&o!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(t,o)}return this}};aee.exports=KF});var Jo=$((ZQA,gee)=>{"use strict";var UKe=/\s+/g,xF=class n{constructor(t,o){if(o=KKe(o),t instanceof n)return t.loose===!!o.loose&&t.includePrerelease===!!o.includePrerelease?t:new n(t.raw,o);if(t instanceof YF)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=o,this.loose=!!o.loose,this.includePrerelease=!!o.includePrerelease,this.raw=t.trim().replace(UKe," "),this.set=this.raw.split("||").map(i=>this.parseRange(i.trim())).filter(i=>i.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter(e=>!nee(e[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&ZKe(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t0&&(this.formatted+="||");let o=this.set[t];for(let i=0;i0&&(this.formatted+=" "),this.formatted+=o[i].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(WKe,"");let i=((this.options.includePrerelease&&zKe)|(this.options.loose&&VKe))+":"+t,e=oee.get(i);if(e)return e;let a=this.options.loose,A=a?ii[Sa.HYPHENRANGELOOSE]:ii[Sa.HYPHENRANGE];t=t.replace(A,sxe(this.options.includePrerelease)),Jt("hyphen replace",t),t=t.replace(ii[Sa.COMPARATORTRIM],jKe),Jt("comparator trim",t),t=t.replace(ii[Sa.TILDETRIM],JKe),Jt("tilde trim",t),t=t.replace(ii[Sa.CARETTRIM],qKe),Jt("caret trim",t);let r=t.split(" ").map(I=>XKe(I,this.options)).join(" ").split(/\s+/).map(I=>nxe(I,this.options));a&&(r=r.filter(I=>(Jt("loose invalid filter",I,this.options),!!I.match(ii[Sa.COMPARATORLOOSE])))),Jt("range list",r);let s=new Map,g=r.map(I=>new YF(I,this.options));for(let I of g){if(nee(I))return[I];s.set(I.value,I)}s.size>1&&s.has("")&&s.delete("");let c=[...s.values()];return oee.set(i,c),c}intersects(t,o){if(!(t instanceof n))throw new TypeError("a Range is required");return this.set.some(i=>see(i,o)&&t.set.some(e=>see(e,o)&&i.every(a=>e.every(A=>a.intersects(A,o)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new xKe(t,this.options)}catch{return!1}for(let o=0;on.value==="<0.0.0-0",ZKe=n=>n.value==="",see=(n,t)=>{let o=!0,i=n.slice(),e=i.pop();for(;o&&i.length;)o=i.every(a=>e.intersects(a,t)),e=i.pop();return o},XKe=(n,t)=>(n=n.replace(ii[Sa.BUILD],""),Jt("comp",n,t),n=txe(n,t),Jt("caret",n),n=exe(n,t),Jt("tildes",n),n=axe(n,t),Jt("xrange",n),n=oxe(n,t),Jt("stars",n),n),xr=n=>!n||n.toLowerCase()==="x"||n==="*",$Ke=(n,t,o)=>xr(n)&&!xr(t)||xr(t)&&o&&!xr(o),exe=(n,t)=>n.trim().split(/\s+/).map(o=>Axe(o,t)).join(" "),Axe=(n,t)=>{let o=t.loose?ii[Sa.TILDELOOSE]:ii[Sa.TILDE],i=t.includePrerelease?"-0":"";return n.replace(o,(e,a,A,r,s)=>{Jt("tilde",n,e,a,A,r,s);let g;return xr(a)?g="":xr(A)?g=`>=${a}.0.0${i} <${+a+1}.0.0-0`:xr(r)?g=`>=${a}.${A}.0${i} <${a}.${+A+1}.0-0`:s?(Jt("replaceTilde pr",s),g=`>=${a}.${A}.${r}-${s} <${a}.${+A+1}.0-0`):g=`>=${a}.${A}.${r} <${a}.${+A+1}.0-0`,Jt("tilde return",g),g})},txe=(n,t)=>n.trim().split(/\s+/).map(o=>rxe(o,t)).join(" "),rxe=(n,t)=>{Jt("caret",n,t);let o=t.loose?ii[Sa.CARETLOOSE]:ii[Sa.CARET],i=t.includePrerelease?"-0":"";return n.replace(o,(e,a,A,r,s)=>{Jt("caret",n,e,a,A,r,s);let g;return xr(a)?g="":xr(A)?g=`>=${a}.0.0${i} <${+a+1}.0.0-0`:xr(r)?a==="0"?g=`>=${a}.${A}.0${i} <${a}.${+A+1}.0-0`:g=`>=${a}.${A}.0${i} <${+a+1}.0.0-0`:s?(Jt("replaceCaret pr",s),a==="0"?A==="0"?g=`>=${a}.${A}.${r}-${s} <${a}.${A}.${+r+1}-0`:g=`>=${a}.${A}.${r}-${s} <${a}.${+A+1}.0-0`:g=`>=${a}.${A}.${r}-${s} <${+a+1}.0.0-0`):(Jt("no pr"),a==="0"?A==="0"?g=`>=${a}.${A}.${r} <${a}.${A}.${+r+1}-0`:g=`>=${a}.${A}.${r} <${a}.${+A+1}.0-0`:g=`>=${a}.${A}.${r} <${+a+1}.0.0-0`),Jt("caret return",g),g})},axe=(n,t)=>(Jt("replaceXRanges",n,t),n.split(/\s+/).map(o=>ixe(o,t)).join(" ")),ixe=(n,t)=>{n=n.trim();let o=t.loose?ii[Sa.XRANGELOOSE]:ii[Sa.XRANGE];return n.replace(o,(i,e,a,A,r,s)=>{if(Jt("xRange",n,i,e,a,A,r,s),$Ke(a,A,r))return n;let g=xr(a),c=g||xr(A),I=c||xr(r),d=I;return e==="="&&d&&(e=""),s=t.includePrerelease?"-0":"",g?e===">"||e==="<"?i="<0.0.0-0":i="*":e&&d?(c&&(A=0),r=0,e===">"?(e=">=",c?(a=+a+1,A=0,r=0):(A=+A+1,r=0)):e==="<="&&(e="<",c?a=+a+1:A=+A+1),e==="<"&&(s="-0"),i=`${e+a}.${A}.${r}${s}`):c?i=`>=${a}.0.0${s} <${+a+1}.0.0-0`:I&&(i=`>=${a}.${A}.0${s} <${a}.${+A+1}.0-0`),Jt("xRange return",i),i})},oxe=(n,t)=>(Jt("replaceStars",n,t),n.trim().replace(ii[Sa.STAR],"")),nxe=(n,t)=>(Jt("replaceGTE0",n,t),n.trim().replace(ii[t.includePrerelease?Sa.GTE0PRE:Sa.GTE0],"")),sxe=n=>(t,o,i,e,a,A,r,s,g,c,I,d)=>(xr(i)?o="":xr(e)?o=`>=${i}.0.0${n?"-0":""}`:xr(a)?o=`>=${i}.${e}.0${n?"-0":""}`:A?o=`>=${o}`:o=`>=${o}${n?"-0":""}`,xr(g)?s="":xr(c)?s=`<${+g+1}.0.0-0`:xr(I)?s=`<${g}.${+c+1}.0-0`:d?s=`<=${g}.${c}.${I}-${d}`:n?s=`<${g}.${c}.${+I+1}-0`:s=`<=${s}`,`${o} ${s}`.trim()),gxe=(n,t,o)=>{for(let i=0;i0){let e=n[i].semver;if(e.major===t.major&&e.minor===t.minor&&e.patch===t.patch)return!0}return!1}return!0}});var MB=$((XQA,hee)=>{"use strict";var _B=Symbol("SemVer ANY"),qF=class n{static get ANY(){return _B}constructor(t,o){if(o=cee(o),t instanceof n){if(t.loose===!!o.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),JF("comparator",t,o),this.options=o,this.loose=!!o.loose,this.parse(t),this.semver===_B?this.value="":this.value=this.operator+this.semver.version,JF("comp",this)}parse(t){let o=this.options.loose?Iee[lee.COMPARATORLOOSE]:Iee[lee.COMPARATOR],i=t.match(o);if(!i)throw new TypeError(`Invalid comparator: ${t}`);this.operator=i[1]!==void 0?i[1]:"",this.operator==="="&&(this.operator=""),i[2]?this.semver=new pee(i[2],this.options.loose):this.semver=_B}toString(){return this.value}test(t){if(JF("Comparator.test",t,this.options.loose),this.semver===_B||t===_B)return!0;if(typeof t=="string")try{t=new pee(t,this.options)}catch{return!1}return jF(t,this.operator,this.semver,this.options)}intersects(t,o){if(!(t instanceof n))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new dee(t.value,o).test(this.value):t.operator===""?t.value===""?!0:new dee(this.value,o).test(t.semver):(o=cee(o),o.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!o.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||jF(this.semver,"<",t.semver,o)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||jF(this.semver,">",t.semver,o)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};hee.exports=qF;var cee=dD(),{safeRe:Iee,t:lee}=hh(),jF=HF(),JF=OB(),pee=ma(),dee=Jo()});var TB=$(($QA,Eee)=>{"use strict";var cxe=Jo(),Ixe=(n,t,o)=>{try{t=new cxe(t,o)}catch{return!1}return t.test(n)};Eee.exports=Ixe});var uee=$((eyA,Cee)=>{"use strict";var lxe=Jo(),pxe=(n,t)=>new lxe(n,t).set.map(o=>o.map(i=>i.value).join(" ").trim().split(" "));Cee.exports=pxe});var fee=$((AyA,Bee)=>{"use strict";var dxe=ma(),hxe=Jo(),Exe=(n,t,o)=>{let i=null,e=null,a=null;try{a=new hxe(t,o)}catch{return null}return n.forEach(A=>{a.test(A)&&(!i||e.compare(A)===-1)&&(i=A,e=new dxe(i,o))}),i};Bee.exports=Exe});var yee=$((tyA,Qee)=>{"use strict";var Cxe=ma(),uxe=Jo(),Bxe=(n,t,o)=>{let i=null,e=null,a=null;try{a=new uxe(t,o)}catch{return null}return n.forEach(A=>{a.test(A)&&(!i||e.compare(A)===1)&&(i=A,e=new Cxe(i,o))}),i};Qee.exports=Bxe});var wee=$((ryA,See)=>{"use strict";var zF=ma(),fxe=Jo(),mee=bB(),Qxe=(n,t)=>{n=new fxe(n,t);let o=new zF("0.0.0");if(n.test(o)||(o=new zF("0.0.0-0"),n.test(o)))return o;o=null;for(let i=0;i{let r=new zF(A.semver.version);switch(A.operator){case">":r.prerelease.length===0?r.patch++:r.prerelease.push(0),r.raw=r.format();case"":case">=":(!a||mee(r,a))&&(a=r);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${A.operator}`)}}),a&&(!o||mee(o,a))&&(o=a)}return o&&n.test(o)?o:null};See.exports=Qxe});var Oee=$((ayA,Dee)=>{"use strict";var yxe=Jo(),mxe=(n,t)=>{try{return new yxe(n,t).range||"*"}catch{return null}};Dee.exports=mxe});var wD=$((iyA,Tee)=>{"use strict";var Sxe=ma(),_ee=MB(),{ANY:wxe}=_ee,Dxe=Jo(),Oxe=TB(),bee=bB(),Mee=fD(),bxe=yD(),Mxe=QD(),_xe=(n,t,o,i)=>{n=new Sxe(n,i),t=new Dxe(t,i);let e,a,A,r,s;switch(o){case">":e=bee,a=bxe,A=Mee,r=">",s=">=";break;case"<":e=Mee,a=Mxe,A=bee,r="<",s="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Oxe(n,t,i))return!1;for(let g=0;g{B.semver===wxe&&(B=new _ee(">=0.0.0")),I=I||B,d=d||B,e(B.semver,I.semver,i)?I=B:A(B.semver,d.semver,i)&&(d=B)}),I.operator===r||I.operator===s||(!d.operator||d.operator===r)&&a(n,d.semver))return!1;if(d.operator===s&&A(n,d.semver))return!1}return!0};Tee.exports=_xe});var Ree=$((oyA,Nee)=>{"use strict";var Txe=wD(),Nxe=(n,t,o)=>Txe(n,t,">",o);Nee.exports=Nxe});var vee=$((nyA,kee)=>{"use strict";var Rxe=wD(),kxe=(n,t,o)=>Rxe(n,t,"<",o);kee.exports=kxe});var Fee=$((syA,Gee)=>{"use strict";var Pee=Jo(),vxe=(n,t,o)=>(n=new Pee(n,o),t=new Pee(t,o),n.intersects(t,o));Gee.exports=vxe});var Uee=$((gyA,Lee)=>{"use strict";var Pxe=TB(),Gxe=jo();Lee.exports=(n,t,o)=>{let i=[],e=null,a=null,A=n.sort((c,I)=>Gxe(c,I,o));for(let c of A)Pxe(c,t,o)?(a=c,e||(e=c)):(a&&i.push([e,a]),a=null,e=null);e&&i.push([e,null]);let r=[];for(let[c,I]of i)c===I?r.push(c):!I&&c===A[0]?r.push("*"):I?c===A[0]?r.push(`<=${I}`):r.push(`${c} - ${I}`):r.push(`>=${c}`);let s=r.join(" || "),g=typeof t.raw=="string"?t.raw:String(t);return s.length{"use strict";var Hee=Jo(),ZF=MB(),{ANY:VF}=ZF,WF=TB(),XF=jo(),Fxe=(n,t,o={})=>{if(n===t)return!0;n=new Hee(n,o),t=new Hee(t,o);let i=!1;e:for(let e of n.set){for(let a of t.set){let A=Uxe(e,a,o);if(i=i||A!==null,A)continue e}if(i)return!1}return!0},Lxe=[new ZF(">=0.0.0-0")],Kee=[new ZF(">=0.0.0")],Uxe=(n,t,o)=>{if(n===t)return!0;if(n.length===1&&n[0].semver===VF){if(t.length===1&&t[0].semver===VF)return!0;o.includePrerelease?n=Lxe:n=Kee}if(t.length===1&&t[0].semver===VF){if(o.includePrerelease)return!0;t=Kee}let i=new Set,e,a;for(let B of n)B.operator===">"||B.operator===">="?e=xee(e,B,o):B.operator==="<"||B.operator==="<="?a=Yee(a,B,o):i.add(B.semver);if(i.size>1)return null;let A;if(e&&a){if(A=XF(e.semver,a.semver,o),A>0)return null;if(A===0&&(e.operator!==">="||a.operator!=="<="))return null}for(let B of i){if(e&&!WF(B,String(e),o)||a&&!WF(B,String(a),o))return null;for(let f of t)if(!WF(B,String(f),o))return!1;return!0}let r,s,g,c,I=a&&!o.includePrerelease&&a.semver.prerelease.length?a.semver:!1,d=e&&!o.includePrerelease&&e.semver.prerelease.length?e.semver:!1;I&&I.prerelease.length===1&&a.operator==="<"&&I.prerelease[0]===0&&(I=!1);for(let B of t){if(c=c||B.operator===">"||B.operator===">=",g=g||B.operator==="<"||B.operator==="<=",e){if(d&&B.semver.prerelease&&B.semver.prerelease.length&&B.semver.major===d.major&&B.semver.minor===d.minor&&B.semver.patch===d.patch&&(d=!1),B.operator===">"||B.operator===">="){if(r=xee(e,B,o),r===B&&r!==e)return!1}else if(e.operator===">="&&!B.test(e.semver))return!1}if(a){if(I&&B.semver.prerelease&&B.semver.prerelease.length&&B.semver.major===I.major&&B.semver.minor===I.minor&&B.semver.patch===I.patch&&(I=!1),B.operator==="<"||B.operator==="<="){if(s=Yee(a,B,o),s===B&&s!==a)return!1}else if(a.operator==="<="&&!B.test(a.semver))return!1}if(!B.operator&&(a||e)&&A!==0)return!1}return!(e&&g&&!a&&A!==0||a&&c&&!e&&A!==0||d||I)},xee=(n,t,o)=>{if(!n)return t;let i=XF(n.semver,t.semver,o);return i>0?n:i<0||t.operator===">"&&n.operator===">="?t:n},Yee=(n,t,o)=>{if(!n)return t;let i=XF(n.semver,t.semver,o);return i<0?n:i>0||t.operator==="<"&&n.operator==="<="?t:n};jee.exports=Fxe});var DD=$((IyA,Vee)=>{"use strict";var $F=hh(),qee=dh(),Hxe=ma(),zee=PF(),Kxe=zc(),xxe=u$(),Yxe=f$(),jxe=m$(),Jxe=D$(),qxe=b$(),zxe=_$(),Vxe=N$(),Wxe=k$(),Zxe=jo(),Xxe=F$(),$xe=U$(),eYe=BD(),AYe=Y$(),tYe=J$(),rYe=bB(),aYe=fD(),iYe=LF(),oYe=UF(),nYe=QD(),sYe=yD(),gYe=HF(),cYe=Aee(),IYe=ree(),lYe=MB(),pYe=Jo(),dYe=TB(),hYe=uee(),EYe=fee(),CYe=yee(),uYe=wee(),BYe=Oee(),fYe=wD(),QYe=Ree(),yYe=vee(),mYe=Fee(),SYe=Uee(),wYe=Jee();Vee.exports={parse:Kxe,valid:xxe,clean:Yxe,inc:jxe,diff:Jxe,major:qxe,minor:zxe,patch:Vxe,prerelease:Wxe,compare:Zxe,rcompare:Xxe,compareLoose:$xe,compareBuild:eYe,sort:AYe,rsort:tYe,gt:rYe,lt:aYe,eq:iYe,neq:oYe,gte:nYe,lte:sYe,cmp:gYe,coerce:cYe,truncate:IYe,Comparator:lYe,Range:pYe,satisfies:dYe,toComparators:hYe,maxSatisfying:EYe,minSatisfying:CYe,minVersion:uYe,validRange:BYe,outside:fYe,gtr:QYe,ltr:yYe,intersects:mYe,simplifyRange:SYe,subset:wYe,SemVer:Hxe,re:$F.re,src:$F.src,tokens:$F.t,SEMVER_SPEC_VERSION:qee.SEMVER_SPEC_VERSION,RELEASE_TYPES:qee.RELEASE_TYPES,compareIdentifiers:zee.compareIdentifiers,rcompareIdentifiers:zee.rcompareIdentifiers}});var Pg,OD=ue(()=>{Pg={name:"sharp",description:"High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",version:"0.35.4",author:"Lovell Fuller ",homepage:"https://sharp.pixelplumbing.com",contributors:["Pierre Inglebert ","Jonathan Ong ","Chanon Sajjamanochai ","Juliano Julio ","Daniel Gasienica ","Julian Walker ","Amit Pitaru ","Brandon Aaron ","Andreas Lind ","Maurus Cuelenaere ","Linus Unneb\xE4ck ","Victor Mateevitsi ","Alaric Holloway ","Bernhard K. Weisshuhn ","Chris Riley ","David Carley ","John Tobin ","Kenton Gray ","Felix B\xFCnemann ","Samy Al Zahrani ","Chintan Thakkar ","F. Orlando Galashan ","Kleis Auke Wolthuizen ","Matt Hirsch ","Matthias Thoemmes ","Patrick Paskaris ","J\xE9r\xE9my Lal ","Rahul Nanwani ","Alice Monday ","Kristo Jorgenson ","YvesBos ","Guy Maliar ","Nicolas Coden ","Matt Parrish ","Marcel Bretschneider ","Matthew McEachen ","Jarda Kot\u011B\u0161ovec ","Kenric D'Souza ","Oleh Aleinyk ","Marcel Bretschneider ","Andrea Bianco ","Rik Heywood ","Thomas Parisot ","Nathan Graves ","Tom Lokhorst ","Espen Hovlandsdal ","Sylvain Dumont ","Alun Davies ","Aidan Hoolachan ","Axel Eirola ","Freezy ","Daiz ","Julian Aubourg ","Keith Belovay ","Michael B. Klein ","Jordan Prudhomme ","Ilya Ovdin ","Andargor ","Paul Neave ","Brendan Kennedy ","Brychan Bennett-Odlum ","Edward Silverton ","Roman Malieiev ","Tomas Szabo ","Robert O'Rourke ","Guillermo Alfonso Varela Chouci\xF1o ","Christian Flintrup ","Manan Jadhav ","Leon Radley ","alza54 ","Jacob Smith ","Michael Nutt ","Brad Parham ","Taneli Vatanen ","Joris Dugu\xE9 ","Chris Banks ","Ompal Singh ","Brodan ","Ankur Parihar ","Brahim Ait elhaj ","Mart Jansink ","Lachlan Newman ","Dennis Beatty ","Ingvar Stepanyan ","Don Denton ","Dmytro Tiapukhin ","Florian Lefebvre "],scripts:{build:"node install/build.js","build:dist":"node scripts/build.mjs",clean:"rm -rf src/build/ test/fixtures/output.*",test:"npm run lint && npm run test-unit",lint:"npm run lint-cpp && npm run lint-js && npm run lint-types && npm run lint-publish","lint-cpp":"cpplint --quiet src/*.h src/*.cc","lint-js":"biome lint","lint-publish":"publint --strict","lint-types":"tsd --files ./test/types/sharp.test-d.{cts,mts}","test-leak":"./test/leak/leak.sh","test-unit":"node --experimental-test-coverage test/unit.mjs","package-from-local-build":"node npm/from-local-build.js","package-wasm-wrappers":"node npm/wasm-wrappers.js","package-release-notes":"node npm/release-notes.js","docs-build":"node docs/build.mjs","docs-serve":"cd docs && npm start","docs-publish":"cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"},type:"commonjs",files:["dist","install","lib/index.d.ts","src/*.{cc,h,gyp}"],main:"./dist/index.cjs",module:"./dist/index.mjs",types:"./dist/index.d.mts",exports:{".":{import:{types:"./dist/index.d.mts",default:"./dist/index.mjs"},require:{types:"./dist/index.d.cts",default:"./dist/index.cjs"}}},sideEffects:!0,repository:{type:"git",url:"git+https://github.com/lovell/sharp.git"},keywords:["jpeg","png","webp","avif","tiff","gif","svg","jp2","dzi","image","resize","thumbnail","crop","embed","libvips","vips"],dependencies:{"@img/colour":"^1.1.0","detect-libc":"^2.1.2",semver:"^7.8.5"},optionalDependencies:{"@img/sharp-darwin-arm64":"0.35.4","@img/sharp-darwin-x64":"0.35.4","@img/sharp-freebsd-wasm32":"0.35.4","@img/sharp-libvips-darwin-arm64":"1.3.3","@img/sharp-libvips-darwin-x64":"1.3.3","@img/sharp-libvips-linux-arm":"1.3.3","@img/sharp-libvips-linux-arm64":"1.3.3","@img/sharp-libvips-linux-ppc64":"1.3.3","@img/sharp-libvips-linux-riscv64":"1.3.3","@img/sharp-libvips-linux-s390x":"1.3.3","@img/sharp-libvips-linux-x64":"1.3.3","@img/sharp-libvips-linuxmusl-arm64":"1.3.3","@img/sharp-libvips-linuxmusl-x64":"1.3.3","@img/sharp-linux-arm":"0.35.4","@img/sharp-linux-arm64":"0.35.4","@img/sharp-linux-ppc64":"0.35.4","@img/sharp-linux-riscv64":"0.35.4","@img/sharp-linux-s390x":"0.35.4","@img/sharp-linux-x64":"0.35.4","@img/sharp-linuxmusl-arm64":"0.35.4","@img/sharp-linuxmusl-x64":"0.35.4","@img/sharp-webcontainers-wasm32":"0.35.4","@img/sharp-win32-arm64":"0.35.4","@img/sharp-win32-ia32":"0.35.4","@img/sharp-win32-x64":"0.35.4"},peerDependenciesMeta:{"@types/node":{optional:!0}},devDependencies:{"@biomejs/biome":"^2.5.10","@cpplint/cli":"^0.1.0","@emnapi/runtime":"^1.11.3","@img/sharp-libvips-dev":"1.3.3","@img/sharp-libvips-dev-wasm32":"1.3.3","@img/sharp-libvips-win32-arm64":"1.3.3","@img/sharp-libvips-win32-ia32":"1.3.3","@img/sharp-libvips-win32-x64":"1.3.3","@types/node":"*",emnapi:"^1.11.3","exif-reader":"^2.0.3",yauzl:"^3.4.0",icc:"^4.0.0","node-addon-api":"^8.9.2","node-gyp":"^12.4.0",publint:"^0.3.24","tar-fs":"^3.1.3",tsd:"^0.33.0"},license:"Apache-2.0",engines:{node:">=20.9.0"},config:{libvips:">=8.18.6"},funding:{url:"https://opencollective.com/libvips"}}});import{spawnSync as NB}from"node:child_process";import{createHash as OYe}from"node:crypto";var RB,AL,bYe,Zee,MYe,tL,_Ye,Xee,TYe,Eh,NYe,RYe,kYe,vYe,$ee,PYe,Wee,GYe,FYe,eAe,LYe,UYe,AAe,eL,HYe,bD,rL=ue(()=>{RB=Je(DD(),1),AL=Je(pD(),1);OD();bYe=process.env.npm_package_config_libvips||Pg.config.libvips,Zee=RB.default.coerce(bYe).version,MYe=["darwin-arm64","darwin-x64","freebsd-arm64","freebsd-x64","linux-arm","linux-arm64","linux-ppc64","linux-riscv64","linux-s390x","linux-wasm32","linux-x64","linuxmusl-arm64","linuxmusl-x64","win32-arm64","win32-ia32","win32-x64"],tL={encoding:"utf8",shell:!0},_Ye=n=>{n instanceof Error?console.error(`sharp: Installation error: ${n.message}`):console.log(`sharp: ${n}`)},Xee=()=>AL.default.isNonGlibcLinuxSync()?AL.default.familySync():"",TYe=()=>`${process.platform}${Xee()}-${process.arch}`,Eh=()=>{if($ee())return"wasm32";let{npm_config_arch:n,npm_config_platform:t,npm_config_libc:o}=process.env,i=typeof o=="string"?o:Xee();return`${t||process.platform}${i}-${n||process.arch}`},NYe=()=>{try{return $e(`@img/sharp-libvips-dev-${Eh()}/include`)}catch{try{return $e("@img/sharp-libvips-dev/include")}catch{}}return""},RYe=()=>{try{return $e("@img/sharp-libvips-dev/cplusplus")}catch{}return""},kYe=()=>{try{return $e(`@img/sharp-libvips-dev-${Eh()}/lib`)}catch{try{return $e(`@img/sharp-libvips-${Eh()}/lib`)}catch{}}return""},vYe=()=>{if(process.release?.name==="node"&&process.versions&&!RB.default.satisfies(process.versions.node,Pg.engines.node))return{found:process.versions.node,expected:Pg.engines.node}},$ee=()=>{let{CC:n}=process.env;return!!n?.endsWith("/emcc")},PYe=()=>process.platform==="darwin"&&process.arch==="x64"?(NB("sysctl sysctl.proc_translated",tL).stdout||"").trim()==="sysctl.proc_translated: 1":!1,Wee=n=>OYe("sha512").update(n).digest("hex"),GYe=()=>{try{let n=Wee(`imgsharp-libvips-${Eh()}`),t=RB.default.coerce(Pg.optionalDependencies[`@img/sharp-libvips-${Eh()}`],{includePrerelease:!0}).version;return Wee(`${n}npm:${t}`).slice(0,10)}catch{}return""},FYe=()=>NB(`node-gyp rebuild --directory=src ${$ee()?"--nodedir=emscripten":""}`,{...tL,stdio:"inherit"}).status,eAe=()=>process.platform!=="win32"?(NB("pkg-config --modversion vips-cpp",{...tL,env:{...process.env,PKG_CONFIG_PATH:AAe()}}).stdout||"").trim():"",LYe=()=>{try{let n=(NB("brew",["--prefix"],{encoding:"utf8"}).stdout||"").trim();if(n)return`${n}/lib/pkgconfig`}catch{}},UYe=()=>{try{let n=(NB("pkg-config",["--variable","pc_path","pkg-config"],{encoding:"utf8"}).stdout||"").trim();if(n)return n}catch{}},AAe=()=>process.platform!=="win32"?[LYe(),UYe(),process.env.PKG_CONFIG_PATH].filter(Boolean).join(":"):"",eL=(n,t,o)=>(o&&o(`Detected ${t}, skipping search for globally-installed libvips`),n),HYe=n=>{if(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS)return eL(!1,"SHARP_IGNORE_GLOBAL_LIBVIPS",n);if(process.env.SHARP_FORCE_GLOBAL_LIBVIPS)return eL(!0,"SHARP_FORCE_GLOBAL_LIBVIPS",n);if(PYe())return eL(!1,"Rosetta",n);let t=eAe();return!!t&&RB.default.gte(t,Zee)},bD={minimumLibvipsVersion:Zee,prebuiltPlatforms:MYe,buildPlatformArch:Eh,buildSharpLibvipsIncludeDir:NYe,buildSharpLibvipsCPlusPlusDir:RYe,buildSharpLibvipsLibDir:kYe,isUnsupportedNodeRuntime:vYe,runtimePlatformArch:TYe,log:_Ye,yarnLocator:GYe,spawnRebuild:FYe,globalLibvipsVersion:eAe,pkgConfigPath:AAe,useGlobalLibvips:HYe}});import{createRequire as KYe}from"node:module";var MD,Yr,rAe,xYe,tAe,YYe,jYe,Gg,Gt,Vc,St,kB=ue(()=>{MD=Je(pD(),1);rL();OD();Yr=KYe(import.meta.url),{version:rAe}=Pg,{runtimePlatformArch:xYe,isUnsupportedNodeRuntime:tAe,prebuiltPlatforms:YYe,minimumLibvipsVersion:jYe}=bD,Gg=xYe(),Vc=[];try{Gt=Yr(`../src/build/Release/sharp-${Gg}-${rAe}.node`)}catch(n){Vc.push(n)}if(!Gt)try{Gt=Yr(`../src/build/Release/sharp-wasm32-${rAe}.node`)}catch(n){Vc.push(n)}if(!Gt)try{switch(Gg){case"darwin-arm64":Gt=Yr("@img/sharp-darwin-arm64/sharp.node");break;case"darwin-x64":Gt=Yr("@img/sharp-darwin-x64/sharp.node");break;case"linux-arm":Gt=Yr("@img/sharp-linux-arm/sharp.node");break;case"linux-arm64":Gt=Yr("@img/sharp-linux-arm64/sharp.node");break;case"linux-ppc64":Gt=Yr("@img/sharp-linux-ppc64/sharp.node");break;case"linux-riscv64":Gt=Yr("@img/sharp-linux-riscv64/sharp.node");break;case"linux-s390x":Gt=Yr("@img/sharp-linux-s390x/sharp.node");break;case"linux-x64":Gt=Yr("@img/sharp-linux-x64/sharp.node");break;case"linuxmusl-arm64":Gt=Yr("@img/sharp-linuxmusl-arm64/sharp.node");break;case"linuxmusl-x64":Gt=Yr("@img/sharp-linuxmusl-x64/sharp.node");break;case"win32-arm64":Gt=Yr("@img/sharp-win32-arm64/sharp.node");break;case"win32-ia32":Gt=Yr("@img/sharp-win32-ia32/sharp.node");break;case"win32-x64":Gt=Yr("@img/sharp-win32-x64/sharp.node");break;case"freebsd-arm64":case"freebsd-x64":Gt=Yr("@img/sharp-freebsd-wasm32/sharp.node");break;case"linux-wasm32":Gt=Yr("@img/sharp-webcontainers-wasm32/sharp.node");break}if(Gt&&["linux-x64","linuxmusl-x64"].includes(Gg)&&!Gt._isUsingX64V2()){let n=new Error("Prebuilt binaries for Linux x64 require v2 microarchitecture");n.code="Unsupported CPU",Vc.push(n),Gt=null}Gt&&process.versions.electron&&Gg.startsWith("linux")&&process.emitWarning("Binaries provided by Electron for use on Linux may be incompatible with sharp - see https://sharp.pixelplumbing.com/install#electron-and-linux",{code:"SharpElectronLinux"})}catch(n){Vc.push(n)}if(!Gt)try{Gt=Yr("@img/sharp-wasm32/sharp.node")}catch(n){Vc.push(n)}if(!Gt){let[n,t,o]=["linux","darwin","win32"].map(a=>Gg.startsWith(a)),i=[`Could not load the "sharp" module using the ${Gg} runtime`];Vc.forEach(a=>{a.code.endsWith("MODULE_NOT_FOUND")||i.push(`${a.code}: ${a.message}`)});let e=Vc.map(a=>a.message).join(" ");if(i.push("Possible solutions:"),tAe()){let{found:a,expected:A}=tAe();i.push("- Please upgrade Node.js:",` Found ${a}`,` Requires ${A}`)}else if(YYe.includes(Gg)){let[a,A]=Gg.split("-"),r=a.endsWith("musl")?" --libc=musl":"";i.push("- Ensure optional dependencies can be installed:"," npm install --include=optional sharp","- Ensure your package manager supports multi-platform installation:"," See https://sharp.pixelplumbing.com/install#cross-platform","- Add platform-specific dependencies:",` npm install --os=${a.replace("musl","")}${r} --cpu=${A} sharp`)}else i.push(`- Manually install libvips >= ${jYe}`," See https://sharp.pixelplumbing.com/install#building-from-source","- Add WebAssembly-based dependencies:"," npm install sharp @img/sharp-wasm32");if(n&&/(symbol not found|CXXABI_)/i.test(e))try{let{config:a}=Yr(`@img/sharp-libvips-${Gg}/package`),A=`${(0,MD.familySync)()} ${(0,MD.versionSync)()}`,r=`${a.musl?"musl":"glibc"} ${a.musl||a.glibc}`;i.push("- Update your OS:",` Found ${A}`,` Requires ${r}`)}catch{}throw n&&/\/snap\/core[0-9]{2}/.test(e)&&i.push("- Remove the Node.js Snap, which does not support native modules"," snap remove node"),t&&/Incompatible library version/.test(e)&&i.push("- Update Homebrew:"," brew update && brew upgrade vips"),Vc.some(a=>a.code==="ERR_DLOPEN_DISABLED")&&i.push("- Run Node.js without using the --no-addons flag"),o&&/The specified procedure could not be found/.test(e)&&i.push("- Using the canvas package on Windows?"," See https://sharp.pixelplumbing.com/install#canvas-and-windows","- Check for outdated versions of sharp in the dependency tree:"," npm ls sharp"),i.push("- Consult the installation documentation:"," See https://sharp.pixelplumbing.com/install"),new Error(i.join(` +Check the top-level render call using <`+de+">.")}return te}function EK(K,te){if(!(!K._store||K._store.validated||K.key!=null)){K._store.validated=!0;var de=DIe(te);if(!hK[de]){hK[de]=!0;var Se="";K&&K._owner&&K._owner!==R.current&&(Se=" It was passed a child from "+Me(K._owner.type)+"."),hp(K),k('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',de,Se),hp(null)}}}function CK(K,te){if(typeof K=="object"){if(Ye(K))for(var de=0;de",qe=" Did you accidentally export a JSX literal instead of a component?"):EA=typeof K,k("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",EA,qe)}var KA=Ie.apply(this,arguments);if(KA==null)return KA;if(Se)for(var pt=2;pt10&&N("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),Se._updatedFibers.clear()}}}var QK=!1,eQ=null;function TIe(K){if(eQ===null)try{var te=("require"+Math.random()).slice(0,7),de=yS&&yS[te];eQ=de.call(yS,"timers").setImmediate}catch{eQ=function(qe){QK===!1&&(QK=!0,typeof MessageChannel>"u"&&k("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var MA=new MessageChannel;MA.port1.onmessage=qe,MA.port2.postMessage(void 0)}}return eQ(K)}var Ep=0,yK=!1;function mK(K){{var te=Ep;Ep++,T.current===null&&(T.current=[]);var de=T.isBatchingLegacy,Se;try{if(T.isBatchingLegacy=!0,Se=K(),!de&&T.didScheduleLegacyUpdate){var qe=T.current;qe!==null&&(T.didScheduleLegacyUpdate=!1,SM(qe))}}catch(ar){throw AQ(te),ar}finally{T.isBatchingLegacy=de}if(Se!==null&&typeof Se=="object"&&typeof Se.then=="function"){var MA=Se,EA=!1,KA={then:function(ar,br){EA=!0,MA.then(function(ha){AQ(te),Ep===0?yM(ha,ar,br):ar(ha)},function(ha){AQ(te),br(ha)})}};return!yK&&typeof Promise<"u"&&Promise.resolve().then(function(){}).then(function(){EA||(yK=!0,k("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),KA}else{var pt=Se;if(AQ(te),Ep===0){var vt=T.current;vt!==null&&(SM(vt),T.current=null);var zt={then:function(ar,br){T.current===null?(T.current=[],yM(pt,ar,br)):ar(pt)}};return zt}else{var Vt={then:function(ar,br){ar(pt)}};return Vt}}}}function AQ(K){K!==Ep-1&&k("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),Ep=K}function yM(K,te,de){{var Se=T.current;if(Se!==null)try{SM(Se),TIe(function(){Se.length===0?(T.current=null,te(K)):yM(K,te,de)})}catch(qe){de(qe)}else te(K)}}var mM=!1;function SM(K){if(!mM){mM=!0;var te=0;try{for(;te{"use strict";process.env.NODE_ENV==="production"?lP.exports=K6():lP.exports=x6()});var yl=$((lBA,VZ)=>{"use strict";var _w=$e("crypto"),n2e=$e("assert");function Uo(n){if(!(n instanceof Buffer))throw TypeError(`Expected Buffer instead of: ${n.constructor.name}`);return n}function s2e(n,t,o){Uo(n),Uo(t),Uo(o);let i=_w.createCipheriv("aes-256-cbc",n,o);return Buffer.concat([i.update(t),i.final()])}function g2e(n,t,o){Uo(n),Uo(t),Uo(o);let i=_w.createDecipheriv("aes-256-cbc",n,o);return Buffer.concat([i.update(t),i.final()])}function Vd(n,t){Uo(n),Uo(t);let o=_w.createHmac("sha256",n);return o.update(t),Buffer.from(o.digest())}function c2e(n){Uo(n);let t=_w.createHash("sha512");return t.update(n),t.digest()}function I2e(n,t,o,i){if(Uo(n),Uo(t),Uo(o),t.byteLength!=32)throw new Error("Got salt of incorrect length");i=i||3,n2e(i>=1&&i<=3);let e=Vd(t,n),a=new Uint8Array(o.byteLength+1+32);a.set(o,32),a[a.length-1]=1;let A=[Vd(e,Buffer.from(a.slice(32)))];return i>1&&(a.set(A[A.length-1]),a[a.length-1]=2,A.push(Vd(e,Buffer.from(a)))),i>2&&(a.set(A[A.length-1]),a[a.length-1]=3,A.push(Vd(e,Buffer.from(a)))),A}function l2e(n,t,o,i){let e=Vd(t,n).slice(0,i);if(o.length!==i||e.length!==i)throw new Error("Bad MAC length");if(!o.equals(e))throw new Error("Bad MAC")}VZ.exports={deriveSecrets:I2e,decrypt:g2e,encrypt:s2e,hash:c2e,calculateMAC:Vd,verifyMAC:l2e}});var g9=$(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var pBA=new Uint8Array(16),r9=new Uint8Array(32);r9[0]=9;function hA(n){var t,o=new Float64Array(16);if(n)for(t=0;t>24&255,n[t+1]=o>>16&255,n[t+2]=o>>8&255,n[t+3]=o&255,n[t+4]=i>>24&255,n[t+5]=i>>16&255,n[t+6]=i>>8&255,n[t+7]=i&255}function C2e(n,t,o,i,e){var a,A=0;for(a=0;a>>8)-1}function a9(n,t,o,i){return C2e(n,t,o,i,32)}function Rc(n,t){var o;for(o=0;o<16;o++)n[o]=t[o]|0}function UG(n){var t,o,i=1;for(t=0;t<16;t++)o=n[t]+i+65535,i=Math.floor(o/65536),n[t]=o-i*65536;n[0]+=i-1+37*(i-1)}function Wd(n,t,o){for(var i,e=~(o-1),a=0;a<16;a++)i=e&(n[a]^t[a]),n[a]^=i,t[a]^=i}function Xd(n,t){var o,i,e,a=hA(),A=hA();for(o=0;o<16;o++)A[o]=t[o];for(UG(A),UG(A),UG(A),i=0;i<2;i++){for(a[0]=A[0]-65517,o=1;o<15;o++)a[o]=A[o]-65535-(a[o-1]>>16&1),a[o-1]&=65535;a[15]=A[15]-32767-(a[14]>>16&1),e=a[15]>>16&1,a[14]&=65535,Wd(A,a,1-e)}for(o=0;o<16;o++)n[2*o]=A[o]&255,n[2*o+1]=A[o]>>8}function $Z(n,t){var o=new Uint8Array(32),i=new Uint8Array(32);return Xd(o,n),Xd(i,t),a9(o,0,i,0)}function i9(n){var t=new Uint8Array(32);return Xd(t,n),t[0]&1}function jG(n,t){var o;for(o=0;o<16;o++)n[o]=t[2*o]+(t[2*o+1]<<8);n[15]&=32767}function Dn(n,t,o){for(var i=0;i<16;i++)n[i]=t[i]+o[i]}function bn(n,t,o){for(var i=0;i<16;i++)n[i]=t[i]-o[i]}function It(n,t,o){var i,e,a=0,A=0,r=0,s=0,g=0,c=0,I=0,d=0,B=0,f=0,Q=0,y=0,m=0,_=0,T=0,R=0,L=0,U=0,F=0,q=0,z=0,j=0,P=0,J=0,H=0,N=0,k=0,V=0,Ae=0,ie=0,De=0,fe=o[0],_e=o[1],Ee=o[2],Qe=o[3],Le=o[4],AA=o[5],aA=o[6],He=o[7],ce=o[8],Be=o[9],We=o[10],Ye=o[11],Re=o[12],Ze=o[13],iA=o[14],gA=o[15];i=t[0],a+=i*fe,A+=i*_e,r+=i*Ee,s+=i*Qe,g+=i*Le,c+=i*AA,I+=i*aA,d+=i*He,B+=i*ce,f+=i*Be,Q+=i*We,y+=i*Ye,m+=i*Re,_+=i*Ze,T+=i*iA,R+=i*gA,i=t[1],A+=i*fe,r+=i*_e,s+=i*Ee,g+=i*Qe,c+=i*Le,I+=i*AA,d+=i*aA,B+=i*He,f+=i*ce,Q+=i*Be,y+=i*We,m+=i*Ye,_+=i*Re,T+=i*Ze,R+=i*iA,L+=i*gA,i=t[2],r+=i*fe,s+=i*_e,g+=i*Ee,c+=i*Qe,I+=i*Le,d+=i*AA,B+=i*aA,f+=i*He,Q+=i*ce,y+=i*Be,m+=i*We,_+=i*Ye,T+=i*Re,R+=i*Ze,L+=i*iA,U+=i*gA,i=t[3],s+=i*fe,g+=i*_e,c+=i*Ee,I+=i*Qe,d+=i*Le,B+=i*AA,f+=i*aA,Q+=i*He,y+=i*ce,m+=i*Be,_+=i*We,T+=i*Ye,R+=i*Re,L+=i*Ze,U+=i*iA,F+=i*gA,i=t[4],g+=i*fe,c+=i*_e,I+=i*Ee,d+=i*Qe,B+=i*Le,f+=i*AA,Q+=i*aA,y+=i*He,m+=i*ce,_+=i*Be,T+=i*We,R+=i*Ye,L+=i*Re,U+=i*Ze,F+=i*iA,q+=i*gA,i=t[5],c+=i*fe,I+=i*_e,d+=i*Ee,B+=i*Qe,f+=i*Le,Q+=i*AA,y+=i*aA,m+=i*He,_+=i*ce,T+=i*Be,R+=i*We,L+=i*Ye,U+=i*Re,F+=i*Ze,q+=i*iA,z+=i*gA,i=t[6],I+=i*fe,d+=i*_e,B+=i*Ee,f+=i*Qe,Q+=i*Le,y+=i*AA,m+=i*aA,_+=i*He,T+=i*ce,R+=i*Be,L+=i*We,U+=i*Ye,F+=i*Re,q+=i*Ze,z+=i*iA,j+=i*gA,i=t[7],d+=i*fe,B+=i*_e,f+=i*Ee,Q+=i*Qe,y+=i*Le,m+=i*AA,_+=i*aA,T+=i*He,R+=i*ce,L+=i*Be,U+=i*We,F+=i*Ye,q+=i*Re,z+=i*Ze,j+=i*iA,P+=i*gA,i=t[8],B+=i*fe,f+=i*_e,Q+=i*Ee,y+=i*Qe,m+=i*Le,_+=i*AA,T+=i*aA,R+=i*He,L+=i*ce,U+=i*Be,F+=i*We,q+=i*Ye,z+=i*Re,j+=i*Ze,P+=i*iA,J+=i*gA,i=t[9],f+=i*fe,Q+=i*_e,y+=i*Ee,m+=i*Qe,_+=i*Le,T+=i*AA,R+=i*aA,L+=i*He,U+=i*ce,F+=i*Be,q+=i*We,z+=i*Ye,j+=i*Re,P+=i*Ze,J+=i*iA,H+=i*gA,i=t[10],Q+=i*fe,y+=i*_e,m+=i*Ee,_+=i*Qe,T+=i*Le,R+=i*AA,L+=i*aA,U+=i*He,F+=i*ce,q+=i*Be,z+=i*We,j+=i*Ye,P+=i*Re,J+=i*Ze,H+=i*iA,N+=i*gA,i=t[11],y+=i*fe,m+=i*_e,_+=i*Ee,T+=i*Qe,R+=i*Le,L+=i*AA,U+=i*aA,F+=i*He,q+=i*ce,z+=i*Be,j+=i*We,P+=i*Ye,J+=i*Re,H+=i*Ze,N+=i*iA,k+=i*gA,i=t[12],m+=i*fe,_+=i*_e,T+=i*Ee,R+=i*Qe,L+=i*Le,U+=i*AA,F+=i*aA,q+=i*He,z+=i*ce,j+=i*Be,P+=i*We,J+=i*Ye,H+=i*Re,N+=i*Ze,k+=i*iA,V+=i*gA,i=t[13],_+=i*fe,T+=i*_e,R+=i*Ee,L+=i*Qe,U+=i*Le,F+=i*AA,q+=i*aA,z+=i*He,j+=i*ce,P+=i*Be,J+=i*We,H+=i*Ye,N+=i*Re,k+=i*Ze,V+=i*iA,Ae+=i*gA,i=t[14],T+=i*fe,R+=i*_e,L+=i*Ee,U+=i*Qe,F+=i*Le,q+=i*AA,z+=i*aA,j+=i*He,P+=i*ce,J+=i*Be,H+=i*We,N+=i*Ye,k+=i*Re,V+=i*Ze,Ae+=i*iA,ie+=i*gA,i=t[15],R+=i*fe,L+=i*_e,U+=i*Ee,F+=i*Qe,q+=i*Le,z+=i*AA,j+=i*aA,P+=i*He,J+=i*ce,H+=i*Be,N+=i*We,k+=i*Ye,V+=i*Re,Ae+=i*Ze,ie+=i*iA,De+=i*gA,a+=38*L,A+=38*U,r+=38*F,s+=38*q,g+=38*z,c+=38*j,I+=38*P,d+=38*J,B+=38*H,f+=38*N,Q+=38*k,y+=38*V,m+=38*Ae,_+=38*ie,T+=38*De,e=1,i=a+e+65535,e=Math.floor(i/65536),a=i-e*65536,i=A+e+65535,e=Math.floor(i/65536),A=i-e*65536,i=r+e+65535,e=Math.floor(i/65536),r=i-e*65536,i=s+e+65535,e=Math.floor(i/65536),s=i-e*65536,i=g+e+65535,e=Math.floor(i/65536),g=i-e*65536,i=c+e+65535,e=Math.floor(i/65536),c=i-e*65536,i=I+e+65535,e=Math.floor(i/65536),I=i-e*65536,i=d+e+65535,e=Math.floor(i/65536),d=i-e*65536,i=B+e+65535,e=Math.floor(i/65536),B=i-e*65536,i=f+e+65535,e=Math.floor(i/65536),f=i-e*65536,i=Q+e+65535,e=Math.floor(i/65536),Q=i-e*65536,i=y+e+65535,e=Math.floor(i/65536),y=i-e*65536,i=m+e+65535,e=Math.floor(i/65536),m=i-e*65536,i=_+e+65535,e=Math.floor(i/65536),_=i-e*65536,i=T+e+65535,e=Math.floor(i/65536),T=i-e*65536,i=R+e+65535,e=Math.floor(i/65536),R=i-e*65536,a+=e-1+37*(e-1),e=1,i=a+e+65535,e=Math.floor(i/65536),a=i-e*65536,i=A+e+65535,e=Math.floor(i/65536),A=i-e*65536,i=r+e+65535,e=Math.floor(i/65536),r=i-e*65536,i=s+e+65535,e=Math.floor(i/65536),s=i-e*65536,i=g+e+65535,e=Math.floor(i/65536),g=i-e*65536,i=c+e+65535,e=Math.floor(i/65536),c=i-e*65536,i=I+e+65535,e=Math.floor(i/65536),I=i-e*65536,i=d+e+65535,e=Math.floor(i/65536),d=i-e*65536,i=B+e+65535,e=Math.floor(i/65536),B=i-e*65536,i=f+e+65535,e=Math.floor(i/65536),f=i-e*65536,i=Q+e+65535,e=Math.floor(i/65536),Q=i-e*65536,i=y+e+65535,e=Math.floor(i/65536),y=i-e*65536,i=m+e+65535,e=Math.floor(i/65536),m=i-e*65536,i=_+e+65535,e=Math.floor(i/65536),_=i-e*65536,i=T+e+65535,e=Math.floor(i/65536),T=i-e*65536,i=R+e+65535,e=Math.floor(i/65536),R=i-e*65536,a+=e-1+37*(e-1),n[0]=a,n[1]=A,n[2]=r,n[3]=s,n[4]=g,n[5]=c,n[6]=I,n[7]=d,n[8]=B,n[9]=f,n[10]=Q,n[11]=y,n[12]=m,n[13]=_,n[14]=T,n[15]=R}function On(n,t){It(n,t,t)}function JG(n,t){var o=hA(),i;for(i=0;i<16;i++)o[i]=t[i];for(i=253;i>=0;i--)On(o,o),i!==2&&i!==4&&It(o,o,t);for(i=0;i<16;i++)n[i]=o[i]}function u2e(n,t){var o=hA(),i;for(i=0;i<16;i++)o[i]=t[i];for(i=250;i>=0;i--)On(o,o),i!==1&&It(o,o,t);for(i=0;i<16;i++)n[i]=o[i]}function o9(n,t,o){var i=new Uint8Array(32),e=new Float64Array(80),a,A,r=hA(),s=hA(),g=hA(),c=hA(),I=hA(),d=hA();for(A=0;A<31;A++)i[A]=t[A];for(i[31]=t[31]&127|64,i[0]&=248,jG(e,o),A=0;A<16;A++)s[A]=e[A],c[A]=r[A]=g[A]=0;for(r[0]=c[0]=1,A=254;A>=0;--A)a=i[A>>>3]>>>(A&7)&1,Wd(r,s,a),Wd(g,c,a),Dn(I,r,g),bn(r,r,g),Dn(g,s,c),bn(s,s,c),On(c,I),On(d,r),It(r,g,r),It(g,s,I),Dn(I,r,g),bn(r,r,g),On(s,r),bn(g,c,d),It(r,g,p2e),Dn(r,r,c),It(g,g,r),It(r,c,d),It(c,s,e),On(s,I),Wd(r,s,a),Wd(g,c,a);for(A=0;A<16;A++)e[A+16]=r[A],e[A+32]=g[A],e[A+48]=s[A],e[A+64]=c[A];var B=e.subarray(32),f=e.subarray(16);return JG(B,B),It(f,f,B),Xd(n,f),0}function B2e(n,t){return o9(n,t,r9)}var e9=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function A9(n,t,o,i){for(var e=new Int32Array(16),a=new Int32Array(16),A,r,s,g,c,I,d,B,f,Q,y,m,_,T,R,L,U,F,q,z,j,P,J,H,N,k,V=n[0],Ae=n[1],ie=n[2],De=n[3],fe=n[4],_e=n[5],Ee=n[6],Qe=n[7],Le=t[0],AA=t[1],aA=t[2],He=t[3],ce=t[4],Be=t[5],We=t[6],Ye=t[7],Re=0;i>=128;){for(q=0;q<16;q++)z=8*q+Re,e[q]=o[z+0]<<24|o[z+1]<<16|o[z+2]<<8|o[z+3],a[q]=o[z+4]<<24|o[z+5]<<16|o[z+6]<<8|o[z+7];for(q=0;q<80;q++)if(A=V,r=Ae,s=ie,g=De,c=fe,I=_e,d=Ee,B=Qe,f=Le,Q=AA,y=aA,m=He,_=ce,T=Be,R=We,L=Ye,j=Qe,P=Ye,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=(fe>>>14|ce<<18)^(fe>>>18|ce<<14)^(ce>>>9|fe<<23),P=(ce>>>14|fe<<18)^(ce>>>18|fe<<14)^(fe>>>9|ce<<23),J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,j=fe&_e^~fe&Ee,P=ce&Be^~ce&We,J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,j=e9[q*2],P=e9[q*2+1],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,j=e[q%16],P=a[q%16],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,U=N&65535|k<<16,F=J&65535|H<<16,j=U,P=F,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=(V>>>28|Le<<4)^(Le>>>2|V<<30)^(Le>>>7|V<<25),P=(Le>>>28|V<<4)^(V>>>2|Le<<30)^(V>>>7|Le<<25),J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,j=V&Ae^V&ie^Ae&ie,P=Le&AA^Le&aA^AA&aA,J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,B=N&65535|k<<16,L=J&65535|H<<16,j=g,P=m,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=U,P=F,J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,g=N&65535|k<<16,m=J&65535|H<<16,Ae=A,ie=r,De=s,fe=g,_e=c,Ee=I,Qe=d,V=B,AA=f,aA=Q,He=y,ce=m,Be=_,We=T,Ye=R,Le=L,q%16===15)for(z=0;z<16;z++)j=e[z],P=a[z],J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=e[(z+9)%16],P=a[(z+9)%16],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,U=e[(z+1)%16],F=a[(z+1)%16],j=(U>>>1|F<<31)^(U>>>8|F<<24)^U>>>7,P=(F>>>1|U<<31)^(F>>>8|U<<24)^(F>>>7|U<<25),J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,U=e[(z+14)%16],F=a[(z+14)%16],j=(U>>>19|F<<13)^(F>>>29|U<<3)^U>>>6,P=(F>>>19|U<<13)^(U>>>29|F<<3)^(F>>>6|U<<26),J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,e[z]=N&65535|k<<16,a[z]=J&65535|H<<16;j=V,P=Le,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=n[0],P=t[0],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,n[0]=V=N&65535|k<<16,t[0]=Le=J&65535|H<<16,j=Ae,P=AA,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=n[1],P=t[1],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,n[1]=Ae=N&65535|k<<16,t[1]=AA=J&65535|H<<16,j=ie,P=aA,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=n[2],P=t[2],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,n[2]=ie=N&65535|k<<16,t[2]=aA=J&65535|H<<16,j=De,P=He,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=n[3],P=t[3],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,n[3]=De=N&65535|k<<16,t[3]=He=J&65535|H<<16,j=fe,P=ce,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=n[4],P=t[4],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,n[4]=fe=N&65535|k<<16,t[4]=ce=J&65535|H<<16,j=_e,P=Be,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=n[5],P=t[5],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,n[5]=_e=N&65535|k<<16,t[5]=Be=J&65535|H<<16,j=Ee,P=We,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=n[6],P=t[6],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,n[6]=Ee=N&65535|k<<16,t[6]=We=J&65535|H<<16,j=Qe,P=Ye,J=P&65535,H=P>>>16,N=j&65535,k=j>>>16,j=n[7],P=t[7],J+=P&65535,H+=P>>>16,N+=j&65535,k+=j>>>16,H+=J>>>16,N+=H>>>16,k+=N>>>16,n[7]=Qe=N&65535|k<<16,t[7]=Ye=J&65535|H<<16,Re+=128,i-=128}return i}function nB(n,t,o){var i=new Int32Array(8),e=new Int32Array(8),a=new Uint8Array(256),A,r=o;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,e[0]=4089235720,e[1]=2227873595,e[2]=4271175723,e[3]=1595750129,e[4]=2917565137,e[5]=725511199,e[6]=4215389547,e[7]=327033209,A9(i,e,t,o),o%=128,A=0;A=0;--e)i=o[e/8|0]>>(e&7)&1,t9(n,t,i),xG(t,n),xG(n,n),t9(n,t,i)}function Nw(n,t){var o=[hA(),hA(),hA(),hA()];Rc(o[0],WZ),Rc(o[1],ZZ),Rc(o[2],Zd),It(o[3],WZ,ZZ),n9(n,o,t)}var HG=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function qG(n,t){var o,i,e,a;for(i=63;i>=32;--i){for(o=0,e=i-32,a=i-12;e>8,t[e]-=o*256;t[e]+=o,t[i]=0}for(o=0,e=0;e<32;e++)t[e]+=o-(t[31]>>4)*HG[e],o=t[e]>>8,t[e]&=255;for(e=0;e<32;e++)t[e]-=o*HG[e];for(i=0;i<32;i++)t[i+1]+=t[i]>>8,n[i]=t[i]&255}function sB(n){var t=new Float64Array(64),o;for(o=0;o<64;o++)t[o]=n[o];for(o=0;o<64;o++)n[o]=0;qG(n,t)}function f2e(n,t,o,i){var e=new Uint8Array(64),a=new Uint8Array(64),A,r,s=new Float64Array(64),g=[hA(),hA(),hA(),hA()];for(A=0;A>7&&bn(n[0],KG,n[0]),It(n[3],n[0],n[1]),0)}function m2e(n,t,o,i){var e,a,A=new Uint8Array(32),r=new Uint8Array(64),s=[hA(),hA(),hA(),hA()],g=[hA(),hA(),hA(),hA()];if(a=-1,o<64||y2e(g,i))return-1;for(e=0;e=0}Dg.verify=M2e;function _2e(n){if(kc(n),n.length!==32)throw new Error("wrong seed length");for(var t=new Uint8Array(32),o=new Uint8Array(32),i=0;i<32;i++)t[i]=n[i];return B2e(o,t),t[0]&=248,t[31]&=127,t[31]|=64,o[31]&=127,{public:o,private:t}}Dg.generateKeyPair=_2e;Dg.default={}});var vc=$(eh=>{"use strict";var gB=g9(),$d=$e("crypto"),zG=Buffer.from([48,42,48,5,6,3,43,101,110,3,33,0]),VG=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),T2e=Buffer.from([5]),WG=function(n){return Buffer.concat([T2e,n])};function c9(n){if(n===void 0)throw new Error("Undefined private key");if(!(n instanceof Buffer))throw new Error(`Invalid private key type: ${n.constructor.name}`);if(n.byteLength!=32)throw new Error(`Incorrect private key length: ${n.byteLength}`)}function I9(n){if(!(n instanceof Buffer))throw new Error(`Invalid public key type: ${n.constructor.name}`);if(n===void 0||(n.byteLength!=33||n[0]!=5)&&n.byteLength!=32)throw new Error("Invalid public key");return n.byteLength==33?n.slice(1):(console.error("WARNING: Expected pubkey of length 33, please report the ST and client that generated the pubkey"),n)}function N2e(n){let t=new Uint8Array(n);return t[0]|=6,t[31]|=128,t[31]&=-65,t}eh.getPublicFromPrivateKey=function(n){let t=N2e(n),o=gB.generateKeyPair(t);return WG(Buffer.from(o.public))};eh.generateKeyPair=function(){try{let{publicKey:n,privateKey:t}=$d.generateKeyPairSync("x25519",{publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}}),o=n.slice(zG.length,zG.length+32),i=t.slice(VG.length,VG.length+32);return{pubKey:WG(o),privKey:i}}catch{let t=gB.generateKeyPair($d.randomBytes(32));return{privKey:Buffer.from(t.private),pubKey:WG(Buffer.from(t.public))}}};eh.calculateAgreement=function(n,t){if(n=I9(n),c9(t),!n||n.byteLength!=32)throw new Error("Invalid public key");if(typeof $d.diffieHellman=="function"){let o=$d.createPrivateKey({key:Buffer.concat([VG,t]),format:"der",type:"pkcs8"}),i=$d.createPublicKey({key:Buffer.concat([zG,n]),format:"der",type:"spki"});return $d.diffieHellman({privateKey:o,publicKey:i})}else{let o=gB.sharedKey(t,n);return Buffer.from(o)}};eh.calculateSignature=function(n,t){if(c9(n),!t)throw new Error("Invalid message");return Buffer.from(gB.sign(n,t))};eh.verifySignature=function(n,t,o,i){if(n=I9(n),!n||n.byteLength!=32)throw new Error("Invalid public key");if(!t)throw new Error("Invalid message");if(!o||o.byteLength!=64)throw new Error("Invalid signature");return i?!0:gB.verify(n,t,o)}});var p9=$(cB=>{var Rw=vc(),R2e=$e("crypto");function l9(n){return typeof n=="number"&&n%1===0&&n>=0}cB.generateIdentityKeyPair=Rw.generateKeyPair;cB.generateRegistrationId=function(){var n=Uint16Array.from(R2e.randomBytes(2))[0];return n&16383};cB.generateSignedPreKey=function(n,t){if(!(n.privKey instanceof Buffer)||n.privKey.byteLength!=32||!(n.pubKey instanceof Buffer)||n.pubKey.byteLength!=33)throw new TypeError("Invalid argument for identityKeyPair");if(!l9(t))throw new TypeError("Invalid argument for signedKeyId: "+t);let o=Rw.generateKeyPair(),i=Rw.calculateSignature(n.privKey,o.pubKey);return{keyId:t,keyPair:o,signature:i}};cB.generatePreKey=function(n){if(!l9(n))throw new TypeError("Invalid argument for keyId: "+n);let t=Rw.generateKeyPair();return{keyId:n,keyPair:t}}});var XG=$((CBA,d9)=>{var ZG=class n{static from(t){if(typeof t!="string"||!t.match(/.*\.\d+/))throw new Error("Invalid address encoding");let o=t.split(".");return new this(o[0],parseInt(o[1]))}constructor(t,o){if(typeof t!="string")throw new TypeError("id required for addr");if(t.indexOf(".")!==-1)throw new TypeError("encoded addr detected");if(this.id=t,typeof o!="number")throw new TypeError("number required for deviceId");this.deviceId=o}toString(){return`${this.id}.${this.deviceId}`}is(t){return t instanceof n?t.id===this.id&&t.deviceId===this.deviceId:!1}};d9.exports=ZG});var $G=$((uBA,h9)=>{var k2e={OURS:1,THEIRS:2};h9.exports=k2e});var eF=$((BBA,E9)=>{var v2e={SENDING:1,RECEIVING:2};E9.exports=v2e});var Gw=$((fBA,u9)=>{var P2e=$G(),G2e=40,C9="v1";function vw(n){if(!Buffer.isBuffer(n))throw new TypeError("Buffer required")}var Pw=class{constructor(){this._chains={}}toString(){return``}inspect(){return this.toString()}addChain(t,o){vw(t);let i=t.toString("base64");if(this._chains.hasOwnProperty(i))throw new Error("Overwrite attempt");this._chains[i]=o}getChain(t){return vw(t),this._chains[t.toString("base64")]}deleteChain(t){vw(t);let o=t.toString("base64");if(!this._chains.hasOwnProperty(o))throw new ReferenceError("Not Found");delete this._chains[o]}*chains(){for(let[t,o]of Object.entries(this._chains))yield[Buffer.from(t,"base64"),o]}serialize(){let t={registrationId:this.registrationId,currentRatchet:{ephemeralKeyPair:{pubKey:this.currentRatchet.ephemeralKeyPair.pubKey.toString("base64"),privKey:this.currentRatchet.ephemeralKeyPair.privKey.toString("base64")},lastRemoteEphemeralKey:this.currentRatchet.lastRemoteEphemeralKey.toString("base64"),previousCounter:this.currentRatchet.previousCounter,rootKey:this.currentRatchet.rootKey.toString("base64")},indexInfo:{baseKey:this.indexInfo.baseKey.toString("base64"),baseKeyType:this.indexInfo.baseKeyType,closed:this.indexInfo.closed,used:this.indexInfo.used,created:this.indexInfo.created,remoteIdentityKey:this.indexInfo.remoteIdentityKey.toString("base64")},_chains:this._serialize_chains(this._chains)};return this.pendingPreKey&&(t.pendingPreKey=Object.assign({},this.pendingPreKey),t.pendingPreKey.baseKey=this.pendingPreKey.baseKey.toString("base64")),t}static deserialize(t){let o=new this;return o.registrationId=t.registrationId,o.currentRatchet={ephemeralKeyPair:{pubKey:Buffer.from(t.currentRatchet.ephemeralKeyPair.pubKey,"base64"),privKey:Buffer.from(t.currentRatchet.ephemeralKeyPair.privKey,"base64")},lastRemoteEphemeralKey:Buffer.from(t.currentRatchet.lastRemoteEphemeralKey,"base64"),previousCounter:t.currentRatchet.previousCounter,rootKey:Buffer.from(t.currentRatchet.rootKey,"base64")},o.indexInfo={baseKey:Buffer.from(t.indexInfo.baseKey,"base64"),baseKeyType:t.indexInfo.baseKeyType,closed:t.indexInfo.closed,used:t.indexInfo.used,created:t.indexInfo.created,remoteIdentityKey:Buffer.from(t.indexInfo.remoteIdentityKey,"base64")},o._chains=this._deserialize_chains(t._chains),t.pendingPreKey&&(o.pendingPreKey=Object.assign({},t.pendingPreKey),o.pendingPreKey.baseKey=Buffer.from(t.pendingPreKey.baseKey,"base64")),o}_serialize_chains(t){let o={};for(let i of Object.keys(t)){let e=t[i],a={};for(let[A,r]of Object.entries(e.messageKeys))a[A]=r.toString("base64");o[i]={chainKey:{counter:e.chainKey.counter,key:e.chainKey.key&&e.chainKey.key.toString("base64")},chainType:e.chainType,messageKeys:a}}return o}static _deserialize_chains(t){let o={};for(let i of Object.keys(t)){let e=t[i],a={};for(let[A,r]of Object.entries(e.messageKeys))a[A]=Buffer.from(r,"base64");o[i]={chainKey:{counter:e.chainKey.counter,key:e.chainKey.key&&Buffer.from(e.chainKey.key,"base64")},chainType:e.chainType,messageKeys:a}}return o}},kw=[{version:"v1",migrate:function(t){let o=t._sessions;if(t.registrationId)for(let i in o)o[i].registrationId||(o[i].registrationId=t.registrationId);else for(let i in o)o[i].indexInfo.closed===-1&&console.error("V1 session storage migration error: registrationId",t.registrationId,"for open session version",t.version)}}],AF=class{static createEntry(){return new Pw}static migrate(t){let o=t.version===void 0;for(let i=0;i{let i=t.indexInfo.used||0,e=o.indexInfo.used||0;return i===e?0:iG2e;){let t,o;for(let[i,e]of Object.entries(this.sessions))e.indexInfo.closed!==-1&&(!o||e.indexInfo.closed{Bs.SignalError=class extends Error{};Bs.UntrustedIdentityKeyError=class extends Bs.SignalError{constructor(t,o){super(),this.name="UntrustedIdentityKeyError",this.addr=t,this.identityKey=o}};Bs.SessionError=class extends Bs.SignalError{constructor(t){super(t),this.name="SessionError"}};Bs.MessageCounterError=class extends Bs.SessionError{constructor(t){super(t),this.name="MessageCounterError"}};Bs.PreKeyError=class extends Bs.SessionError{constructor(t){super(t),this.name="PreKeyError"}}});var tF=$((OBA,f9)=>{"use strict";var Lw=new Map,B9=1e4;async function F2e(n,t){let o=0;for(;;){let i=Math.min(n.length,B9);for(let e=o;e=B9?(n.splice(0,i),o=0):o=i;else break}t()}f9.exports=function(n,t){t.name||(Object.defineProperty(t,"name",{writable:!0}),typeof n=="string"?t.name=n:console.warn("Unhandled bucket type (for naming):",typeof n,n));let o;Lw.has(n)||(Lw.set(n,[]),o=!0);let i=Lw.get(n),e=new Promise((a,A)=>i.push({awaitable:t,resolve:a,reject:A}));return o&&F2e(i,()=>Lw.delete(n)),e}});var aF=$((bBA,S9)=>{"use strict";var Q9=$G(),L2e=eF(),y9=Gw(),m9=yl(),Pc=vc(),Uw=Fw(),U2e=tF(),rF=class{constructor(t,o){this.addr=o,this.storage=t}async initOutgoing(t){let o=this.addr.toString();return await U2e(o,async()=>{if(!await this.storage.isTrustedIdentity(this.addr.id,t.identityKey))throw new Uw.UntrustedIdentityKeyError(this.addr.id,t.identityKey);Pc.verifySignature(t.identityKey,t.signedPreKey.publicKey,t.signedPreKey.signature,!0);let i=Pc.generateKeyPair(),e=t.preKey&&t.preKey.publicKey,a=await this.initSession(!0,i,void 0,t.identityKey,e,t.signedPreKey.publicKey,t.registrationId);a.pendingPreKey={signedKeyId:t.signedPreKey.keyId,baseKey:i.pubKey},t.preKey&&(a.pendingPreKey.preKeyId=t.preKey.keyId);let A=await this.storage.loadSession(o);if(!A)A=new y9;else{let r=A.getOpenSession();r&&A.closeSession(r)}A.setSession(a),await this.storage.storeSession(o,A)})}async initIncoming(t,o){let i=this.addr.toString();if(!await this.storage.isTrustedIdentity(i,o.identityKey))throw new Uw.UntrustedIdentityKeyError(this.addr.id,o.identityKey);if(t.getSession(o.baseKey))return;let e=await this.storage.loadPreKey(o.preKeyId);if(o.preKeyId&&!e)throw new Uw.PreKeyError("Invalid PreKey ID");let a=await this.storage.loadSignedPreKey(o.signedPreKeyId);if(!a)throw new Uw.PreKeyError("Missing SignedPreKey");let A=t.getOpenSession();return A&&(console.warn("Closing open session in favor of incoming prekey bundle"),t.closeSession(A)),t.setSession(await this.initSession(!1,e,a,o.identityKey,o.baseKey,void 0,o.registrationId)),o.preKeyId}async initSession(t,o,i,e,a,A,r){if(t){if(i)throw new Error("Invalid call to initSession");i=o}else{if(A)throw new Error("Invalid call to initSession");A=a}let s;!o||!a?s=new Uint8Array(128):s=new Uint8Array(160);for(var g=0;g<32;g++)s[g]=255;let c=await this.storage.getOurIdentity(),I=Pc.calculateAgreement(A,c.privKey),d=Pc.calculateAgreement(e,i.privKey),B=Pc.calculateAgreement(A,i.privKey);if(t?(s.set(new Uint8Array(I),32),s.set(new Uint8Array(d),64)):(s.set(new Uint8Array(I),64),s.set(new Uint8Array(d),32)),s.set(new Uint8Array(B),96),o&&a){let y=Pc.calculateAgreement(a,o.privKey);s.set(new Uint8Array(y),128)}let f=m9.deriveSecrets(Buffer.from(s),Buffer.alloc(32),Buffer.from("WhisperText")),Q=y9.createEntry();return Q.registrationId=r,Q.currentRatchet={rootKey:f[0],ephemeralKeyPair:t?Pc.generateKeyPair():i,lastRemoteEphemeralKey:A,previousCounter:0},Q.indexInfo={created:Date.now(),used:Date.now(),remoteIdentityKey:e,baseKey:t?o.pubKey:a,baseKeyType:t?Q9.OURS:Q9.THEIRS,closed:-1},t&&this.calculateSendingRatchet(Q,A),Q}calculateSendingRatchet(t,o){let i=t.currentRatchet,e=Pc.calculateAgreement(o,i.ephemeralKeyPair.privKey),a=m9.deriveSecrets(e,i.rootKey,Buffer.from("WhisperRatchet"));t.addChain(i.ephemeralKeyPair.pubKey,{messageKeys:{},chainKey:{counter:-1,key:a[1]},chainType:L2e.SENDING}),i.rootKey=a[0]}};S9.exports=rF});var D9=$((MBA,w9)=>{"use strict";var Gc=Sm(),Ho=Gc.Reader,iF=Gc.Writer,nA=Gc.util,Mn=Gc.roots.default||(Gc.roots.default={});Mn.textsecure=(function(){var n={};return n.WhisperMessage=(function(){function t(o){if(o)for(var i=Object.keys(o),e=0;e>>3){case 1:A.ephemeralKey=i.bytes();break;case 2:A.counter=i.uint32();break;case 3:A.previousCounter=i.uint32();break;case 4:A.ciphertext=i.bytes();break;default:i.skipType(r&7);break}}return A},t.decodeDelimited=function(i){return i instanceof Ho||(i=new Ho(i)),this.decode(i,i.uint32())},t.verify=function(i){return typeof i!="object"||i===null?"object expected":i.ephemeralKey!=null&&i.hasOwnProperty("ephemeralKey")&&!(i.ephemeralKey&&typeof i.ephemeralKey.length=="number"||nA.isString(i.ephemeralKey))?"ephemeralKey: buffer expected":i.counter!=null&&i.hasOwnProperty("counter")&&!nA.isInteger(i.counter)?"counter: integer expected":i.previousCounter!=null&&i.hasOwnProperty("previousCounter")&&!nA.isInteger(i.previousCounter)?"previousCounter: integer expected":i.ciphertext!=null&&i.hasOwnProperty("ciphertext")&&!(i.ciphertext&&typeof i.ciphertext.length=="number"||nA.isString(i.ciphertext))?"ciphertext: buffer expected":null},t.fromObject=function(i){if(i instanceof Mn.textsecure.WhisperMessage)return i;var e=new Mn.textsecure.WhisperMessage;return i.ephemeralKey!=null&&(typeof i.ephemeralKey=="string"?nA.base64.decode(i.ephemeralKey,e.ephemeralKey=nA.newBuffer(nA.base64.length(i.ephemeralKey)),0):i.ephemeralKey.length&&(e.ephemeralKey=i.ephemeralKey)),i.counter!=null&&(e.counter=i.counter>>>0),i.previousCounter!=null&&(e.previousCounter=i.previousCounter>>>0),i.ciphertext!=null&&(typeof i.ciphertext=="string"?nA.base64.decode(i.ciphertext,e.ciphertext=nA.newBuffer(nA.base64.length(i.ciphertext)),0):i.ciphertext.length&&(e.ciphertext=i.ciphertext)),e},t.toObject=function(i,e){e||(e={});var a={};return e.defaults&&(e.bytes===String?a.ephemeralKey="":(a.ephemeralKey=[],e.bytes!==Array&&(a.ephemeralKey=nA.newBuffer(a.ephemeralKey))),a.counter=0,a.previousCounter=0,e.bytes===String?a.ciphertext="":(a.ciphertext=[],e.bytes!==Array&&(a.ciphertext=nA.newBuffer(a.ciphertext)))),i.ephemeralKey!=null&&i.hasOwnProperty("ephemeralKey")&&(a.ephemeralKey=e.bytes===String?nA.base64.encode(i.ephemeralKey,0,i.ephemeralKey.length):e.bytes===Array?Array.prototype.slice.call(i.ephemeralKey):i.ephemeralKey),i.counter!=null&&i.hasOwnProperty("counter")&&(a.counter=i.counter),i.previousCounter!=null&&i.hasOwnProperty("previousCounter")&&(a.previousCounter=i.previousCounter),i.ciphertext!=null&&i.hasOwnProperty("ciphertext")&&(a.ciphertext=e.bytes===String?nA.base64.encode(i.ciphertext,0,i.ciphertext.length):e.bytes===Array?Array.prototype.slice.call(i.ciphertext):i.ciphertext),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,Gc.util.toJSONOptions)},t})(),n.PreKeyWhisperMessage=(function(){function t(o){if(o)for(var i=Object.keys(o),e=0;e>>3){case 5:A.registrationId=i.uint32();break;case 1:A.preKeyId=i.uint32();break;case 6:A.signedPreKeyId=i.uint32();break;case 2:A.baseKey=i.bytes();break;case 3:A.identityKey=i.bytes();break;case 4:A.message=i.bytes();break;default:i.skipType(r&7);break}}return A},t.decodeDelimited=function(i){return i instanceof Ho||(i=new Ho(i)),this.decode(i,i.uint32())},t.verify=function(i){return typeof i!="object"||i===null?"object expected":i.registrationId!=null&&i.hasOwnProperty("registrationId")&&!nA.isInteger(i.registrationId)?"registrationId: integer expected":i.preKeyId!=null&&i.hasOwnProperty("preKeyId")&&!nA.isInteger(i.preKeyId)?"preKeyId: integer expected":i.signedPreKeyId!=null&&i.hasOwnProperty("signedPreKeyId")&&!nA.isInteger(i.signedPreKeyId)?"signedPreKeyId: integer expected":i.baseKey!=null&&i.hasOwnProperty("baseKey")&&!(i.baseKey&&typeof i.baseKey.length=="number"||nA.isString(i.baseKey))?"baseKey: buffer expected":i.identityKey!=null&&i.hasOwnProperty("identityKey")&&!(i.identityKey&&typeof i.identityKey.length=="number"||nA.isString(i.identityKey))?"identityKey: buffer expected":i.message!=null&&i.hasOwnProperty("message")&&!(i.message&&typeof i.message.length=="number"||nA.isString(i.message))?"message: buffer expected":null},t.fromObject=function(i){if(i instanceof Mn.textsecure.PreKeyWhisperMessage)return i;var e=new Mn.textsecure.PreKeyWhisperMessage;return i.registrationId!=null&&(e.registrationId=i.registrationId>>>0),i.preKeyId!=null&&(e.preKeyId=i.preKeyId>>>0),i.signedPreKeyId!=null&&(e.signedPreKeyId=i.signedPreKeyId>>>0),i.baseKey!=null&&(typeof i.baseKey=="string"?nA.base64.decode(i.baseKey,e.baseKey=nA.newBuffer(nA.base64.length(i.baseKey)),0):i.baseKey.length&&(e.baseKey=i.baseKey)),i.identityKey!=null&&(typeof i.identityKey=="string"?nA.base64.decode(i.identityKey,e.identityKey=nA.newBuffer(nA.base64.length(i.identityKey)),0):i.identityKey.length&&(e.identityKey=i.identityKey)),i.message!=null&&(typeof i.message=="string"?nA.base64.decode(i.message,e.message=nA.newBuffer(nA.base64.length(i.message)),0):i.message.length&&(e.message=i.message)),e},t.toObject=function(i,e){e||(e={});var a={};return e.defaults&&(a.preKeyId=0,e.bytes===String?a.baseKey="":(a.baseKey=[],e.bytes!==Array&&(a.baseKey=nA.newBuffer(a.baseKey))),e.bytes===String?a.identityKey="":(a.identityKey=[],e.bytes!==Array&&(a.identityKey=nA.newBuffer(a.identityKey))),e.bytes===String?a.message="":(a.message=[],e.bytes!==Array&&(a.message=nA.newBuffer(a.message))),a.registrationId=0,a.signedPreKeyId=0),i.preKeyId!=null&&i.hasOwnProperty("preKeyId")&&(a.preKeyId=i.preKeyId),i.baseKey!=null&&i.hasOwnProperty("baseKey")&&(a.baseKey=e.bytes===String?nA.base64.encode(i.baseKey,0,i.baseKey.length):e.bytes===Array?Array.prototype.slice.call(i.baseKey):i.baseKey),i.identityKey!=null&&i.hasOwnProperty("identityKey")&&(a.identityKey=e.bytes===String?nA.base64.encode(i.identityKey,0,i.identityKey.length):e.bytes===Array?Array.prototype.slice.call(i.identityKey):i.identityKey),i.message!=null&&i.hasOwnProperty("message")&&(a.message=e.bytes===String?nA.base64.encode(i.message,0,i.message.length):e.bytes===Array?Array.prototype.slice.call(i.message):i.message),i.registrationId!=null&&i.hasOwnProperty("registrationId")&&(a.registrationId=i.registrationId),i.signedPreKeyId!=null&&i.hasOwnProperty("signedPreKeyId")&&(a.signedPreKeyId=i.signedPreKeyId),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,Gc.util.toJSONOptions)},t})(),n.KeyExchangeMessage=(function(){function t(o){if(o)for(var i=Object.keys(o),e=0;e>>3){case 1:A.id=i.uint32();break;case 2:A.baseKey=i.bytes();break;case 3:A.ephemeralKey=i.bytes();break;case 4:A.identityKey=i.bytes();break;case 5:A.baseKeySignature=i.bytes();break;default:i.skipType(r&7);break}}return A},t.decodeDelimited=function(i){return i instanceof Ho||(i=new Ho(i)),this.decode(i,i.uint32())},t.verify=function(i){return typeof i!="object"||i===null?"object expected":i.id!=null&&i.hasOwnProperty("id")&&!nA.isInteger(i.id)?"id: integer expected":i.baseKey!=null&&i.hasOwnProperty("baseKey")&&!(i.baseKey&&typeof i.baseKey.length=="number"||nA.isString(i.baseKey))?"baseKey: buffer expected":i.ephemeralKey!=null&&i.hasOwnProperty("ephemeralKey")&&!(i.ephemeralKey&&typeof i.ephemeralKey.length=="number"||nA.isString(i.ephemeralKey))?"ephemeralKey: buffer expected":i.identityKey!=null&&i.hasOwnProperty("identityKey")&&!(i.identityKey&&typeof i.identityKey.length=="number"||nA.isString(i.identityKey))?"identityKey: buffer expected":i.baseKeySignature!=null&&i.hasOwnProperty("baseKeySignature")&&!(i.baseKeySignature&&typeof i.baseKeySignature.length=="number"||nA.isString(i.baseKeySignature))?"baseKeySignature: buffer expected":null},t.fromObject=function(i){if(i instanceof Mn.textsecure.KeyExchangeMessage)return i;var e=new Mn.textsecure.KeyExchangeMessage;return i.id!=null&&(e.id=i.id>>>0),i.baseKey!=null&&(typeof i.baseKey=="string"?nA.base64.decode(i.baseKey,e.baseKey=nA.newBuffer(nA.base64.length(i.baseKey)),0):i.baseKey.length&&(e.baseKey=i.baseKey)),i.ephemeralKey!=null&&(typeof i.ephemeralKey=="string"?nA.base64.decode(i.ephemeralKey,e.ephemeralKey=nA.newBuffer(nA.base64.length(i.ephemeralKey)),0):i.ephemeralKey.length&&(e.ephemeralKey=i.ephemeralKey)),i.identityKey!=null&&(typeof i.identityKey=="string"?nA.base64.decode(i.identityKey,e.identityKey=nA.newBuffer(nA.base64.length(i.identityKey)),0):i.identityKey.length&&(e.identityKey=i.identityKey)),i.baseKeySignature!=null&&(typeof i.baseKeySignature=="string"?nA.base64.decode(i.baseKeySignature,e.baseKeySignature=nA.newBuffer(nA.base64.length(i.baseKeySignature)),0):i.baseKeySignature.length&&(e.baseKeySignature=i.baseKeySignature)),e},t.toObject=function(i,e){e||(e={});var a={};return e.defaults&&(a.id=0,e.bytes===String?a.baseKey="":(a.baseKey=[],e.bytes!==Array&&(a.baseKey=nA.newBuffer(a.baseKey))),e.bytes===String?a.ephemeralKey="":(a.ephemeralKey=[],e.bytes!==Array&&(a.ephemeralKey=nA.newBuffer(a.ephemeralKey))),e.bytes===String?a.identityKey="":(a.identityKey=[],e.bytes!==Array&&(a.identityKey=nA.newBuffer(a.identityKey))),e.bytes===String?a.baseKeySignature="":(a.baseKeySignature=[],e.bytes!==Array&&(a.baseKeySignature=nA.newBuffer(a.baseKeySignature)))),i.id!=null&&i.hasOwnProperty("id")&&(a.id=i.id),i.baseKey!=null&&i.hasOwnProperty("baseKey")&&(a.baseKey=e.bytes===String?nA.base64.encode(i.baseKey,0,i.baseKey.length):e.bytes===Array?Array.prototype.slice.call(i.baseKey):i.baseKey),i.ephemeralKey!=null&&i.hasOwnProperty("ephemeralKey")&&(a.ephemeralKey=e.bytes===String?nA.base64.encode(i.ephemeralKey,0,i.ephemeralKey.length):e.bytes===Array?Array.prototype.slice.call(i.ephemeralKey):i.ephemeralKey),i.identityKey!=null&&i.hasOwnProperty("identityKey")&&(a.identityKey=e.bytes===String?nA.base64.encode(i.identityKey,0,i.identityKey.length):e.bytes===Array?Array.prototype.slice.call(i.identityKey):i.identityKey),i.baseKeySignature!=null&&i.hasOwnProperty("baseKeySignature")&&(a.baseKeySignature=e.bytes===String?nA.base64.encode(i.baseKeySignature,0,i.baseKeySignature.length):e.bytes===Array?Array.prototype.slice.call(i.baseKeySignature):i.baseKeySignature),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,Gc.util.toJSONOptions)},t})(),n})();w9.exports=Mn});var oF=$((_BA,O9)=>{"use strict";var{textsecure:{WhisperMessage:H2e,PreKeyWhisperMessage:K2e}}=D9();O9.exports={WhisperMessage:H2e,PreKeyWhisperMessage:K2e}});var T9=$((TBA,_9)=>{var Hw=eF(),x2e=XG(),Y2e=aF(),b9=Gw(),Og=yl(),M9=vc(),fs=Fw(),Ah=oF(),j2e=tF(),Fc=3;function Kw(n){if(!(n instanceof Buffer))throw TypeError(`Expected Buffer instead of: ${n.constructor.name}`);return n}var nF=class{constructor(t,o){if(!(o instanceof x2e))throw new TypeError("protocolAddress must be a ProtocolAddress");this.addr=o,this.storage=t}_encodeTupleByte(t,o){if(t>15||o>15)throw TypeError("Numbers must be 4 bits or less");return t<<4|o}_decodeTupleByte(t){return[t>>4,t&15]}toString(){return``}async getRecord(){let t=await this.storage.loadSession(this.addr.toString());if(t&&!(t instanceof b9))throw new TypeError("SessionRecord type expected from loadSession");return t}async storeRecord(t){t.removeOldSessions(),await this.storage.storeSession(this.addr.toString(),t)}async queueJob(t){return await j2e(this.addr.toString(),t)}async encrypt(t){Kw(t);let o=await this.storage.getOurIdentity();return await this.queueJob(async()=>{let i=await this.getRecord();if(!i)throw new fs.SessionError("No sessions");let e=i.getOpenSession();if(!e)throw new fs.SessionError("No open session");let a=e.indexInfo.remoteIdentityKey;if(!await this.storage.isTrustedIdentity(this.addr.id,a))throw new fs.UntrustedIdentityKeyError(this.addr.id,a);let A=e.getChain(e.currentRatchet.ephemeralKeyPair.pubKey);if(A.chainType===Hw.RECEIVING)throw new Error("Tried to encrypt on a receiving chain");this.fillMessageKeys(A,A.chainKey.counter+1);let r=Og.deriveSecrets(A.messageKeys[A.chainKey.counter],Buffer.alloc(32),Buffer.from("WhisperMessageKeys"));delete A.messageKeys[A.chainKey.counter];let s=Ah.WhisperMessage.create();s.ephemeralKey=e.currentRatchet.ephemeralKeyPair.pubKey,s.counter=A.chainKey.counter,s.previousCounter=e.currentRatchet.previousCounter,s.ciphertext=Og.encrypt(r[0],t,r[2].slice(0,16));let g=Ah.WhisperMessage.encode(s).finish(),c=Buffer.alloc(g.byteLength+66+1);c.set(o.pubKey),c.set(e.indexInfo.remoteIdentityKey,33),c[66]=this._encodeTupleByte(Fc,Fc),c.set(g,67);let I=Og.calculateMAC(r[1],c),d=Buffer.alloc(g.byteLength+9);d[0]=this._encodeTupleByte(Fc,Fc),d.set(g,1),d.set(I.slice(0,8),g.byteLength+1),await this.storeRecord(i);let B,f;if(e.pendingPreKey){B=3;let Q=Ah.PreKeyWhisperMessage.create({identityKey:o.pubKey,registrationId:await this.storage.getOurRegistrationId(),baseKey:e.pendingPreKey.baseKey,signedPreKeyId:e.pendingPreKey.signedKeyId,message:d});e.pendingPreKey.preKeyId&&(Q.preKeyId=e.pendingPreKey.preKeyId),f=Buffer.concat([Buffer.from([this._encodeTupleByte(Fc,Fc)]),Buffer.from(Ah.PreKeyWhisperMessage.encode(Q).finish())])}else B=1,f=d;return{type:B,body:f,registrationId:e.registrationId}})}async decryptWithSessions(t,o){if(!o.length)throw new fs.SessionError("No sessions available");let i=[];for(let e of o){let a;try{return a=await this.doDecryptWhisperMessage(t,e),e.indexInfo.used=Date.now(),{session:e,plaintext:a}}catch(A){i.push(A)}}console.error("Failed to decrypt message with any known session...");for(let e of i)console.error("Session error:"+e,e.stack);throw new fs.SessionError("No matching sessions found for message")}async decryptWhisperMessage(t){return Kw(t),await this.queueJob(async()=>{let o=await this.getRecord();if(!o)throw new fs.SessionError("No session record");let i=await this.decryptWithSessions(t,o.getSessions()),e=i.session.indexInfo.remoteIdentityKey;if(!await this.storage.isTrustedIdentity(this.addr.id,e))throw new fs.UntrustedIdentityKeyError(this.addr.id,e);return o.isClosed(i.session)&&console.warn("Decrypted message with closed session."),await this.storeRecord(o),i.plaintext})}async decryptPreKeyWhisperMessage(t){Kw(t);let o=this._decodeTupleByte(t[0]);if(o[1]>3||o[0]<3)throw new Error("Incompatible version number on PreKeyWhisperMessage");return await this.queueJob(async()=>{let i=await this.getRecord(),e=Ah.PreKeyWhisperMessage.decode(t.slice(1));if(!i){if(e.registrationId==null)throw new Error("No registrationId");i=new b9}let A=await new Y2e(this.storage,this.addr).initIncoming(i,e),r=i.getSession(e.baseKey),s=await this.doDecryptWhisperMessage(e.message,r);return await this.storeRecord(i),A&&await this.storage.removePreKey(A),s})}async doDecryptWhisperMessage(t,o){if(Kw(t),!o)throw new TypeError("session required");let i=this._decodeTupleByte(t[0]);if(i[1]>3||i[0]<3)throw new Error("Incompatible version number on WhisperMessage");let e=t.slice(1,-8),a=Ah.WhisperMessage.decode(e);this.maybeStepRatchet(o,a.ephemeralKey,a.previousCounter);let A=o.getChain(a.ephemeralKey);if(A.chainType===Hw.SENDING)throw new Error("Tried to decrypt on a sending chain");if(this.fillMessageKeys(A,a.counter),!A.messageKeys.hasOwnProperty(a.counter))throw new fs.MessageCounterError("Key used already or never filled");let r=A.messageKeys[a.counter];delete A.messageKeys[a.counter];let s=Og.deriveSecrets(r,Buffer.alloc(32),Buffer.from("WhisperMessageKeys")),g=await this.storage.getOurIdentity(),c=Buffer.alloc(e.byteLength+66+1);c.set(o.indexInfo.remoteIdentityKey),c.set(g.pubKey,33),c[66]=this._encodeTupleByte(Fc,Fc),c.set(e,67),Og.verifyMAC(c,s[1],t.slice(-8),8);let I=Og.decrypt(s[0],a.ciphertext,s[2].slice(0,16));return delete o.pendingPreKey,I}fillMessageKeys(t,o){if(t.chainKey.counter>=o)return;if(o-t.chainKey.counter>2e3)throw new fs.SessionError("Over 2000 messages into the future!");if(t.chainKey.key===void 0)throw new fs.SessionError("Chain closed");let i=t.chainKey.key;return t.messageKeys[t.chainKey.counter+1]=Og.calculateMAC(i,Buffer.from([1])),t.chainKey.key=Og.calculateMAC(i,Buffer.from([2])),t.chainKey.counter+=1,this.fillMessageKeys(t,o)}maybeStepRatchet(t,o,i){if(t.getChain(o))return;let e=t.currentRatchet,a=t.getChain(e.lastRemoteEphemeralKey);a&&(this.fillMessageKeys(a,i),delete a.chainKey.key),this.calculateRatchet(t,o,!1);let A=t.getChain(e.ephemeralKeyPair.pubKey);A&&(e.previousCounter=A.chainKey.counter,t.deleteChain(e.ephemeralKeyPair.pubKey)),e.ephemeralKeyPair=M9.generateKeyPair(),this.calculateRatchet(t,o,!0),e.lastRemoteEphemeralKey=o}calculateRatchet(t,o,i){let e=t.currentRatchet,a=M9.calculateAgreement(o,e.ephemeralKeyPair.privKey),A=Og.deriveSecrets(a,e.rootKey,Buffer.from("WhisperRatchet"),2),r=i?e.ephemeralKeyPair.pubKey:o;t.addChain(r,{messageKeys:{},chainKey:{counter:-1,key:A[1]},chainType:i?Hw.SENDING:Hw.RECEIVING}),e.rootKey=A[0]}async hasOpenSession(){return await this.queueJob(async()=>{let t=await this.getRecord();return t?t.haveOpenSession():!1})}async closeOpenSession(){return await this.queueJob(async()=>{let t=await this.getRecord();if(t){let o=t.getOpenSession();o&&(t.closeSession(o),await this.storeRecord(t))}})}};_9.exports=nF});var N9=$(bg=>{"use strict";bg.crypto=yl();bg.curve=vc();bg.keyhelper=p9();bg.ProtocolAddress=XG();bg.SessionBuilder=aF();bg.SessionCipher=T9();bg.SessionRecord=Gw();Object.assign(bg,Fw())});var gF=$((PBA,G9)=>{"use strict";G9.exports=function(...n){try{return JSON.stringify.apply(null,n)}catch(t){return"[Cannot display object: "+t.message+"]"}}});var cF=$((F9,L9)=>{"use strict";var X2e=gF();L9.exports=class extends Error{constructor(n){let t=n.filter(o=>o!=="").map(o=>typeof o=="string"?o:o instanceof Error?o.message:X2e(o));super(t.join(" ")||"Unknown error"),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,F9.assert)}}});var ml=$((FBA,U9)=>{"use strict";var $2e=cF();U9.exports=function(n,...t){if(!n)throw t.length===1&&t[0]instanceof Error?t[0]:new $2e(t)}});var pB=$((LBA,K9)=>{"use strict";var IF=ml(),H9={};K9.exports=function(n,t,o){if(t===!1||t===null||t===void 0)return n;o=o||{},typeof o=="string"&&(o={separator:o});let i=Array.isArray(t);IF(!i||!o.separator,"Separator option no valid for array-based chain");let e=i?t:t.split(o.separator||"."),a=n;for(let A=0;A{"use strict";var x9={};ai=Y9.exports={array:Array.prototype,buffer:Buffer&&Buffer.prototype,date:Date.prototype,error:Error.prototype,generic:Object.prototype,map:Map.prototype,promise:Promise.prototype,regex:RegExp.prototype,set:Set.prototype,weakMap:WeakMap.prototype,weakSet:WeakSet.prototype};x9.typeMap=new Map([["[object Error]",ai.error],["[object Map]",ai.map],["[object Promise]",ai.promise],["[object Set]",ai.set],["[object WeakMap]",ai.weakMap],["[object WeakSet]",ai.weakSet]]);ai.getInternalProto=function(n){if(Array.isArray(n))return ai.array;if(Buffer&&n instanceof Buffer)return ai.buffer;if(n instanceof Date)return ai.date;if(n instanceof RegExp)return ai.regex;if(n instanceof Error)return ai.error;let t=Object.prototype.toString.call(n);return x9.typeMap.get(t)||ai.generic}});var Yw=$(j9=>{"use strict";j9.keys=function(n,t={}){return t.symbols!==!1?Reflect.ownKeys(n):Object.getOwnPropertyNames(n)}});var jw=$((HBA,J9)=>{"use strict";var eUe=pB(),Ko=lF(),AUe=Yw(),_g={needsProtoHack:new Set([Ko.set,Ko.map,Ko.weakSet,Ko.weakMap])};J9.exports=_g.clone=function(n,t={},o=null){if(typeof n!="object"||n===null)return n;let i=_g.clone,e=o;if(t.shallow){if(t.shallow!==!0)return _g.cloneWithShallow(n,t);i=s=>s}else{e=e||new Map;let s=e.get(n);if(s)return s}let a=Ko.getInternalProto(n);if(a===Ko.buffer)return Buffer&&Buffer.from(n);if(a===Ko.date)return new Date(n.getTime());if(a===Ko.regex)return new RegExp(n);let A=_g.base(n,a,t);if(A===n)return n;if(e&&e.set(n,A),a===Ko.set)for(let s of n)A.add(i(s,t,e));else if(a===Ko.map)for(let[s,g]of n)A.set(s,i(g,t,e));let r=AUe.keys(n,t);for(let s of r){if(a===Ko.array&&s==="length"){A.length=n.length;continue}let g=Object.getOwnPropertyDescriptor(n,s);g?g.get||g.set?Object.defineProperty(A,s,g):g.enumerable?A[s]=i(n[s],t,e):Object.defineProperty(A,s,{enumerable:!1,writable:!0,configurable:!0,value:i(n[s],t,e)}):Object.defineProperty(A,s,{enumerable:!0,writable:!0,configurable:!0,value:i(n[s],t,e)})}return A};_g.cloneWithShallow=function(n,t){let o=t.shallow;t=Object.assign({},t),t.shallow=!1;let i=new Map;for(let e of o){let a=eUe(n,e);(typeof a=="object"||typeof a=="function")&&i.set(a,a)}return _g.clone(n,t,i)};_g.base=function(n,t,o){if(t===Ko.array)return[];if(o.prototype===!1)return _g.needsProtoHack.has(t)?new t.constructor:{};let i=Object.getPrototypeOf(n);if(i&&i.isImmutable)return n;if(_g.needsProtoHack.has(t)){let e=new i.constructor;return i!==t&&Object.setPrototypeOf(e,i),e}return Object.create(i)}});var dF=$((KBA,V9)=>{"use strict";var pF=ml(),q9=jw(),tUe=Yw(),z9={};V9.exports=z9.merge=function(n,t,o){if(pF(n&&typeof n=="object","Invalid target value: must be an object"),pF(t==null||typeof t=="object","Invalid source value: must be null, undefined, or an object"),!t)return n;if(o=Object.assign({nullOverride:!0,mergeArrays:!0},o),Array.isArray(t)){pF(Array.isArray(n),"Cannot merge array onto an object"),o.mergeArrays||(n.length=0);for(let e=0;e{"use strict";var Jw=ml(),Z9=jw(),X9=dF(),W9=pB(),qw={};$9.exports=function(n,t,o={}){if(Jw(n&&typeof n=="object","Invalid defaults value: must be an object"),Jw(!t||t===!0||typeof t=="object","Invalid source value: must be true, falsy or an object"),Jw(typeof o=="object","Invalid options: must be an object"),!t)return null;if(o.shallow)return qw.applyToDefaultsWithShallow(n,t,o);let i=Z9(n);if(t===!0)return i;let e=o.nullOverride!==void 0?o.nullOverride:!1;return X9(i,t,{nullOverride:e,mergeArrays:!1})};qw.applyToDefaultsWithShallow=function(n,t,o){let i=o.shallow;Jw(Array.isArray(i),"Invalid keys");let e=new Map,a=t===!0?null:new Set;for(let r of i){r=Array.isArray(r)?r:r.split(".");let s=W9(n,r);s&&typeof s=="object"?e.set(s,a?W9(t,r):s):a&&a.add(r)}let A=Z9(n,{},e);if(!a)return A;for(let r of a)qw.reachCopy(A,t,r);return X9(A,t,{mergeArrays:!1,nullOverride:!1})};qw.reachCopy=function(n,t,o){for(let a of o){if(!(a in t))return;t=t[a]}let i=t,e=n;for(let a=0;a{"use strict";var hF={};AX.exports=hF.Bench=class{constructor(){this.ts=0,this.reset()}reset(){this.ts=hF.Bench.now()}elapsed(){return hF.Bench.now()-this.ts}static now(){let n=process.hrtime();return n[0]*1e3+n[1]/1e6}}});var EF=$((JBA,rX)=>{"use strict";rX.exports=function(){}});var iX=$((qBA,aX)=>{"use strict";var rUe=EF();aX.exports=function(){return new Promise(rUe)}});var CF=$((zBA,oX)=>{"use strict";var Qs=lF(),Za={mismatched:null};oX.exports=function(n,t,o){return o=Object.assign({prototype:!0},o),!!Za.isDeepEqual(n,t,o,[])};Za.isDeepEqual=function(n,t,o,i){if(n===t)return n!==0||1/n===1/t;let e=typeof n;if(e!==typeof t||n===null||t===null)return!1;if(e==="function"){if(!o.deepFunction||n.toString()!==t.toString())return!1}else if(e!=="object")return n!==n&&t!==t;let a=Za.getSharedType(n,t,!!o.prototype);switch(a){case Qs.buffer:return Buffer&&Buffer.prototype.equals.call(n,t);case Qs.promise:return n===t;case Qs.regex:return n.toString()===t.toString();case Za.mismatched:return!1}for(let A=i.length-1;A>=0;--A)if(i[A].isSame(n,t))return!0;i.push(new Za.SeenEntry(n,t));try{return!!Za.isDeepEqualObj(a,n,t,o,i)}finally{i.pop()}};Za.getSharedType=function(n,t,o){if(o)return Object.getPrototypeOf(n)!==Object.getPrototypeOf(t)?Za.mismatched:Qs.getInternalProto(n);let i=Qs.getInternalProto(n);return i!==Qs.getInternalProto(t)?Za.mismatched:i};Za.valueOf=function(n){let t=n.valueOf;if(t===void 0)return n;try{return t.call(n)}catch(o){return o}};Za.hasOwnEnumerableProperty=function(n,t){return Object.prototype.propertyIsEnumerable.call(n,t)};Za.isSetSimpleEqual=function(n,t){for(let o of n)if(!t.has(o))return!1;return!0};Za.isDeepEqualObj=function(n,t,o,i,e){let{isDeepEqual:a,valueOf:A,hasOwnEnumerableProperty:r}=Za,{keys:s,getOwnPropertySymbols:g}=Object;if(n===Qs.array)if(i.part){for(let f of t)for(let Q of o)if(a(f,Q,i,e))return!0}else{if(t.length!==o.length)return!1;for(let f=0;f{"use strict";nX.exports=function(n){return n.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g,"\\$&")}});var gX=$((ZBA,sX)=>{"use strict";var zw=ml(),aUe=CF(),iUe=uF(),oUe=Yw(),xo={};sX.exports=function(n,t,o={}){return typeof t!="object"&&(t=[t]),zw(!Array.isArray(t)||t.length,"Values array cannot be empty"),typeof n=="string"?xo.string(n,t,o):Array.isArray(n)?xo.array(n,t,o):(zw(typeof n=="object","Reference must be string or an object"),xo.object(n,t,o))};xo.array=function(n,t,o){if(Array.isArray(t)||(t=[t]),!n.length||o.only&&o.once&&n.length!==t.length)return!1;let i,e=new Map;for(let A of t)if(!o.deep||!A||typeof A!="object"){let r=e.get(A);r?++r.allowed:e.set(A,{allowed:1,hits:0})}else{i=i||xo.compare(o);let r=!1;for(let[s,g]of e.entries())if(i(s,A)){++g.allowed,r=!0;break}r||e.set(A,{allowed:1,hits:0})}let a=0;for(let A of n){let r;if(!o.deep||!A||typeof A!="object")r=e.get(A);else for(let[s,g]of e.entries())if(i(s,A)){r=g;break}if(r&&(++r.hits,++a,o.once&&r.hits>r.allowed))return!1}if(o.only&&a!==n.length)return!1;for(let A of e.values())if(A.hits!==A.allowed&&A.hitst.propertyIsEnumerable(s)),a=[...Object.keys(t),...e],A=xo.compare(o),r=new Set(a);for(let s of i){if(!r.has(s)){if(o.only)return!1;continue}if(!A(t[s],n[s]))return!1;r.delete(s)}return r.size?o.part?r.sizes!=="");let i=new Map,e=[];for(let s of t)if(zw(typeof s=="string","Cannot compare string reference to non-string value"),s){let g=i.get(s);g?++g.allowed:(i.set(s,{allowed:1,hits:0}),e.push(iUe(s)))}else if(o.once||o.only)return!1;if(!e.length)return!0;let a=new RegExp(`(${e.join("|")})`,"g"),A=n.replace(a,(s,g)=>(++i.get(g).hits,""));if(o.only&&A)return!1;let r=!1;for(let s of i.values())if(s.hits&&(r=!0),s.hits!==s.allowed&&(s.hitsaUe(e,a,i)};xo.shallow=function(n,t){return n===t}});var IX=$((XBA,cX)=>{"use strict";var nUe=ml();cX.exports=function(n){return nUe(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(n),"Bad attribute value ("+n+")"),n.replace(/\\/g,"\\\\").replace(/\"/g,'\\"')}});var pX=$(($BA,lX)=>{"use strict";var Uc={};lX.exports=function(n){if(!n)return"";let t="";for(let o=0;o=256?"&#"+n+";":`&#x${n.toString(16).padStart(2,"0")};`};Uc.isSafe=function(n){return typeof Uc.safeCharCodes[n]<"u"};Uc.namedHtml={38:"&",60:"<",62:">",34:""",160:" ",162:"¢",163:"£",164:"¤",169:"©",174:"®"};Uc.safeCharCodes=(function(){let n={};for(let t=32;t<123;++t)(t>=97||t>=65&&t<=90||t>=48&&t<=57||t===32||t===46||t===44||t===45||t===58||t===95)&&(n[t]=null);return n})()});var hX=$((efA,dX)=>{"use strict";dX.exports=function(n){if(!n)return"";let t=60,o=62,i=38,e=8232,a;return n.replace(/[<>&\u2028\u2029]/g,A=>(a=A.charCodeAt(0),a===t?"\\u003c":a===o?"\\u003e":a===i?"\\u0026":a===e?"\\u2028":"\\u2029"))}});var uX=$((AfA,CX)=>{"use strict";var EX={};CX.exports=EX.flatten=function(n,t){let o=t||[];for(let i=0;i{"use strict";var BX={};fX.exports=function(n,t,o={}){if(!n||!t)return o.first?null:[];let i=[],e=Array.isArray(n)?new Set(n):n,a=new Set;for(let A of t)if(BX.has(e,A)&&!a.has(A)){if(o.first)return A;i.push(A),a.add(A)}return o.first?null:i};BX.has=function(n,t){return typeof n.has=="function"?n.has(t):n[t]!==void 0}});var mX=$((rfA,yX)=>{"use strict";yX.exports=function(n){return!!n&&typeof n.then=="function"}});var wX=$((afA,SX)=>{"use strict";SX.exports=function(n){if(n._hoekOnce)return n;let t=!1,o=function(...i){t||(t=!0,n(...i))};return o._hoekOnce=!0,o}});var OX=$((ifA,DX)=>{"use strict";var sUe=pB();DX.exports=function(n,t,o){return t.replace(/{([^}]+)}/g,(i,e)=>{let a=sUe(n,e,o);return a??""})}});var MX=$((ofA,bX)=>{"use strict";bX.exports=function(n){return new Promise(t=>setTimeout(t,n))}});var TX=$((nfA,_X)=>{"use strict";_X.exports={applyToDefaults:eX(),assert:ml(),Bench:tX(),block:iX(),clone:jw(),contain:gX(),deepEqual:CF(),Error:cF(),escapeHeaderAttribute:IX(),escapeHtml:pX(),escapeJson:hX(),escapeRegex:uF(),flatten:uX(),ignore:EF(),intersect:QX(),isPromise:mX(),merge:dF(),once:wX(),reach:pB(),reachTemplate:OX(),stringify:gF(),wait:MX()}});var Lr=$(ke=>{"use strict";var Sl=TX(),Fi={codes:new Map([[100,"Continue"],[101,"Switching Protocols"],[102,"Processing"],[200,"OK"],[201,"Created"],[202,"Accepted"],[203,"Non-Authoritative Information"],[204,"No Content"],[205,"Reset Content"],[206,"Partial Content"],[207,"Multi-Status"],[300,"Multiple Choices"],[301,"Moved Permanently"],[302,"Moved Temporarily"],[303,"See Other"],[304,"Not Modified"],[305,"Use Proxy"],[307,"Temporary Redirect"],[400,"Bad Request"],[401,"Unauthorized"],[402,"Payment Required"],[403,"Forbidden"],[404,"Not Found"],[405,"Method Not Allowed"],[406,"Not Acceptable"],[407,"Proxy Authentication Required"],[408,"Request Time-out"],[409,"Conflict"],[410,"Gone"],[411,"Length Required"],[412,"Precondition Failed"],[413,"Request Entity Too Large"],[414,"Request-URI Too Large"],[415,"Unsupported Media Type"],[416,"Requested Range Not Satisfiable"],[417,"Expectation Failed"],[418,"I'm a teapot"],[422,"Unprocessable Entity"],[423,"Locked"],[424,"Failed Dependency"],[425,"Too Early"],[426,"Upgrade Required"],[428,"Precondition Required"],[429,"Too Many Requests"],[431,"Request Header Fields Too Large"],[451,"Unavailable For Legal Reasons"],[500,"Internal Server Error"],[501,"Not Implemented"],[502,"Bad Gateway"],[503,"Service Unavailable"],[504,"Gateway Time-out"],[505,"HTTP Version Not Supported"],[506,"Variant Also Negotiates"],[507,"Insufficient Storage"],[509,"Bandwidth Limit Exceeded"],[510,"Not Extended"],[511,"Network Authentication Required"]])};ke.Boom=class extends Error{constructor(n,t={}){if(n instanceof Error)return ke.boomify(Sl.clone(n),t);let{statusCode:o=500,data:i=null,ctor:e=ke.Boom}=t,a=new Error(n||void 0);Error.captureStackTrace(a,e),a.data=i;let A=Fi.initialize(a,o);return Object.defineProperty(A,"typeof",{value:e}),t.decorate&&Object.assign(A,t.decorate),A}static[Symbol.hasInstance](n){return this===ke.Boom?ke.isBoom(n):this.prototype.isPrototypeOf(n)}};ke.isBoom=function(n,t){return n instanceof Error&&!!n.isBoom&&(!t||n.output.statusCode===t)};ke.boomify=function(n,t){return Sl.assert(n instanceof Error,"Cannot wrap non-Error object"),t=t||{},t.data!==void 0&&(n.data=t.data),t.decorate&&Object.assign(n,t.decorate),n.isBoom?t.override===!1||!t.statusCode&&!t.message?n:Fi.initialize(n,t.statusCode||n.output.statusCode,t.message):Fi.initialize(n,t.statusCode||500,t.message)};ke.badRequest=function(n,t){return new ke.Boom(n,{statusCode:400,data:t,ctor:ke.badRequest})};ke.unauthorized=function(n,t,o){let i=new ke.Boom(n,{statusCode:401,ctor:ke.unauthorized});if(!t)return i;if(typeof t!="string")return i.output.headers["WWW-Authenticate"]=t.join(", "),i;let e=`${t}`;return(o||n)&&(i.output.payload.attributes={}),o&&(typeof o=="string"?(e+=" "+Sl.escapeHeaderAttribute(o),i.output.payload.attributes=o):e+=" "+Object.keys(o).map(a=>{let A=o[a];return A==null&&(A=""),i.output.payload.attributes[a]=A,`${a}="${Sl.escapeHeaderAttribute(A.toString())}"`}).join(", ")),n?(o&&(e+=","),e+=` error="${Sl.escapeHeaderAttribute(n)}"`,i.output.payload.attributes.error=n):i.isMissing=!0,i.output.headers["WWW-Authenticate"]=e,i};ke.paymentRequired=function(n,t){return new ke.Boom(n,{statusCode:402,data:t,ctor:ke.paymentRequired})};ke.forbidden=function(n,t){return new ke.Boom(n,{statusCode:403,data:t,ctor:ke.forbidden})};ke.notFound=function(n,t){return new ke.Boom(n,{statusCode:404,data:t,ctor:ke.notFound})};ke.methodNotAllowed=function(n,t,o){let i=new ke.Boom(n,{statusCode:405,data:t,ctor:ke.methodNotAllowed});return typeof o=="string"&&(o=[o]),Array.isArray(o)&&(i.output.headers.Allow=o.join(", ")),i};ke.notAcceptable=function(n,t){return new ke.Boom(n,{statusCode:406,data:t,ctor:ke.notAcceptable})};ke.proxyAuthRequired=function(n,t){return new ke.Boom(n,{statusCode:407,data:t,ctor:ke.proxyAuthRequired})};ke.clientTimeout=function(n,t){return new ke.Boom(n,{statusCode:408,data:t,ctor:ke.clientTimeout})};ke.conflict=function(n,t){return new ke.Boom(n,{statusCode:409,data:t,ctor:ke.conflict})};ke.resourceGone=function(n,t){return new ke.Boom(n,{statusCode:410,data:t,ctor:ke.resourceGone})};ke.lengthRequired=function(n,t){return new ke.Boom(n,{statusCode:411,data:t,ctor:ke.lengthRequired})};ke.preconditionFailed=function(n,t){return new ke.Boom(n,{statusCode:412,data:t,ctor:ke.preconditionFailed})};ke.entityTooLarge=function(n,t){return new ke.Boom(n,{statusCode:413,data:t,ctor:ke.entityTooLarge})};ke.uriTooLong=function(n,t){return new ke.Boom(n,{statusCode:414,data:t,ctor:ke.uriTooLong})};ke.unsupportedMediaType=function(n,t){return new ke.Boom(n,{statusCode:415,data:t,ctor:ke.unsupportedMediaType})};ke.rangeNotSatisfiable=function(n,t){return new ke.Boom(n,{statusCode:416,data:t,ctor:ke.rangeNotSatisfiable})};ke.expectationFailed=function(n,t){return new ke.Boom(n,{statusCode:417,data:t,ctor:ke.expectationFailed})};ke.teapot=function(n,t){return new ke.Boom(n,{statusCode:418,data:t,ctor:ke.teapot})};ke.badData=function(n,t){return new ke.Boom(n,{statusCode:422,data:t,ctor:ke.badData})};ke.locked=function(n,t){return new ke.Boom(n,{statusCode:423,data:t,ctor:ke.locked})};ke.failedDependency=function(n,t){return new ke.Boom(n,{statusCode:424,data:t,ctor:ke.failedDependency})};ke.tooEarly=function(n,t){return new ke.Boom(n,{statusCode:425,data:t,ctor:ke.tooEarly})};ke.preconditionRequired=function(n,t){return new ke.Boom(n,{statusCode:428,data:t,ctor:ke.preconditionRequired})};ke.tooManyRequests=function(n,t){return new ke.Boom(n,{statusCode:429,data:t,ctor:ke.tooManyRequests})};ke.illegal=function(n,t){return new ke.Boom(n,{statusCode:451,data:t,ctor:ke.illegal})};ke.internal=function(n,t,o=500){return Fi.serverError(n,t,o,ke.internal)};ke.notImplemented=function(n,t){return Fi.serverError(n,t,501,ke.notImplemented)};ke.badGateway=function(n,t){return Fi.serverError(n,t,502,ke.badGateway)};ke.serverUnavailable=function(n,t){return Fi.serverError(n,t,503,ke.serverUnavailable)};ke.gatewayTimeout=function(n,t){return Fi.serverError(n,t,504,ke.gatewayTimeout)};ke.badImplementation=function(n,t){let o=Fi.serverError(n,t,500,ke.badImplementation);return o.isDeveloperError=!0,o};Fi.initialize=function(n,t,o){let i=parseInt(t,10);if(Sl.assert(!isNaN(i)&&i>=400,"First argument must be a number (400+):",t),n.isBoom=!0,n.isServer=i>=500,n.hasOwnProperty("data")||(n.data=null),n.output={statusCode:i,payload:{},headers:{}},Object.defineProperty(n,"reformat",{value:Fi.reformat}),!o&&!n.message&&(n.reformat(),o=n.output.payload.error),o){let e=Object.getOwnPropertyDescriptor(n,"message")||Object.getOwnPropertyDescriptor(Object.getPrototypeOf(n),"message");Sl.assert(!e||e.configurable&&!e.get,"The error is not compatible with boom"),n.message=o+(n.message?": "+n.message:""),n.output.payload.message=n.message}return n.reformat(),n};Fi.reformat=function(n=!1){this.output.payload.statusCode=this.output.statusCode,this.output.payload.error=Fi.codes.get(this.output.statusCode)||"Unknown",this.output.statusCode===500&&n!==!0?this.output.payload.message="An internal server error occurred":this.message&&(this.output.payload.message=this.message)};Fi.serverError=function(n,t,o,i){return t instanceof Error&&!t.isBoom?ke.boomify(t,{statusCode:o,message:n}):new ke.Boom(n,{statusCode:o,data:t,ctor:i})}});var k7,KUe,xUe,YUe,jUe,JUe,qUe,zUe,VUe,WUe,ZUe,XUe,$Ue,eHe,AHe,O,ms=ue(()=>{k7=n=>typeof n<"u"&&n!==null,KUe=n=>typeof n=="object",xUe=n=>Object.prototype.toString.call(n)==="[object Object]",YUe=n=>typeof n=="function",jUe=n=>typeof n=="boolean",JUe=n=>n instanceof Buffer,qUe=n=>{if(k7(n))switch(n.constructor){case Uint8Array:case Uint8ClampedArray:case Int8Array:case Uint16Array:case Int16Array:case Uint32Array:case Int32Array:case Float32Array:case Float64Array:return!0}return!1},zUe=n=>n instanceof ArrayBuffer,VUe=n=>typeof n=="string"&&n.length>0,WUe=n=>typeof n=="number"&&Number.isFinite(n),ZUe=n=>Number.isInteger(n),XUe=(n,t,o)=>n>=t&&n<=o,$Ue=(n,t)=>t.includes(n),eHe=(n,t,o)=>new Error(`Expected ${t} for ${n} but received ${o} of type ${typeof o}`),AHe=(n,t)=>(t.message=n.message,t),O={defined:k7,object:KUe,plainObject:xUe,fn:YUe,bool:jUe,buffer:JUe,typedArray:qUe,arrayBuffer:zUe,string:VUe,number:WUe,integer:ZUe,inRange:XUe,inArray:$Ue,invalidParameterError:eHe,nativeError:AHe}});var G7=$((CQA,P7)=>{"use strict";var v7=()=>process.platform==="linux",cD=null,tHe=()=>{if(!cD)if(v7()&&process.report){let n=process.report.excludeNetwork;process.report.excludeNetwork=!0,cD=process.report.getReport(),process.report.excludeNetwork=n}else cD={};return cD};P7.exports={isLinux:v7,getReport:tHe}});var L7=$((uQA,F7)=>{"use strict";var lh=$e("fs"),rHe="/usr/bin/ldd",aHe="/proc/self/exe",ID=2048,iHe=n=>{let t=lh.openSync(n,"r"),o=Buffer.alloc(ID),i=lh.readSync(t,o,0,ID,0);return lh.close(t,()=>{}),o.subarray(0,i)},oHe=n=>new Promise((t,o)=>{lh.open(n,"r",(i,e)=>{if(i)o(i);else{let a=Buffer.alloc(ID);lh.read(e,a,0,ID,0,(A,r)=>{t(a.subarray(0,r)),lh.close(e,()=>{})})}})});F7.exports={LDD_PATH:rHe,SELF_PATH:aHe,readFileSync:iHe,readFile:oHe}});var H7=$((BQA,U7)=>{"use strict";var nHe=n=>{if(n.length<64||n.readUInt32BE(0)!==2135247942||n.readUInt8(4)!==2||n.readUInt8(5)!==1)return null;let t=n.readUInt32LE(32),o=n.readUInt16LE(54),i=n.readUInt16LE(56);for(let e=0;e{"use strict";var x7=$e("child_process"),{isLinux:ph,getReport:Y7}=G7(),{LDD_PATH:lD,SELF_PATH:j7,readFile:NF,readFileSync:RF}=L7(),{interpreterPath:J7}=H7(),Ss,ws,Ds,q7="getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",qc="",z7=()=>qc||new Promise(n=>{x7.exec(q7,(t,o)=>{qc=t?" ":o,n(qc)})}),V7=()=>{if(!qc)try{qc=x7.execSync(q7,{encoding:"utf8"})}catch{qc=" "}return qc},vg="glibc",W7=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,_l="musl",sHe=n=>n.includes("libc.musl-")||n.includes("ld-musl-"),Z7=()=>{let n=Y7();return n.header&&n.header.glibcVersionRuntime?vg:Array.isArray(n.sharedObjects)&&n.sharedObjects.some(sHe)?_l:null},X7=n=>{let[t,o]=n.split(/[\r\n]+/);return t&&t.includes(vg)?vg:o&&o.includes(_l)?_l:null},$7=n=>{if(n){if(n.includes("/ld-musl-"))return _l;if(n.includes("/ld-linux-"))return vg}return null},e$=n=>(n=n.toString(),n.includes("musl")?_l:n.includes("GNU C Library")?vg:null),gHe=async()=>{if(ws!==void 0)return ws;ws=null;try{let n=await NF(lD);ws=e$(n)}catch{}return ws},cHe=()=>{if(ws!==void 0)return ws;ws=null;try{let n=RF(lD);ws=e$(n)}catch{}return ws},IHe=async()=>{if(Ss!==void 0)return Ss;Ss=null;try{let n=await NF(j7),t=J7(n);Ss=$7(t)}catch{}return Ss},lHe=()=>{if(Ss!==void 0)return Ss;Ss=null;try{let n=RF(j7),t=J7(n);Ss=$7(t)}catch{}return Ss},A$=async()=>{let n=null;if(ph()&&(n=await IHe(),!n&&(n=await gHe(),n||(n=Z7()),!n))){let t=await z7();n=X7(t)}return n},t$=()=>{let n=null;if(ph()&&(n=lHe(),!n&&(n=cHe(),n||(n=Z7()),!n))){let t=V7();n=X7(t)}return n},pHe=async()=>ph()&&await A$()!==vg,dHe=()=>ph()&&t$()!==vg,hHe=async()=>{if(Ds!==void 0)return Ds;Ds=null;try{let t=(await NF(lD)).match(W7);t&&(Ds=t[1])}catch{}return Ds},EHe=()=>{if(Ds!==void 0)return Ds;Ds=null;try{let t=RF(lD).match(W7);t&&(Ds=t[1])}catch{}return Ds},r$=()=>{let n=Y7();return n.header&&n.header.glibcVersionRuntime?n.header.glibcVersionRuntime:null},K7=n=>n.trim().split(/\s+/)[1],a$=n=>{let[t,o,i]=n.split(/[\r\n]+/);return t&&t.includes(vg)?K7(t):o&&i&&o.includes(_l)?K7(i):null},CHe=async()=>{let n=null;if(ph()&&(n=await hHe(),n||(n=r$()),!n)){let t=await z7();n=a$(t)}return n},uHe=()=>{let n=null;if(ph()&&(n=EHe(),n||(n=r$()),!n)){let t=V7();n=a$(t)}return n};i$.exports={GLIBC:vg,MUSL:_l,family:A$,familySync:t$,isNonGlibcLinux:pHe,isNonGlibcLinuxSync:dHe,version:CHe,versionSync:uHe}});var dh=$((QQA,o$)=>{"use strict";var BHe="2.0.0",fHe=Number.MAX_SAFE_INTEGER||9007199254740991,QHe=16,yHe=250,mHe=["major","premajor","minor","preminor","patch","prepatch","prerelease"];o$.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:QHe,MAX_SAFE_BUILD_LENGTH:yHe,MAX_SAFE_INTEGER:fHe,RELEASE_TYPES:mHe,SEMVER_SPEC_VERSION:BHe,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var OB=$((yQA,n$)=>{"use strict";var SHe=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...n)=>console.error("SEMVER",...n):()=>{};n$.exports=SHe});var hh=$((Os,s$)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:kF,MAX_SAFE_BUILD_LENGTH:wHe,MAX_LENGTH:DHe}=dh(),OHe=OB();Os=s$.exports={};var bHe=Os.re=[],MHe=Os.safeRe=[],cA=Os.src=[],_He=Os.safeSrc=[],IA=Os.t={},THe=0,vF="[a-zA-Z0-9-]",NHe=[["\\s",1],["\\d",DHe],[vF,wHe]],RHe=n=>{for(let[t,o]of NHe)n=n.split(`${t}*`).join(`${t}{0,${o}}`).split(`${t}+`).join(`${t}{1,${o}}`);return n},jA=(n,t,o)=>{let i=RHe(t),e=THe++;OHe(n,e,t),IA[n]=e,cA[e]=t,_He[e]=i,bHe[e]=new RegExp(t,o?"g":void 0),MHe[e]=new RegExp(i,o?"g":void 0)};jA("NUMERICIDENTIFIER","0|[1-9]\\d*");jA("NUMERICIDENTIFIERLOOSE","\\d+");jA("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${vF}*`);jA("MAINVERSION",`(${cA[IA.NUMERICIDENTIFIER]})\\.(${cA[IA.NUMERICIDENTIFIER]})\\.(${cA[IA.NUMERICIDENTIFIER]})`);jA("MAINVERSIONLOOSE",`(${cA[IA.NUMERICIDENTIFIERLOOSE]})\\.(${cA[IA.NUMERICIDENTIFIERLOOSE]})\\.(${cA[IA.NUMERICIDENTIFIERLOOSE]})`);jA("PRERELEASEIDENTIFIER",`(?:${cA[IA.NONNUMERICIDENTIFIER]}|${cA[IA.NUMERICIDENTIFIER]})`);jA("PRERELEASEIDENTIFIERLOOSE",`(?:${cA[IA.NONNUMERICIDENTIFIER]}|${cA[IA.NUMERICIDENTIFIERLOOSE]})`);jA("PRERELEASE",`(?:-(${cA[IA.PRERELEASEIDENTIFIER]}(?:\\.${cA[IA.PRERELEASEIDENTIFIER]})*))`);jA("PRERELEASELOOSE",`(?:-?(${cA[IA.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${cA[IA.PRERELEASEIDENTIFIERLOOSE]})*))`);jA("BUILDIDENTIFIER",`${vF}+`);jA("BUILD",`(?:\\+(${cA[IA.BUILDIDENTIFIER]}(?:\\.${cA[IA.BUILDIDENTIFIER]})*))`);jA("FULLPLAIN",`v?${cA[IA.MAINVERSION]}${cA[IA.PRERELEASE]}?${cA[IA.BUILD]}?`);jA("FULL",`^${cA[IA.FULLPLAIN]}$`);jA("LOOSEPLAIN",`[v=\\s]*${cA[IA.MAINVERSIONLOOSE]}${cA[IA.PRERELEASELOOSE]}?${cA[IA.BUILD]}?`);jA("LOOSE",`^${cA[IA.LOOSEPLAIN]}$`);jA("GTLT","((?:<|>)?=?)");jA("XRANGEIDENTIFIERLOOSE",`${cA[IA.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);jA("XRANGEIDENTIFIER",`${cA[IA.NUMERICIDENTIFIER]}|x|X|\\*`);jA("XRANGEPLAIN",`[v=\\s]*(${cA[IA.XRANGEIDENTIFIER]})(?:\\.(${cA[IA.XRANGEIDENTIFIER]})(?:\\.(${cA[IA.XRANGEIDENTIFIER]})(?:${cA[IA.PRERELEASE]})?${cA[IA.BUILD]}?)?)?`);jA("XRANGEPLAINLOOSE",`[v=\\s]*(${cA[IA.XRANGEIDENTIFIERLOOSE]})(?:\\.(${cA[IA.XRANGEIDENTIFIERLOOSE]})(?:\\.(${cA[IA.XRANGEIDENTIFIERLOOSE]})(?:${cA[IA.PRERELEASELOOSE]})?${cA[IA.BUILD]}?)?)?`);jA("XRANGE",`^${cA[IA.GTLT]}\\s*${cA[IA.XRANGEPLAIN]}$`);jA("XRANGELOOSE",`^${cA[IA.GTLT]}\\s*${cA[IA.XRANGEPLAINLOOSE]}$`);jA("COERCEPLAIN",`(^|[^\\d])(\\d{1,${kF}})(?:\\.(\\d{1,${kF}}))?(?:\\.(\\d{1,${kF}}))?`);jA("COERCE",`${cA[IA.COERCEPLAIN]}(?:$|[^\\d])`);jA("COERCEFULL",cA[IA.COERCEPLAIN]+`(?:${cA[IA.PRERELEASE]})?(?:${cA[IA.BUILD]})?(?:$|[^\\d])`);jA("COERCERTL",cA[IA.COERCE],!0);jA("COERCERTLFULL",cA[IA.COERCEFULL],!0);jA("LONETILDE","(?:~>?)");jA("TILDETRIM",`(\\s*)${cA[IA.LONETILDE]}\\s+`,!0);Os.tildeTrimReplace="$1~";jA("TILDE",`^${cA[IA.LONETILDE]}${cA[IA.XRANGEPLAIN]}$`);jA("TILDELOOSE",`^${cA[IA.LONETILDE]}${cA[IA.XRANGEPLAINLOOSE]}$`);jA("LONECARET","(?:\\^)");jA("CARETTRIM",`(\\s*)${cA[IA.LONECARET]}\\s+`,!0);Os.caretTrimReplace="$1^";jA("CARET",`^${cA[IA.LONECARET]}${cA[IA.XRANGEPLAIN]}$`);jA("CARETLOOSE",`^${cA[IA.LONECARET]}${cA[IA.XRANGEPLAINLOOSE]}$`);jA("COMPARATORLOOSE",`^${cA[IA.GTLT]}\\s*(${cA[IA.LOOSEPLAIN]})$|^$`);jA("COMPARATOR",`^${cA[IA.GTLT]}\\s*(${cA[IA.FULLPLAIN]})$|^$`);jA("COMPARATORTRIM",`(\\s*)${cA[IA.GTLT]}\\s*(${cA[IA.LOOSEPLAIN]}|${cA[IA.XRANGEPLAIN]})`,!0);Os.comparatorTrimReplace="$1$2$3";jA("HYPHENRANGE",`^\\s*(${cA[IA.XRANGEPLAIN]})\\s+-\\s+(${cA[IA.XRANGEPLAIN]})\\s*$`);jA("HYPHENRANGELOOSE",`^\\s*(${cA[IA.XRANGEPLAINLOOSE]})\\s+-\\s+(${cA[IA.XRANGEPLAINLOOSE]})\\s*$`);jA("STAR","(<|>)?=?\\s*\\*");jA("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");jA("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var dD=$((mQA,g$)=>{"use strict";var kHe=Object.freeze({loose:!0}),vHe=Object.freeze({}),PHe=n=>n?typeof n!="object"?kHe:n:vHe;g$.exports=PHe});var PF=$((SQA,l$)=>{"use strict";var c$=/^[0-9]+$/,I$=(n,t)=>{if(typeof n=="number"&&typeof t=="number")return n===t?0:nI$(t,n);l$.exports={compareIdentifiers:I$,rcompareIdentifiers:GHe}});var ma=$((wQA,d$)=>{"use strict";var hD=OB(),{MAX_LENGTH:p$,MAX_SAFE_INTEGER:ED}=dh(),{safeRe:CD,t:uD}=hh(),FHe=dD(),{compareIdentifiers:GF}=PF(),LHe=(n,t)=>{let o=t.split(".");if(o.length>n.length)return!1;for(let i=0;ip$)throw new TypeError(`version is longer than ${p$} characters`);hD("SemVer",t,o),this.options=o,this.loose=!!o.loose,this.includePrerelease=!!o.includePrerelease;let i=t.trim().match(o.loose?CD[uD.LOOSE]:CD[uD.FULL]);if(!i)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>ED||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ED||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ED||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){let a=+e;if(a>=0&&at.major?1:this.minort.minor?1:this.patcht.patch?1:0}comparePre(t){if(t instanceof n||(t=new n(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let o=0;do{let i=this.prerelease[o],e=t.prerelease[o];if(hD("prerelease compare",o,i,e),i===void 0&&e===void 0)return 0;if(e===void 0)return 1;if(i===void 0)return-1;if(i===e)continue;return GF(i,e)}while(++o)}compareBuild(t){t instanceof n||(t=new n(t,this.options));let o=0;do{let i=this.build[o],e=t.build[o];if(hD("build compare",o,i,e),i===void 0&&e===void 0)return 0;if(e===void 0)return 1;if(i===void 0)return-1;if(i===e)continue;return GF(i,e)}while(++o)}inc(t,o,i){if(t.startsWith("pre")){if(!o&&i===!1)throw new Error("invalid increment argument: identifier is empty");if(o){let e=`-${o}`.match(this.options.loose?CD[uD.PRERELEASELOOSE]:CD[uD.PRERELEASE]);if(!e||e[1]!==o)throw new Error(`invalid identifier: ${o}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",o,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",o,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",o,i),this.inc("pre",o,i);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",o,i),this.inc("pre",o,i);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let e=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[e];else{let a=this.prerelease.length;for(;--a>=0;)typeof this.prerelease[a]=="number"&&(this.prerelease[a]++,a=-2);if(a===-1){if(o===this.prerelease.join(".")&&i===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(o){let a=[o,e];if(i===!1&&(a=[o]),LHe(this.prerelease,o)){let A=this.prerelease[o.split(".").length];isNaN(A)&&(this.prerelease=a)}else this.prerelease=a}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};d$.exports=FF});var zc=$((DQA,E$)=>{"use strict";var h$=ma(),UHe=(n,t,o=!1)=>{if(n instanceof h$)return n;try{return new h$(n,t)}catch(i){if(!o)return null;throw i}};E$.exports=UHe});var u$=$((OQA,C$)=>{"use strict";var HHe=zc(),KHe=(n,t)=>{let o=HHe(n,t);return o?o.version:null};C$.exports=KHe});var f$=$((bQA,B$)=>{"use strict";var xHe=zc(),YHe=(n,t)=>{let o=xHe(n.trim().replace(/^[=v]+/,""),t);return o?o.version:null};B$.exports=YHe});var m$=$((MQA,y$)=>{"use strict";var Q$=ma(),jHe=(n,t,o,i,e)=>{typeof o=="string"&&(e=i,i=o,o=void 0);try{return new Q$(n instanceof Q$?n.version:n,o).inc(t,i,e).version}catch{return null}};y$.exports=jHe});var D$=$((_QA,w$)=>{"use strict";var S$=zc(),JHe=(n,t)=>{let o=S$(n,null,!0),i=S$(t,null,!0),e=o.compare(i);if(e===0)return null;let a=e>0,A=a?o:i,r=a?i:o,s=!!A.prerelease.length;if(!!r.prerelease.length&&!s){if(!r.patch&&!r.minor)return"major";if(r.compareMain(A)===0)return r.minor&&!r.patch?"minor":"patch"}let c=s?"pre":"";return o.major!==i.major?c+"major":o.minor!==i.minor?c+"minor":o.patch!==i.patch?c+"patch":"prerelease"};w$.exports=JHe});var b$=$((TQA,O$)=>{"use strict";var qHe=ma(),zHe=(n,t)=>new qHe(n,t).major;O$.exports=zHe});var _$=$((NQA,M$)=>{"use strict";var VHe=ma(),WHe=(n,t)=>new VHe(n,t).minor;M$.exports=WHe});var N$=$((RQA,T$)=>{"use strict";var ZHe=ma(),XHe=(n,t)=>new ZHe(n,t).patch;T$.exports=XHe});var k$=$((kQA,R$)=>{"use strict";var $He=zc(),eKe=(n,t)=>{let o=$He(n,t);return o&&o.prerelease.length?o.prerelease:null};R$.exports=eKe});var jo=$((vQA,P$)=>{"use strict";var v$=ma(),AKe=(n,t,o)=>new v$(n,o).compare(new v$(t,o));P$.exports=AKe});var F$=$((PQA,G$)=>{"use strict";var tKe=jo(),rKe=(n,t,o)=>tKe(t,n,o);G$.exports=rKe});var U$=$((GQA,L$)=>{"use strict";var aKe=jo(),iKe=(n,t)=>aKe(n,t,!0);L$.exports=iKe});var BD=$((FQA,K$)=>{"use strict";var H$=ma(),oKe=(n,t,o)=>{let i=new H$(n,o),e=new H$(t,o);return i.compare(e)||i.compareBuild(e)};K$.exports=oKe});var Y$=$((LQA,x$)=>{"use strict";var nKe=BD(),sKe=(n,t)=>n.sort((o,i)=>nKe(o,i,t));x$.exports=sKe});var J$=$((UQA,j$)=>{"use strict";var gKe=BD(),cKe=(n,t)=>n.sort((o,i)=>gKe(i,o,t));j$.exports=cKe});var bB=$((HQA,q$)=>{"use strict";var IKe=jo(),lKe=(n,t,o)=>IKe(n,t,o)>0;q$.exports=lKe});var fD=$((KQA,z$)=>{"use strict";var pKe=jo(),dKe=(n,t,o)=>pKe(n,t,o)<0;z$.exports=dKe});var LF=$((xQA,V$)=>{"use strict";var hKe=jo(),EKe=(n,t,o)=>hKe(n,t,o)===0;V$.exports=EKe});var UF=$((YQA,W$)=>{"use strict";var CKe=jo(),uKe=(n,t,o)=>CKe(n,t,o)!==0;W$.exports=uKe});var QD=$((jQA,Z$)=>{"use strict";var BKe=jo(),fKe=(n,t,o)=>BKe(n,t,o)>=0;Z$.exports=fKe});var yD=$((JQA,X$)=>{"use strict";var QKe=jo(),yKe=(n,t,o)=>QKe(n,t,o)<=0;X$.exports=yKe});var HF=$((qQA,$$)=>{"use strict";var mKe=LF(),SKe=UF(),wKe=bB(),DKe=QD(),OKe=fD(),bKe=yD(),MKe=(n,t,o,i)=>{switch(t){case"===":return typeof n=="object"&&(n=n.version),typeof o=="object"&&(o=o.version),n===o;case"!==":return typeof n=="object"&&(n=n.version),typeof o=="object"&&(o=o.version),n!==o;case"":case"=":case"==":return mKe(n,o,i);case"!=":return SKe(n,o,i);case">":return wKe(n,o,i);case">=":return DKe(n,o,i);case"<":return OKe(n,o,i);case"<=":return bKe(n,o,i);default:throw new TypeError(`Invalid operator: ${t}`)}};$$.exports=MKe});var Aee=$((zQA,eee)=>{"use strict";var _Ke=ma(),TKe=zc(),{safeRe:mD,t:SD}=hh(),NKe=(n,t)=>{if(n instanceof _Ke)return n;if(typeof n=="number"&&(n=String(n)),typeof n!="string")return null;t=t||{};let o=null;if(!t.rtl)o=n.match(t.includePrerelease?mD[SD.COERCEFULL]:mD[SD.COERCE]);else{let s=t.includePrerelease?mD[SD.COERCERTLFULL]:mD[SD.COERCERTL],g;for(;(g=s.exec(n))&&(!o||o.index+o[0].length!==n.length);)(!o||g.index+g[0].length!==o.index+o[0].length)&&(o=g),s.lastIndex=g.index+g[1].length+g[2].length;s.lastIndex=-1}if(o===null)return null;let i=o[2],e=o[3]||"0",a=o[4]||"0",A=t.includePrerelease&&o[5]?`-${o[5]}`:"",r=t.includePrerelease&&o[6]?`+${o[6]}`:"";return TKe(`${i}.${e}.${a}${A}${r}`,t)};eee.exports=NKe});var ree=$((VQA,tee)=>{"use strict";var RKe=zc(),kKe=dh(),vKe=ma(),PKe=(n,t,o)=>{if(!kKe.RELEASE_TYPES.includes(t))return null;let i=GKe(n,o);return i&&FKe(i,t)},GKe=(n,t)=>{let o=n instanceof vKe?n.version:n;return RKe(o,t)},FKe=(n,t)=>{if(LKe(t))return n.version;switch(n.prerelease=[],t){case"major":n.minor=0,n.patch=0;break;case"minor":n.patch=0;break}return n.format()},LKe=n=>n.startsWith("pre");tee.exports=PKe});var iee=$((WQA,aee)=>{"use strict";var KF=class{constructor(){this.max=1e3,this.map=new Map}get(t){let o=this.map.get(t);if(o!==void 0)return this.map.delete(t),this.map.set(t,o),o}delete(t){return this.map.delete(t)}set(t,o){if(!this.delete(t)&&o!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(t,o)}return this}};aee.exports=KF});var Jo=$((ZQA,gee)=>{"use strict";var UKe=/\s+/g,xF=class n{constructor(t,o){if(o=KKe(o),t instanceof n)return t.loose===!!o.loose&&t.includePrerelease===!!o.includePrerelease?t:new n(t.raw,o);if(t instanceof YF)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=o,this.loose=!!o.loose,this.includePrerelease=!!o.includePrerelease,this.raw=t.trim().replace(UKe," "),this.set=this.raw.split("||").map(i=>this.parseRange(i.trim())).filter(i=>i.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter(e=>!nee(e[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&ZKe(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t0&&(this.formatted+="||");let o=this.set[t];for(let i=0;i0&&(this.formatted+=" "),this.formatted+=o[i].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(WKe,"");let i=((this.options.includePrerelease&&zKe)|(this.options.loose&&VKe))+":"+t,e=oee.get(i);if(e)return e;let a=this.options.loose,A=a?ii[Sa.HYPHENRANGELOOSE]:ii[Sa.HYPHENRANGE];t=t.replace(A,sxe(this.options.includePrerelease)),Jt("hyphen replace",t),t=t.replace(ii[Sa.COMPARATORTRIM],jKe),Jt("comparator trim",t),t=t.replace(ii[Sa.TILDETRIM],JKe),Jt("tilde trim",t),t=t.replace(ii[Sa.CARETTRIM],qKe),Jt("caret trim",t);let r=t.split(" ").map(I=>XKe(I,this.options)).join(" ").split(/\s+/).map(I=>nxe(I,this.options));a&&(r=r.filter(I=>(Jt("loose invalid filter",I,this.options),!!I.match(ii[Sa.COMPARATORLOOSE])))),Jt("range list",r);let s=new Map,g=r.map(I=>new YF(I,this.options));for(let I of g){if(nee(I))return[I];s.set(I.value,I)}s.size>1&&s.has("")&&s.delete("");let c=[...s.values()];return oee.set(i,c),c}intersects(t,o){if(!(t instanceof n))throw new TypeError("a Range is required");return this.set.some(i=>see(i,o)&&t.set.some(e=>see(e,o)&&i.every(a=>e.every(A=>a.intersects(A,o)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new xKe(t,this.options)}catch{return!1}for(let o=0;on.value==="<0.0.0-0",ZKe=n=>n.value==="",see=(n,t)=>{let o=!0,i=n.slice(),e=i.pop();for(;o&&i.length;)o=i.every(a=>e.intersects(a,t)),e=i.pop();return o},XKe=(n,t)=>(n=n.replace(ii[Sa.BUILD],""),Jt("comp",n,t),n=txe(n,t),Jt("caret",n),n=exe(n,t),Jt("tildes",n),n=axe(n,t),Jt("xrange",n),n=oxe(n,t),Jt("stars",n),n),xr=n=>!n||n.toLowerCase()==="x"||n==="*",$Ke=(n,t,o)=>xr(n)&&!xr(t)||xr(t)&&o&&!xr(o),exe=(n,t)=>n.trim().split(/\s+/).map(o=>Axe(o,t)).join(" "),Axe=(n,t)=>{let o=t.loose?ii[Sa.TILDELOOSE]:ii[Sa.TILDE],i=t.includePrerelease?"-0":"";return n.replace(o,(e,a,A,r,s)=>{Jt("tilde",n,e,a,A,r,s);let g;return xr(a)?g="":xr(A)?g=`>=${a}.0.0${i} <${+a+1}.0.0-0`:xr(r)?g=`>=${a}.${A}.0${i} <${a}.${+A+1}.0-0`:s?(Jt("replaceTilde pr",s),g=`>=${a}.${A}.${r}-${s} <${a}.${+A+1}.0-0`):g=`>=${a}.${A}.${r} <${a}.${+A+1}.0-0`,Jt("tilde return",g),g})},txe=(n,t)=>n.trim().split(/\s+/).map(o=>rxe(o,t)).join(" "),rxe=(n,t)=>{Jt("caret",n,t);let o=t.loose?ii[Sa.CARETLOOSE]:ii[Sa.CARET],i=t.includePrerelease?"-0":"";return n.replace(o,(e,a,A,r,s)=>{Jt("caret",n,e,a,A,r,s);let g;return xr(a)?g="":xr(A)?g=`>=${a}.0.0${i} <${+a+1}.0.0-0`:xr(r)?a==="0"?g=`>=${a}.${A}.0${i} <${a}.${+A+1}.0-0`:g=`>=${a}.${A}.0${i} <${+a+1}.0.0-0`:s?(Jt("replaceCaret pr",s),a==="0"?A==="0"?g=`>=${a}.${A}.${r}-${s} <${a}.${A}.${+r+1}-0`:g=`>=${a}.${A}.${r}-${s} <${a}.${+A+1}.0-0`:g=`>=${a}.${A}.${r}-${s} <${+a+1}.0.0-0`):(Jt("no pr"),a==="0"?A==="0"?g=`>=${a}.${A}.${r} <${a}.${A}.${+r+1}-0`:g=`>=${a}.${A}.${r} <${a}.${+A+1}.0-0`:g=`>=${a}.${A}.${r} <${+a+1}.0.0-0`),Jt("caret return",g),g})},axe=(n,t)=>(Jt("replaceXRanges",n,t),n.split(/\s+/).map(o=>ixe(o,t)).join(" ")),ixe=(n,t)=>{n=n.trim();let o=t.loose?ii[Sa.XRANGELOOSE]:ii[Sa.XRANGE];return n.replace(o,(i,e,a,A,r,s)=>{if(Jt("xRange",n,i,e,a,A,r,s),$Ke(a,A,r))return n;let g=xr(a),c=g||xr(A),I=c||xr(r),d=I;return e==="="&&d&&(e=""),s=t.includePrerelease?"-0":"",g?e===">"||e==="<"?i="<0.0.0-0":i="*":e&&d?(c&&(A=0),r=0,e===">"?(e=">=",c?(a=+a+1,A=0,r=0):(A=+A+1,r=0)):e==="<="&&(e="<",c?a=+a+1:A=+A+1),e==="<"&&(s="-0"),i=`${e+a}.${A}.${r}${s}`):c?i=`>=${a}.0.0${s} <${+a+1}.0.0-0`:I&&(i=`>=${a}.${A}.0${s} <${a}.${+A+1}.0-0`),Jt("xRange return",i),i})},oxe=(n,t)=>(Jt("replaceStars",n,t),n.trim().replace(ii[Sa.STAR],"")),nxe=(n,t)=>(Jt("replaceGTE0",n,t),n.trim().replace(ii[t.includePrerelease?Sa.GTE0PRE:Sa.GTE0],"")),sxe=n=>(t,o,i,e,a,A,r,s,g,c,I,d)=>(xr(i)?o="":xr(e)?o=`>=${i}.0.0${n?"-0":""}`:xr(a)?o=`>=${i}.${e}.0${n?"-0":""}`:A?o=`>=${o}`:o=`>=${o}${n?"-0":""}`,xr(g)?s="":xr(c)?s=`<${+g+1}.0.0-0`:xr(I)?s=`<${g}.${+c+1}.0-0`:d?s=`<=${g}.${c}.${I}-${d}`:n?s=`<${g}.${c}.${+I+1}-0`:s=`<=${s}`,`${o} ${s}`.trim()),gxe=(n,t,o)=>{for(let i=0;i0){let e=n[i].semver;if(e.major===t.major&&e.minor===t.minor&&e.patch===t.patch)return!0}return!1}return!0}});var MB=$((XQA,hee)=>{"use strict";var _B=Symbol("SemVer ANY"),qF=class n{static get ANY(){return _B}constructor(t,o){if(o=cee(o),t instanceof n){if(t.loose===!!o.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),JF("comparator",t,o),this.options=o,this.loose=!!o.loose,this.parse(t),this.semver===_B?this.value="":this.value=this.operator+this.semver.version,JF("comp",this)}parse(t){let o=this.options.loose?Iee[lee.COMPARATORLOOSE]:Iee[lee.COMPARATOR],i=t.match(o);if(!i)throw new TypeError(`Invalid comparator: ${t}`);this.operator=i[1]!==void 0?i[1]:"",this.operator==="="&&(this.operator=""),i[2]?this.semver=new pee(i[2],this.options.loose):this.semver=_B}toString(){return this.value}test(t){if(JF("Comparator.test",t,this.options.loose),this.semver===_B||t===_B)return!0;if(typeof t=="string")try{t=new pee(t,this.options)}catch{return!1}return jF(t,this.operator,this.semver,this.options)}intersects(t,o){if(!(t instanceof n))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new dee(t.value,o).test(this.value):t.operator===""?t.value===""?!0:new dee(this.value,o).test(t.semver):(o=cee(o),o.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!o.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||jF(this.semver,"<",t.semver,o)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||jF(this.semver,">",t.semver,o)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};hee.exports=qF;var cee=dD(),{safeRe:Iee,t:lee}=hh(),jF=HF(),JF=OB(),pee=ma(),dee=Jo()});var TB=$(($QA,Eee)=>{"use strict";var cxe=Jo(),Ixe=(n,t,o)=>{try{t=new cxe(t,o)}catch{return!1}return t.test(n)};Eee.exports=Ixe});var uee=$((eyA,Cee)=>{"use strict";var lxe=Jo(),pxe=(n,t)=>new lxe(n,t).set.map(o=>o.map(i=>i.value).join(" ").trim().split(" "));Cee.exports=pxe});var fee=$((AyA,Bee)=>{"use strict";var dxe=ma(),hxe=Jo(),Exe=(n,t,o)=>{let i=null,e=null,a=null;try{a=new hxe(t,o)}catch{return null}return n.forEach(A=>{a.test(A)&&(!i||e.compare(A)===-1)&&(i=A,e=new dxe(i,o))}),i};Bee.exports=Exe});var yee=$((tyA,Qee)=>{"use strict";var Cxe=ma(),uxe=Jo(),Bxe=(n,t,o)=>{let i=null,e=null,a=null;try{a=new uxe(t,o)}catch{return null}return n.forEach(A=>{a.test(A)&&(!i||e.compare(A)===1)&&(i=A,e=new Cxe(i,o))}),i};Qee.exports=Bxe});var wee=$((ryA,See)=>{"use strict";var zF=ma(),fxe=Jo(),mee=bB(),Qxe=(n,t)=>{n=new fxe(n,t);let o=new zF("0.0.0");if(n.test(o)||(o=new zF("0.0.0-0"),n.test(o)))return o;o=null;for(let i=0;i{let r=new zF(A.semver.version);switch(A.operator){case">":r.prerelease.length===0?r.patch++:r.prerelease.push(0),r.raw=r.format();case"":case">=":(!a||mee(r,a))&&(a=r);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${A.operator}`)}}),a&&(!o||mee(o,a))&&(o=a)}return o&&n.test(o)?o:null};See.exports=Qxe});var Oee=$((ayA,Dee)=>{"use strict";var yxe=Jo(),mxe=(n,t)=>{try{return new yxe(n,t).range||"*"}catch{return null}};Dee.exports=mxe});var wD=$((iyA,Tee)=>{"use strict";var Sxe=ma(),_ee=MB(),{ANY:wxe}=_ee,Dxe=Jo(),Oxe=TB(),bee=bB(),Mee=fD(),bxe=yD(),Mxe=QD(),_xe=(n,t,o,i)=>{n=new Sxe(n,i),t=new Dxe(t,i);let e,a,A,r,s;switch(o){case">":e=bee,a=bxe,A=Mee,r=">",s=">=";break;case"<":e=Mee,a=Mxe,A=bee,r="<",s="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Oxe(n,t,i))return!1;for(let g=0;g{B.semver===wxe&&(B=new _ee(">=0.0.0")),I=I||B,d=d||B,e(B.semver,I.semver,i)?I=B:A(B.semver,d.semver,i)&&(d=B)}),I.operator===r||I.operator===s||(!d.operator||d.operator===r)&&a(n,d.semver))return!1;if(d.operator===s&&A(n,d.semver))return!1}return!0};Tee.exports=_xe});var Ree=$((oyA,Nee)=>{"use strict";var Txe=wD(),Nxe=(n,t,o)=>Txe(n,t,">",o);Nee.exports=Nxe});var vee=$((nyA,kee)=>{"use strict";var Rxe=wD(),kxe=(n,t,o)=>Rxe(n,t,"<",o);kee.exports=kxe});var Fee=$((syA,Gee)=>{"use strict";var Pee=Jo(),vxe=(n,t,o)=>(n=new Pee(n,o),t=new Pee(t,o),n.intersects(t,o));Gee.exports=vxe});var Uee=$((gyA,Lee)=>{"use strict";var Pxe=TB(),Gxe=jo();Lee.exports=(n,t,o)=>{let i=[],e=null,a=null,A=n.sort((c,I)=>Gxe(c,I,o));for(let c of A)Pxe(c,t,o)?(a=c,e||(e=c)):(a&&i.push([e,a]),a=null,e=null);e&&i.push([e,null]);let r=[];for(let[c,I]of i)c===I?r.push(c):!I&&c===A[0]?r.push("*"):I?c===A[0]?r.push(`<=${I}`):r.push(`${c} - ${I}`):r.push(`>=${c}`);let s=r.join(" || "),g=typeof t.raw=="string"?t.raw:String(t);return s.length{"use strict";var Hee=Jo(),ZF=MB(),{ANY:VF}=ZF,WF=TB(),XF=jo(),Fxe=(n,t,o={})=>{if(n===t)return!0;n=new Hee(n,o),t=new Hee(t,o);let i=!1;e:for(let e of n.set){for(let a of t.set){let A=Uxe(e,a,o);if(i=i||A!==null,A)continue e}if(i)return!1}return!0},Lxe=[new ZF(">=0.0.0-0")],Kee=[new ZF(">=0.0.0")],Uxe=(n,t,o)=>{if(n===t)return!0;if(n.length===1&&n[0].semver===VF){if(t.length===1&&t[0].semver===VF)return!0;o.includePrerelease?n=Lxe:n=Kee}if(t.length===1&&t[0].semver===VF){if(o.includePrerelease)return!0;t=Kee}let i=new Set,e,a;for(let B of n)B.operator===">"||B.operator===">="?e=xee(e,B,o):B.operator==="<"||B.operator==="<="?a=Yee(a,B,o):i.add(B.semver);if(i.size>1)return null;let A;if(e&&a){if(A=XF(e.semver,a.semver,o),A>0)return null;if(A===0&&(e.operator!==">="||a.operator!=="<="))return null}for(let B of i){if(e&&!WF(B,String(e),o)||a&&!WF(B,String(a),o))return null;for(let f of t)if(!WF(B,String(f),o))return!1;return!0}let r,s,g,c,I=a&&!o.includePrerelease&&a.semver.prerelease.length?a.semver:!1,d=e&&!o.includePrerelease&&e.semver.prerelease.length?e.semver:!1;I&&I.prerelease.length===1&&a.operator==="<"&&I.prerelease[0]===0&&(I=!1);for(let B of t){if(c=c||B.operator===">"||B.operator===">=",g=g||B.operator==="<"||B.operator==="<=",e){if(d&&B.semver.prerelease&&B.semver.prerelease.length&&B.semver.major===d.major&&B.semver.minor===d.minor&&B.semver.patch===d.patch&&(d=!1),B.operator===">"||B.operator===">="){if(r=xee(e,B,o),r===B&&r!==e)return!1}else if(e.operator===">="&&!B.test(e.semver))return!1}if(a){if(I&&B.semver.prerelease&&B.semver.prerelease.length&&B.semver.major===I.major&&B.semver.minor===I.minor&&B.semver.patch===I.patch&&(I=!1),B.operator==="<"||B.operator==="<="){if(s=Yee(a,B,o),s===B&&s!==a)return!1}else if(a.operator==="<="&&!B.test(a.semver))return!1}if(!B.operator&&(a||e)&&A!==0)return!1}return!(e&&g&&!a&&A!==0||a&&c&&!e&&A!==0||d||I)},xee=(n,t,o)=>{if(!n)return t;let i=XF(n.semver,t.semver,o);return i>0?n:i<0||t.operator===">"&&n.operator===">="?t:n},Yee=(n,t,o)=>{if(!n)return t;let i=XF(n.semver,t.semver,o);return i<0?n:i>0||t.operator==="<"&&n.operator==="<="?t:n};jee.exports=Fxe});var DD=$((IyA,Vee)=>{"use strict";var $F=hh(),qee=dh(),Hxe=ma(),zee=PF(),Kxe=zc(),xxe=u$(),Yxe=f$(),jxe=m$(),Jxe=D$(),qxe=b$(),zxe=_$(),Vxe=N$(),Wxe=k$(),Zxe=jo(),Xxe=F$(),$xe=U$(),eYe=BD(),AYe=Y$(),tYe=J$(),rYe=bB(),aYe=fD(),iYe=LF(),oYe=UF(),nYe=QD(),sYe=yD(),gYe=HF(),cYe=Aee(),IYe=ree(),lYe=MB(),pYe=Jo(),dYe=TB(),hYe=uee(),EYe=fee(),CYe=yee(),uYe=wee(),BYe=Oee(),fYe=wD(),QYe=Ree(),yYe=vee(),mYe=Fee(),SYe=Uee(),wYe=Jee();Vee.exports={parse:Kxe,valid:xxe,clean:Yxe,inc:jxe,diff:Jxe,major:qxe,minor:zxe,patch:Vxe,prerelease:Wxe,compare:Zxe,rcompare:Xxe,compareLoose:$xe,compareBuild:eYe,sort:AYe,rsort:tYe,gt:rYe,lt:aYe,eq:iYe,neq:oYe,gte:nYe,lte:sYe,cmp:gYe,coerce:cYe,truncate:IYe,Comparator:lYe,Range:pYe,satisfies:dYe,toComparators:hYe,maxSatisfying:EYe,minSatisfying:CYe,minVersion:uYe,validRange:BYe,outside:fYe,gtr:QYe,ltr:yYe,intersects:mYe,simplifyRange:SYe,subset:wYe,SemVer:Hxe,re:$F.re,src:$F.src,tokens:$F.t,SEMVER_SPEC_VERSION:qee.SEMVER_SPEC_VERSION,RELEASE_TYPES:qee.RELEASE_TYPES,compareIdentifiers:zee.compareIdentifiers,rcompareIdentifiers:zee.rcompareIdentifiers}});var Pg,OD=ue(()=>{Pg={name:"sharp",description:"High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",version:"0.35.4",author:"Lovell Fuller ",homepage:"https://sharp.pixelplumbing.com",contributors:["Pierre Inglebert ","Jonathan Ong ","Chanon Sajjamanochai ","Juliano Julio ","Daniel Gasienica ","Julian Walker ","Amit Pitaru ","Brandon Aaron ","Andreas Lind ","Maurus Cuelenaere ","Linus Unneb\xE4ck ","Victor Mateevitsi ","Alaric Holloway ","Bernhard K. Weisshuhn ","Chris Riley ","David Carley ","John Tobin ","Kenton Gray ","Felix B\xFCnemann ","Samy Al Zahrani ","Chintan Thakkar ","F. Orlando Galashan ","Kleis Auke Wolthuizen ","Matt Hirsch ","Matthias Thoemmes ","Patrick Paskaris ","J\xE9r\xE9my Lal ","Rahul Nanwani ","Alice Monday ","Kristo Jorgenson ","YvesBos ","Guy Maliar ","Nicolas Coden ","Matt Parrish ","Marcel Bretschneider ","Matthew McEachen ","Jarda Kot\u011B\u0161ovec ","Kenric D'Souza ","Oleh Aleinyk ","Marcel Bretschneider ","Andrea Bianco ","Rik Heywood ","Thomas Parisot ","Nathan Graves ","Tom Lokhorst ","Espen Hovlandsdal ","Sylvain Dumont ","Alun Davies ","Aidan Hoolachan ","Axel Eirola ","Freezy ","Daiz ","Julian Aubourg ","Keith Belovay ","Michael B. Klein ","Jordan Prudhomme ","Ilya Ovdin ","Andargor ","Paul Neave ","Brendan Kennedy ","Brychan Bennett-Odlum ","Edward Silverton ","Roman Malieiev ","Tomas Szabo ","Robert O'Rourke ","Guillermo Alfonso Varela Chouci\xF1o ","Christian Flintrup ","Manan Jadhav ","Leon Radley ","alza54 ","Jacob Smith ","Michael Nutt ","Brad Parham ","Taneli Vatanen ","Joris Dugu\xE9 ","Chris Banks ","Ompal Singh ","Brodan ","Ankur Parihar ","Brahim Ait elhaj ","Mart Jansink ","Lachlan Newman ","Dennis Beatty ","Ingvar Stepanyan ","Don Denton ","Dmytro Tiapukhin ","Florian Lefebvre "],scripts:{build:"node install/build.js","build:dist":"node scripts/build.mjs",clean:"rm -rf src/build/ test/fixtures/output.*",test:"npm run lint && npm run test-unit",lint:"npm run lint-cpp && npm run lint-js && npm run lint-types && npm run lint-publish","lint-cpp":"cpplint --quiet src/*.h src/*.cc","lint-js":"biome lint","lint-publish":"publint --strict","lint-types":"tsd --files ./test/types/sharp.test-d.{cts,mts}","test-leak":"./test/leak/leak.sh","test-unit":"node --experimental-test-coverage test/unit.mjs","package-from-local-build":"node npm/from-local-build.js","package-wasm-wrappers":"node npm/wasm-wrappers.js","package-release-notes":"node npm/release-notes.js","docs-build":"node docs/build.mjs","docs-serve":"cd docs && npm start","docs-publish":"cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"},type:"commonjs",files:["dist","install","lib/index.d.ts","src/*.{cc,h,gyp}"],main:"./dist/index.cjs",module:"./dist/index.mjs",types:"./dist/index.d.mts",exports:{".":{import:{types:"./dist/index.d.mts",default:"./dist/index.mjs"},require:{types:"./dist/index.d.cts",default:"./dist/index.cjs"}}},sideEffects:!0,repository:{type:"git",url:"git+https://github.com/lovell/sharp.git"},keywords:["jpeg","png","webp","avif","tiff","gif","svg","jp2","dzi","image","resize","thumbnail","crop","embed","libvips","vips"],dependencies:{"@img/colour":"^1.1.0","detect-libc":"^2.1.2",semver:"^7.8.5"},optionalDependencies:{"@img/sharp-darwin-arm64":"0.35.4","@img/sharp-darwin-x64":"0.35.4","@img/sharp-freebsd-wasm32":"0.35.4","@img/sharp-libvips-darwin-arm64":"1.3.3","@img/sharp-libvips-darwin-x64":"1.3.3","@img/sharp-libvips-linux-arm":"1.3.3","@img/sharp-libvips-linux-arm64":"1.3.3","@img/sharp-libvips-linux-ppc64":"1.3.3","@img/sharp-libvips-linux-riscv64":"1.3.3","@img/sharp-libvips-linux-s390x":"1.3.3","@img/sharp-libvips-linux-x64":"1.3.3","@img/sharp-libvips-linuxmusl-arm64":"1.3.3","@img/sharp-libvips-linuxmusl-x64":"1.3.3","@img/sharp-linux-arm":"0.35.4","@img/sharp-linux-arm64":"0.35.4","@img/sharp-linux-ppc64":"0.35.4","@img/sharp-linux-riscv64":"0.35.4","@img/sharp-linux-s390x":"0.35.4","@img/sharp-linux-x64":"0.35.4","@img/sharp-linuxmusl-arm64":"0.35.4","@img/sharp-linuxmusl-x64":"0.35.4","@img/sharp-webcontainers-wasm32":"0.35.4","@img/sharp-win32-arm64":"0.35.4","@img/sharp-win32-ia32":"0.35.4","@img/sharp-win32-x64":"0.35.4"},peerDependenciesMeta:{"@types/node":{optional:!0}},devDependencies:{"@biomejs/biome":"^2.5.10","@cpplint/cli":"^0.1.0","@emnapi/runtime":"^1.11.3","@img/sharp-libvips-dev":"1.3.3","@img/sharp-libvips-dev-wasm32":"1.3.3","@img/sharp-libvips-win32-arm64":"1.3.3","@img/sharp-libvips-win32-ia32":"1.3.3","@img/sharp-libvips-win32-x64":"1.3.3","@types/node":"*",emnapi:"^1.11.3","exif-reader":"^2.0.3",yauzl:"^3.4.0",icc:"^4.0.0","node-addon-api":"^8.9.2","node-gyp":"^12.4.0",publint:"^0.3.24","tar-fs":"^3.1.3",tsd:"^0.33.0"},license:"Apache-2.0",engines:{node:">=20.9.0"},config:{libvips:">=8.18.6"},funding:{url:"https://opencollective.com/libvips"}}});import{spawnSync as NB}from"node:child_process";import{createHash as OYe}from"node:crypto";var RB,AL,bYe,Zee,MYe,tL,_Ye,Xee,TYe,Eh,NYe,RYe,kYe,vYe,$ee,PYe,Wee,GYe,FYe,eAe,LYe,UYe,AAe,eL,HYe,bD,rL=ue(()=>{RB=Je(DD(),1),AL=Je(pD(),1);OD();bYe=process.env.npm_package_config_libvips||Pg.config.libvips,Zee=RB.default.coerce(bYe).version,MYe=["darwin-arm64","darwin-x64","freebsd-arm64","freebsd-x64","linux-arm","linux-arm64","linux-ppc64","linux-riscv64","linux-s390x","linux-wasm32","linux-x64","linuxmusl-arm64","linuxmusl-x64","win32-arm64","win32-ia32","win32-x64"],tL={encoding:"utf8",shell:!0},_Ye=n=>{n instanceof Error?console.error(`sharp: Installation error: ${n.message}`):console.log(`sharp: ${n}`)},Xee=()=>AL.default.isNonGlibcLinuxSync()?AL.default.familySync():"",TYe=()=>`${process.platform}${Xee()}-${process.arch}`,Eh=()=>{if($ee())return"wasm32";let{npm_config_arch:n,npm_config_platform:t,npm_config_libc:o}=process.env,i=typeof o=="string"?o:Xee();return`${t||process.platform}${i}-${n||process.arch}`},NYe=()=>{try{return $e(`@img/sharp-libvips-dev-${Eh()}/include`)}catch{try{return $e("@img/sharp-libvips-dev/include")}catch{}}return""},RYe=()=>{try{return $e("@img/sharp-libvips-dev/cplusplus")}catch{}return""},kYe=()=>{try{return $e(`@img/sharp-libvips-dev-${Eh()}/lib`)}catch{try{return $e(`@img/sharp-libvips-${Eh()}/lib`)}catch{}}return""},vYe=()=>{if(process.release?.name==="node"&&process.versions&&!RB.default.satisfies(process.versions.node,Pg.engines.node))return{found:process.versions.node,expected:Pg.engines.node}},$ee=()=>{let{CC:n}=process.env;return!!n?.endsWith("/emcc")},PYe=()=>process.platform==="darwin"&&process.arch==="x64"?(NB("sysctl sysctl.proc_translated",tL).stdout||"").trim()==="sysctl.proc_translated: 1":!1,Wee=n=>OYe("sha512").update(n).digest("hex"),GYe=()=>{try{let n=Wee(`imgsharp-libvips-${Eh()}`),t=RB.default.coerce(Pg.optionalDependencies[`@img/sharp-libvips-${Eh()}`],{includePrerelease:!0}).version;return Wee(`${n}npm:${t}`).slice(0,10)}catch{}return""},FYe=()=>NB(`node-gyp rebuild --directory=src ${$ee()?"--nodedir=emscripten":""}`,{...tL,stdio:"inherit"}).status,eAe=()=>process.platform!=="win32"?(NB("pkg-config --modversion vips-cpp",{...tL,env:{...process.env,PKG_CONFIG_PATH:AAe()}}).stdout||"").trim():"",LYe=()=>{try{let n=(NB("brew",["--prefix"],{encoding:"utf8"}).stdout||"").trim();if(n)return`${n}/lib/pkgconfig`}catch{}},UYe=()=>{try{let n=(NB("pkg-config",["--variable","pc_path","pkg-config"],{encoding:"utf8"}).stdout||"").trim();if(n)return n}catch{}},AAe=()=>process.platform!=="win32"?[LYe(),UYe(),process.env.PKG_CONFIG_PATH].filter(Boolean).join(":"):"",eL=(n,t,o)=>(o&&o(`Detected ${t}, skipping search for globally-installed libvips`),n),HYe=n=>{if(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS)return eL(!1,"SHARP_IGNORE_GLOBAL_LIBVIPS",n);if(process.env.SHARP_FORCE_GLOBAL_LIBVIPS)return eL(!0,"SHARP_FORCE_GLOBAL_LIBVIPS",n);if(PYe())return eL(!1,"Rosetta",n);let t=eAe();return!!t&&RB.default.gte(t,Zee)},bD={minimumLibvipsVersion:Zee,prebuiltPlatforms:MYe,buildPlatformArch:Eh,buildSharpLibvipsIncludeDir:NYe,buildSharpLibvipsCPlusPlusDir:RYe,buildSharpLibvipsLibDir:kYe,isUnsupportedNodeRuntime:vYe,runtimePlatformArch:TYe,log:_Ye,yarnLocator:GYe,spawnRebuild:FYe,globalLibvipsVersion:eAe,pkgConfigPath:AAe,useGlobalLibvips:HYe}});import{createRequire as KYe}from"node:module";var MD,Yr,rAe,xYe,tAe,YYe,jYe,Gg,Gt,Vc,St,kB=ue(()=>{MD=Je(pD(),1);rL();OD();Yr=KYe(import.meta.url),{version:rAe}=Pg,{runtimePlatformArch:xYe,isUnsupportedNodeRuntime:tAe,prebuiltPlatforms:YYe,minimumLibvipsVersion:jYe}=bD,Gg=xYe(),Vc=[];try{Gt=Yr(`../src/build/Release/sharp-${Gg}-${rAe}.node`)}catch(n){Vc.push(n)}if(!Gt)try{Gt=Yr(`../src/build/Release/sharp-wasm32-${rAe}.node`)}catch(n){Vc.push(n)}if(!Gt)try{switch(Gg){case"darwin-arm64":Gt=Yr("@img/sharp-darwin-arm64/sharp.node");break;case"darwin-x64":Gt=Yr("@img/sharp-darwin-x64/sharp.node");break;case"linux-arm":Gt=Yr("@img/sharp-linux-arm/sharp.node");break;case"linux-arm64":Gt=Yr("@img/sharp-linux-arm64/sharp.node");break;case"linux-ppc64":Gt=Yr("@img/sharp-linux-ppc64/sharp.node");break;case"linux-riscv64":Gt=Yr("@img/sharp-linux-riscv64/sharp.node");break;case"linux-s390x":Gt=Yr("@img/sharp-linux-s390x/sharp.node");break;case"linux-x64":Gt=Yr("@img/sharp-linux-x64/sharp.node");break;case"linuxmusl-arm64":Gt=Yr("@img/sharp-linuxmusl-arm64/sharp.node");break;case"linuxmusl-x64":Gt=Yr("@img/sharp-linuxmusl-x64/sharp.node");break;case"win32-arm64":Gt=Yr("@img/sharp-win32-arm64/sharp.node");break;case"win32-ia32":Gt=Yr("@img/sharp-win32-ia32/sharp.node");break;case"win32-x64":Gt=Yr("@img/sharp-win32-x64/sharp.node");break;case"freebsd-arm64":case"freebsd-x64":Gt=Yr("@img/sharp-freebsd-wasm32/sharp.node");break;case"linux-wasm32":Gt=Yr("@img/sharp-webcontainers-wasm32/sharp.node");break}if(Gt&&["linux-x64","linuxmusl-x64"].includes(Gg)&&!Gt._isUsingX64V2()){let n=new Error("Prebuilt binaries for Linux x64 require v2 microarchitecture");n.code="Unsupported CPU",Vc.push(n),Gt=null}Gt&&process.versions.electron&&Gg.startsWith("linux")&&process.emitWarning("Binaries provided by Electron for use on Linux may be incompatible with sharp - see https://sharp.pixelplumbing.com/install#electron-and-linux",{code:"SharpElectronLinux"})}catch(n){Vc.push(n)}if(!Gt)try{Gt=Yr("@img/sharp-wasm32/sharp.node")}catch(n){Vc.push(n)}if(!Gt){let[n,t,o]=["linux","darwin","win32"].map(a=>Gg.startsWith(a)),i=[`Could not load the "sharp" module using the ${Gg} runtime`];Vc.forEach(a=>{a.code.endsWith("MODULE_NOT_FOUND")||i.push(`${a.code}: ${a.message}`)});let e=Vc.map(a=>a.message).join(" ");if(i.push("Possible solutions:"),tAe()){let{found:a,expected:A}=tAe();i.push("- Please upgrade Node.js:",` Found ${a}`,` Requires ${A}`)}else if(YYe.includes(Gg)){let[a,A]=Gg.split("-"),r=a.endsWith("musl")?" --libc=musl":"";i.push("- Ensure optional dependencies can be installed:"," npm install --include=optional sharp","- Ensure your package manager supports multi-platform installation:"," See https://sharp.pixelplumbing.com/install#cross-platform","- Add platform-specific dependencies:",` npm install --os=${a.replace("musl","")}${r} --cpu=${A} sharp`)}else i.push(`- Manually install libvips >= ${jYe}`," See https://sharp.pixelplumbing.com/install#building-from-source","- Add WebAssembly-based dependencies:"," npm install sharp @img/sharp-wasm32");if(n&&/(symbol not found|CXXABI_)/i.test(e))try{let{config:a}=Yr(`@img/sharp-libvips-${Gg}/package`),A=`${(0,MD.familySync)()} ${(0,MD.versionSync)()}`,r=`${a.musl?"musl":"glibc"} ${a.musl||a.glibc}`;i.push("- Update your OS:",` Found ${A}`,` Requires ${r}`)}catch{}throw n&&/\/snap\/core[0-9]{2}/.test(e)&&i.push("- Remove the Node.js Snap, which does not support native modules"," snap remove node"),t&&/Incompatible library version/.test(e)&&i.push("- Update Homebrew:"," brew update && brew upgrade vips"),Vc.some(a=>a.code==="ERR_DLOPEN_DISABLED")&&i.push("- Run Node.js without using the --no-addons flag"),o&&/The specified procedure could not be found/.test(e)&&i.push("- Using the canvas package on Windows?"," See https://sharp.pixelplumbing.com/install#canvas-and-windows","- Check for outdated versions of sharp in the dependency tree:"," npm ls sharp"),i.push("- Consult the installation documentation:"," See https://sharp.pixelplumbing.com/install"),new Error(i.join(` `))}St=Gt});import JYe from"node:util";import aL from"node:stream";function VYe(){let n=this.constructor.call(),{debuglog:t,queueListener:o,...i}=this.options;return n.options=structuredClone(i),n.options.debuglog=t,n.options.queueListener=o,this._isStreamInput()&&this._whenStreamInFinished(()=>{this._flattenBufferIn(),n.options.input.buffer=this.options.input.buffer,n.emit("finish")}),n}var qYe,zYe,Tl,bs,aAe=ue(()=>{ms();kB();qYe=JYe.debuglog("sharp"),zYe=n=>{Tl.queue.emit("change",n)},Tl=function(n,t){if(arguments.length===1&&!O.defined(n))throw new Error("Invalid input");return this instanceof Tl?(aL.Duplex.call(this),this.options={topOffsetPre:-1,leftOffsetPre:-1,widthPre:-1,heightPre:-1,topOffsetPost:-1,leftOffsetPost:-1,widthPost:-1,heightPost:-1,width:-1,height:-1,canvas:"crop",position:0,resizeBackground:[0,0,0,255],angle:0,rotationAngle:0,rotationBackground:[0,0,0,255],rotateBefore:!1,orientBefore:!1,flip:!1,flop:!1,extendTop:0,extendBottom:0,extendLeft:0,extendRight:0,extendBackground:[0,0,0,255],extendWith:"background",withoutEnlargement:!1,withoutReduction:!1,affineMatrix:[],affineBackground:[0,0,0,255],affineIdx:0,affineIdy:0,affineOdx:0,affineOdy:0,affineInterpolator:this.constructor.interpolators.bilinear,kernel:"lanczos3",fastShrinkOnLoad:!0,tint:[-1,0,0,0],flatten:!1,flattenBackground:[0,0,0],unflatten:!1,negate:!1,negateAlpha:!0,medianSize:0,blurSigma:0,precision:"integer",minAmpl:.2,sharpenSigma:0,sharpenM1:1,sharpenM2:2,sharpenX1:2,sharpenY2:10,sharpenY3:20,threshold:0,thresholdGrayscale:!0,trimBackground:[],trimThreshold:-1,trimLineArt:!1,trimMargin:0,dilateWidth:0,erodeWidth:0,gamma:0,gammaOut:0,greyscale:!1,normalise:!1,normaliseLower:1,normaliseUpper:99,claheWidth:0,claheHeight:0,claheMaxSlope:3,brightness:1,saturation:1,hue:0,lightness:0,booleanBufferIn:null,booleanFileIn:"",joinChannelIn:[],extractChannel:-1,removeAlpha:!1,ensureAlpha:-1,colourspace:"srgb",colourspacePipeline:"last",composite:[],fileOut:"",formatOut:"input",streamOut:!1,typedArrayOut:!1,keepMetadata:0,withMetadataOrientation:-1,withMetadataDensity:0,withIccProfile:"",withExif:{},withExifMerge:!0,withXmp:"",keepGainMap:!1,withGainMap:!1,resolveWithObject:!1,loop:-1,delay:[],jpegQuality:80,jpegProgressive:!1,jpegChromaSubsampling:"4:2:0",jpegTrellisQuantisation:!1,jpegOvershootDeringing:!1,jpegOptimiseScans:!1,jpegOptimiseCoding:!0,jpegQuantisationTable:0,pngProgressive:!1,pngCompressionLevel:6,pngAdaptiveFiltering:!1,pngPalette:!1,pngQuality:100,pngEffort:7,pngBitdepth:8,pngDither:1,jp2Quality:80,jp2TileHeight:512,jp2TileWidth:512,jp2Lossless:!1,jp2ChromaSubsampling:"4:4:4",webpQuality:80,webpAlphaQuality:100,webpLossless:!1,webpNearLossless:!1,webpSmartSubsample:!1,webpSmartDeblock:!1,webpPreset:"default",webpEffort:4,webpMinSize:!1,webpMixed:!1,webpExact:!1,gifBitdepth:8,gifEffort:7,gifDither:1,gifInterFrameMaxError:0,gifInterPaletteMaxError:3,gifKeepDuplicateFrames:!1,gifReuse:!0,gifProgressive:!1,tiffQuality:80,tiffCompression:"jpeg",tiffBigtiff:!1,tiffPredictor:"horizontal",tiffPyramid:!1,tiffMiniswhite:!1,tiffBitdepth:0,tiffTile:!1,tiffTileHeight:256,tiffTileWidth:256,tiffXres:1,tiffYres:1,tiffResolutionUnit:"inch",heifQuality:50,heifLossless:!1,heifCompression:"av1",heifEffort:4,heifChromaSubsampling:"4:4:4",heifBitdepth:8,heifTune:"auto",jxlDistance:1,jxlDecodingTier:0,jxlEffort:7,jxlLossless:!1,rawDepth:"uchar",tileSize:256,tileOverlap:0,tileContainer:"fs",tileLayout:"dz",tileFormat:"last",tileDepth:"last",tileAngle:0,tileSkipBlanks:-1,tileBackground:[255,255,255,255],tileCentre:!1,tileId:"https://example.com/iiif",tileBasename:"",timeoutSeconds:0,linearA:[],linearB:[],pdfBackground:[255,255,255,255],debuglog:o=>{this.emit("warning",o),qYe(o)},queueListener:zYe},this.options.input=this._createInputDescriptor(n,t,{allowStream:!0}),this):new Tl(n,t)};Object.setPrototypeOf(Tl.prototype,aL.Duplex.prototype);Object.setPrototypeOf(Tl,aL.Duplex);Object.assign(Tl.prototype,{clone:VYe});bs=Tl});function iAe(n){let t=ZYe.filter(o=>O.defined(n[o])).map(o=>[o,n[o]]);return t.length?Object.fromEntries(t):void 0}function XYe(n,t,o){let i={autoOrient:!1,failOn:"warning",limitInputPixels:268402689,limitInputChannels:5,ignoreIcc:!1,unlimited:!1,sequentialRead:!0};if(O.string(n))i.file=n;else if(O.buffer(n)){if(n.length===0)throw Error("Input Buffer is empty");i.buffer=n}else if(O.arrayBuffer(n)){if(n.byteLength===0)throw Error("Input bit Array is empty");i.buffer=Buffer.from(n,0,n.byteLength)}else if(O.typedArray(n)){if(n.length===0)throw Error("Input Bit Array is empty");i.buffer=Buffer.from(n.buffer,n.byteOffset,n.byteLength)}else if(O.plainObject(n)&&!O.defined(t))t=n,iAe(t)&&(i.buffer=[]);else if(!O.defined(n)&&!O.defined(t)&&O.object(o)&&o.allowStream)i.buffer=[];else if(Array.isArray(n))if(n.length>1)if(!this.options.joining)this.options.joining=!0,this.options.join=n.map(e=>this._createInputDescriptor(e));else throw new Error("Recursive join is unsupported");else throw new Error("Expected at least two images to join");else throw new Error(`Unsupported input '${n}' of type ${typeof n}${O.defined(t)?` when also providing options of type ${typeof t}`:""}`);if(O.object(t)){if(O.defined(t.failOn))if(O.string(t.failOn)&&O.inArray(t.failOn,["none","truncated","error","warning"]))i.failOn=t.failOn;else throw O.invalidParameterError("failOn","one of: none, truncated, error, warning",t.failOn);if(O.defined(t.autoOrient))if(O.bool(t.autoOrient))i.autoOrient=t.autoOrient;else throw O.invalidParameterError("autoOrient","boolean",t.autoOrient);if(O.defined(t.density))if(O.number(t.density)&&O.inRange(t.density,1,1e5))i.density=t.density;else throw O.invalidParameterError("density","number between 1 and 100000",t.density);if(O.defined(t.ignoreIcc))if(O.bool(t.ignoreIcc))i.ignoreIcc=t.ignoreIcc;else throw O.invalidParameterError("ignoreIcc","boolean",t.ignoreIcc);if(O.defined(t.limitInputPixels))if(O.bool(t.limitInputPixels))i.limitInputPixels=t.limitInputPixels?16383**2:0;else if(O.integer(t.limitInputPixels)&&O.inRange(t.limitInputPixels,0,Number.MAX_SAFE_INTEGER))i.limitInputPixels=t.limitInputPixels;else throw O.invalidParameterError("limitInputPixels","positive integer",t.limitInputPixels);if(O.defined(t.limitInputChannels))if(O.bool(t.limitInputChannels))i.limitInputChannels=t.limitInputChannels?5:0;else if(O.integer(t.limitInputChannels)&&O.inRange(t.limitInputChannels,0,Number.MAX_SAFE_INTEGER))i.limitInputChannels=t.limitInputChannels;else throw O.invalidParameterError("limitInputChannels","positive integer",t.limitInputChannels);if(O.defined(t.unlimited))if(O.bool(t.unlimited))i.unlimited=t.unlimited;else throw O.invalidParameterError("unlimited","boolean",t.unlimited);if(O.defined(t.sequentialRead))if(O.bool(t.sequentialRead))i.sequentialRead=t.sequentialRead;else throw O.invalidParameterError("sequentialRead","boolean",t.sequentialRead);if(O.defined(t.raw)){if(O.object(t.raw)&&O.integer(t.raw.width)&&O.inRange(t.raw.width,1,1e8)&&O.integer(t.raw.height)&&O.inRange(t.raw.height,1,1e8)&&O.integer(t.raw.channels)&&O.inRange(t.raw.channels,1,4))switch(i.rawWidth=t.raw.width,i.rawHeight=t.raw.height,i.rawChannels=t.raw.channels,n.constructor){case Uint8Array:case Uint8ClampedArray:i.rawDepth="uchar";break;case Int8Array:i.rawDepth="char";break;case Uint16Array:i.rawDepth="ushort";break;case Int16Array:i.rawDepth="short";break;case Uint32Array:i.rawDepth="uint";break;case Int32Array:i.rawDepth="int";break;case Float32Array:i.rawDepth="float";break;case Float64Array:i.rawDepth="double";break;default:i.rawDepth="uchar";break}else throw new Error("Expected width, height and channels for raw pixel input");if(i.rawPremultiplied=!1,O.defined(t.raw.premultiplied))if(O.bool(t.raw.premultiplied))i.rawPremultiplied=t.raw.premultiplied;else throw O.invalidParameterError("raw.premultiplied","boolean",t.raw.premultiplied);if(i.rawPageHeight=0,O.defined(t.raw.pageHeight))if(O.integer(t.raw.pageHeight)&&t.raw.pageHeight>0&&t.raw.pageHeight<=t.raw.height){if(t.raw.height%t.raw.pageHeight!==0)throw new Error(`Expected raw.height ${t.raw.height} to be a multiple of raw.pageHeight ${t.raw.pageHeight}`);i.rawPageHeight=t.raw.pageHeight}else throw O.invalidParameterError("raw.pageHeight","positive integer",t.raw.pageHeight)}if(O.defined(t.animated))if(O.bool(t.animated))i.pages=t.animated?-1:1;else throw O.invalidParameterError("animated","boolean",t.animated);if(O.defined(t.pages))if(O.integer(t.pages)&&O.inRange(t.pages,-1,1e5))i.pages=t.pages;else throw O.invalidParameterError("pages","integer between -1 and 100000",t.pages);if(O.defined(t.page))if(O.integer(t.page)&&O.inRange(t.page,0,1e5))i.page=t.page;else throw O.invalidParameterError("page","integer between 0 and 100000",t.page);if(O.object(t.openSlide)&&O.defined(t.openSlide.level))if(O.integer(t.openSlide.level)&&O.inRange(t.openSlide.level,0,256))i.openSlideLevel=t.openSlide.level;else throw O.invalidParameterError("openSlide.level","integer between 0 and 256",t.openSlide.level);else if(O.defined(t.level))if(O.integer(t.level)&&O.inRange(t.level,0,256))i.openSlideLevel=t.level;else throw O.invalidParameterError("level","integer between 0 and 256",t.level);if(O.object(t.tiff)&&O.defined(t.tiff.subifd))if(O.integer(t.tiff.subifd)&&O.inRange(t.tiff.subifd,-1,1e5))i.tiffSubifd=t.tiff.subifd;else throw O.invalidParameterError("tiff.subifd","integer between -1 and 100000",t.tiff.subifd);else if(O.defined(t.subifd))if(O.integer(t.subifd)&&O.inRange(t.subifd,-1,1e5))i.tiffSubifd=t.subifd;else throw O.invalidParameterError("subifd","integer between -1 and 100000",t.subifd);if(O.object(t.svg)){if(O.defined(t.svg.stylesheet))if(O.string(t.svg.stylesheet))i.svgStylesheet=t.svg.stylesheet;else throw O.invalidParameterError("svg.stylesheet","string",t.svg.stylesheet);if(O.defined(t.svg.highBitdepth))if(O.bool(t.svg.highBitdepth))i.svgHighBitdepth=t.svg.highBitdepth;else throw O.invalidParameterError("svg.highBitdepth","boolean",t.svg.highBitdepth)}if(O.object(t.pdf)&&O.defined(t.pdf.background)?i.pdfBackground=this._getBackgroundColourOption(t.pdf.background):O.defined(t.pdfBackground)&&(i.pdfBackground=this._getBackgroundColourOption(t.pdfBackground)),O.object(t.jp2)&&O.defined(t.jp2.oneshot))if(O.bool(t.jp2.oneshot))i.jp2Oneshot=t.jp2.oneshot;else throw O.invalidParameterError("jp2.oneshot","boolean",t.jp2.oneshot);if(O.defined(t.create))if(O.object(t.create)&&O.integer(t.create.width)&&O.inRange(t.create.width,1,1e8)&&O.integer(t.create.height)&&O.inRange(t.create.height,1,1e8)&&O.integer(t.create.channels)){if(i.createWidth=t.create.width,i.createHeight=t.create.height,i.createChannels=t.create.channels,i.createPageHeight=0,O.defined(t.create.pageHeight))if(O.integer(t.create.pageHeight)&&t.create.pageHeight>0&&t.create.pageHeight<=t.create.height){if(t.create.height%t.create.pageHeight!==0)throw new Error(`Expected create.height ${t.create.height} to be a multiple of create.pageHeight ${t.create.pageHeight}`);i.createPageHeight=t.create.pageHeight}else throw O.invalidParameterError("create.pageHeight","positive integer",t.create.pageHeight);if(O.defined(t.create.noise)){if(!O.object(t.create.noise))throw new Error("Expected noise to be an object");if(t.create.noise.type!=="gaussian")throw new Error("Only gaussian noise is supported at the moment");if(i.createNoiseType=t.create.noise.type,!O.inRange(t.create.channels,1,4))throw O.invalidParameterError("create.channels","number between 1 and 4",t.create.channels);if(i.createNoiseMean=128,O.defined(t.create.noise.mean))if(O.number(t.create.noise.mean)&&O.inRange(t.create.noise.mean,0,1e4))i.createNoiseMean=t.create.noise.mean;else throw O.invalidParameterError("create.noise.mean","number between 0 and 10000",t.create.noise.mean);if(i.createNoiseSigma=30,O.defined(t.create.noise.sigma))if(O.number(t.create.noise.sigma)&&O.inRange(t.create.noise.sigma,0,1e4))i.createNoiseSigma=t.create.noise.sigma;else throw O.invalidParameterError("create.noise.sigma","number between 0 and 10000",t.create.noise.sigma)}else if(O.defined(t.create.background)){if(!O.inRange(t.create.channels,3,4))throw O.invalidParameterError("create.channels","number between 3 and 4",t.create.channels);i.createBackground=this._getBackgroundColourOption(t.create.background)}else throw new Error("Expected valid noise or background to create a new input image");delete i.buffer}else throw new Error("Expected valid width, height and channels to create a new input image");if(O.defined(t.text))if(O.object(t.text)&&O.string(t.text.text)){if(i.textValue=t.text.text,O.defined(t.text.height)&&O.defined(t.text.dpi))throw new Error("Expected only one of dpi or height");if(O.defined(t.text.font))if(O.string(t.text.font))i.textFont=t.text.font;else throw O.invalidParameterError("text.font","string",t.text.font);if(O.defined(t.text.fontfile))if(O.string(t.text.fontfile))i.textFontfile=t.text.fontfile;else throw O.invalidParameterError("text.fontfile","string",t.text.fontfile);if(O.defined(t.text.width))if(O.integer(t.text.width)&&O.inRange(t.text.width,1,1e6))i.textWidth=t.text.width;else throw O.invalidParameterError("text.width","integer between 1 and 1000000",t.text.width);if(O.defined(t.text.height))if(O.integer(t.text.height)&&O.inRange(t.text.height,1,1e6))i.textHeight=t.text.height;else throw O.invalidParameterError("text.height","integer between 1 and 1000000",t.text.height);if(O.defined(t.text.align))if(O.string(t.text.align)&&O.string(this.constructor.align[t.text.align]))i.textAlign=this.constructor.align[t.text.align];else throw O.invalidParameterError("text.align","valid alignment",t.text.align);if(O.defined(t.text.justify))if(O.bool(t.text.justify))i.textJustify=t.text.justify;else throw O.invalidParameterError("text.justify","boolean",t.text.justify);if(O.defined(t.text.dpi))if(O.integer(t.text.dpi)&&O.inRange(t.text.dpi,1,1e6))i.textDpi=t.text.dpi;else throw O.invalidParameterError("text.dpi","integer between 1 and 1000000",t.text.dpi);if(O.defined(t.text.rgba))if(O.bool(t.text.rgba))i.textRgba=t.text.rgba;else throw O.invalidParameterError("text.rgba","bool",t.text.rgba);if(O.defined(t.text.spacing))if(O.integer(t.text.spacing)&&O.inRange(t.text.spacing,-1e6,1e6))i.textSpacing=t.text.spacing;else throw O.invalidParameterError("text.spacing","integer between -1000000 and 1000000",t.text.spacing);if(O.defined(t.text.wrap))if(O.string(t.text.wrap)&&O.inArray(t.text.wrap,["word","char","word-char","none"]))i.textWrap=t.text.wrap;else throw O.invalidParameterError("text.wrap","one of: word, char, word-char, none",t.text.wrap);delete i.buffer}else throw new Error("Expected a valid string to create an image with text.");if(O.defined(t.join))if(O.defined(this.options.join)){if(O.defined(t.join.animated))if(O.bool(t.join.animated))i.joinAnimated=t.join.animated;else throw O.invalidParameterError("join.animated","boolean",t.join.animated);if(O.defined(t.join.across))if(O.integer(t.join.across)&&O.inRange(t.join.across,1,1e6))i.joinAcross=t.join.across;else throw O.invalidParameterError("join.across","integer between 1 and 100000",t.join.across);if(O.defined(t.join.shim))if(O.integer(t.join.shim)&&O.inRange(t.join.shim,0,1e6))i.joinShim=t.join.shim;else throw O.invalidParameterError("join.shim","integer between 0 and 100000",t.join.shim);if(O.defined(t.join.background)&&(i.joinBackground=this._getBackgroundColourOption(t.join.background)),O.defined(t.join.halign))if(O.string(t.join.halign)&&O.string(this.constructor.align[t.join.halign]))i.joinHalign=this.constructor.align[t.join.halign];else throw O.invalidParameterError("join.halign","valid alignment",t.join.halign);if(O.defined(t.join.valign))if(O.string(t.join.valign)&&O.string(this.constructor.align[t.join.valign]))i.joinValign=this.constructor.align[t.join.valign];else throw O.invalidParameterError("join.valign","valid alignment",t.join.valign)}else throw new Error("Expected input to be an array of images to join")}else if(O.defined(t))throw new Error(`Invalid input options ${t}`);return i}function $Ye(n,t,o){Array.isArray(this.options.input.buffer)?O.buffer(n)?(this.options.input.buffer.push(n),o()):o(new Error("Non-Buffer data on Writable Stream")):o(new Error("Unexpected data on Writable Stream"))}function e1e(){this._isStreamInput()&&(this.options.input.buffer=Buffer.concat(this.options.input.buffer))}function A1e(){return Array.isArray(this.options.input.buffer)}function t1e(n){this.writableFinished?n():this.once("finish",n)}function r1e(n){let t=Error();return O.fn(n)?(this._isStreamInput()?this._whenStreamInFinished(()=>{this._flattenBufferIn(),St.metadata(this.options,(o,i)=>{o?n(O.nativeError(o,t)):n(null,i)})}):St.metadata(this.options,(o,i)=>{o?n(O.nativeError(o,t)):n(null,i)}),this):this._isStreamInput()?new Promise((o,i)=>{this._whenStreamInFinished(()=>{this._flattenBufferIn(),St.metadata(this.options,(e,a)=>{e?i(O.nativeError(e,t)):o(a)})})}):new Promise((o,i)=>{St.metadata(this.options,(e,a)=>{e?i(O.nativeError(e,t)):o(a)})})}function a1e(n){let t=Error();return O.fn(n)?(this._isStreamInput()?this._whenStreamInFinished(()=>{this._flattenBufferIn(),St.stats(this.options,(o,i)=>{o?n(O.nativeError(o,t)):n(null,i)})}):St.stats(this.options,(o,i)=>{o?n(O.nativeError(o,t)):n(null,i)}),this):this._isStreamInput()?new Promise((o,i)=>{this._whenStreamInFinished(()=>{this._flattenBufferIn(),St.stats(this.options,(e,a)=>{e?i(O.nativeError(e,t)):o(a)})})}):new Promise((o,i)=>{St.stats(this.options,(e,a)=>{e?i(O.nativeError(e,t)):o(a)})})}var WYe,ZYe,oAe,nAe=ue(()=>{ms();kB();WYe={left:"low",top:"low",low:"low",center:"centre",centre:"centre",right:"high",bottom:"high",high:"high"},ZYe=["failOn","limitInputPixels","limitInputChannels","unlimited","animated","autoOrient","density","ignoreIcc","page","pages","sequentialRead","jp2","openSlide","pdf","raw","svg","tiff","openSlideLevel","pdfBackground","tiffSubifd"];oAe=n=>{Object.assign(n.prototype,{_inputOptionsFromObject:iAe,_createInputDescriptor:XYe,_write:$Ye,_flattenBufferIn:e1e,_isStreamInput:A1e,_whenStreamInFinished:t1e,metadata:r1e,stats:a1e}),n.align=WYe}});function oL(n){return n.angle%360!==0||n.rotationAngle!==0}function _D(n){return n.width!==-1||n.height!==-1}function n1e(n,t,o){if(_D(this.options)&&this.options.debuglog("ignoring previous resize options"),this.options.widthPost!==-1&&this.options.debuglog("operation order will be: extract, resize, extract"),O.defined(n))if(O.object(n)&&!O.defined(o))o=n;else if(O.integer(n)&&O.inRange(n,1,1e8))this.options.width=n;else throw O.invalidParameterError("width","positive integer between 1 and 100000000",n);else this.options.width=-1;if(O.defined(t))if(O.integer(t)&&O.inRange(t,1,1e8))this.options.height=t;else throw O.invalidParameterError("height","positive integer between 1 and 100000000",t);else this.options.height=-1;if(O.object(o)){if(O.defined(o.width))if(O.integer(o.width)&&O.inRange(o.width,1,1e8))this.options.width=o.width;else throw O.invalidParameterError("width","positive integer between 1 and 100000000",o.width);if(O.defined(o.height))if(O.integer(o.height)&&O.inRange(o.height,1,1e8))this.options.height=o.height;else throw O.invalidParameterError("height","positive integer between 1 and 100000000",o.height);if(O.defined(o.fit)){let i=o1e[o.fit];if(O.string(i))this.options.canvas=i;else throw O.invalidParameterError("fit","valid fit",o.fit)}if(O.defined(o.position)){let i=O.integer(o.position)?o.position:IAe[o.position]||cAe[o.position]||gAe[o.position];if(O.integer(i)&&(O.inRange(i,0,8)||O.inRange(i,16,17)))this.options.position=i;else throw O.invalidParameterError("position","valid position/gravity/strategy",o.position)}if(this._setBackgroundColourOption("resizeBackground",o.background),O.defined(o.kernel))if(O.string(iL[o.kernel]))this.options.kernel=iL[o.kernel];else throw O.invalidParameterError("kernel","valid kernel name",o.kernel);O.defined(o.withoutEnlargement)&&this._setBooleanOption("withoutEnlargement",o.withoutEnlargement),O.defined(o.withoutReduction)&&this._setBooleanOption("withoutReduction",o.withoutReduction),O.defined(o.fastShrinkOnLoad)&&this._setBooleanOption("fastShrinkOnLoad",o.fastShrinkOnLoad)}return oL(this.options)&&_D(this.options)&&(this.options.rotateBefore=!0),this}function s1e(n){if(O.integer(n))if(O.inRange(n,1,1e4))this.options.extendTop=n,this.options.extendBottom=n,this.options.extendLeft=n,this.options.extendRight=n;else throw O.invalidParameterError("extend","integer between 1 and 10000",n);else if(O.object(n)){if(O.defined(n.top))if(O.integer(n.top)&&O.inRange(n.top,0,1e4))this.options.extendTop=n.top;else throw O.invalidParameterError("top","integer between 0 and 10000",n.top);if(O.defined(n.bottom))if(O.integer(n.bottom)&&O.inRange(n.bottom,0,1e4))this.options.extendBottom=n.bottom;else throw O.invalidParameterError("bottom","integer between 0 and 10000",n.bottom);if(O.defined(n.left))if(O.integer(n.left)&&O.inRange(n.left,0,1e4))this.options.extendLeft=n.left;else throw O.invalidParameterError("left","integer between 0 and 10000",n.left);if(O.defined(n.right))if(O.integer(n.right)&&O.inRange(n.right,0,1e4))this.options.extendRight=n.right;else throw O.invalidParameterError("right","integer between 0 and 10000",n.right);if(this._setBackgroundColourOption("extendBackground",n.background),O.defined(n.extendWith))if(O.string(sAe[n.extendWith]))this.options.extendWith=sAe[n.extendWith];else throw O.invalidParameterError("extendWith","one of: background, copy, repeat, mirror",n.extendWith)}else throw O.invalidParameterError("extend","integer or object",n);return this}function g1e(n){let t=_D(this.options)||this.options.widthPre!==-1?"Post":"Pre";return this.options[`width${t}`]!==-1&&this.options.debuglog("ignoring previous extract options"),["left","top","width","height"].forEach(function(o){let i=n[o];if(O.integer(i)&&O.inRange(i,0,1e8))this.options[o+(o==="left"||o==="top"?"Offset":"")+t]=i;else throw O.invalidParameterError(o,"integer between 0 and 100000000",i)},this),oL(this.options)&&!_D(this.options)&&(this.options.widthPre===-1||this.options.widthPost===-1)&&(this.options.rotateBefore=!0),this.options.input.autoOrient&&(this.options.orientBefore=!0),this}function c1e(n){if(this.options.trimThreshold=10,O.defined(n))if(O.object(n)){if(O.defined(n.background)&&this._setBackgroundColourOption("trimBackground",n.background),O.defined(n.threshold))if(O.number(n.threshold)&&n.threshold>=0)this.options.trimThreshold=n.threshold;else throw O.invalidParameterError("threshold","positive number",n.threshold);if(O.defined(n.lineArt)&&this._setBooleanOption("trimLineArt",n.lineArt),O.defined(n.margin))if(O.integer(n.margin)&&O.inRange(n.margin,0,1e7))this.options.trimMargin=n.margin;else throw O.invalidParameterError("margin","integer between 0 and 10000000",n.margin)}else throw O.invalidParameterError("trim","object",n);return oL(this.options)&&(this.options.rotateBefore=!0),this}var gAe,cAe,sAe,IAe,iL,i1e,o1e,lAe,pAe=ue(()=>{ms();gAe={center:0,centre:0,north:1,east:2,south:3,west:4,northeast:5,southeast:6,southwest:7,northwest:8},cAe={top:1,right:2,bottom:3,left:4,"right top":5,"right bottom":6,"left bottom":7,"left top":8},sAe={background:"background",copy:"copy",repeat:"repeat",mirror:"mirror"},IAe={entropy:16,attention:17},iL={nearest:"nearest",linear:"linear",cubic:"cubic",mitchell:"mitchell",lanczos2:"lanczos2",lanczos3:"lanczos3",mks2013:"mks2013",mks2021:"mks2021"},i1e={contain:"contain",cover:"cover",fill:"fill",inside:"inside",outside:"outside"},o1e={contain:"embed",cover:"crop",fill:"ignore_aspect",inside:"max",outside:"min"};lAe=n=>{Object.assign(n.prototype,{resize:n1e,extend:s1e,extract:g1e,trim:c1e}),n.gravity=gAe,n.strategy=IAe,n.kernel=iL,n.fit=i1e,n.position=cAe}});function I1e(n){if(!Array.isArray(n))throw O.invalidParameterError("images to composite","array",n);return this.options.composite=n.map(t=>{if(!O.object(t))throw O.invalidParameterError("image to composite","object",t);let o=this._inputOptionsFromObject(t),i={input:this._createInputDescriptor(t.input,o,{allowStream:!1}),blend:"over",tile:!1,left:0,top:0,hasOffset:!1,gravity:0,premultiplied:!1};if(O.defined(t.blend))if(O.string(nL[t.blend]))i.blend=nL[t.blend];else throw O.invalidParameterError("blend","valid blend name",t.blend);if(O.defined(t.tile))if(O.bool(t.tile))i.tile=t.tile;else throw O.invalidParameterError("tile","boolean",t.tile);if(O.defined(t.left))if(O.integer(t.left)&&O.inRange(t.left,-1e8,1e8))i.left=t.left;else throw O.invalidParameterError("left","integer between -100000000 and 100000000",t.left);if(O.defined(t.top))if(O.integer(t.top)&&O.inRange(t.top,-1e8,1e8))i.top=t.top;else throw O.invalidParameterError("top","integer between -100000000 and 100000000",t.top);if(O.defined(t.top)!==O.defined(t.left))throw new Error("Expected both left and top to be set");if(i.hasOffset=O.integer(t.top)&&O.integer(t.left),O.defined(t.gravity))if(O.integer(t.gravity)&&O.inRange(t.gravity,0,8))i.gravity=t.gravity;else if(O.string(t.gravity)&&O.integer(this.constructor.gravity[t.gravity]))i.gravity=this.constructor.gravity[t.gravity];else throw O.invalidParameterError("gravity","valid gravity",t.gravity);if(O.defined(t.premultiplied))if(O.bool(t.premultiplied))i.premultiplied=t.premultiplied;else throw O.invalidParameterError("premultiplied","boolean",t.premultiplied);return i}),this}var nL,dAe,hAe=ue(()=>{ms();nL={clear:"clear",source:"source",over:"over",in:"in",out:"out",atop:"atop",dest:"dest","dest-over":"dest-over","dest-in":"dest-in","dest-out":"dest-out","dest-atop":"dest-atop",xor:"xor",add:"add",saturate:"saturate",multiply:"multiply",screen:"screen",overlay:"overlay",darken:"darken",lighten:"lighten","colour-dodge":"colour-dodge","color-dodge":"colour-dodge","colour-burn":"colour-burn","color-burn":"colour-burn","hard-light":"hard-light","soft-light":"soft-light",difference:"difference",exclusion:"exclusion"};dAe=n=>{n.prototype.composite=I1e,n.blend=nL}});function l1e(n,t){if(!O.defined(n))return this.autoOrient();if((this.options.angle||this.options.rotationAngle)&&(this.options.debuglog("ignoring previous rotate options"),this.options.angle=0,this.options.rotationAngle=0),O.integer(n)&&!(n%90))this.options.angle=n;else if(O.number(n))this.options.rotationAngle=n,O.object(t)&&t.background&&this._setBackgroundColourOption("rotationBackground",t.background);else throw O.invalidParameterError("angle","numeric",n);return this}function p1e(){return this.options.input.autoOrient=!0,this}function d1e(n){return this.options.flip=O.bool(n)?n:!0,this}function h1e(n){return this.options.flop=O.bool(n)?n:!0,this}function E1e(n,t){let i=Array.isArray(n)&&(n.length===4&&n.every(O.number)||n.length===2&&n.every(e=>Array.isArray(e)&&e.length===2))?n.flat():[];if(i.length===4&&i.every(O.number))this.options.affineMatrix=i;else throw O.invalidParameterError("matrix","1x4 or 2x2 array",n);if(O.defined(t))if(O.object(t)){if(this._setBackgroundColourOption("affineBackground",t.background),O.defined(t.idx))if(O.number(t.idx))this.options.affineIdx=t.idx;else throw O.invalidParameterError("options.idx","number",t.idx);if(O.defined(t.idy))if(O.number(t.idy))this.options.affineIdy=t.idy;else throw O.invalidParameterError("options.idy","number",t.idy);if(O.defined(t.odx))if(O.number(t.odx))this.options.affineOdx=t.odx;else throw O.invalidParameterError("options.odx","number",t.odx);if(O.defined(t.ody))if(O.number(t.ody))this.options.affineOdy=t.ody;else throw O.invalidParameterError("options.ody","number",t.ody);if(O.defined(t.interpolator))if(O.inArray(t.interpolator,Object.values(this.constructor.interpolators)))this.options.affineInterpolator=t.interpolator;else throw O.invalidParameterError("options.interpolator","valid interpolator name",t.interpolator)}else throw O.invalidParameterError("options","object",t);return this}function C1e(n){if(O.plainObject(n)){if(O.number(n.sigma)&&O.inRange(n.sigma,1e-6,10))this.options.sharpenSigma=n.sigma;else throw O.invalidParameterError("options.sigma","number between 0.000001 and 10",n.sigma);if(O.defined(n.m1))if(O.number(n.m1)&&O.inRange(n.m1,0,1e6))this.options.sharpenM1=n.m1;else throw O.invalidParameterError("options.m1","number between 0 and 1000000",n.m1);if(O.defined(n.m2))if(O.number(n.m2)&&O.inRange(n.m2,0,1e6))this.options.sharpenM2=n.m2;else throw O.invalidParameterError("options.m2","number between 0 and 1000000",n.m2);if(O.defined(n.x1))if(O.number(n.x1)&&O.inRange(n.x1,0,1e6))this.options.sharpenX1=n.x1;else throw O.invalidParameterError("options.x1","number between 0 and 1000000",n.x1);if(O.defined(n.y2))if(O.number(n.y2)&&O.inRange(n.y2,0,1e6))this.options.sharpenY2=n.y2;else throw O.invalidParameterError("options.y2","number between 0 and 1000000",n.y2);if(O.defined(n.y3))if(O.number(n.y3)&&O.inRange(n.y3,0,1e6))this.options.sharpenY3=n.y3;else throw O.invalidParameterError("options.y3","number between 0 and 1000000",n.y3)}else this.options.sharpenSigma=-1;return this}function u1e(n){if(!O.defined(n))this.options.medianSize=3;else if(O.integer(n)&&O.inRange(n,1,1e3))this.options.medianSize=n;else throw O.invalidParameterError("size","integer between 1 and 1000",n);return this}function B1e(n){let t;if(O.number(n))t=n;else if(O.plainObject(n)){if(!O.number(n.sigma))throw O.invalidParameterError("options.sigma","number between 0.3 and 1000",t);if(t=n.sigma,"precision"in n)if(O.string(EAe[n.precision]))this.options.precision=EAe[n.precision];else throw O.invalidParameterError("precision","one of: integer, float, approximate",n.precision);if("minAmplitude"in n)if(O.number(n.minAmplitude)&&O.inRange(n.minAmplitude,.001,1))this.options.minAmpl=n.minAmplitude;else throw O.invalidParameterError("minAmplitude","number between 0.001 and 1",n.minAmplitude)}if(!O.defined(n))this.options.blurSigma=-1;else if(O.bool(n))this.options.blurSigma=n?-1:0;else if(O.number(t)&&O.inRange(t,.3,1e3))this.options.blurSigma=t;else throw O.invalidParameterError("sigma","number between 0.3 and 1000",t);return this}function f1e(n){if(!O.defined(n))this.options.dilateWidth=1;else if(O.integer(n)&&O.inRange(n,1,65536))this.options.dilateWidth=n;else throw O.invalidParameterError("width","integer between 1 and 65536",n);return this}function Q1e(n){if(!O.defined(n))this.options.erodeWidth=1;else if(O.integer(n)&&O.inRange(n,1,65536))this.options.erodeWidth=n;else throw O.invalidParameterError("width","integer between 1 and 65536",n);return this}function y1e(n){return this.options.flatten=O.bool(n)?n:!0,O.object(n)&&this._setBackgroundColourOption("flattenBackground",n.background),this}function m1e(){return this.options.unflatten=!0,this}function S1e(n,t){if(!O.defined(n))this.options.gamma=2.2;else if(O.number(n)&&O.inRange(n,1,3))this.options.gamma=n;else throw O.invalidParameterError("gamma","number between 1.0 and 3.0",n);if(!O.defined(t))this.options.gammaOut=this.options.gamma;else if(O.number(t)&&O.inRange(t,1,3))this.options.gammaOut=t;else throw O.invalidParameterError("gammaOut","number between 1.0 and 3.0",t);return this}function w1e(n){if(this.options.negate=O.bool(n)?n:!0,O.plainObject(n)&&"alpha"in n)if(O.bool(n.alpha))this.options.negateAlpha=n.alpha;else throw O.invalidParameterError("alpha","should be boolean value",n.alpha);return this}function D1e(n){if(O.plainObject(n)){if(O.defined(n.lower))if(O.number(n.lower)&&O.inRange(n.lower,0,99))this.options.normaliseLower=n.lower;else throw O.invalidParameterError("lower","number between 0 and 99",n.lower);if(O.defined(n.upper))if(O.number(n.upper)&&O.inRange(n.upper,1,100))this.options.normaliseUpper=n.upper;else throw O.invalidParameterError("upper","number between 1 and 100",n.upper)}if(this.options.normaliseLower>=this.options.normaliseUpper)throw O.invalidParameterError("range","lower to be less than upper",`${this.options.normaliseLower} >= ${this.options.normaliseUpper}`);return this.options.normalise=!0,this}function O1e(n){return this.normalise(n)}function b1e(n){if(O.plainObject(n)){if(O.integer(n.width)&&O.inRange(n.width,1,65536))this.options.claheWidth=n.width;else throw O.invalidParameterError("width","integer between 1 and 65536",n.width);if(O.integer(n.height)&&O.inRange(n.height,1,65536))this.options.claheHeight=n.height;else throw O.invalidParameterError("height","integer between 1 and 65536",n.height);if(O.defined(n.maxSlope))if(O.integer(n.maxSlope)&&O.inRange(n.maxSlope,0,100))this.options.claheMaxSlope=n.maxSlope;else throw O.invalidParameterError("maxSlope","integer between 0 and 100",n.maxSlope)}else throw O.invalidParameterError("options","plain object",n);return this}function M1e(n){if(!O.object(n)||!Array.isArray(n.kernel)||!O.integer(n.width)||!O.integer(n.height)||!O.inRange(n.width,3,1001)||!O.inRange(n.height,3,1001)||n.height*n.width!==n.kernel.length||!n.kernel.every(O.number))throw new Error("Invalid convolution kernel");return O.integer(n.scale)||(n.scale=n.kernel.reduce((t,o)=>t+o,0)),n.scale<1&&(n.scale=1),O.integer(n.offset)||(n.offset=0),this.options.convKernel=n,this}function _1e(n,t){if(!O.defined(n))this.options.threshold=128;else if(O.bool(n))this.options.threshold=n?128:0;else if(O.integer(n)&&O.inRange(n,0,255))this.options.threshold=n;else throw O.invalidParameterError("threshold","integer between 0 and 255",n);return!O.object(t)||t.greyscale===!0||t.grayscale===!0?this.options.thresholdGrayscale=!0:this.options.thresholdGrayscale=!1,this}function T1e(n,t,o){if(this.options.boolean=this._createInputDescriptor(n,o),O.string(t)&&O.inArray(t,["and","or","eor"]))this.options.booleanOp=t;else throw O.invalidParameterError("operator","one of: and, or, eor",t);return this}function N1e(n,t){if(!O.defined(n)&&O.number(t)?n=1:O.number(n)&&!O.defined(t)&&(t=0),!O.defined(n))this.options.linearA=[];else if(O.number(n))this.options.linearA=[n];else if(Array.isArray(n)&&n.length&&n.every(O.number))this.options.linearA=n;else throw O.invalidParameterError("a","number or array of numbers",n);if(!O.defined(t))this.options.linearB=[];else if(O.number(t))this.options.linearB=[t];else if(Array.isArray(t)&&t.length&&t.every(O.number))this.options.linearB=t;else throw O.invalidParameterError("b","number or array of numbers",t);if(this.options.linearA.length!==this.options.linearB.length)throw new Error("Expected a and b to be arrays of the same length");return this}function R1e(n){if(!Array.isArray(n))throw O.invalidParameterError("inputMatrix","array",n);let t=n.length;if(t!==3&&t!==4)throw O.invalidParameterError("inputMatrix","3x3 or 4x4 array",t);if(!n.every(i=>Array.isArray(i)&&i.length===t))throw O.invalidParameterError("inputMatrix",`array of ${t} arrays of length ${t}`,n);let o=n.flat();if(!o.every(O.number))throw O.invalidParameterError("inputMatrix","array of numbers",o);return this.options.recombMatrix=o,this}function k1e(n){if(!O.plainObject(n))throw O.invalidParameterError("options","plain object",n);if("brightness"in n)if(O.number(n.brightness)&&n.brightness>=0)this.options.brightness=n.brightness;else throw O.invalidParameterError("brightness","number above zero",n.brightness);if("saturation"in n)if(O.number(n.saturation)&&n.saturation>=0)this.options.saturation=n.saturation;else throw O.invalidParameterError("saturation","number above zero",n.saturation);if("hue"in n)if(O.integer(n.hue))this.options.hue=n.hue%360;else throw O.invalidParameterError("hue","number",n.hue);if("lightness"in n)if(O.number(n.lightness))this.options.lightness=n.lightness;else throw O.invalidParameterError("lightness","number",n.lightness);return this}var EAe,CAe,uAe=ue(()=>{ms();EAe={integer:"integer",float:"float",approximate:"approximate"};CAe=n=>{Object.assign(n.prototype,{autoOrient:p1e,rotate:l1e,flip:d1e,flop:h1e,affine:E1e,sharpen:C1e,erode:Q1e,dilate:f1e,median:u1e,blur:B1e,flatten:y1e,unflatten:m1e,gamma:S1e,negate:w1e,normalise:D1e,normalize:O1e,clahe:b1e,convolve:M1e,threshold:_1e,boolean:T1e,linear:N1e,recomb:R1e,modulate:k1e})}});var SAe=$((PyA,mAe)=>{var lL=Object.defineProperty,v1e=Object.getOwnPropertyDescriptor,P1e=Object.getOwnPropertyNames,G1e=Object.prototype.hasOwnProperty,F1e=(n,t)=>{for(var o in t)lL(n,o,{get:t[o],enumerable:!0})},L1e=(n,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of P1e(t))!G1e.call(n,e)&&e!==o&&lL(n,e,{get:()=>t[e],enumerable:!(i=v1e(t,e))||i.enumerable});return n},U1e=n=>L1e(lL({},"__esModule",{value:!0}),n),BAe={};F1e(BAe,{default:()=>e3e});mAe.exports=U1e(BAe);var sL={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};for(let n in sL)Object.freeze(sL[n]);var Ms=Object.freeze(sL),fAe=Object.create(null);for(let n in Ms)Object.hasOwn(Ms,n)&&(fAe[Ms[n]]=n);var Ui={to:{},get:{}};Ui.get=function(n){let t=n.slice(0,3).toLowerCase(),o,i;switch(t){case"hsl":{o=Ui.get.hsl(n),i="hsl";break}case"hwb":{o=Ui.get.hwb(n),i="hwb";break}default:{o=Ui.get.rgb(n),i="rgb";break}}return o?{model:i,value:o}:null};Ui.get.rgb=function(n){if(!n)return null;let t=/^#([a-f\d]{3,4})$/i,o=/^#([a-f\d]{6})([a-f\d]{2})?$/i,i=/^rgba?\(\s*([+-]?(?:\d*\.)?\d+(?:e\d+)?)(?=[\s,])\s*(?:,\s*)?([+-]?(?:\d*\.)?\d+(?:e\d+)?)(?=[\s,])\s*(?:,\s*)?([+-]?(?:\d*\.)?\d+(?:e\d+)?)\s*(?:[\s,|/]\s*([+-]?(?:\d*\.)?\d+(?:e\d+)?)(%?)\s*)?\)$/i,e=/^rgba?\(\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/i,a=/^(\w+)$/,A=[0,0,0,1],r,s,g;if(r=n.match(o)){for(g=r[2],r=r[1],s=0;s<3;s++){let c=s*2;A[s]=Number.parseInt(r.slice(c,c+2),16)}g&&(A[3]=Number.parseInt(g,16)/255)}else if(r=n.match(t)){for(r=r[1],g=r[3],s=0;s<3;s++)A[s]=Number.parseInt(r[s]+r[s],16);g&&(A[3]=Number.parseInt(g+g,16)/255)}else if(r=n.match(i)){for(s=0;s<3;s++)A[s]=Number.parseFloat(r[s+1]);r[4]&&(A[3]=r[5]?Number.parseFloat(r[4])*.01:Number.parseFloat(r[4]))}else if(r=n.match(e)){for(s=0;s<3;s++)A[s]=Math.round(Number.parseFloat(r[s+1])*2.55);r[4]&&(A[3]=r[5]?Number.parseFloat(r[4])*.01:Number.parseFloat(r[4]))}else return(r=n.toLowerCase().match(a))?r[1]==="transparent"?[0,0,0,0]:Object.hasOwn(Ms,r[1])?(A=Ms[r[1]].slice(),A[3]=1,A):null:null;for(s=0;s<3;s++)A[s]=Wc(A[s],0,255);return A[3]=Wc(A[3],0,1),A};Ui.get.hsl=function(n){if(!n)return null;let t=/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[,|/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:e[+-]?\d+)?)\s*)?\)$/i,o=n.match(t);if(o){let i=Number.parseFloat(o[4]),e=(Number.parseFloat(o[1])%360+360)%360,a=Wc(Number.parseFloat(o[2]),0,100),A=Wc(Number.parseFloat(o[3]),0,100),r=Wc(Number.isNaN(i)?1:i,0,1);return[e,a,A,r]}return null};Ui.get.hwb=function(n){if(!n)return null;let t=/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*[\s,]\s*([+-]?[\d.]+)%\s*[\s,]\s*([+-]?[\d.]+)%\s*(?:[\s,]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:e[+-]?\d+)?)\s*)?\)$/i,o=n.match(t);if(o){let i=Number.parseFloat(o[4]),e=(Number.parseFloat(o[1])%360+360)%360,a=Wc(Number.parseFloat(o[2]),0,100),A=Wc(Number.parseFloat(o[3]),0,100),r=Wc(Number.isNaN(i)?1:i,0,1);return[e,a,A,r]}return null};Ui.to.hex=function(...n){return"#"+TD(n[0])+TD(n[1])+TD(n[2])+(n[3]<1?TD(Math.round(n[3]*255)):"")};Ui.to.rgb=function(...n){return n.length<4||n[3]===1?"rgb("+Math.round(n[0])+", "+Math.round(n[1])+", "+Math.round(n[2])+")":"rgba("+Math.round(n[0])+", "+Math.round(n[1])+", "+Math.round(n[2])+", "+n[3]+")"};Ui.to.rgb.percent=function(...n){let t=Math.round(n[0]/255*100),o=Math.round(n[1]/255*100),i=Math.round(n[2]/255*100);return n.length<4||n[3]===1?"rgb("+t+"%, "+o+"%, "+i+"%)":"rgba("+t+"%, "+o+"%, "+i+"%, "+n[3]+")"};Ui.to.hsl=function(...n){return n.length<4||n[3]===1?"hsl("+n[0]+", "+n[1]+"%, "+n[2]+"%)":"hsla("+n[0]+", "+n[1]+"%, "+n[2]+"%, "+n[3]+")"};Ui.to.hwb=function(...n){let t="";return n.length>=4&&n[3]!==1&&(t=", "+n[3]),"hwb("+n[0]+", "+n[1]+"%, "+n[2]+"%"+t+")"};Ui.to.keyword=function(...n){return fAe[n.slice(0,3)]};function Wc(n,t,o){return Math.min(Math.max(t,n),o)}function TD(n){let t=Math.round(n).toString(16).toUpperCase();return t.length<2?"0"+t:t}var Ch=Ui,QAe={};for(let n of Object.keys(Ms))QAe[Ms[n]]=n;var sA={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},oklab:{channels:3,labels:["okl","oka","okb"]},lch:{channels:3,labels:"lch"},oklch:{channels:3,labels:["okl","okc","okh"]},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}},Nl=sA,Fg=(6/29)**3;function Bh(n){let t=n>.0031308?1.055*n**.4166666666666667-.055:n*12.92;return Math.min(Math.max(0,t),1)}function fh(n){return n>.04045?((n+.055)/1.055)**2.4:n/12.92}for(let n of Object.keys(sA)){if(!("channels"in sA[n]))throw new Error("missing channels property: "+n);if(!("labels"in sA[n]))throw new Error("missing channel labels property: "+n);if(sA[n].labels.length!==sA[n].channels)throw new Error("channel and label counts mismatch: "+n);let{channels:t,labels:o}=sA[n];delete sA[n].channels,delete sA[n].labels,Object.defineProperty(sA[n],"channels",{value:t}),Object.defineProperty(sA[n],"labels",{value:o})}sA.rgb.hsl=function(n){let t=n[0]/255,o=n[1]/255,i=n[2]/255,e=Math.min(t,o,i),a=Math.max(t,o,i),A=a-e,r,s;switch(a){case e:{r=0;break}case t:{r=(o-i)/A;break}case o:{r=2+(i-t)/A;break}case i:{r=4+(t-o)/A;break}}r=Math.min(r*60,360),r<0&&(r+=360);let g=(e+a)/2;return a===e?s=0:g<=.5?s=A/(a+e):s=A/(2-a-e),[r,s*100,g*100]};sA.rgb.hsv=function(n){let t,o,i,e,a,A=n[0]/255,r=n[1]/255,s=n[2]/255,g=Math.max(A,r,s),c=g-Math.min(A,r,s),I=function(d){return(g-d)/6/c+1/2};if(c===0)e=0,a=0;else{switch(a=c/g,t=I(A),o=I(r),i=I(s),g){case A:{e=i-o;break}case r:{e=1/3+t-i;break}case s:{e=2/3+o-t;break}}e<0?e+=1:e>1&&(e-=1)}return[e*360,a*100,g*100]};sA.rgb.hwb=function(n){let t=n[0],o=n[1],i=n[2],e=sA.rgb.hsl(n)[0],a=1/255*Math.min(t,Math.min(o,i));return i=1-1/255*Math.max(t,Math.max(o,i)),[e,a*100,i*100]};sA.rgb.oklab=function(n){let t=fh(n[0]/255),o=fh(n[1]/255),i=fh(n[2]/255),e=Math.cbrt(.4122214708*t+.5363325363*o+.0514459929*i),a=Math.cbrt(.2119034982*t+.6806995451*o+.1073969566*i),A=Math.cbrt(.0883024619*t+.2817188376*o+.6299787005*i),r=.2104542553*e+.793617785*a-.0040720468*A,s=1.9779984951*e-2.428592205*a+.4505937099*A,g=.0259040371*e+.7827717662*a-.808675766*A;return[r*100,s*100,g*100]};sA.rgb.cmyk=function(n){let t=n[0]/255,o=n[1]/255,i=n[2]/255,e=Math.min(1-t,1-o,1-i),a=(1-t-e)/(1-e)||0,A=(1-o-e)/(1-e)||0,r=(1-i-e)/(1-e)||0;return[a*100,A*100,r*100,e*100]};function H1e(n,t){return(n[0]-t[0])**2+(n[1]-t[1])**2+(n[2]-t[2])**2}sA.rgb.keyword=function(n){let t=QAe[n];if(t)return t;let o=Number.POSITIVE_INFINITY,i;for(let e of Object.keys(Ms)){let a=Ms[e],A=H1e(n,a);AFg?o**(1/3):7.787*o+16/116,i=i>Fg?i**(1/3):7.787*i+16/116,e=e>Fg?e**(1/3):7.787*e+16/116;let a=116*i-16,A=500*(o-i),r=200*(i-e);return[a,A,r]};sA.hsl.rgb=function(n){let t=n[0]/360,o=n[1]/100,i=n[2]/100,e,a;if(o===0)return a=i*255,[a,a,a];let A=i<.5?i*(1+o):i+o-i*o,r=2*i-A,s=[0,0,0];for(let g=0;g<3;g++)e=t+1/3*-(g-1),e<0&&e++,e>1&&e--,6*e<1?a=r+(A-r)*6*e:2*e<1?a=A:3*e<2?a=r+(A-r)*(2/3-e)*6:a=r,s[g]=a*255;return s};sA.hsl.hsv=function(n){let t=n[0],o=n[1]/100,i=n[2]/100,e=o,a=Math.max(i,.01);i*=2,o*=i<=1?i:2-i,e*=a<=1?a:2-a;let A=(i+o)/2,r=i===0?2*e/(a+e):2*o/(i+o);return[t,r*100,A*100]};sA.hsv.rgb=function(n){let t=n[0]/60,o=n[1]/100,i=n[2]/100,e=Math.floor(t)%6,a=t-Math.floor(t),A=255*i*(1-o),r=255*i*(1-o*a),s=255*i*(1-o*(1-a));switch(i*=255,e){case 0:return[i,s,A];case 1:return[r,i,A];case 2:return[A,i,s];case 3:return[A,r,i];case 4:return[s,A,i];case 5:return[i,A,r]}};sA.hsv.hsl=function(n){let t=n[0],o=n[1]/100,i=n[2]/100,e=Math.max(i,.01),a,A;A=(2-o)*i;let r=(2-o)*e;return a=o*e,a/=r<=1?r:2-r,a=a||0,A/=2,[t,a*100,A*100]};sA.hwb.rgb=function(n){let t=n[0]/360,o=n[1]/100,i=n[2]/100,e=o+i,a;e>1&&(o/=e,i/=e);let A=Math.floor(6*t),r=1-i;a=6*t-A,(A&1)!==0&&(a=1-a);let s=o+a*(r-o),g,c,I;switch(A){default:case 6:case 0:{g=r,c=s,I=o;break}case 1:{g=s,c=r,I=o;break}case 2:{g=o,c=r,I=s;break}case 3:{g=o,c=s,I=r;break}case 4:{g=s,c=o,I=r;break}case 5:{g=r,c=o,I=s;break}}return[g*255,c*255,I*255]};sA.cmyk.rgb=function(n){let t=n[0]/100,o=n[1]/100,i=n[2]/100,e=n[3]/100,a=1-Math.min(1,t*(1-e)+e),A=1-Math.min(1,o*(1-e)+e),r=1-Math.min(1,i*(1-e)+e);return[a*255,A*255,r*255]};sA.xyz.rgb=function(n){let t=n[0]/100,o=n[1]/100,i=n[2]/100,e,a,A;return e=t*3.2404542+o*-1.5371385+i*-.4985314,a=t*-.969266+o*1.8760108+i*.041556,A=t*.0556434+o*-.2040259+i*1.0572252,e=Bh(e),a=Bh(a),A=Bh(A),[e*255,a*255,A*255]};sA.xyz.lab=function(n){let t=n[0],o=n[1],i=n[2];t/=95.047,o/=100,i/=108.883,t=t>Fg?t**(1/3):7.787*t+16/116,o=o>Fg?o**(1/3):7.787*o+16/116,i=i>Fg?i**(1/3):7.787*i+16/116;let e=116*o-16,a=500*(t-o),A=200*(o-i);return[e,a,A]};sA.xyz.oklab=function(n){let t=n[0]/100,o=n[1]/100,i=n[2]/100,e=Math.cbrt(.8189330101*t+.3618667424*o-.1288597137*i),a=Math.cbrt(.0329845436*t+.9293118715*o+.0361456387*i),A=Math.cbrt(.0482003018*t+.2643662691*o+.633851707*i),r=.2104542553*e+.793617785*a-.0040720468*A,s=1.9779984951*e-2.428592205*a+.4505937099*A,g=.0259040371*e+.7827717662*a-.808675766*A;return[r*100,s*100,g*100]};sA.oklab.oklch=function(n){return sA.lab.lch(n)};sA.oklab.xyz=function(n){let t=n[0]/100,o=n[1]/100,i=n[2]/100,e=(.999999998*t+.396337792*o+.215803758*i)**3,a=(1.000000008*t-.105561342*o-.063854175*i)**3,A=(1.000000055*t-.089484182*o-1.291485538*i)**3,r=1.227013851*e-.55779998*a+.281256149*A,s=-.040580178*e+1.11225687*a-.071676679*A,g=-.076381285*e-.421481978*a+1.58616322*A;return[r*100,s*100,g*100]};sA.oklab.rgb=function(n){let t=n[0]/100,o=n[1]/100,i=n[2]/100,e=(t+.3963377774*o+.2158037573*i)**3,a=(t-.1055613458*o-.0638541728*i)**3,A=(t-.0894841775*o-1.291485548*i)**3,r=Bh(4.0767416621*e-3.3077115913*a+.2309699292*A),s=Bh(-1.2684380046*e+2.6097574011*a-.3413193965*A),g=Bh(-.0041960863*e-.7034186147*a+1.707614701*A);return[r*255,s*255,g*255]};sA.oklch.oklab=function(n){return sA.lch.lab(n)};sA.lab.xyz=function(n){let t=n[0],o=n[1],i=n[2],e,a,A;a=(t+16)/116,e=o/500+a,A=a-i/200;let r=a**3,s=e**3,g=A**3;return a=r>Fg?r:(a-16/116)/7.787,e=s>Fg?s:(e-16/116)/7.787,A=g>Fg?g:(A-16/116)/7.787,e*=95.047,a*=100,A*=108.883,[e,a,A]};sA.lab.lch=function(n){let t=n[0],o=n[1],i=n[2],e;e=Math.atan2(i,o)*360/2/Math.PI,e<0&&(e+=360);let A=Math.sqrt(o*o+i*i);return[t,A,e]};sA.lch.lab=function(n){let t=n[0],o=n[1],e=n[2]/360*2*Math.PI,a=o*Math.cos(e),A=o*Math.sin(e);return[t,a,A]};sA.rgb.ansi16=function(n,t=null){let[o,i,e]=n,a=t===null?sA.rgb.hsv(n)[2]:t;if(a=Math.round(a/50),a===0)return 30;let A=30+(Math.round(e/255)<<2|Math.round(i/255)<<1|Math.round(o/255));return a===2&&(A+=60),A};sA.hsv.ansi16=function(n){return sA.rgb.ansi16(sA.hsv.rgb(n),n[2])};sA.rgb.ansi256=function(n){let t=n[0],o=n[1],i=n[2];return t>>4===o>>4&&o>>4===i>>4?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(o/255*5)+Math.round(i/255*5)};sA.ansi16.rgb=function(n){n=n[0];let t=n%10;if(t===0||t===7)return n>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let o=(Math.trunc(n>50)+1)*.5,i=(t&1)*o*255,e=(t>>1&1)*o*255,a=(t>>2&1)*o*255;return[i,e,a]};sA.ansi256.rgb=function(n){if(n=n[0],n>=232){let a=(n-232)*10+8;return[a,a,a]}n-=16;let t,o=Math.floor(n/36)/5*255,i=Math.floor((t=n%36)/6)/5*255,e=t%6/5*255;return[o,i,e]};sA.rgb.hex=function(n){let o=(((Math.round(n[0])&255)<<16)+((Math.round(n[1])&255)<<8)+(Math.round(n[2])&255)).toString(16).toUpperCase();return"000000".slice(o.length)+o};sA.hex.rgb=function(n){let t=n.toString(16).match(/[a-f\d]{6}|[a-f\d]{3}/i);if(!t)return[0,0,0];let o=t[0];t[0].length===3&&(o=[...o].map(r=>r+r).join(""));let i=Number.parseInt(o,16),e=i>>16&255,a=i>>8&255,A=i&255;return[e,a,A]};sA.rgb.hcg=function(n){let t=n[0]/255,o=n[1]/255,i=n[2]/255,e=Math.max(Math.max(t,o),i),a=Math.min(Math.min(t,o),i),A=e-a,r,s=A<1?a/(1-A):0;return A<=0?r=0:e===t?r=(o-i)/A%6:e===o?r=2+(i-t)/A:r=4+(t-o)/A,r/=6,r%=1,[r*360,A*100,s*100]};sA.hsl.hcg=function(n){let t=n[1]/100,o=n[2]/100,i=o<.5?2*t*o:2*t*(1-o),e=0;return i<1&&(e=(o-.5*i)/(1-i)),[n[0],i*100,e*100]};sA.hsv.hcg=function(n){let t=n[1]/100,o=n[2]/100,i=t*o,e=0;return i<1&&(e=(o-i)/(1-i)),[n[0],i*100,e*100]};sA.hcg.rgb=function(n){let t=n[0]/360,o=n[1]/100,i=n[2]/100;if(o===0)return[i*255,i*255,i*255];let e=[0,0,0],a=t%1*6,A=a%1,r=1-A,s=0;switch(Math.floor(a)){case 0:{e[0]=1,e[1]=A,e[2]=0;break}case 1:{e[0]=r,e[1]=1,e[2]=0;break}case 2:{e[0]=0,e[1]=1,e[2]=A;break}case 3:{e[0]=0,e[1]=r,e[2]=1;break}case 4:{e[0]=A,e[1]=0,e[2]=1;break}default:e[0]=1,e[1]=0,e[2]=r}return s=(1-o)*i,[(o*e[0]+s)*255,(o*e[1]+s)*255,(o*e[2]+s)*255]};sA.hcg.hsv=function(n){let t=n[1]/100,o=n[2]/100,i=t+o*(1-t),e=0;return i>0&&(e=t/i),[n[0],e*100,i*100]};sA.hcg.hsl=function(n){let t=n[1]/100,i=n[2]/100*(1-t)+.5*t,e=0;return i>0&&i<.5?e=t/(2*i):i>=.5&&i<1&&(e=t/(2*(1-i))),[n[0],e*100,i*100]};sA.hcg.hwb=function(n){let t=n[1]/100,o=n[2]/100,i=t+o*(1-t);return[n[0],(i-t)*100,(1-i)*100]};sA.hwb.hcg=function(n){let t=n[1]/100,i=1-n[2]/100,e=i-t,a=0;return e<1&&(a=(i-e)/(1-e)),[n[0],e*100,a*100]};sA.apple.rgb=function(n){return[n[0]/65535*255,n[1]/65535*255,n[2]/65535*255]};sA.rgb.apple=function(n){return[n[0]/255*65535,n[1]/255*65535,n[2]/255*65535]};sA.gray.rgb=function(n){return[n[0]/100*255,n[0]/100*255,n[0]/100*255]};sA.gray.hsl=function(n){return[0,0,n[0]]};sA.gray.hsv=sA.gray.hsl;sA.gray.hwb=function(n){return[0,100,n[0]]};sA.gray.cmyk=function(n){return[0,0,0,n[0]]};sA.gray.lab=function(n){return[n[0],0,0]};sA.gray.hex=function(n){let t=Math.round(n[0]/100*255)&255,i=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".slice(i.length)+i};sA.rgb.gray=function(n){return[(n[0]+n[1]+n[2])/3/255*100]};function K1e(){let n={},t=Object.keys(Nl);for(let{length:o}=t,i=0;i0;){let i=o.pop(),e=Object.keys(Nl[i]);for(let{length:a}=e,A=0;A1&&(o=i),n(o))};return"conversion"in n&&(t.conversion=n.conversion),t}function W1e(n){let t=function(...o){let i=o[0];if(i==null)return i;i.length>1&&(o=i);let e=n(o);if(typeof e=="object")for(let{length:a}=e,A=0;A0){this.model=t||"rgb",i=oo[this.model].channels;let e=Array.prototype.slice.call(n,0,i);this.color=IL(e,i),this.valpha=typeof n[i]=="number"?n[i]:1}else if(typeof n=="number")this.model="rgb",this.color=[n>>16&255,n>>8&255,n&255],this.valpha=1;else{this.valpha=1;let e=Object.keys(n);"alpha"in n&&(e.splice(e.indexOf("alpha"),1),this.valpha=typeof n.alpha=="number"?n.alpha:0);let a=e.sort().join("");if(!(a in gL))throw new Error("Unable to parse color from object: "+JSON.stringify(n));this.model=gL[a];let{labels:A}=oo[this.model],r=[];for(o=0;o(n%360+360)%360),saturationl:fr("hsl",1,jr(100)),lightness:fr("hsl",2,jr(100)),saturationv:fr("hsv",1,jr(100)),value:fr("hsv",2,jr(100)),chroma:fr("hcg",1,jr(100)),gray:fr("hcg",2,jr(100)),white:fr("hwb",1,jr(100)),wblack:fr("hwb",2,jr(100)),cyan:fr("cmyk",0,jr(100)),magenta:fr("cmyk",1,jr(100)),yellow:fr("cmyk",2,jr(100)),black:fr("cmyk",3,jr(100)),x:fr("xyz",0,jr(95.047)),y:fr("xyz",1,jr(100)),z:fr("xyz",2,jr(108.833)),l:fr("lab",0,jr(100)),a:fr("lab",1),b:fr("lab",2),keyword(n){return n!==void 0?new ca(n):oo[this.model].keyword(this.color)},hex(n){return n!==void 0?new ca(n):Ch.to.hex(...this.rgb().round().color)},hexa(n){if(n!==void 0)return new ca(n);let t=this.rgb().round().color,o=Math.round(this.valpha*255).toString(16).toUpperCase();return o.length===1&&(o="0"+o),Ch.to.hex(...t)+o},rgbNumber(){let n=this.rgb().color;return(n[0]&255)<<16|(n[1]&255)<<8|n[2]&255},luminosity(){let n=this.rgb().color,t=[];for(let[o,i]of n.entries()){let e=i/255;t[o]=e<=.04045?e/12.92:((e+.055)/1.055)**2.4}return .2126*t[0]+.7152*t[1]+.0722*t[2]},contrast(n){let t=this.luminosity(),o=n.luminosity();return t>o?(t+.05)/(o+.05):(o+.05)/(t+.05)},level(n){let t=this.contrast(n);return t>=7?"AAA":t>=4.5?"AA":""},isDark(){let n=this.rgb().color;return(n[0]*2126+n[1]*7152+n[2]*722)/1e4<128},isLight(){return!this.isDark()},negate(){let n=this.rgb();for(let t=0;t<3;t++)n.color[t]=255-n.color[t];return n},lighten(n){let t=this.hsl();return t.color[2]+=t.color[2]*n,t},darken(n){let t=this.hsl();return t.color[2]-=t.color[2]*n,t},saturate(n){let t=this.hsl();return t.color[1]+=t.color[1]*n,t},desaturate(n){let t=this.hsl();return t.color[1]-=t.color[1]*n,t},whiten(n){let t=this.hwb();return t.color[1]+=t.color[1]*n,t},blacken(n){let t=this.hwb();return t.color[2]+=t.color[2]*n,t},grayscale(){let n=this.rgb().color,t=n[0]*.3+n[1]*.59+n[2]*.11;return ca.rgb(t,t,t)},fade(n){return this.alpha(this.valpha-this.valpha*n)},opaquer(n){return this.alpha(this.valpha+this.valpha*n)},rotate(n){let t=this.hsl(),o=t.color[0];return o=(o+n)%360,o=o<0?360+o:o,t.color[0]=o,t},mix(n,t){if(!n||!n.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof n);let o=n.rgb(),i=this.rgb(),e=t===void 0?.5:t,a=2*e-1,A=o.alpha()-i.alpha(),r=((a*A===-1?a:(a+A)/(1+a*A))+1)/2,s=1-r;return ca.rgb(r*o.red()+s*i.red(),r*o.green()+s*i.green(),r*o.blue()+s*i.blue(),o.alpha()*e+i.alpha()*(1-e))}};for(let n of Object.keys(oo)){if(yAe.includes(n))continue;let{channels:t}=oo[n];ca.prototype[n]=function(...o){return this.model===n?new ca(this):o.length>0?new ca(o,n):new ca([...$1e(oo[this.model][n].raw(this.color)),this.valpha],n)},ca[n]=function(...o){let i=o[0];return typeof i=="number"&&(i=IL(o,t)),new ca(i,n)}}function Z1e(n,t){return Number(n.toFixed(t))}function X1e(n){return function(t){return Z1e(t,n)}}function fr(n,t,o){n=Array.isArray(n)?n:[n];for(let i of n)(cL[i]||=[])[t]=o;return n=n[0],function(i){let e;return i!==void 0?(o&&(i=o(i)),e=this[n](),e.color[t]=i,e):(e=this[n]().color[t],o&&(e=o(e)),e)}}function jr(n){return function(t){return Math.max(0,Math.min(n,t))}}function $1e(n){return Array.isArray(n)?n:[n]}function IL(n,t){for(let o=0;o{wAe.exports=SAe().default});function A3e(n){return this._setBackgroundColourOption("tint",n),this}function t3e(n){return this.options.greyscale=O.bool(n)?n:!0,this}function r3e(n){return this.greyscale(n)}function a3e(n){if(!O.string(n))throw O.invalidParameterError("colourspace","string",n);return this.options.colourspacePipeline=n,this}function i3e(n){return this.pipelineColourspace(n)}function o3e(n){if(!O.string(n))throw O.invalidParameterError("colourspace","string",n);return this.options.colourspace=n,this}function n3e(n){return this.toColourspace(n)}function MAe(n){if(O.object(n)||O.string(n)&&n.length>=3&&n.length<=200){let t=(0,bAe.default)(n),o=t.red(),i=t.green(),e=t.blue(),a=Math.round(t.alpha()*255);for(let[A,r]of[["red",o],["green",i],["blue",e],["alpha",a]])if(!O.number(r))throw O.invalidParameterError(`background.${A}`,"number",r);return[o,i,e,a]}else throw O.invalidParameterError("background","object or string",n)}function s3e(n,t){O.defined(t)&&(this.options[n]=MAe(t))}var bAe,OAe,_Ae,TAe=ue(()=>{bAe=Je(DAe(),1);ms();OAe={multiband:"multiband","b-w":"b-w",bw:"b-w",cmyk:"cmyk",srgb:"srgb"};_Ae=n=>{Object.assign(n.prototype,{tint:A3e,greyscale:t3e,grayscale:r3e,pipelineColourspace:a3e,pipelineColorspace:i3e,toColourspace:o3e,toColorspace:n3e,_getBackgroundColourOption:MAe,_setBackgroundColourOption:s3e}),n.colourspace=OAe,n.colorspace=OAe}});function c3e(){return this.options.removeAlpha=!0,this}function I3e(n){if(O.defined(n))if(O.number(n)&&O.inRange(n,0,1))this.options.ensureAlpha=n;else throw O.invalidParameterError("alpha","number between 0 and 1",n);else this.options.ensureAlpha=1;return this}function l3e(n){let t={red:0,green:1,blue:2,alpha:3};if(Object.keys(t).includes(n)&&(n=t[n]),O.integer(n)&&O.inRange(n,0,4))this.options.extractChannel=n;else throw O.invalidParameterError("channel","integer or one of: red, green, blue, alpha",n);return this}function p3e(n,t){return Array.isArray(n)?n.forEach(function(o){this.options.joinChannelIn.push(this._createInputDescriptor(o,t))},this):this.options.joinChannelIn.push(this._createInputDescriptor(n,t)),this}function d3e(n){if(O.string(n)&&O.inArray(n,["and","or","eor"]))this.options.bandBoolOp=n;else throw O.invalidParameterError("boolOp","one of: and, or, eor",n);return this}var g3e,NAe,RAe=ue(()=>{ms();g3e={and:"and",or:"or",eor:"eor"};NAe=n=>{Object.assign(n.prototype,{removeAlpha:c3e,ensureAlpha:I3e,extractChannel:l3e,joinChannel:p3e,bandbool:d3e}),n.bool=g3e}});import pL from"node:path";function E3e(n,t){let o;if(O.string(n)?O.string(this.options.input.file)&&pL.resolve(this.options.input.file)===pL.resolve(n)?o=new Error("Cannot use same file for input and output"):h3e.test(pL.extname(n))&&!this.constructor.format.jp2.output.file&&(o=vAe()):o=new Error("Missing output file path"),o)if(O.fn(t))t(o);else return Promise.reject(o);else{this.options.fileOut=n;let i=Error();return this._pipeline(t,i)}return this}function C3e(n,t){O.object(n)?this._setBooleanOption("resolveWithObject",n.resolveWithObject):this.options.resolveWithObject&&(this.options.resolveWithObject=!1),this.options.fileOut="";let o=Error();return this._pipeline(O.fn(n)?n:t,o)}function u3e(){this.options.resolveWithObject=!0,this.options.typedArrayOut=!0;let n=Error();return this._pipeline(null,n)}function B3e(n){if(O.number(n)&&n>0)this.options.withMetadataDensity=n;else throw O.invalidParameterError("density","positive number",n);return this.keepExif()}function f3e(){return this.options.keepMetadata|=1,this}function Q3e(n){if(O.object(n))for(let[t,o]of Object.entries(n))if(O.object(o))for(let[i,e]of Object.entries(o))if(O.string(e))this.options.withExif[`exif-${t.toLowerCase()}-${i}`]=e;else throw O.invalidParameterError(`${t}.${i}`,"string",e);else throw O.invalidParameterError(t,"object",o);else throw O.invalidParameterError("exif","object",n);return this.options.withExifMerge=!1,this.keepExif()}function y3e(n){return this.withExif(n),this.options.withExifMerge=!0,this}function m3e(){return this.options.keepMetadata|=8,this}function S3e(n,t){if(O.string(n))this.options.withIccProfile=n;else throw O.invalidParameterError("icc","string",n);if(this.keepIccProfile(),O.object(t)&&O.defined(t.attach))if(O.bool(t.attach))t.attach||(this.options.keepMetadata&=-9);else throw O.invalidParameterError("attach","boolean",t.attach);return this}function w3e(){return this.options.keepGainMap=!0,this.options.withGainMap=!1,this.options.keepMetadata|=32,this}function D3e(){return this.options.withGainMap=!0,this.options.keepGainMap=!1,this.options.colourspace="scrgb",this}function O3e(){return this.options.keepMetadata|=2,this}function b3e(n){if(O.string(n)&&n.length>0)this.options.withXmp=n,this.options.keepMetadata|=2;else throw O.invalidParameterError("xmp","non-empty string",n);return this}function M3e(){return this.options.keepMetadata|=31,this}function _3e(n){if(this.keepMetadata(),this.withIccProfile("srgb"),O.object(n)){if(O.defined(n.orientation))if(O.integer(n.orientation)&&O.inRange(n.orientation,1,8))this.options.withMetadataOrientation=n.orientation;else throw O.invalidParameterError("orientation","integer between 1 and 8",n.orientation);if(O.defined(n.density))if(O.number(n.density)&&n.density>0)this.options.withMetadataDensity=n.density;else throw O.invalidParameterError("density","positive number",n.density);O.defined(n.icc)&&this.withIccProfile(n.icc),O.defined(n.exif)&&this.withExifMerge(n.exif)}return this}function T3e(n,t){let o=kAe.get((O.object(n)&&O.string(n.id)?n.id:n).toLowerCase());if(!o)throw O.invalidParameterError("format",`one of: ${[...kAe.keys()].join(", ")}`,n);return this[o](t)}function N3e(n){if(O.object(n)){if(O.defined(n.quality))if(O.integer(n.quality)&&O.inRange(n.quality,1,100))this.options.jpegQuality=n.quality;else throw O.invalidParameterError("quality","integer between 1 and 100",n.quality);if(O.defined(n.progressive)&&this._setBooleanOption("jpegProgressive",n.progressive),O.defined(n.chromaSubsampling))if(O.string(n.chromaSubsampling)&&O.inArray(n.chromaSubsampling,["4:2:0","4:4:4"]))this.options.jpegChromaSubsampling=n.chromaSubsampling;else throw O.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",n.chromaSubsampling);let t=O.bool(n.optimizeCoding)?n.optimizeCoding:n.optimiseCoding;if(O.defined(t)&&this._setBooleanOption("jpegOptimiseCoding",t),O.defined(n.mozjpeg))if(O.bool(n.mozjpeg))n.mozjpeg&&(this.options.jpegTrellisQuantisation=!0,this.options.jpegOvershootDeringing=!0,this.options.jpegOptimiseScans=!0,this.options.jpegProgressive=!0,this.options.jpegQuantisationTable=3);else throw O.invalidParameterError("mozjpeg","boolean",n.mozjpeg);let o=O.bool(n.trellisQuantization)?n.trellisQuantization:n.trellisQuantisation;O.defined(o)&&this._setBooleanOption("jpegTrellisQuantisation",o),O.defined(n.overshootDeringing)&&this._setBooleanOption("jpegOvershootDeringing",n.overshootDeringing);let i=O.bool(n.optimizeScans)?n.optimizeScans:n.optimiseScans;O.defined(i)&&(this._setBooleanOption("jpegOptimiseScans",i),i&&(this.options.jpegProgressive=!0));let e=O.number(n.quantizationTable)?n.quantizationTable:n.quantisationTable;if(O.defined(e))if(O.integer(e)&&O.inRange(e,0,8))this.options.jpegQuantisationTable=e;else throw O.invalidParameterError("quantisationTable","integer between 0 and 8",e)}return this._updateFormatOut("jpeg",n)}function R3e(n){if(O.object(n)){if(O.defined(n.progressive)&&this._setBooleanOption("pngProgressive",n.progressive),O.defined(n.compressionLevel))if(O.integer(n.compressionLevel)&&O.inRange(n.compressionLevel,0,9))this.options.pngCompressionLevel=n.compressionLevel;else throw O.invalidParameterError("compressionLevel","integer between 0 and 9",n.compressionLevel);O.defined(n.adaptiveFiltering)&&this._setBooleanOption("pngAdaptiveFiltering",n.adaptiveFiltering);let t=n.colours||n.colors;if(O.defined(t))if(O.integer(t)&&O.inRange(t,2,256))this.options.pngBitdepth=PAe(t);else throw O.invalidParameterError("colours","integer between 2 and 256",t);if(O.defined(n.palette)?this._setBooleanOption("pngPalette",n.palette):[n.quality,n.effort,n.colours,n.colors,n.dither].some(O.defined)&&this._setBooleanOption("pngPalette",!0),this.options.pngPalette){if(O.defined(n.quality))if(O.integer(n.quality)&&O.inRange(n.quality,0,100))this.options.pngQuality=n.quality;else throw O.invalidParameterError("quality","integer between 0 and 100",n.quality);if(O.defined(n.effort))if(O.integer(n.effort)&&O.inRange(n.effort,1,10))this.options.pngEffort=n.effort;else throw O.invalidParameterError("effort","integer between 1 and 10",n.effort);if(O.defined(n.dither))if(O.number(n.dither)&&O.inRange(n.dither,0,1))this.options.pngDither=n.dither;else throw O.invalidParameterError("dither","number between 0.0 and 1.0",n.dither)}}return this._updateFormatOut("png",n)}function k3e(n){if(O.object(n)){if(O.defined(n.quality))if(O.integer(n.quality)&&O.inRange(n.quality,1,100))this.options.webpQuality=n.quality;else throw O.invalidParameterError("quality","integer between 1 and 100",n.quality);if(O.defined(n.alphaQuality))if(O.integer(n.alphaQuality)&&O.inRange(n.alphaQuality,0,100))this.options.webpAlphaQuality=n.alphaQuality;else throw O.invalidParameterError("alphaQuality","integer between 0 and 100",n.alphaQuality);if(O.defined(n.lossless)&&this._setBooleanOption("webpLossless",n.lossless),O.defined(n.nearLossless)&&this._setBooleanOption("webpNearLossless",n.nearLossless),O.defined(n.smartSubsample)&&this._setBooleanOption("webpSmartSubsample",n.smartSubsample),O.defined(n.smartDeblock)&&this._setBooleanOption("webpSmartDeblock",n.smartDeblock),O.defined(n.preset))if(O.string(n.preset)&&O.inArray(n.preset,["default","photo","picture","drawing","icon","text"]))this.options.webpPreset=n.preset;else throw O.invalidParameterError("preset","one of: default, photo, picture, drawing, icon, text",n.preset);if(O.defined(n.effort))if(O.integer(n.effort)&&O.inRange(n.effort,0,6))this.options.webpEffort=n.effort;else throw O.invalidParameterError("effort","integer between 0 and 6",n.effort);O.defined(n.minSize)&&this._setBooleanOption("webpMinSize",n.minSize),O.defined(n.mixed)&&this._setBooleanOption("webpMixed",n.mixed),O.defined(n.exact)&&this._setBooleanOption("webpExact",n.exact)}return dL(n,this.options),this._updateFormatOut("webp",n)}function v3e(n){if(O.object(n)){O.defined(n.reuse)&&this._setBooleanOption("gifReuse",n.reuse),O.defined(n.progressive)&&this._setBooleanOption("gifProgressive",n.progressive);let t=n.colours||n.colors;if(O.defined(t))if(O.integer(t)&&O.inRange(t,2,256))this.options.gifBitdepth=PAe(t);else throw O.invalidParameterError("colours","integer between 2 and 256",t);if(O.defined(n.effort))if(O.integer(n.effort)&&O.inRange(n.effort,1,10))this.options.gifEffort=n.effort;else throw O.invalidParameterError("effort","integer between 1 and 10",n.effort);if(O.defined(n.dither))if(O.number(n.dither)&&O.inRange(n.dither,0,1))this.options.gifDither=n.dither;else throw O.invalidParameterError("dither","number between 0.0 and 1.0",n.dither);if(O.defined(n.interFrameMaxError))if(O.number(n.interFrameMaxError)&&O.inRange(n.interFrameMaxError,0,32))this.options.gifInterFrameMaxError=n.interFrameMaxError;else throw O.invalidParameterError("interFrameMaxError","number between 0.0 and 32.0",n.interFrameMaxError);if(O.defined(n.interPaletteMaxError))if(O.number(n.interPaletteMaxError)&&O.inRange(n.interPaletteMaxError,0,256))this.options.gifInterPaletteMaxError=n.interPaletteMaxError;else throw O.invalidParameterError("interPaletteMaxError","number between 0.0 and 256.0",n.interPaletteMaxError);if(O.defined(n.keepDuplicateFrames))if(O.bool(n.keepDuplicateFrames))this._setBooleanOption("gifKeepDuplicateFrames",n.keepDuplicateFrames);else throw O.invalidParameterError("keepDuplicateFrames","boolean",n.keepDuplicateFrames)}return dL(n,this.options),this._updateFormatOut("gif",n)}function P3e(n){if(!this.constructor.format.jp2.output.buffer)throw vAe();if(O.object(n)){if(O.defined(n.quality))if(O.integer(n.quality)&&O.inRange(n.quality,1,100))this.options.jp2Quality=n.quality;else throw O.invalidParameterError("quality","integer between 1 and 100",n.quality);if(O.defined(n.lossless))if(O.bool(n.lossless))this.options.jp2Lossless=n.lossless;else throw O.invalidParameterError("lossless","boolean",n.lossless);if(O.defined(n.tileWidth))if(O.integer(n.tileWidth)&&O.inRange(n.tileWidth,1,32768))this.options.jp2TileWidth=n.tileWidth;else throw O.invalidParameterError("tileWidth","integer between 1 and 32768",n.tileWidth);if(O.defined(n.tileHeight))if(O.integer(n.tileHeight)&&O.inRange(n.tileHeight,1,32768))this.options.jp2TileHeight=n.tileHeight;else throw O.invalidParameterError("tileHeight","integer between 1 and 32768",n.tileHeight);if(O.defined(n.chromaSubsampling))if(O.string(n.chromaSubsampling)&&O.inArray(n.chromaSubsampling,["4:2:0","4:4:4"]))this.options.jp2ChromaSubsampling=n.chromaSubsampling;else throw O.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",n.chromaSubsampling)}return this._updateFormatOut("jp2",n)}function dL(n,t){if(O.object(n)&&O.defined(n.loop))if(O.integer(n.loop)&&O.inRange(n.loop,0,65535))t.loop=n.loop;else throw O.invalidParameterError("loop","integer between 0 and 65535",n.loop);if(O.object(n)&&O.defined(n.delay))if(O.integer(n.delay)&&O.inRange(n.delay,0,65535))t.delay=[n.delay];else if(Array.isArray(n.delay)&&n.delay.every(O.integer)&&n.delay.every(o=>O.inRange(o,0,65535)))t.delay=n.delay;else throw O.invalidParameterError("delay","integer or an array of integers between 0 and 65535",n.delay)}function G3e(n){if(O.object(n)){if(O.defined(n.quality))if(O.integer(n.quality)&&O.inRange(n.quality,1,100))this.options.tiffQuality=n.quality;else throw O.invalidParameterError("quality","integer between 1 and 100",n.quality);if(O.defined(n.bitdepth))if(O.integer(n.bitdepth)&&O.inArray(n.bitdepth,[1,2,4]))this.options.tiffBitdepth=n.bitdepth;else throw O.invalidParameterError("bitdepth","1, 2 or 4",n.bitdepth);if(O.defined(n.tile)&&this._setBooleanOption("tiffTile",n.tile),O.defined(n.tileWidth))if(O.integer(n.tileWidth)&&O.inRange(n.tileWidth,1,32768))this.options.tiffTileWidth=n.tileWidth;else throw O.invalidParameterError("tileWidth","integer between 1 and 32768",n.tileWidth);if(O.defined(n.tileHeight))if(O.integer(n.tileHeight)&&O.inRange(n.tileHeight,1,32768))this.options.tiffTileHeight=n.tileHeight;else throw O.invalidParameterError("tileHeight","integer between 1 and 32768",n.tileHeight);if(O.defined(n.miniswhite)&&this._setBooleanOption("tiffMiniswhite",n.miniswhite),O.defined(n.pyramid)&&this._setBooleanOption("tiffPyramid",n.pyramid),O.defined(n.xres))if(O.number(n.xres)&&O.inRange(n.xres,.001,1e6))this.options.tiffXres=n.xres;else throw O.invalidParameterError("xres","number between 0.001 and 1000000",n.xres);if(O.defined(n.yres))if(O.number(n.yres)&&O.inRange(n.yres,.001,1e6))this.options.tiffYres=n.yres;else throw O.invalidParameterError("yres","number between 0.001 and 1000000",n.yres);if(O.defined(n.compression))if(O.string(n.compression)&&O.inArray(n.compression,["none","jpeg","deflate","packbits","ccittfax4","lzw","webp","zstd","jp2k"]))this.options.tiffCompression=n.compression;else throw O.invalidParameterError("compression","one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k",n.compression);if(O.defined(n.bigtiff)&&this._setBooleanOption("tiffBigtiff",n.bigtiff),O.defined(n.predictor))if(O.string(n.predictor)&&O.inArray(n.predictor,["none","horizontal","float"]))this.options.tiffPredictor=n.predictor;else throw O.invalidParameterError("predictor","one of: none, horizontal, float",n.predictor);if(O.defined(n.resolutionUnit))if(O.string(n.resolutionUnit)&&O.inArray(n.resolutionUnit,["inch","cm"]))this.options.tiffResolutionUnit=n.resolutionUnit;else throw O.invalidParameterError("resolutionUnit","one of: inch, cm",n.resolutionUnit)}return this._updateFormatOut("tiff",n)}function F3e(n){return this.heif({...n,compression:"av1"})}function L3e(n){if(O.object(n)){if(O.string(n.compression)&&O.inArray(n.compression,["av1","hevc"]))this.options.heifCompression=n.compression;else throw O.invalidParameterError("compression","one of: av1, hevc",n.compression);if(O.defined(n.quality))if(O.integer(n.quality)&&O.inRange(n.quality,1,100))this.options.heifQuality=n.quality;else throw O.invalidParameterError("quality","integer between 1 and 100",n.quality);if(O.defined(n.lossless))if(O.bool(n.lossless))this.options.heifLossless=n.lossless;else throw O.invalidParameterError("lossless","boolean",n.lossless);if(O.defined(n.effort))if(O.integer(n.effort)&&O.inRange(n.effort,0,9))this.options.heifEffort=n.effort;else throw O.invalidParameterError("effort","integer between 0 and 9",n.effort);if(O.defined(n.chromaSubsampling))if(O.string(n.chromaSubsampling)&&O.inArray(n.chromaSubsampling,["4:2:0","4:4:4"]))this.options.heifChromaSubsampling=n.chromaSubsampling;else throw O.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",n.chromaSubsampling);if(O.defined(n.bitdepth))if(O.integer(n.bitdepth)&&O.inArray(n.bitdepth,[8,10,12]))this.options.heifBitdepth=n.bitdepth;else throw O.invalidParameterError("bitdepth","8, 10 or 12",n.bitdepth);if(O.defined(n.tune))if(O.string(n.tune)&&O.inArray(n.tune,["auto","iq","psnr","ssim"]))this.options.heifLossless&&n.tune==="iq"?this.options.heifTune="ssim":this.options.heifTune=n.tune;else throw O.invalidParameterError("tune","one of: auto, iq, psnr, ssim",n.tune)}else throw O.invalidParameterError("options","Object",n);return this._updateFormatOut("heif",n)}function U3e(n){if(O.object(n)){if(O.defined(n.quality))if(O.integer(n.quality)&&O.inRange(n.quality,1,100))this.options.jxlDistance=n.quality>=30?.1+(100-n.quality)*.09:53/3e3*n.quality*n.quality-23/20*n.quality+25;else throw O.invalidParameterError("quality","integer between 1 and 100",n.quality);else if(O.defined(n.distance))if(O.number(n.distance)&&O.inRange(n.distance,0,15))this.options.jxlDistance=n.distance;else throw O.invalidParameterError("distance","number between 0.0 and 15.0",n.distance);if(O.defined(n.decodingTier))if(O.integer(n.decodingTier)&&O.inRange(n.decodingTier,0,4))this.options.jxlDecodingTier=n.decodingTier;else throw O.invalidParameterError("decodingTier","integer between 0 and 4",n.decodingTier);if(O.defined(n.lossless))if(O.bool(n.lossless))this.options.jxlLossless=n.lossless;else throw O.invalidParameterError("lossless","boolean",n.lossless);if(O.defined(n.effort))if(O.integer(n.effort)&&O.inRange(n.effort,1,9))this.options.jxlEffort=n.effort;else throw O.invalidParameterError("effort","integer between 1 and 9",n.effort)}return dL(n,this.options),this._updateFormatOut("jxl",n)}function H3e(n){if(O.object(n)&&O.defined(n.depth))if(O.string(n.depth)&&O.inArray(n.depth,["char","uchar","short","ushort","int","uint","float","complex","double","dpcomplex"]))this.options.rawDepth=n.depth;else throw O.invalidParameterError("depth","one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex",n.depth);return this._updateFormatOut("raw")}function K3e(n){if(O.object(n)){if(O.defined(n.size))if(O.integer(n.size)&&O.inRange(n.size,1,8192))this.options.tileSize=n.size;else throw O.invalidParameterError("size","integer between 1 and 8192",n.size);if(O.defined(n.overlap))if(O.integer(n.overlap)&&O.inRange(n.overlap,0,8192)){if(n.overlap>this.options.tileSize)throw O.invalidParameterError("overlap",`<= size (${this.options.tileSize})`,n.overlap);this.options.tileOverlap=n.overlap}else throw O.invalidParameterError("overlap","integer between 0 and 8192",n.overlap);if(O.defined(n.container))if(O.string(n.container)&&O.inArray(n.container,["fs","zip"]))this.options.tileContainer=n.container;else throw O.invalidParameterError("container","one of: fs, zip",n.container);if(O.defined(n.layout))if(O.string(n.layout)&&O.inArray(n.layout,["dz","google","iiif","iiif3","zoomify"]))this.options.tileLayout=n.layout;else throw O.invalidParameterError("layout","one of: dz, google, iiif, iiif3, zoomify",n.layout);if(O.defined(n.angle))if(O.integer(n.angle)&&!(n.angle%90))this.options.tileAngle=n.angle;else throw O.invalidParameterError("angle","positive/negative multiple of 90",n.angle);if(this._setBackgroundColourOption("tileBackground",n.background),O.defined(n.depth))if(O.string(n.depth)&&O.inArray(n.depth,["onepixel","onetile","one"]))this.options.tileDepth=n.depth;else throw O.invalidParameterError("depth","one of: onepixel, onetile, one",n.depth);if(O.defined(n.skipBlanks))if(O.integer(n.skipBlanks)&&O.inRange(n.skipBlanks,-1,65535))this.options.tileSkipBlanks=n.skipBlanks;else throw O.invalidParameterError("skipBlanks","integer between -1 and 255/65535",n.skipBlanks);else O.defined(n.layout)&&n.layout==="google"&&(this.options.tileSkipBlanks=5);let t=O.bool(n.center)?n.center:n.centre;if(O.defined(t)&&this._setBooleanOption("tileCentre",t),O.defined(n.id))if(O.string(n.id))this.options.tileId=n.id;else throw O.invalidParameterError("id","string",n.id);if(O.defined(n.basename))if(O.string(n.basename))this.options.tileBasename=n.basename;else throw O.invalidParameterError("basename","string",n.basename)}if(O.inArray(this.options.formatOut,["jpeg","png","webp"]))this.options.tileFormat=this.options.formatOut;else if(this.options.formatOut!=="input")throw O.invalidParameterError("format","one of: jpeg, png, webp",this.options.formatOut);return this._updateFormatOut("dz")}function x3e(n){if(!O.plainObject(n))throw O.invalidParameterError("options","object",n);if(O.integer(n.seconds)&&O.inRange(n.seconds,0,3600))this.options.timeoutSeconds=n.seconds;else throw O.invalidParameterError("seconds","integer between 0 and 3600",n.seconds);return this}function Y3e(n,t){return O.object(t)&&t.force===!1||(this.options.formatOut=n),this}function j3e(n,t){if(O.bool(t))this.options[n]=t;else throw O.invalidParameterError(n,"boolean",t)}function J3e(){if(!this.options.streamOut){this.options.streamOut=!0;let n=Error();this._pipeline(void 0,n)}}function q3e(n,t){return typeof n=="function"?(this._isStreamInput()?this._whenStreamInFinished(()=>{this._flattenBufferIn(),St.pipeline(this.options,(o,i,e)=>{o?n(O.nativeError(o,t)):n(null,i,e)})}):St.pipeline(this.options,(o,i,e)=>{o?n(O.nativeError(o,t)):n(null,i,e)}),this):this.options.streamOut?(this._isStreamInput()?this._whenStreamInFinished(()=>{this._flattenBufferIn(),St.pipeline(this.options,(o,i,e)=>{o?this.emit("error",O.nativeError(o,t)):(this.emit("info",e),this.push(i)),this.push(null),this.on("end",()=>this.emit("close"))})}):St.pipeline(this.options,(o,i,e)=>{o?this.emit("error",O.nativeError(o,t)):(this.emit("info",e),this.push(i)),this.push(null),this.on("end",()=>this.emit("close"))}),this):this._isStreamInput()?new Promise((o,i)=>{this._whenStreamInFinished(()=>{this._flattenBufferIn(),St.pipeline(this.options,(e,a,A)=>{e?i(O.nativeError(e,t)):this.options.resolveWithObject?o({data:a,info:A}):o(a)})})}):new Promise((o,i)=>{St.pipeline(this.options,(e,a,A)=>{e?i(O.nativeError(e,t)):this.options.resolveWithObject?o({data:a,info:A}):o(a)})})}var kAe,h3e,vAe,PAe,GAe,FAe=ue(()=>{ms();kB();kAe=new Map([["heic","heif"],["heif","heif"],["avif","avif"],["jpeg","jpeg"],["jpg","jpeg"],["jpe","jpeg"],["tile","tile"],["dz","tile"],["png","png"],["raw","raw"],["tiff","tiff"],["tif","tiff"],["webp","webp"],["gif","gif"],["jp2","jp2"],["jpx","jp2"],["j2k","jp2"],["j2c","jp2"],["jxl","jxl"]]),h3e=/\.(jp[2x]|j2[kc])$/i,vAe=()=>new Error("JP2 output requires libvips with support for OpenJPEG"),PAe=n=>1<<32-Math.clz32(Math.ceil(Math.log2(n))-1);GAe=n=>{Object.assign(n.prototype,{toFile:E3e,toBuffer:C3e,toUint8Array:u3e,withDensity:B3e,keepExif:f3e,withExif:Q3e,withExifMerge:y3e,keepIccProfile:m3e,withIccProfile:S3e,keepGainMap:w3e,withGainMap:D3e,keepXmp:O3e,withXmp:b3e,keepMetadata:M3e,withMetadata:_3e,toFormat:T3e,jpeg:N3e,jp2:P3e,png:R3e,webp:k3e,tiff:G3e,avif:F3e,heif:L3e,jxl:U3e,gif:v3e,raw:H3e,tile:K3e,timeout:x3e,_updateFormatOut:Y3e,_setBooleanOption:j3e,_read:J3e,_pipeline:q3e})}});import z3e from"node:events";import{createRequire as V3e}from"node:module";import{availableParallelism as W3e}from"node:os";function UAe(n){if(O.bool(n))return n?St.cache(50,20,100):St.cache(0,0,0);if(O.object(n)){for(let t of["memory","files","items"]){let o=n[t];if(O.defined(o)&&!(O.integer(o)&&o>=0))throw O.invalidParameterError(t,"a positive integer",o)}return St.cache(n.memory,n.files,n.items)}else return St.cache()}function X3e(n){return St.concurrency(O.integer(n)?n:null)}function eje(){return St.counters()}function Aje(n){return St.simd(O.bool(n)?n:null)}function tje(n){if(O.object(n))if(Array.isArray(n.operation)&&n.operation.every(O.string))St.block(n.operation,!0);else throw O.invalidParameterError("operation","Array",n.operation);else throw O.invalidParameterError("options","object",n)}function rje(n){if(O.object(n))if(Array.isArray(n.operation)&&n.operation.every(O.string))St.block(n.operation,!1);else throw O.invalidParameterError("operation","Array",n.operation);else throw O.invalidParameterError("options","object",n)}var vB,hL,LAe,EL,Zc,Z3e,Qh,$3e,HAe,KAe=ue(()=>{vB=Je(pD(),1);ms();rL();kB();OD();hL=V3e(import.meta.url),LAe=bD.runtimePlatformArch(),EL=St.libvipsVersion(),Zc=St.format();Zc.heif.output.alias=["avif","heic"];Zc.jpeg.output.alias=["jpe","jpg"];Zc.tiff.output.alias=["tif"];Zc.jp2.output.alias=["j2c","j2k","jp2","jpx"];Z3e={nearest:"nearest",bilinear:"bilinear",bicubic:"bicubic",locallyBoundedBicubic:"lbb",nohalo:"nohalo",vertexSplitQuadraticBasisSpline:"vsqbs"},Qh={vips:EL.semver};if(!EL.isGlobal)if(EL.isWasm)try{Qh=hL("@img/sharp-wasm32/versions")}catch{}else try{Qh=hL(`@img/sharp-${LAe}/versions`)}catch{try{Qh=hL(`@img/sharp-libvips-${LAe}/versions`)}catch{}}Qh.sharp=Pg.version;Qh.heif&&Zc.heif&&(Zc.heif.input.fileSuffix=[".avif"],Zc.heif.output.alias=["avif"]);UAe(!0);!process.env.MALLOC_ARENA_MAX&&vB.default.familySync()===vB.default.GLIBC&&!St._isUsingJemalloc()?St.concurrency(1):vB.default.familySync()===vB.default.MUSL&&St.concurrency()===1024&&St.concurrency(W3e());$3e=new z3e.EventEmitter;HAe=n=>{n.cache=UAe,n.concurrency=X3e,n.counters=eje,n.simd=Aje,n.format=Zc,n.interpolators=Z3e,n.versions=Qh,n.queue=$3e,n.block=tje,n.unblock=rje}});var xAe={};Pr(xAe,{default:()=>aje});var aje,YAe=ue(()=>{aAe();nAe();pAe();hAe();uAe();TAe();RAe();FAe();KAe();oAe(bs);lAe(bs);dAe(bs);CAe(bs);_Ae(bs);NAe(bs);GAe(bs);HAe(bs);aje=bs});var ije,bA,Xc,PB=ue(()=>{ije="End-Of-Stream",bA=class extends Error{constructor(){super(ije),this.name="EndOfStreamError"}},Xc=class extends Error{constructor(t="The operation was aborted"){super(t),this.name="AbortError"}}});var ND,jAe=ue(()=>{ND=class{constructor(){this.resolve=()=>null,this.reject=()=>null,this.promise=new Promise((t,o)=>{this.reject=o,this.resolve=t})}}});var $c,RD=ue(()=>{PB();$c=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(t,o=!1){let i=await this.read(t,o);return this.peekQueue.push(t.subarray(0,i)),i}async read(t,o=!1){if(t.length===0)return 0;let i=this.readFromPeekBuffer(t);if(this.endOfStream||(i+=await this.readRemainderFromStream(t.subarray(i),o)),i===0&&!o)throw new bA;return i}readFromPeekBuffer(t){let o=t.length,i=0;for(;this.peekQueue.length>0&&o>0;){let e=this.peekQueue.pop();if(!e)throw new Error("peekData should be defined");let a=Math.min(e.length,o);t.set(e.subarray(0,a),i),i+=a,o-=a,a{PB();jAe();RD();GB=class extends $c{constructor(t){if(super(),this.s=t,this.deferred=null,!t.read||!t.once)throw new Error("Expected an instance of stream.Readable");this.s.once("end",()=>{this.endOfStream=!0,this.deferred&&this.deferred.resolve(0)}),this.s.once("error",o=>this.reject(o)),this.s.once("close",()=>this.abort())}async readFromStream(t,o){if(t.length===0)return 0;let i=this.s.read(t.length);if(i)return t.set(i),i.length;let e={buffer:t,mayBeLess:o,deferred:new ND};return this.deferred=e.deferred,this.s.once("readable",()=>{this.readDeferred(e)}),e.deferred.promise}readDeferred(t){let o=this.s.read(t.buffer.length);o?(t.buffer.set(o),t.deferred.resolve(o.length),this.deferred=null):this.s.once("readable",()=>{this.readDeferred(t)})}reject(t){this.interrupted=!0,this.deferred&&(this.deferred.reject(t),this.deferred=null)}async abort(){this.reject(new Xc)}async close(){return this.abort()}}});var kD,qAe=ue(()=>{RD();kD=class extends $c{constructor(t){super(),this.reader=t}async abort(){return this.close()}async close(){this.reader.releaseLock()}}});var FB,CL=ue(()=>{qAe();FB=class extends kD{async readFromStream(t,o){if(t.length===0)return 0;let i=await this.reader.read(new Uint8Array(t.length),{min:o?void 0:t.length});return i.done&&(this.endOfStream=i.done),i.value?(t.set(i.value),i.value.length):0}}});var yh,uL=ue(()=>{PB();RD();yh=class extends $c{constructor(t){super(),this.reader=t,this.buffer=null}writeChunk(t,o){let i=Math.min(o.length,t.length);return t.set(o.subarray(0,i)),i{CL();uL()});var eI=ue(()=>{PB();JAe();CL();uL();zAe()});var vn,mh=ue(()=>{eI();vn=class{constructor(t){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=t?.onClose,t?.abortSignal&&t.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(t,o=this.position){let i=new Uint8Array(t.len);if(await this.readBuffer(i,{position:o})o)return this.position+=o,o}return this.position+=t,t}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(t,o){if(!this.supportsRandomAccess()&&o&&o.position!==void 0&&o.position{mh();eI();oje=256e3,LB=class extends vn{constructor(t,o){super(o),this.streamReader=t,this.fileInfo=o?.fileInfo??{}}async readBuffer(t,o){let i=this.normalizeOptions(t,o),e=i.position-this.position;if(e>0)return await this.ignore(e),this.readBuffer(t,o);if(e<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(i.length===0)return 0;let a=await this.streamReader.read(t.subarray(0,i.length),i.mayBeLess);if(this.position+=a,(!o||!o.mayBeLess)&&a0){let A=new Uint8Array(i.length+a);return e=await this.peekBuffer(A,{mayBeLess:i.mayBeLess}),t.set(A.subarray(a)),e-a}if(a<0)throw new Error("Cannot peek from a negative offset in a stream")}if(i.length>0){try{e=await this.streamReader.peek(t.subarray(0,i.length),i.mayBeLess)}catch(a){if(o?.mayBeLess&&a instanceof bA)return 0;throw a}if(!i.mayBeLess&&e{eI();mh();vD=class extends vn{constructor(t,o){super(o),this.uint8Array=t,this.fileInfo={...o?.fileInfo??{},size:t.length}}async readBuffer(t,o){o?.position&&(this.position=o.position);let i=await this.peekBuffer(t,o);return this.position+=i,i}async peekBuffer(t,o){let i=this.normalizeOptions(t,o),e=Math.min(this.uint8Array.length-i.position,i.length);if(!i.mayBeLess&&e{eI();mh();PD=class extends vn{constructor(t,o){super(o),this.blob=t,this.fileInfo={...o?.fileInfo??{},size:t.size,mimeType:t.type}}async readBuffer(t,o){o?.position&&(this.position=o.position);let i=await this.peekBuffer(t,o);return this.position+=i,i}async peekBuffer(t,o){let i=this.normalizeOptions(t,o),e=Math.min(this.blob.size-i.position,i.length);if(!i.mayBeLess&&e{if(await o.close(),e)return e()},new LB(o,i)}function GD(n,t){let o=BL(n),i=t??{},e=i.onClose;return i.onClose=async()=>{if(await o.close(),e)return e()},new LB(o,i)}function no(n,t){return new vD(n,t)}function FD(n,t){return new PD(n,t)}var LD=ue(()=>{eI();VAe();WAe();ZAe();eI();mh()});import{open as sje}from"node:fs/promises";var Sh,fL=ue(()=>{mh();eI();Sh=class n extends vn{static async fromFile(t){let o=await sje(t,"r"),i=await o.stat();return new n(o,{fileInfo:{path:t,size:i.size}})}constructor(t,o){super(o),this.fileHandle=t,this.fileInfo=o.fileInfo}async readBuffer(t,o){let i=this.normalizeOptions(t,o);if(this.position=i.position,i.length===0)return 0;let e=await this.fileHandle.read(t,0,i.length,i.position);if(this.position+=e.bytesRead,e.bytesRead{LD();fL();fL();LD();$Ae=Sh.fromFile});var ete=$(yL=>{yL.read=function(n,t,o,i,e){var a,A,r=e*8-i-1,s=(1<>1,c=-7,I=o?e-1:0,d=o?-1:1,B=n[t+I];for(I+=d,a=B&(1<<-c)-1,B>>=-c,c+=r;c>0;a=a*256+n[t+I],I+=d,c-=8);for(A=a&(1<<-c)-1,a>>=-c,c+=i;c>0;A=A*256+n[t+I],I+=d,c-=8);if(a===0)a=1-g;else{if(a===s)return A?NaN:(B?-1:1)*(1/0);A=A+Math.pow(2,i),a=a-g}return(B?-1:1)*A*Math.pow(2,a-i)};yL.write=function(n,t,o,i,e,a){var A,r,s,g=a*8-e-1,c=(1<>1,d=e===23?Math.pow(2,-24)-Math.pow(2,-77):0,B=i?0:a-1,f=i?1:-1,Q=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(r=isNaN(t)?1:0,A=c):(A=Math.floor(Math.log(t)/Math.LN2),t*(s=Math.pow(2,-A))<1&&(A--,s*=2),A+I>=1?t+=d/s:t+=d*Math.pow(2,1-I),t*s>=2&&(A++,s/=2),A+I>=c?(r=0,A=c):A+I>=1?(r=(t*s-1)*Math.pow(2,e),A=A+I):(r=t*Math.pow(2,I-1)*Math.pow(2,e),A=0));e>=8;n[o+B]=r&255,B+=f,r/=256,e-=8);for(A=A<0;n[o+B]=A&255,B+=f,A/=256,g-=8);n[o+B-f]|=Q*128}});function cje(){if(!(typeof globalThis.TextDecoder>"u"))return UD??(UD=new globalThis.TextDecoder("utf-8"))}function Ije(){if(!(typeof globalThis.TextEncoder>"u"))return HD??(HD=new globalThis.TextEncoder)}function wr(n,t="utf-8"){switch(t.toLowerCase()){case"utf-8":case"utf8":{let o=cje();return o?o.decode(n):pje(n)}case"utf-16le":return dje(n);case"us-ascii":case"ascii":return hje(n);case"latin1":case"iso-8859-1":return Eje(n);case"windows-1252":return Cje(n);default:throw new RangeError(`Encoding '${t}' not supported`)}}function tte(n="",t="utf-8"){switch(t.toLowerCase()){case"utf-8":case"utf8":{let o=Ije();return o?o.encode(n):uje(n)}case"utf-16le":return Bje(n);case"us-ascii":case"ascii":return fje(n);case"latin1":case"iso-8859-1":return Qje(n);case"windows-1252":return yje(n);default:throw new RangeError(`Encoding '${t}' not supported`)}}function SL(n,t){t.length!==0&&(n.push(String.fromCharCode.apply(null,t)),t.length=0)}function Rr(n,t,o){t.push(o),t.length>=wh&&SL(n,t)}function lje(n,t,o){if(o<=65535){Rr(n,t,o);return}o-=65536,Rr(n,t,55296+(o>>10)),Rr(n,t,56320+(o&1023))}function pje(n){let t=[],o=[],i=0;for(n.length>=3&&n[0]===239&&n[1]===187&&n[2]===191&&(i=3);i244){Rr(t,o,wa),i++;continue}if(e<=223){if(i+1>=n.length){Rr(t,o,wa),i++;continue}let c=n[i+1];if((c&192)!==128){Rr(t,o,wa),i++;continue}let I=(e&31)<<6|c&63;Rr(t,o,I),i+=2;continue}if(e<=239){if(i+2>=n.length){Rr(t,o,wa),i++;continue}let c=n[i+1],I=n[i+2];if(!((c&192)===128&&(I&192)===128&&!(e===224&&c<160)&&!(e===237&&c>=160))){Rr(t,o,wa),i++;continue}let B=(e&15)<<12|(c&63)<<6|I&63;Rr(t,o,B),i+=3;continue}if(i+3>=n.length){Rr(t,o,wa),i++;continue}let a=n[i+1],A=n[i+2],r=n[i+3];if(!((a&192)===128&&(A&192)===128&&(r&192)===128&&!(e===240&&a<144)&&!(e===244&&a>143))){Rr(t,o,wa),i++;continue}let g=(e&7)<<18|(a&63)<<12|(A&63)<<6|r&63;lje(t,o,g),i+=4}return SL(t,o),t.join("")}function dje(n){let t=[],o=[],i=n.length,e=0;for(;e+1=55296&&a<=56319){if(e+1=56320&&A<=57343?(Rr(t,o,a),Rr(t,o,A),e+=2):Rr(t,o,wa)}else Rr(t,o,wa);continue}if(a>=56320&&a<=57343){Rr(t,o,wa);continue}Rr(t,o,a)}return e=128&&e<=159?Ate[e]:void 0;o+=a??String.fromCharCode(e),o.length>=wh&&(t.push(o),o="")}return o&&t.push(o),t.join("")}function uje(n){let t=[];for(let o=0;o=55296&&i<=56319)if(o+1=56320&&e<=57343?(i=65536+(i-55296<<10)+(e-56320),o++):i=wa}else i=wa;else i>=56320&&i<=57343&&(i=wa);i<128?t.push(i):i<2048?t.push(192|i>>6,128|i&63):i<65536?t.push(224|i>>12,128|i>>6&63,128|i&63):t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63)}return new Uint8Array(t)}function Bje(n){let t=[];for(let i=0;i=55296&&e<=56319){if(i+1=56320&&a<=57343?(t.push(e,a),i++):t.push(wa)}else t.push(wa);continue}if(e>=56320&&e<=57343){t.push(wa);continue}t.push(e)}let o=new Uint8Array(t.length*2);for(let i=0;i>>8}return o}function fje(n){let t=new Uint8Array(n.length);for(let o=0;o=0&&e<=127||e>=160&&e<=255){t[o]=e;continue}t[o]=63}return t}var Ate,mL,UD,HD,wh,wa,_s=ue(()=>{Ate={128:"\u20AC",130:"\u201A",131:"\u0192",132:"\u201E",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02C6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017D",145:"\u2018",146:"\u2019",147:"\u201C",148:"\u201D",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02DC",153:"\u2122",154:"\u0161",155:"\u203A",156:"\u0153",158:"\u017E",159:"\u0178"},mL={};for(let[n,t]of Object.entries(Ate))mL[t]=Number.parseInt(n,10);wh=32*1024,wa=65533});var VA={};Pr(VA,{AnsiStringType:()=>DL,Float16_BE:()=>wje,Float16_LE:()=>Dje,Float32_BE:()=>ML,Float32_LE:()=>Oje,Float64_BE:()=>xD,Float64_LE:()=>bje,Float80_BE:()=>Mje,Float80_LE:()=>_je,INT16_BE:()=>qo,INT16_LE:()=>mje,INT24_BE:()=>KD,INT24_LE:()=>Sje,INT32_BE:()=>oi,INT32_LE:()=>sr,INT64_BE:()=>bL,INT64_LE:()=>OL,INT8:()=>Ns,IgnoreType:()=>wL,StringType:()=>ze,UINT16_BE:()=>GA,UINT16_LE:()=>SA,UINT24_BE:()=>kr,UINT24_LE:()=>HB,UINT32_BE:()=>Ue,UINT32_LE:()=>Ge,UINT64_BE:()=>Rs,UINT64_LE:()=>Dr,UINT8:()=>fA,Uint8ArrayType:()=>Dt});function zA(n){return new DataView(n.buffer,n.byteOffset)}var Ts,fA,SA,GA,HB,kr,Ge,Ue,Ns,qo,mje,Sje,KD,oi,sr,Dr,OL,Rs,bL,wje,Dje,ML,Oje,xD,bje,Mje,_je,wL,Dt,ze,DL,DA=ue(()=>{Ts=Je(ete(),1);_s();fA={len:1,get(n,t){return zA(n).getUint8(t)},put(n,t,o){return zA(n).setUint8(t,o),t+1}},SA={len:2,get(n,t){return zA(n).getUint16(t,!0)},put(n,t,o){return zA(n).setUint16(t,o,!0),t+2}},GA={len:2,get(n,t){return zA(n).getUint16(t)},put(n,t,o){return zA(n).setUint16(t,o),t+2}},HB={len:3,get(n,t){let o=zA(n);return o.getUint8(t)+(o.getUint16(t+1,!0)<<8)},put(n,t,o){let i=zA(n);return i.setUint8(t,o&255),i.setUint16(t+1,o>>8,!0),t+3}},kr={len:3,get(n,t){let o=zA(n);return(o.getUint16(t)<<8)+o.getUint8(t+2)},put(n,t,o){let i=zA(n);return i.setUint16(t,o>>8),i.setUint8(t+2,o&255),t+3}},Ge={len:4,get(n,t){return zA(n).getUint32(t,!0)},put(n,t,o){return zA(n).setUint32(t,o,!0),t+4}},Ue={len:4,get(n,t){return zA(n).getUint32(t)},put(n,t,o){return zA(n).setUint32(t,o),t+4}},Ns={len:1,get(n,t){return zA(n).getInt8(t)},put(n,t,o){return zA(n).setInt8(t,o),t+1}},qo={len:2,get(n,t){return zA(n).getInt16(t)},put(n,t,o){return zA(n).setInt16(t,o),t+2}},mje={len:2,get(n,t){return zA(n).getInt16(t,!0)},put(n,t,o){return zA(n).setInt16(t,o,!0),t+2}},Sje={len:3,get(n,t){let o=HB.get(n,t);return o>8388607?o-16777216:o},put(n,t,o){let i=zA(n);return i.setUint8(t,o&255),i.setUint16(t+1,o>>8,!0),t+3}},KD={len:3,get(n,t){let o=kr.get(n,t);return o>8388607?o-16777216:o},put(n,t,o){let i=zA(n);return i.setUint16(t,o>>8),i.setUint8(t+2,o&255),t+3}},oi={len:4,get(n,t){return zA(n).getInt32(t)},put(n,t,o){return zA(n).setInt32(t,o),t+4}},sr={len:4,get(n,t){return zA(n).getInt32(t,!0)},put(n,t,o){return zA(n).setInt32(t,o,!0),t+4}},Dr={len:8,get(n,t){return zA(n).getBigUint64(t,!0)},put(n,t,o){return zA(n).setBigUint64(t,o,!0),t+8}},OL={len:8,get(n,t){return zA(n).getBigInt64(t,!0)},put(n,t,o){return zA(n).setBigInt64(t,o,!0),t+8}},Rs={len:8,get(n,t){return zA(n).getBigUint64(t)},put(n,t,o){return zA(n).setBigUint64(t,o),t+8}},bL={len:8,get(n,t){return zA(n).getBigInt64(t)},put(n,t,o){return zA(n).setBigInt64(t,o),t+8}},wje={len:2,get(n,t){return Ts.read(n,t,!1,10,this.len)},put(n,t,o){return Ts.write(n,o,t,!1,10,this.len),t+this.len}},Dje={len:2,get(n,t){return Ts.read(n,t,!0,10,this.len)},put(n,t,o){return Ts.write(n,o,t,!0,10,this.len),t+this.len}},ML={len:4,get(n,t){return zA(n).getFloat32(t)},put(n,t,o){return zA(n).setFloat32(t,o),t+4}},Oje={len:4,get(n,t){return zA(n).getFloat32(t,!0)},put(n,t,o){return zA(n).setFloat32(t,o,!0),t+4}},xD={len:8,get(n,t){return zA(n).getFloat64(t)},put(n,t,o){return zA(n).setFloat64(t,o),t+8}},bje={len:8,get(n,t){return zA(n).getFloat64(t,!0)},put(n,t,o){return zA(n).setFloat64(t,o,!0),t+8}},Mje={len:10,get(n,t){return Ts.read(n,t,!1,63,this.len)},put(n,t,o){return Ts.write(n,o,t,!1,63,this.len),t+this.len}},_je={len:10,get(n,t){return Ts.read(n,t,!0,63,this.len)},put(n,t,o){return Ts.write(n,o,t,!0,63,this.len),t+this.len}},wL=class{constructor(t){this.len=t}get(t,o){}},Dt=class{constructor(t){this.len=t}get(t,o){return t.subarray(o,o+this.len)}},ze=class{constructor(t,o){this.len=t,this.encoding=o}get(t,o=0){let i=t.subarray(o,o+this.len);return wr(i,this.encoding)}},DL=class extends ze{constructor(t){super(t,"windows-1252")}}});var Rl,_L,rte,ate,ite,ote=ue(()=>{DA();Rl={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},_L={get(n){return{signature:Ge.get(n,0),compressedSize:Ge.get(n,8),uncompressedSize:Ge.get(n,12)}},len:16},rte={get(n){let t=SA.get(n,6);return{signature:Ge.get(n,0),minVersion:SA.get(n,4),dataDescriptor:!!(t&8),compressedMethod:SA.get(n,8),compressedSize:Ge.get(n,18),uncompressedSize:Ge.get(n,22),filenameLength:SA.get(n,26),extraFieldLength:SA.get(n,28),filename:null}},len:30},ate={get(n){return{signature:Ge.get(n,0),nrOfThisDisk:SA.get(n,4),nrOfThisDiskWithTheStart:SA.get(n,6),nrOfEntriesOnThisDisk:SA.get(n,8),nrOfEntriesOfSize:SA.get(n,10),sizeOfCd:Ge.get(n,12),offsetOfStartOfCd:Ge.get(n,16),zipFileCommentLength:SA.get(n,20)}},len:22},ite={get(n){let t=SA.get(n,8);return{signature:Ge.get(n,0),minVersion:SA.get(n,6),dataDescriptor:!!(t&8),compressedMethod:SA.get(n,10),compressedSize:Ge.get(n,20),uncompressedSize:Ge.get(n,24),filenameLength:SA.get(n,28),extraFieldLength:SA.get(n,30),fileCommentLength:SA.get(n,32),relativeOffsetOfLocalHeader:Ge.get(n,42),filename:null}},len:46}});function ste(n){let t=new Uint8Array(Ge.len);return Ge.put(t,0,n),t}function Nje(n,t){let o=n.length,i=t.length;if(i>o)return-1;for(let e=0;e<=o-i;e++){let a=!0;for(let A=0;Ae+a.length,0),o=new Uint8Array(t),i=0;for(let e of n)o.set(e,i),i+=e.length;return o}var nte,ks,TL,Tje,YD,kl,gte=ue(()=>{DA();nte=Je(ct(),1);ote();ks=(0,nte.default)("tokenizer:inflate"),TL=256*1024,Tje=ste(Rl.DataDescriptor),YD=ste(Rl.EndOfCentralDirectory),kl=class n{constructor(t){this.tokenizer=t,this.syncBuffer=new Uint8Array(TL)}async isZip(){return await this.peekSignature()===Rl.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(Ge)}async findEndOfCentralDirectoryLocator(){let t=this.tokenizer,o=Math.min(16*1024,t.fileInfo.size),i=this.syncBuffer.subarray(0,o);await this.tokenizer.readBuffer(i,{position:t.fileInfo.size-o});for(let e=i.length-4;e>=0;e--)if(i[e]===YD[0]&&i[e+1]===YD[1]&&i[e+2]===YD[2]&&i[e+3]===YD[3])return t.fileInfo.size-o+e;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){ks("Cannot reading central-directory without random-read support");return}ks("Reading central-directory...");let t=this.tokenizer.position,o=await this.findEndOfCentralDirectoryLocator();if(o>0){ks("Central-directory 32-bit signature found");let i=await this.tokenizer.readToken(ate,o),e=[];this.tokenizer.setPosition(i.offsetOfStartOfCd);for(let a=0;a=0?g:s;if(a.handler){let I=new Uint8Array(c);await this.tokenizer.readBuffer(I),r.push(I)}else await this.tokenizer.ignore(c)}ks(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),a.handler&&await this.inflate(e,Rje(r),a.handler)}else a.handler?(ks(`Reading compressed-file-data: ${e.compressedSize} bytes`),A=new Uint8Array(e.compressedSize),await this.tokenizer.readBuffer(A),await this.inflate(e,A,a.handler)):(ks(`Ignoring compressed-file-data: ${e.compressedSize} bytes`),await this.tokenizer.ignore(e.compressedSize));if(ks(`Reading data-descriptor at pos=${this.tokenizer.position}`),e.dataDescriptor&&(await this.tokenizer.readToken(_L)).signature!==134695760)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-_L.len}`)}while(!i)}async iterateOverCentralDirectory(t,o){for(let i of t){let e=o(i);if(e.handler){this.tokenizer.setPosition(i.relativeOffsetOfLocalHeader);let a=await this.readLocalFileHeader();if(a){await this.tokenizer.ignore(a.extraFieldLength);let A=new Uint8Array(i.compressedSize);await this.tokenizer.readBuffer(A),await this.inflate(a,A,e.handler)}}if(e.stop)break}}async inflate(t,o,i){if(t.compressedMethod===0)return i(o);if(t.compressedMethod!==8)throw new Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);ks(`Decompress filename=${t.filename}, compressed-size=${o.length}`);let e=await n.decompressDeflateRaw(o);return i(e)}static async decompressDeflateRaw(t){let o=new ReadableStream({start(a){a.enqueue(t),a.close()}}),i=new DecompressionStream("deflate-raw"),e=o.pipeThrough(i);try{let A=await new Response(e).arrayBuffer();return new Uint8Array(A)}catch(a){let A=a instanceof Error?`Failed to deflate ZIP entry: ${a.message}`:"Unknown decompression error in ZIP entry";throw new TypeError(A)}}async readLocalFileHeader(){let t=await this.tokenizer.peekToken(Ge);if(t===Rl.LocalFileHeader){let o=await this.tokenizer.readToken(rte);return o.filename=await this.tokenizer.readToken(new ze(o.filenameLength,"utf-8")),o}if(t===Rl.CentralFileHeader)return!1;throw t===3759263696?new Error("Encrypted ZIP"):new Error("Unexpected signature")}}});var KB,cte=ue(()=>{KB=class{constructor(t){this.tokenizer=t}inflate(){let t=this.tokenizer;return new ReadableStream({async pull(o){let i=new Uint8Array(1024),e=await t.readBuffer(i,{mayBeLess:!0});if(e===0){o.close();return}o.enqueue(i.subarray(0,e))}}).pipeThrough(new DecompressionStream("gzip"))}}});var Ite=ue(()=>{gte();cte()});function Pje(n,t,o){return n?n.constructor===t?!0:kje.call(n)===o:!1}function Gje(n){return Pje(n,Uint8Array,vje)}function Fje(n){if(!Gje(n))throw new TypeError(`Expected \`Uint8Array\`, got \`${typeof n}\``)}function jD(n){Fje(n);let t="";for(let o=0;o{kje=Object.prototype.toString,vje="[object Uint8Array]";CSA={utf8:new globalThis.TextDecoder("utf8")},uSA=new globalThis.TextEncoder,Lje=Array.from({length:256},(n,t)=>t.toString(16).padStart(2,"0"))});function lte(n,t){if(t==="utf-16le"){let o=[];for(let i=0;i>8&255)}return o}if(t==="utf-16be"){let o=[];for(let i=0;i>8&255,e&255)}return o}return[...n].map(o=>o.charCodeAt(0))}function pte(n,t=0){let o=Number.parseInt(new ze(6).get(n,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(o))return!1;let i=256;for(let e=t;e{DA();dte={get:(n,t)=>n[t+3]&127|n[t+2]<<7|n[t+1]<<14|n[t]<<21,len:4}});var Ete,Cte,ute=ue(()=>{Ete=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","jmp","rm","sav","ppsm","ppsx","tar.gz","reg","dat"],Cte=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/vnd.apache.arrow.file","video/mp4","audio/midi","video/matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/vnd.apache.parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia","application/x-spss-sav","application/x-ms-regedit","application/x-ft-windows-registry-hive","application/x-jmp-data"]});function $je(n){let t=n?.streamReader;if(t?.constructor?.name!=="WebStreamByobReader")return n;let{reader:o}=t,i=async()=>{await o.cancel(),o.releaseLock()};return t.close=i,t.abort=async()=>{t.interrupted=!0,await i()},n}function vL(n,t,o){if(!Number.isFinite(n)||n<0||n>t)throw new Lg(`${o} has invalid size ${n} (maximum ${t} bytes)`);return n}async function AI(n,t,{maximumLength:o=zo,reason:i="skip"}={}){let e=vL(t,o,i);await n.ignore(e)}async function RL(n,t,o,{maximumLength:i=t.length,reason:e="read"}={}){let a=o?.length??t.length,A=vL(a,i,e);return n.readBuffer(t,{...o,length:A})}async function eJe(n,{maximumLength:t=Ps}={}){let e=new ReadableStream({start(g){g.enqueue(n),g.close()}}).pipeThrough(new DecompressionStream("deflate-raw")).getReader(),a=[],A=0;try{for(;;){let{done:g,value:c}=await e.read();if(g)break;if(A+=c.length,A>t)throw await e.cancel(),new Error(`ZIP entry decompressed data exceeds ${t} bytes`);a.push(c)}}finally{e.releaseLock()}let r=new Uint8Array(A),s=0;for(let g of a)r.set(g,s),s+=g.length;return r}function tJe(n,t){if(n.length=0?0:r===e?Math.min(AJe,r-1):0,c=s>=0?s:r-g;if(c===0)break;if(A+=c,A>o)throw new Error(`ZIP entry compressed data exceeds ${o} bytes`);if(t){let I=new Uint8Array(c);await n.tokenizer.readBuffer(I),a.push(I)}else await n.tokenizer.ignore(c);if(s>=0)break}if(ni(n.tokenizer)||(n.knownSizeDescriptorScannedBytes+=A),!!t)return aJe(a,A)}function oJe(n,t){return ni(n.tokenizer)?Math.max(0,zo-(n.tokenizer.position-t)):Math.max(0,Ps-n.knownSizeDescriptorScannedBytes)}async function nJe(n,t,{shouldBuffer:o,maximumDescriptorLength:i=Ps}={}){if(t.dataDescriptor&&t.compressedSize===0)return iJe(n,{shouldBuffer:o,maximumLength:i});if(!o){await AI(n.tokenizer,t.compressedSize,{maximumLength:ni(n.tokenizer)?Ps:n.tokenizer.fileInfo.size,reason:"ZIP entry compressed data"});return}let e=pJe(n.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>e)throw new Error(`ZIP entry compressed data exceeds ${e} bytes`);let a=new Uint8Array(t.compressedSize);return await n.tokenizer.readBuffer(a),a}function sJe(n,t){let o=n.getReader(),i=0,e=!1,a=!1,A=async r=>{e||a||(a=!0,await o.cancel(r))};return new ReadableStream({async pull(r){if(i>=t){r.close(),await A();return}let{done:s,value:g}=await o.read();if(s||!g){e=!0,r.close();return}let c=t-i;if(g.length>c){r.enqueue(g.subarray(0,c)),i+=c,r.close(),await A();return}r.enqueue(g),i+=g.length},async cancel(r){await A(r)}})}async function qB(n,t){return new kL(t).fromBuffer(n)}function bte(n){switch(n=n.toLowerCase(),n){case"application/epub+zip":return{ext:"epub",mime:n};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:n};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:n};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:n};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:n};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:n};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:n};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:n};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:n};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:n};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:n};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:n};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:n};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:n};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:n};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:n};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"};default:}}function vs(n,t,o){o={offset:0,...o};for(let[i,e]of t.entries())if(o.mask){if(e!==(o.mask[i]&n[i+o.offset]))return!1}else if(e!==n[i+o.offset])return!1;return!0}function gJe(n){return Number.isFinite(n)?Math.max(1,Math.trunc(n)):jB}function cJe(n,t,o){return o===void 0?n.read(t):(o.throwIfAborted(),new Promise((i,e)=>{let a=()=>{o.removeEventListener("abort",A)},A=()=>{let r=o.reason;a(),(async()=>{try{await n.cancel(r)}catch{}})(),e(r)};o.addEventListener("abort",A,{once:!0}),(async()=>{try{let r=await n.read(t);a(),i(r)}catch(r){a(),e(r)}})()}))}function IJe(n){return Number.isFinite(n)?Math.max(0,Math.min(Uje,Math.trunc(n))):0}function lJe(n){return Number.isFinite(n)?Math.max(0,n):Number.MAX_SAFE_INTEGER}function ni(n){let t=n.fileInfo.size;return!Number.isFinite(t)||t===Number.MAX_SAFE_INTEGER}function JB(n,t,o){return ni(n)&&n.position-t>o}function pJe(n){let t=n.fileInfo.size,o=Number.isFinite(t)?Math.max(0,t-n.position):Number.MAX_SAFE_INTEGER;return Math.min(o,Hje)}function dJe(n){if(n instanceof bA||n instanceof Lg)return!0;if(!(n instanceof Error))return!1;if(Wje.has(n.message)||Xje.has(n.code))return!0;for(let t of Zje)if(n.message.startsWith(t))return!0;return!1}function Mte(n,t=Ps){let o=[n.compressedSize,n.uncompressedSize];for(let i of o)if(!Number.isFinite(i)||i<0||i>t)return!1;return!0}function hJe(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function EJe(n,t){t.startsWith("word/")&&(n.hasWordDirectory=!0),t.startsWith("ppt/")&&(n.hasPresentationDirectory=!0),t.startsWith("xl/")&&(n.hasSpreadsheetDirectory=!0),t.startsWith("3D/")&&t.endsWith(".model")&&(n.hasThreeDimensionalModelEntry=!0)}function _te(n){if(!(!n.hasContentTypesEntry||n.hasUnparseableContentTypes||n.isParsingContentTypes||n.hasParsedContentTypesEntry)){if(n.hasWordDirectory)return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};if(n.hasPresentationDirectory)return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};if(n.hasSpreadsheetDirectory)return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};if(n.hasThreeDimensionalModelEntry)return{ext:"3mf",mime:"model/3mf"}}}function CJe(n){let t=n.indexOf('.main+xml"');if(t===-1){let e="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";return n.includes(`ContentType="${e}"`)?e:void 0}let o=n.slice(0,t),i=o.lastIndexOf('"');return o.slice(i+1)}var jB,Uje,Ps,Bte,Hje,zo,qD,fte,Kje,xje,Qte,NL,yte,mte,Yje,jje,Jje,qje,zje,Ste,wte,Dte,Vje,Ote,Wje,Zje,Xje,Lg,Tte,JD,AJe,kL,uJe,BJe,Nte=ue(()=>{DA();LD();Ite();YB();hte();ute();jB=4100,Uje=jB-2,Ps=1024*1024,Bte=1024,Hje=2**31-1,zo=16*1024*1024,qD=Ps,fte=Ps,Kje=zo,xje=1,Qte=100,NL=zo,yte=64,mte=qD,Yje=256,jje=512,Jje=zo,qje=512,zje=512,Ste=256,wte=qD,Dte=qD,Vje=qD,Ote=zo,Wje=new Set(["Unexpected signature","Encrypted ZIP","Expected Central-File-Header signature"]),Zje=["ZIP entry count exceeds ","Unsupported ZIP compression method:","ZIP entry compressed data exceeds ","ZIP entry decompressed data exceeds ","Expected data-descriptor-signature at position "],Xje=new Set(["Z_BUF_ERROR","Z_DATA_ERROR","ERR_INVALID_STATE"]),Lg=class extends Error{};Tte=134695760,JD=16,AJe=JD-1;kl.prototype.inflate=async function(n,t,o){if(n.compressedMethod===0)return o(t);if(n.compressedMethod!==8)throw new Error(`Unsupported ZIP compression method: ${n.compressedMethod}`);let i=await eJe(t,{maximumLength:Ps});return o(i)};kl.prototype.unzip=async function(n){let t=!1,o=0,i=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(JB(this.tokenizer,i,zo))throw new Lg(`ZIP stream probing exceeds ${zo} bytes`);let e=await this.readLocalFileHeader();if(!e)break;if(o++,o>Bte)throw new Error(`ZIP entry count exceeds ${Bte}`);let a=n(e);t=!!a.stop,await this.tokenizer.ignore(e.extraFieldLength);let A=await nJe(this,e,{shouldBuffer:!!a.handler,maximumDescriptorLength:Math.min(Ps,oJe(this,i))});if(a.handler&&await this.inflate(e,A,a.handler),e.dataDescriptor){let r=new Uint8Array(JD);if(await this.tokenizer.readBuffer(r),Ge.get(r,0)!==Tte)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-r.length}`)}if(JB(this.tokenizer,i,zo))throw new Lg(`ZIP stream probing exceeds ${zo} bytes`)}while(!t)};kL=class n{constructor(t){let o=IJe(t?.mpegOffsetTolerance);this.options={...t,mpegOffsetTolerance:o},this.detectors=[...this.options.customDetectors??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(t){return $je(GD(t,this.getTokenizerOptions()))}async parseTokenizer(t,o=0){this.detectionReentryCount=o;let i=t.position;for(let e of this.detectors){let a;try{a=await e.detect(t)}catch(A){if(A instanceof bA||A instanceof Lg)return;throw A}if(a)return a;if(i!==t.position)return}}async fromTokenizer(t){try{return await this.parseTokenizer(t)}finally{await t.close()}}async fromBuffer(t){if(!(t instanceof Uint8Array||t instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof t}\``);let o=t instanceof Uint8Array?t:new Uint8Array(t);if(o?.length>1)return this.fromTokenizer(no(o,this.getTokenizerOptions()))}async fromBlob(t){this.options.signal?.throwIfAborted();let o=FD(t,this.getTokenizerOptions());return this.fromTokenizer(o)}async fromStream(t){this.options.signal?.throwIfAborted();let o=this.createTokenizerFromWebStream(t);return this.fromTokenizer(o)}async toDetectionStream(t,o){let i=gJe(o?.sampleSize??jB),e,a,A=t.getReader({mode:"byob"});try{let{value:g,done:c}=await cJe(A,new Uint8Array(i),this.options.signal);if(a=g,!c&&g)try{e=await this.fromBuffer(g.subarray(0,i))}catch(I){if(!(I instanceof bA))throw I;e=void 0}a=g}finally{A.releaseLock()}let r=new TransformStream({async start(g){g.enqueue(a)},transform(g,c){c.enqueue(g)}}),s=t.pipeThrough(r);return s.fileType=e,s}async detectGzip(t){if(this.gzipProbeDepth>=xje)return{ext:"gz",mime:"application/gzip"};let o=new KB(t),i=sJe(o.inflate(),Kje),e=ni(t),a,A,r,s;if(e){let g=new AbortController;a=setTimeout(()=>{g.abort(new DOMException(`Operation timed out after ${Qte} ms`,"TimeoutError"))},Qte),A=this.options.signal===void 0?g.signal:AbortSignal.any([this.options.signal,g.signal]),r=new n({...this.options,signal:A}),r.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{s=await(r??this).fromStream(i)}catch(g){if(g?.name==="AbortError"&&A?.reason?.name!=="TimeoutError")throw g}finally{clearTimeout(a),e||this.gzipProbeDepth--}return s?.ext==="tar"?{ext:"tar.gz",mime:"application/gzip"}:{ext:"gz",mime:"application/gzip"}}check(t,o){return vs(this.buffer,t,o)}checkString(t,o){return this.check(lte(t,o?.encoding),o)}detectConfident=async t=>{if(this.buffer=new Uint8Array(jB),t.fileInfo.size===void 0&&(t.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=t,ni(t)&&(await t.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(t);if(await t.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await t.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.detectionReentryCount>=Ste?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(t));if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return this.detectGzip(t);if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await AI(t,6,{maximumLength:6,reason:"ID3 header prefix"});let o=await t.readToken(dte),i=ni(t);if(!Number.isFinite(o)||o<0||i&&(o>NL||t.position+o>NL))return;if(t.position+o>t.fileInfo.size)return i?void 0:{ext:"mp3",mime:"audio/mpeg"};try{await AI(t,o,{maximumLength:i?NL:t.fileInfo.size,reason:"ID3 payload"})}catch(e){if(e instanceof bA)return;throw e}return this.detectionReentryCount>=Ste?void 0:(this.detectionReentryCount++,this.parseTokenizer(t,this.detectionReentryCount))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let o,i=hJe();try{await new kl(t).unzip(e=>{EJe(i,e.filename);let a=e.filename==="[Content_Types].xml",A=_te(i);if(!a&&A)return o=A,{stop:!0};switch(e.filename){case"META-INF/mozilla.rsa":return o={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return o={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return Mte(e,fte)?{async handler(r){let s=new TextDecoder("utf-8").decode(r).trim();o=bte(s)},stop:!0}:{};case"[Content_Types].xml":return i.hasContentTypesEntry=!0,Mte(e,fte)?(i.isParsingContentTypes=!0,{async handler(r){let s=new TextDecoder("utf-8").decode(r),g=CJe(s);g&&(o=bte(g)),i.hasParsedContentTypesEntry=!0,i.isParsingContentTypes=!1},stop:!0}):(i.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/.test(e.filename)?(o={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}})}catch(e){if(!dJe(e))throw e;i.isParsingContentTypes&&(i.isParsingContentTypes=!1,i.hasUnparseableContentTypes=!0)}return o??_te(i)??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await t.ignore(28);let o=new Uint8Array(8);return await t.readBuffer(o),vs(o,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:vs(o,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:vs(o,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:vs(o,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:vs(o,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:vs(o,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF"))return{ext:"pdf",mime:"application/pdf"};if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let o=await this.readTiffHeader(!1);if(o)return o}if(this.check([77,77])){let o=await this.readTiffHeader(!0);if(o)return o}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function o(){let s=await t.peekNumber(fA),g=128,c=0;for(;(s&g)===0&&g!==0;)++c,g>>=1;let I=new Uint8Array(c+1);return await RL(t,I,void 0,{maximumLength:I.length,reason:"EBML field"}),I}async function i(){let s=await o(),g=await o();g[0]^=128>>g.length-1;let c=Math.min(6,g.length),I=new DataView(s.buffer),d=new DataView(g.buffer,g.length-c,c);return{id:xB(I),len:xB(d)}}async function e(s){let g=0;for(;s>0;){if(g++,g>Yje||JB(t,A,zo))return;let c=t.position,I=await i();if(I.id===17026){if(I.len>yte)return;let d=vL(I.len,yte,"EBML DocType");return(await t.readToken(new ze(d))).replaceAll(/\00.*$/g,"")}if(ni(t)&&(!Number.isFinite(I.len)||I.len<0||I.len>mte)||(await AI(t,I.len,{maximumLength:ni(t)?mte:t.fileInfo.size,reason:"EBML payload"}),--s,t.position<=c))return}}let a=await i(),A=t.position;switch(await e(a.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1")||this.checkString("PARE"))return{ext:"parquet",mime:"application/vnd.apache.parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.checkString("regf"))return{ext:"dat",mime:"application/x-ft-windows-registry-hive"};if(this.checkString("$FL2")||this.checkString("$FL3"))return{ext:"sav",mime:"application/x-spss-sav"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190])){let o=Ue.get(this.buffer,4),i=GA.get(this.buffer,6);if(o>0&&o<=30)return{ext:"macho",mime:"application/x-mach-binary"};if(i>30)return{ext:"class",mime:"application/java-vm"}}if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("=1e3&&o<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!"))return await t.ignore(8),await t.readToken(new ze(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[` `,"\r"," "," ","\0"].some(o=>this.checkString(o,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){let o={ext:"png",mime:"image/png"},i={ext:"apng",mime:"image/apng"};await t.ignore(8);async function e(){return{length:await t.readToken(oi),type:await t.readToken(new ze(4,"latin1"))}}let a=ni(t),A=t.position,r=0,s=!1;do{if(r++,r>jje||JB(t,A,Jje))break;let g=t.position,c=await e();if(c.length<0)return;if(c.type==="IHDR"){if(c.length!==13)return;s=!0}switch(c.type){case"IDAT":return o;case"acTL":return i;default:if(!s&&c.type!=="CgBI")return;if(a&&c.length>wte)return s&&rJe(c.type)?o:void 0;try{await AI(t,c.length+4,{maximumLength:a?wte+4:t.fileInfo.size,reason:"PNG chunk payload"})}catch(I){if(!a&&(I instanceof Lg||I instanceof bA))return o;throw I}}if(t.position<=g)break}while(t.position+8qje||JB(t,a,zo)));){let r=t.position,s=await i(),g=s.size-24;if(!Number.isFinite(g)||g<0){o=!0;break}if(vs(s.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let c=new Uint8Array(16);if(g-=await RL(t,c,void 0,{maximumLength:c.length,reason:"ASF stream type GUID"}),vs(c,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(vs(c,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}if(e&&g>Dte){o=!0;break}if(await AI(t,g,{maximumLength:e?Dte:t.fileInfo.size,reason:"ASF header payload"}),t.position<=r){o=!0;break}}}catch(i){if(i instanceof bA||i instanceof Lg)ni(t)&&(o=!0);else throw i}return o?void 0:{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await t.ignore(20),await t.readToken(new ze(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.checkString("=16){let o=new DataView(this.buffer.buffer).getUint32(12,!0);if(o>12&&this.buffer.length>=o+16)try{let i=new TextDecoder().decode(this.buffer.subarray(16,o+16));if(JSON.parse(i).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:"jmp",mime:"application/x-jmp-data"};if(await t.peekBuffer(this.buffer,{length:Math.min(512,t.fileInfo.size),mayBeLess:!0}),this.checkString("ustar",{offset:257})&&(this.checkString("\0",{offset:262})||this.checkString(" ",{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&pte(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254])){let o="utf-16le";return this.checkString("{this.buffer=new Uint8Array(jB);let o=lJe(t.fileInfo.size);if(await t.peekBuffer(this.buffer,{length:Math.min(8,o),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(await t.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,o),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let i=0;i<=this.options.mpegOffsetTolerance;++i){let e=this.scanMpeg(i);if(e)return e}};async readTiffTag(t){let o=await this.tokenizer.readToken(t?GA:SA);switch(await this.tokenizer.ignore(10),o){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(t){let o=await this.tokenizer.readToken(t?GA:SA);if(!(o>zje)&&!(ni(this.tokenizer)&&2+o*12>Ote))for(let i=0;i=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(e>=8){let r=(t?GA:SA).get(this.buffer,8),s=(t?GA:SA).get(this.buffer,10);if(r===28&&s===254||r===31&&s===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}if(ni(this.tokenizer)&&e>Vje)return o;let a=ni(this.tokenizer)?Ote:this.tokenizer.fileInfo.size;try{await AI(this.tokenizer,e,{maximumLength:a,reason:"TIFF IFD offset"})}catch(r){if(r instanceof bA)return;throw r}let A;try{A=await this.readTiffIFD(t)}catch(r){if(r instanceof bA)return;throw r}return A??o}if(i===43)return o}scanMpeg(t){if(this.check([255,224],{offset:t,mask:[255,224]})){if(this.check([16],{offset:t+1,mask:[22]}))return this.check([8],{offset:t+1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:t+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:t+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:t+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}},uJe=new Set(Ete),BJe=new Set(Cte)});var PL=ue(()=>{so();Nte()});var Lte=$(zD=>{"use strict";Object.defineProperty(zD,"__esModule",{value:!0});zD.format=mJe;zD.parse=SJe;var fJe=/^[\u0009\u0020-\u007e\u0080-\u00ff]*$/,kte=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,QJe=/[\\"]/g,yJe=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,vte=(()=>{let n=function(){};return n.prototype=Object.create(null),n})();function mJe(n){let{type:t,parameters:o}=n;if(!t||!yJe.test(t))throw new TypeError(`Invalid type: ${t}`);let i=t;if(o)for(let e of Object.keys(o)){if(!kte.test(e))throw new TypeError(`Invalid parameter name: ${e}`);i+=`; ${e}=${MJe(o[e])}`}return i}function SJe(n,t){let o=t?.comma===!0?OJe:65536,i=n.length,e=FL(n,t?.start??0,i),a=e;e=GL(n,e,i,o);let A=LL(n,a,e),r=n.slice(a,A).toLowerCase();return t?.parameters===!1?{type:r,index:e,parameters:new vte}:bJe(n,r,e,i,o)}var Pte=32,Gte=9,Fte=59,wJe=61,Rte=34,DJe=92,OJe=44;function bJe(n,t,o,i,e){let a=new vte;e:for(;ot;){let i=n.charCodeAt(o-1);if(i!==Pte&&i!==Gte)break;o--}return o}function MJe(n){if(kte.test(n))return n;if(fJe.test(n))return`"${n.replace(QJe,"\\$&")}"`;throw new TypeError(`Invalid parameter value: ${n}`)}});function Ute(n){if(!_Je.test(n))throw new TypeError(`Invalid media type: ${n}`);let t=n.indexOf("/"),o=n.slice(0,t).toLowerCase(),i=n.slice(t+1).toLowerCase(),e,a=i.lastIndexOf("+");return a!==-1&&(e=i.slice(a+1),i=i.slice(0,a)),{type:o,subtype:i,suffix:e}}var _Je,Hte=ue(()=>{_Je=/^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}$/});var Kte,Ia,UL,HL=ue(()=>{Kte={10:"shot",20:"scene",30:"track",40:"part",50:"album",60:"edition",70:"collection"},Ia={video:1,audio:2,complex:3,logo:4,subtitle:17,button:18,control:32},UL={[Ia.video]:"video",[Ia.audio]:"audio",[Ia.complex]:"complex",[Ia.logo]:"logo",[Ia.subtitle]:"subtitle",[Ia.button]:"button",[Ia.control]:"control"}});var Dh,tI,rI,VD,Vo,vl,Qt,er=ue(()=>{Dh=n=>class extends Error{constructor(o){super(o),this.name=n}},tI=class extends Dh("CouldNotDetermineFileTypeError"){},rI=class extends Dh("UnsupportedFileTypeError"){},VD=class extends Dh("UnexpectedFileContentError"){constructor(t,o){super(o),this.fileType=t}toString(){return`${this.name} (FileType: ${this.fileType}): ${this.message}`}},Vo=class extends Dh("FieldDecodingError"){},vl=class extends Dh("InternalParserError"){},Qt=n=>class extends VD{constructor(t){super(n,t)}}});function vA(n,t,o){return(n[t]&1<>a;let r=8-a,s=i-r;return s<0?A>>=8-a-i:s>0&&(A<<=s,A|=XA(n,t,o+r,s)),A}function Da(n,t,o){return XA(n,t,o,1)===1}function Yte(n){let t=[];for(let o=0,i=n.length;oo.trim().toLowerCase());if(t.length>=1){let o=Number.parseFloat(t[0]);return t.length===2&&t[1]==="db"?{dB:o,ratio:NJe(o)}:{dB:TJe(o),ratio:o}}}function KL(n){if(n.length===0)throw new Error("decodeUintBE: empty Uint8Array");let t=new DataView(n.buffer,n.byteOffset,n.byteLength);return xB(t)}var Ar=ue(()=>{DA();er();YB()});var Oh,bh,Mh,xL,Pl,YL,_h,ZD,jL,Ug=ue(()=>{DA();Ar();Oh={0:"Other",1:"32x32 pixels 'file icon' (PNG only)",2:"Other file icon",3:"Cover (front)",4:"Cover (back)",5:"Leaflet page",6:"Media (e.g. label side of CD)",7:"Lead artist/lead performer/soloist",8:"Artist/performer",9:"Conductor",10:"Band/Orchestra",11:"Composer",12:"Lyricist/text writer",13:"Recording Location",14:"During recording",15:"During performance",16:"Movie/video screen capture",17:"A bright coloured fish",18:"Illustration",19:"Band/artist logotype",20:"Publisher/Studio logotype"},bh={other:0,lyrics:1,text:2,movement_part:3,events:4,chord:5,trivia_pop:6},Mh={notSynchronized:0,mpegFrameNumber:1,milliseconds:2},xL={get:(n,t)=>n[t+3]&127|n[t+2]<<7|n[t+1]<<14|n[t]<<21,len:4},Pl={len:10,get:(n,t)=>({fileIdentifier:new ze(3,"ascii").get(n,t),version:{major:Ns.get(n,t+3),revision:Ns.get(n,t+4)},flags:{unsynchronisation:vA(n,t+5,7),isExtendedHeader:vA(n,t+5,6),expIndicator:vA(n,t+5,5),footer:vA(n,t+5,4)},size:xL.get(n,t+6)})},YL={len:10,get:(n,t)=>({size:Ue.get(n,t),extendedFlags:GA.get(n,t+4),sizeOfPadding:Ue.get(n,t+6),crcDataPresent:vA(n,t+4,31)})},_h={len:1,get:(n,t)=>{switch(n[t]){case 0:return{encoding:"latin1"};case 1:return{encoding:"utf-16le",bom:!0};case 2:return{encoding:"utf-16be",bom:!1};case 3:return{encoding:"utf8",bom:!1};default:return{encoding:"utf8",bom:!1}}}},ZD={len:4,get:(n,t)=>({encoding:_h.get(n,t),language:new ze(3,"latin1").get(n,t+1)})},jL={len:6,get:(n,t)=>{let o=ZD.get(n,t);return{encoding:o.encoding,language:o.language,timeStampFormat:fA.get(n,t+4),contentType:fA.get(n,t+5)}}}});var Gl=ue(()=>{HL();Ug()});function Jte(n){return XD[n]&&!XD[n].multiple}function qte(n){return!XD[n].multiple||XD[n].unique||!1}var eA,XD,zte=ue(()=>{eA={multiple:!1},XD={year:eA,track:eA,disk:eA,title:eA,artist:eA,artists:{multiple:!0,unique:!0},albumartist:eA,albumartists:{multiple:!0,unique:!0},album:eA,date:eA,originaldate:eA,originalyear:eA,releasedate:eA,comment:{multiple:!0,unique:!1},genre:{multiple:!0,unique:!0},picture:{multiple:!0,unique:!0},composer:{multiple:!0,unique:!0},lyrics:{multiple:!0,unique:!1},albumsort:{multiple:!1,unique:!0},titlesort:{multiple:!1,unique:!0},work:{multiple:!1,unique:!0},artistsort:{multiple:!1,unique:!0},albumartistsort:{multiple:!1,unique:!0},composersort:{multiple:!1,unique:!0},lyricist:{multiple:!0,unique:!0},writer:{multiple:!0,unique:!0},conductor:{multiple:!0,unique:!0},remixer:{multiple:!0,unique:!0},arranger:{multiple:!0,unique:!0},engineer:{multiple:!0,unique:!0},producer:{multiple:!0,unique:!0},technician:{multiple:!0,unique:!0},djmixer:{multiple:!0,unique:!0},mixer:{multiple:!0,unique:!0},label:{multiple:!0,unique:!0},grouping:eA,subtitle:{multiple:!0},discsubtitle:eA,totaltracks:eA,totaldiscs:eA,compilation:eA,rating:{multiple:!0},bpm:eA,mood:eA,media:eA,catalognumber:{multiple:!0,unique:!0},tvShow:eA,tvShowSort:eA,tvSeason:eA,tvEpisode:eA,tvEpisodeId:eA,tvNetwork:eA,podcast:eA,podcasturl:eA,releasestatus:eA,releasetype:{multiple:!0},releasecountry:eA,script:eA,language:eA,copyright:eA,license:eA,encodedby:eA,encodersettings:eA,gapless:eA,barcode:eA,isrc:{multiple:!0},asin:eA,musicbrainz_recordingid:eA,musicbrainz_trackid:eA,musicbrainz_albumid:eA,musicbrainz_artistid:{multiple:!0},musicbrainz_albumartistid:{multiple:!0},musicbrainz_releasegroupid:eA,musicbrainz_workid:eA,musicbrainz_trmid:eA,musicbrainz_discid:eA,acoustid_id:eA,acoustid_fingerprint:eA,musicip_puid:eA,musicip_fingerprint:eA,website:eA,"performer:instrument":{multiple:!0,unique:!0},averageLevel:eA,peakLevel:eA,notes:{multiple:!0,unique:!1},key:eA,originalalbum:eA,originalartist:eA,discogs_artist_id:{multiple:!0,unique:!0},discogs_release_id:eA,discogs_label_id:eA,discogs_master_release_id:eA,discogs_votes:eA,discogs_rating:eA,replaygain_track_peak:eA,replaygain_track_gain:eA,replaygain_album_peak:eA,replaygain_album_gain:eA,replaygain_track_minmax:eA,replaygain_album_minmax:eA,replaygain_undo:eA,description:{multiple:!0},longDescription:eA,category:{multiple:!0},hdVideo:eA,keywords:{multiple:!0},movement:eA,movementIndex:eA,movementTotal:eA,podcastId:eA,showMovement:eA,stik:eA,playCounter:eA}});var gr,Hg=ue(()=>{gr=class{static toIntOrNull(t){let o=Number.parseInt(t,10);return Number.isNaN(o)?null:o}static normalizeTrack(t){let o=t.toString().split("/");return{no:Number.parseInt(o[0],10)||null,of:Number.parseInt(o[1],10)||null}}constructor(t,o){this.tagTypes=t,this.tagMap=o}mapGenericTag(t,o){t={id:t.id,value:t.value},this.postMap(t,o);let i=this.getCommonName(t.id);return i?{id:i,value:t.value}:null}getCommonName(t){return this.tagMap[t]}postMap(t,o){}};gr.maxRatingScore=1});var RJe,$D,Vte=ue(()=>{Hg();RJe={title:"title",artist:"artist",album:"album",year:"year",comment:"comment",track:"track",genre:"genre"},$D=class extends gr{constructor(){super(["ID3v1"],RJe)}}});var Zo,Th=ue(()=>{Hg();Zo=class extends gr{constructor(t,o){let i={};for(let e of Object.keys(o))i[e.toUpperCase()]=o[e];super(t,i)}getCommonName(t){return this.tagMap[t.toUpperCase()]}}});var kJe,eO,Wte=ue(()=>{DA();Hg();Th();Ar();kJe={TIT2:"title",TPE1:"artist","TXXX:Artists":"artists",TPE2:"albumartist",TALB:"album",TDRV:"date",TORY:"originalyear",TPOS:"disk",TCON:"genre",APIC:"picture",TCOM:"composer",USLT:"lyrics",TSOA:"albumsort",TSOT:"titlesort",TOAL:"originalalbum",TSOP:"artistsort",TSO2:"albumartistsort",TSOC:"composersort",TEXT:"lyricist","TXXX:Writer":"writer",TPE3:"conductor",TPE4:"remixer","IPLS:arranger":"arranger","IPLS:engineer":"engineer","IPLS:producer":"producer","IPLS:DJ-mix":"djmixer","IPLS:mix":"mixer",TPUB:"label",TIT1:"grouping",TIT3:"subtitle",TRCK:"track",TCMP:"compilation",POPM:"rating",TBPM:"bpm",TMED:"media","TXXX:CATALOGNUMBER":"catalognumber","TXXX:MusicBrainz Album Status":"releasestatus","TXXX:MusicBrainz Album Type":"releasetype","TXXX:MusicBrainz Album Release Country":"releasecountry","TXXX:RELEASECOUNTRY":"releasecountry","TXXX:SCRIPT":"script",TLAN:"language",TCOP:"copyright",WCOP:"license",TENC:"encodedby",TSSE:"encodersettings","TXXX:BARCODE":"barcode","TXXX:ISRC":"isrc",TSRC:"isrc","TXXX:ASIN":"asin","TXXX:originalyear":"originalyear","UFID:http://musicbrainz.org":"musicbrainz_recordingid","TXXX:MusicBrainz Release Track Id":"musicbrainz_trackid","TXXX:MusicBrainz Album Id":"musicbrainz_albumid","TXXX:MusicBrainz Artist Id":"musicbrainz_artistid","TXXX:MusicBrainz Album Artist Id":"musicbrainz_albumartistid","TXXX:MusicBrainz Release Group Id":"musicbrainz_releasegroupid","TXXX:MusicBrainz Work Id":"musicbrainz_workid","TXXX:MusicBrainz TRM Id":"musicbrainz_trmid","TXXX:MusicBrainz Disc Id":"musicbrainz_discid","TXXX:ACOUSTID_ID":"acoustid_id","TXXX:Acoustid Id":"acoustid_id","TXXX:Acoustid Fingerprint":"acoustid_fingerprint","TXXX:MusicIP PUID":"musicip_puid","TXXX:MusicMagic Fingerprint":"musicip_fingerprint",WOAR:"website",TDRC:"date",TYER:"year",TDOR:"originaldate","TIPL:arranger":"arranger","TIPL:engineer":"engineer","TIPL:producer":"producer","TIPL:DJ-mix":"djmixer","TIPL:mix":"mixer",TMOO:"mood",SYLT:"lyrics",TSST:"discsubtitle",TKEY:"key",COMM:"comment",TOPE:"originalartist","PRIV:AverageLevel":"averageLevel","PRIV:PeakLevel":"peakLevel","TXXX:DISCOGS_ARTIST_ID":"discogs_artist_id","TXXX:DISCOGS_ARTISTS":"artists","TXXX:DISCOGS_ARTIST_NAME":"artists","TXXX:DISCOGS_ALBUM_ARTISTS":"albumartist","TXXX:DISCOGS_CATALOG":"catalognumber","TXXX:DISCOGS_COUNTRY":"releasecountry","TXXX:DISCOGS_DATE":"originaldate","TXXX:DISCOGS_LABEL":"label","TXXX:DISCOGS_LABEL_ID":"discogs_label_id","TXXX:DISCOGS_MASTER_RELEASE_ID":"discogs_master_release_id","TXXX:DISCOGS_RATING":"discogs_rating","TXXX:DISCOGS_RELEASED":"date","TXXX:DISCOGS_RELEASE_ID":"discogs_release_id","TXXX:DISCOGS_VOTES":"discogs_votes","TXXX:CATALOGID":"catalognumber","TXXX:STYLE":"genre","TXXX:REPLAYGAIN_TRACK_PEAK":"replaygain_track_peak","TXXX:REPLAYGAIN_TRACK_GAIN":"replaygain_track_gain","TXXX:REPLAYGAIN_ALBUM_PEAK":"replaygain_album_peak","TXXX:REPLAYGAIN_ALBUM_GAIN":"replaygain_album_gain","TXXX:MP3GAIN_MINMAX":"replaygain_track_minmax","TXXX:MP3GAIN_ALBUM_MINMAX":"replaygain_album_minmax","TXXX:MP3GAIN_UNDO":"replaygain_undo",MVNM:"movement",MVIN:"movementIndex",PCST:"podcast",TCAT:"category",TDES:"description",TDRL:"releasedate",TGID:"podcastId",TKWD:"keywords",WFED:"podcasturl",GRP1:"grouping",PCNT:"playCounter"},eO=class n extends Zo{static toRating(t){return{source:t.email,rating:t.rating>0?(t.rating-1)/254*gr.maxRatingScore:void 0}}constructor(){super(["ID3v2.3","ID3v2.4"],kJe)}postMap(t,o){switch(t.id){case"UFID":{let i=t.value;i.owner_identifier==="http://musicbrainz.org"&&(t.id+=`:${i.owner_identifier}`,t.value=la(i.identifier,"latin1"))}break;case"PRIV":{let i=t.value;switch(i.owner_identifier){case"AverageLevel":case"PeakValue":t.id+=`:${i.owner_identifier}`,t.value=i.data.length===4?Ge.get(i.data,0):null,t.value===null&&o.addWarning("Failed to parse PRIV:PeakValue");break;default:o.addWarning(`Unknown PRIV owner-identifier: ${i.data}`)}}break;case"POPM":t.value=n.toRating(t.value);break;default:break}}}});var vJe,AO,Zte=ue(()=>{Hg();vJe={Title:"title",Author:"artist","WM/AlbumArtist":"albumartist","WM/AlbumTitle":"album","WM/Year":"date","WM/OriginalReleaseTime":"originaldate","WM/OriginalReleaseYear":"originalyear",Description:"comment","WM/TrackNumber":"track","WM/PartOfSet":"disk","WM/Genre":"genre","WM/Composer":"composer","WM/Lyrics":"lyrics","WM/AlbumSortOrder":"albumsort","WM/TitleSortOrder":"titlesort","WM/ArtistSortOrder":"artistsort","WM/AlbumArtistSortOrder":"albumartistsort","WM/ComposerSortOrder":"composersort","WM/Writer":"lyricist","WM/Conductor":"conductor","WM/ModifiedBy":"remixer","WM/Engineer":"engineer","WM/Producer":"producer","WM/DJMixer":"djmixer","WM/Mixer":"mixer","WM/Publisher":"label","WM/ContentGroupDescription":"grouping","WM/SubTitle":"subtitle","WM/SetSubTitle":"discsubtitle","WM/IsCompilation":"compilation","WM/SharedUserRating":"rating","WM/BeatsPerMinute":"bpm","WM/Mood":"mood","WM/Media":"media","WM/CatalogNo":"catalognumber","MusicBrainz/Album Status":"releasestatus","MusicBrainz/Album Type":"releasetype","MusicBrainz/Album Release Country":"releasecountry","WM/Script":"script","WM/Language":"language",Copyright:"copyright",LICENSE:"license","WM/EncodedBy":"encodedby","WM/EncodingSettings":"encodersettings","WM/Barcode":"barcode","WM/ISRC":"isrc","MusicBrainz/Track Id":"musicbrainz_recordingid","MusicBrainz/Release Track Id":"musicbrainz_trackid","MusicBrainz/Album Id":"musicbrainz_albumid","MusicBrainz/Artist Id":"musicbrainz_artistid","MusicBrainz/Album Artist Id":"musicbrainz_albumartistid","MusicBrainz/Release Group Id":"musicbrainz_releasegroupid","MusicBrainz/Work Id":"musicbrainz_workid","MusicBrainz/TRM Id":"musicbrainz_trmid","MusicBrainz/Disc Id":"musicbrainz_discid","Acoustid/Id":"acoustid_id","Acoustid/Fingerprint":"acoustid_fingerprint","MusicIP/PUID":"musicip_puid","WM/ARTISTS":"artists","WM/InitialKey":"key",ASIN:"asin","WM/Work":"work","WM/AuthorURL":"website","WM/Picture":"picture"},AO=class n extends gr{static toRating(t){return{rating:Number.parseFloat(t+1)/5}}constructor(){super(["asf"],vJe)}postMap(t){switch(t.id){case"WM/SharedUserRating":{let o=t.id.split(":");t.value=n.toRating(t.value),t.id=o[0];break}}}}});var PJe,tO,Xte=ue(()=>{Th();PJe={TT2:"title",TP1:"artist",TP2:"albumartist",TAL:"album",TYE:"year",COM:"comment",TRK:"track",TPA:"disk",TCO:"genre",PIC:"picture",TCM:"composer",TOR:"originaldate",TOT:"originalalbum",TXT:"lyricist",TP3:"conductor",TPB:"label",TT1:"grouping",TT3:"subtitle",TLA:"language",TCR:"copyright",WCP:"license",TEN:"encodedby",TSS:"encodersettings",WAR:"website",PCS:"podcast",TCP:"compilation",TDR:"date",TS2:"albumartistsort",TSA:"albumsort",TSC:"composersort",TSP:"artistsort",TST:"titlesort",WFD:"podcasturl",TBP:"bpm",GP1:"grouping"},tO=class extends Zo{constructor(){super(["ID3v2.2"],PJe)}}});var GJe,rO,$te=ue(()=>{Th();GJe={Title:"title",Artist:"artist",Artists:"artists","Album Artist":"albumartist",Album:"album",Year:"date",Originalyear:"originalyear",Originaldate:"originaldate",Releasedate:"releasedate",Comment:"comment",Track:"track",Disc:"disk",DISCNUMBER:"disk",Genre:"genre","Cover Art (Front)":"picture","Cover Art (Back)":"picture",Composer:"composer",Lyrics:"lyrics",ALBUMSORT:"albumsort",TITLESORT:"titlesort",WORK:"work",ARTISTSORT:"artistsort",ALBUMARTISTSORT:"albumartistsort",COMPOSERSORT:"composersort",Lyricist:"lyricist",Writer:"writer",Conductor:"conductor",MixArtist:"remixer",Arranger:"arranger",Engineer:"engineer",Producer:"producer",DJMixer:"djmixer",Mixer:"mixer",Label:"label",Grouping:"grouping",Subtitle:"subtitle",DiscSubtitle:"discsubtitle",Compilation:"compilation",BPM:"bpm",Mood:"mood",Media:"media",CatalogNumber:"catalognumber",MUSICBRAINZ_ALBUMSTATUS:"releasestatus",MUSICBRAINZ_ALBUMTYPE:"releasetype",RELEASECOUNTRY:"releasecountry",Script:"script",Language:"language",Copyright:"copyright",LICENSE:"license",EncodedBy:"encodedby",EncoderSettings:"encodersettings",Barcode:"barcode",ISRC:"isrc",ASIN:"asin",musicbrainz_trackid:"musicbrainz_recordingid",musicbrainz_releasetrackid:"musicbrainz_trackid",MUSICBRAINZ_ALBUMID:"musicbrainz_albumid",MUSICBRAINZ_ARTISTID:"musicbrainz_artistid",MUSICBRAINZ_ALBUMARTISTID:"musicbrainz_albumartistid",MUSICBRAINZ_RELEASEGROUPID:"musicbrainz_releasegroupid",MUSICBRAINZ_WORKID:"musicbrainz_workid",MUSICBRAINZ_TRMID:"musicbrainz_trmid",MUSICBRAINZ_DISCID:"musicbrainz_discid",Acoustid_Id:"acoustid_id",ACOUSTID_FINGERPRINT:"acoustid_fingerprint",MUSICIP_PUID:"musicip_puid",Weblink:"website",REPLAYGAIN_TRACK_GAIN:"replaygain_track_gain",REPLAYGAIN_TRACK_PEAK:"replaygain_track_peak",MP3GAIN_MINMAX:"replaygain_track_minmax",MP3GAIN_UNDO:"replaygain_undo"},rO=class extends Zo{constructor(){super(["APEv2"],GJe)}}});var FJe,LJe,zB,ere=ue(()=>{Th();FJe={"\xA9nam":"title","\xA9ART":"artist",aART:"albumartist","----:com.apple.iTunes:Band":"albumartist","\xA9alb":"album","\xA9day":"date","\xA9cmt":"comment","\xA9com":"comment",trkn:"track",disk:"disk","\xA9gen":"genre",covr:"picture","\xA9wrt":"composer","\xA9lyr":"lyrics",soal:"albumsort",sonm:"titlesort",soar:"artistsort",soaa:"albumartistsort",soco:"composersort","----:com.apple.iTunes:LYRICIST":"lyricist","----:com.apple.iTunes:CONDUCTOR":"conductor","----:com.apple.iTunes:REMIXER":"remixer","----:com.apple.iTunes:ENGINEER":"engineer","----:com.apple.iTunes:PRODUCER":"producer","----:com.apple.iTunes:DJMIXER":"djmixer","----:com.apple.iTunes:MIXER":"mixer","----:com.apple.iTunes:LABEL":"label","\xA9grp":"grouping","----:com.apple.iTunes:SUBTITLE":"subtitle","----:com.apple.iTunes:DISCSUBTITLE":"discsubtitle",cpil:"compilation",tmpo:"bpm","----:com.apple.iTunes:MOOD":"mood","----:com.apple.iTunes:MEDIA":"media","----:com.apple.iTunes:CATALOGNUMBER":"catalognumber",tvsh:"tvShow",tvsn:"tvSeason",tves:"tvEpisode",sosn:"tvShowSort",tven:"tvEpisodeId",tvnn:"tvNetwork",pcst:"podcast",purl:"podcasturl","----:com.apple.iTunes:MusicBrainz Album Status":"releasestatus","----:com.apple.iTunes:MusicBrainz Album Type":"releasetype","----:com.apple.iTunes:MusicBrainz Album Release Country":"releasecountry","----:com.apple.iTunes:SCRIPT":"script","----:com.apple.iTunes:LANGUAGE":"language",cprt:"copyright","\xA9cpy":"copyright","----:com.apple.iTunes:LICENSE":"license","\xA9too":"encodedby",pgap:"gapless","----:com.apple.iTunes:BARCODE":"barcode","----:com.apple.iTunes:ISRC":"isrc","----:com.apple.iTunes:ASIN":"asin","----:com.apple.iTunes:NOTES":"comment","----:com.apple.iTunes:MusicBrainz Track Id":"musicbrainz_recordingid","----:com.apple.iTunes:MusicBrainz Release Track Id":"musicbrainz_trackid","----:com.apple.iTunes:MusicBrainz Album Id":"musicbrainz_albumid","----:com.apple.iTunes:MusicBrainz Artist Id":"musicbrainz_artistid","----:com.apple.iTunes:MusicBrainz Album Artist Id":"musicbrainz_albumartistid","----:com.apple.iTunes:MusicBrainz Release Group Id":"musicbrainz_releasegroupid","----:com.apple.iTunes:MusicBrainz Work Id":"musicbrainz_workid","----:com.apple.iTunes:MusicBrainz TRM Id":"musicbrainz_trmid","----:com.apple.iTunes:MusicBrainz Disc Id":"musicbrainz_discid","----:com.apple.iTunes:Acoustid Id":"acoustid_id","----:com.apple.iTunes:Acoustid Fingerprint":"acoustid_fingerprint","----:com.apple.iTunes:MusicIP PUID":"musicip_puid","----:com.apple.iTunes:fingerprint":"musicip_fingerprint","----:com.apple.iTunes:replaygain_track_gain":"replaygain_track_gain","----:com.apple.iTunes:replaygain_track_peak":"replaygain_track_peak","----:com.apple.iTunes:replaygain_album_gain":"replaygain_album_gain","----:com.apple.iTunes:replaygain_album_peak":"replaygain_album_peak","----:com.apple.iTunes:replaygain_track_minmax":"replaygain_track_minmax","----:com.apple.iTunes:replaygain_album_minmax":"replaygain_album_minmax","----:com.apple.iTunes:replaygain_undo":"replaygain_undo",gnre:"genre","----:com.apple.iTunes:ALBUMARTISTSORT":"albumartistsort","----:com.apple.iTunes:ARTISTS":"artists","----:com.apple.iTunes:ORIGINALDATE":"originaldate","----:com.apple.iTunes:ORIGINALYEAR":"originalyear","----:com.apple.iTunes:RELEASEDATE":"releasedate",desc:"description",ldes:"longDescription","\xA9mvn":"movement","\xA9mvi":"movementIndex","\xA9mvc":"movementTotal","\xA9wrk":"work",catg:"category",egid:"podcastId",hdvd:"hdVideo",keyw:"keywords",shwm:"showMovement",stik:"stik",rate:"rating"},LJe="iTunes",zB=class extends Zo{constructor(){super([LJe],FJe)}postMap(t,o){switch(t.id){case"rate":t.value={source:void 0,rating:Number.parseFloat(t.value)/100};break}}}});var UJe,aO,Are=ue(()=>{Hg();UJe={TITLE:"title",ARTIST:"artist",ARTISTS:"artists",ALBUMARTIST:"albumartist","ALBUM ARTIST":"albumartist",ALBUM:"album",DATE:"date",ORIGINALDATE:"originaldate",ORIGINALYEAR:"originalyear",RELEASEDATE:"releasedate",COMMENT:"comment",TRACKNUMBER:"track",DISCNUMBER:"disk",GENRE:"genre",METADATA_BLOCK_PICTURE:"picture",COMPOSER:"composer",LYRICS:"lyrics",ALBUMSORT:"albumsort",TITLESORT:"titlesort",WORK:"work",ARTISTSORT:"artistsort",ALBUMARTISTSORT:"albumartistsort",COMPOSERSORT:"composersort",LYRICIST:"lyricist",WRITER:"writer",CONDUCTOR:"conductor",REMIXER:"remixer",ARRANGER:"arranger",ENGINEER:"engineer",PRODUCER:"producer",DJMIXER:"djmixer",MIXER:"mixer",LABEL:"label",GROUPING:"grouping",SUBTITLE:"subtitle",DISCSUBTITLE:"discsubtitle",TRACKTOTAL:"totaltracks",DISCTOTAL:"totaldiscs",COMPILATION:"compilation",RATING:"rating",BPM:"bpm",KEY:"key",MOOD:"mood",MEDIA:"media",CATALOGNUMBER:"catalognumber",RELEASESTATUS:"releasestatus",RELEASETYPE:"releasetype",RELEASECOUNTRY:"releasecountry",SCRIPT:"script",LANGUAGE:"language",COPYRIGHT:"copyright",LICENSE:"license",ENCODEDBY:"encodedby",ENCODERSETTINGS:"encodersettings",BARCODE:"barcode",ISRC:"isrc",ASIN:"asin",MUSICBRAINZ_TRACKID:"musicbrainz_recordingid",MUSICBRAINZ_RELEASETRACKID:"musicbrainz_trackid",MUSICBRAINZ_ALBUMID:"musicbrainz_albumid",MUSICBRAINZ_ARTISTID:"musicbrainz_artistid",MUSICBRAINZ_ALBUMARTISTID:"musicbrainz_albumartistid",MUSICBRAINZ_RELEASEGROUPID:"musicbrainz_releasegroupid",MUSICBRAINZ_WORKID:"musicbrainz_workid",MUSICBRAINZ_TRMID:"musicbrainz_trmid",MUSICBRAINZ_DISCID:"musicbrainz_discid",ACOUSTID_ID:"acoustid_id",ACOUSTID_ID_FINGERPRINT:"acoustid_fingerprint",MUSICIP_PUID:"musicip_puid",WEBSITE:"website",NOTES:"notes",TOTALTRACKS:"totaltracks",TOTALDISCS:"totaldiscs",DISCOGS_ARTIST_ID:"discogs_artist_id",DISCOGS_ARTISTS:"artists",DISCOGS_ARTIST_NAME:"artists",DISCOGS_ALBUM_ARTISTS:"albumartist",DISCOGS_CATALOG:"catalognumber",DISCOGS_COUNTRY:"releasecountry",DISCOGS_DATE:"originaldate",DISCOGS_LABEL:"label",DISCOGS_LABEL_ID:"discogs_label_id",DISCOGS_MASTER_RELEASE_ID:"discogs_master_release_id",DISCOGS_RATING:"discogs_rating",DISCOGS_RELEASED:"date",DISCOGS_RELEASE_ID:"discogs_release_id",DISCOGS_VOTES:"discogs_votes",CATALOGID:"catalognumber",STYLE:"genre",REPLAYGAIN_TRACK_GAIN:"replaygain_track_gain",REPLAYGAIN_TRACK_PEAK:"replaygain_track_peak",REPLAYGAIN_ALBUM_GAIN:"replaygain_album_gain",REPLAYGAIN_ALBUM_PEAK:"replaygain_album_peak",REPLAYGAIN_MINMAX:"replaygain_track_minmax",REPLAYGAIN_ALBUM_MINMAX:"replaygain_album_minmax",REPLAYGAIN_UNDO:"replaygain_undo"},aO=class n extends gr{static toRating(t,o,i){return{source:t?t.toLowerCase():void 0,rating:Number.parseFloat(o)/i*gr.maxRatingScore}}constructor(){super(["vorbis"],UJe)}postMap(t){if(t.id==="RATING")t.value=n.toRating(void 0,t.value,100);else if(t.id.indexOf("RATING:")===0){let o=t.id.split(":");t.value=n.toRating(o[1],t.value,1),t.id=o[0]}}}});var HJe,iO,tre=ue(()=>{Hg();HJe={IART:"artist",ICRD:"date",INAM:"title",TITL:"title",IPRD:"album",ITRK:"track",IPRT:"track",COMM:"comment",ICMT:"comment",ICNT:"releasecountry",GNRE:"genre",IWRI:"writer",RATE:"rating",YEAR:"year",ISFT:"encodedby",CODE:"encodedby",TURL:"website",IGNR:"genre",IENG:"engineer",ITCH:"technician",IMED:"media",IRPD:"album"},iO=class extends gr{constructor(){super(["exif"],HJe)}}});var KJe,oO,rre=ue(()=>{Th();KJe={"segment:title":"title","album:ARTIST":"albumartist","album:ARTISTSORT":"albumartistsort","album:TITLE":"album","album:DATE_RECORDED":"originaldate","album:DATE_RELEASED":"releasedate","album:PART_NUMBER":"disk","album:TOTAL_PARTS":"totaltracks","track:ARTIST":"artist","track:ARTISTSORT":"artistsort","track:TITLE":"title","track:PART_NUMBER":"track","track:MUSICBRAINZ_TRACKID":"musicbrainz_recordingid","track:MUSICBRAINZ_ALBUMID":"musicbrainz_albumid","track:MUSICBRAINZ_ARTISTID":"musicbrainz_artistid","track:PUBLISHER":"label","track:GENRE":"genre","track:ENCODER":"encodedby","track:ENCODER_OPTIONS":"encodersettings","edition:TOTAL_PARTS":"totaldiscs",picture:"picture"},oO=class extends Zo{constructor(){super(["matroska"],KJe)}}});var xJe,nO,are=ue(()=>{Hg();xJe={NAME:"title",AUTH:"artist","(c) ":"copyright",ANNO:"comment"},nO=class extends gr{constructor(){super(["AIFF"],xJe)}}});var sO,ire=ue(()=>{Vte();Wte();Zte();Xte();$te();ere();Are();tre();rre();are();er();sO=class{constructor(){this.tagMappers={},[new $D,new tO,new eO,new zB,new zB,new aO,new rO,new AO,new iO,new oO,new nO].forEach(t=>{this.registerTagMapper(t)})}mapTag(t,o,i){if(this.tagMappers[t])return this.tagMappers[t].mapGenericTag(o,i);throw new vl(`No generic tag mapper defined for tag-format: ${t}`)}registerTagMapper(t){for(let o of t.tagTypes)this.tagMappers[o]=t}}});function ore(n){return JL.test(n)?jJe(n):YJe(n)}function YJe(n){return{contentType:bh.lyrics,timeStampFormat:Mh.notSynchronized,text:n.trim(),syncText:[]}}function jJe(n){let t=n.split(` `),o=[];for(let i of t){let e=i.match(JL);if(e){let a=Number.parseInt(e[1],10),A=Number.parseInt(e[2],10),r=e[3].length===3?Number.parseInt(e[3],10):Number.parseInt(e[3],10)*10,s=(a*60+A)*1e3+r,g=i.replace(JL,"").trim();o.push({timestamp:s,text:g})}}return{contentType:bh.lyrics,timeStampFormat:Mh.milliseconds,text:o.map(i=>i.text).join(` -`),syncText:o}}var JL,nre=ue(()=>{Gl();JL=/\[(\d{2}):(\d{2})\.(\d{2,3})]/});function qJe(n){return n.length>2?`${n.slice(0,n.length-1).join(", ")} & ${n[n.length-1]}`:n.join(" & ")}var sre,Fl,JJe,gO,gre=ue(()=>{Gl();sre=Je(ct(),1);zte();ire();Hg();Ar();PL();nre();Fl=(0,sre.default)("music-metadata:collector"),JJe=["matroska","APEv2","vorbis","ID3v2.4","ID3v2.3","ID3v2.2","exif","asf","iTunes","AIFF","ID3v1"],gO=class{constructor(t){this.format={tagTypes:[],trackInfo:[]},this.native={},this.common={track:{no:null,of:null},disk:{no:null,of:null},movementIndex:{no:null,of:null}},this.quality={warnings:[]},this.commonOrigin={},this.originPriority={},this.tagMapper=new sO,this.opts=t;let o=1;for(let i of JJe)this.originPriority[i]=o++;this.originPriority.artificial=500,this.originPriority.id3v1=600}hasAny(){return Object.keys(this.native).length>0}addStreamInfo(t){Fl(`streamInfo: type=${t.type?UL[t.type]:"?"}, codec=${t.codecName}`),this.format.trackInfo.push(t)}setFormat(t,o){Fl(`format: ${t} = ${o}`),this.format[t]=o,this.opts?.observer&&this.opts.observer({metadata:this,tag:{type:"format",id:t,value:o}})}setAudioOnly(){this.setFormat("hasAudio",!0),this.setFormat("hasVideo",!1)}async addTag(t,o,i){Fl(`tag ${t}.${o} = ${i}`),this.native[t]||(this.format.tagTypes.push(t),this.native[t]=[]),this.native[t].push({id:o,value:i}),await this.toCommon(t,o,i)}addWarning(t){this.quality.warnings.push({message:t})}async postMap(t,o){switch(o.id){case"artist":return this.handleSingularArtistTag(t,o,"artist","artists");case"albumartist":return this.handleSingularArtistTag(t,o,"albumartist","albumartists");case"artists":return this.handlePluralArtistTag(t,o,"artist","artists");case"albumartists":return this.handlePluralArtistTag(t,o,"albumartist","albumartists");case"picture":return this.postFixPicture(o.value).then(i=>{i!==null&&(o.value=i,this.setGenericTag(t,o))});case"totaltracks":this.common.track.of=gr.toIntOrNull(o.value);return;case"totaldiscs":this.common.disk.of=gr.toIntOrNull(o.value);return;case"movementTotal":this.common.movementIndex.of=gr.toIntOrNull(o.value);return;case"track":case"disk":case"movementIndex":{let i=this.common[o.id].of;this.common[o.id]=gr.normalizeTrack(o.value),this.common[o.id].of=i??this.common[o.id].of;return}case"bpm":case"year":case"originalyear":o.value=Number.parseInt(o.value,10);break;case"date":{let i=Number.parseInt(o.value.substr(0,4),10);Number.isNaN(i)||(this.common.year=i);break}case"discogs_label_id":case"discogs_release_id":case"discogs_master_release_id":case"discogs_artist_id":case"discogs_votes":o.value=typeof o.value=="string"?Number.parseInt(o.value,10):o.value;break;case"replaygain_track_gain":case"replaygain_track_peak":case"replaygain_album_gain":case"replaygain_album_peak":o.value=jte(o.value);break;case"replaygain_track_minmax":o.value=o.value.split(",").map(i=>Number.parseInt(i,10));break;case"replaygain_undo":{let i=o.value.split(",").map(e=>Number.parseInt(e,10));o.value={leftChannel:i[0],rightChannel:i[1]};break}case"gapless":case"compilation":case"podcast":case"showMovement":o.value=o.value==="1"||o.value===1;break;case"isrc":{let i=this.common[o.id];if(i&&i.indexOf(o.value)!==-1)return;break}case"comment":typeof o.value=="string"&&(o.value={text:o.value}),o.value.descriptor==="iTunPGAP"&&this.setGenericTag(t,{id:"gapless",value:o.value.text==="1"});break;case"lyrics":typeof o.value=="string"&&(o.value=ore(o.value));break;default:}o.value!==null&&this.setGenericTag(t,o)}toCommonMetadata(){return{format:this.format,native:this.native,quality:this.quality,common:this.common}}handleSingularArtistTag(t,o,i,e){if(this.commonOrigin[i]===this.originPriority[t])return this.postMap("artificial",{id:e,value:o.value});this.common[e]||this.setGenericTag("artificial",{id:e,value:o.value}),this.setGenericTag(t,o)}handlePluralArtistTag(t,o,i,e){if((!this.common[i]||this.commonOrigin[i]===this.originPriority.artificial)&&(!this.common[e]||this.common[e].indexOf(o.value)===-1)){let a=(this.common[e]||[]).concat([o.value]),A=qJe(a);this.setGenericTag("artificial",{id:i,value:A})}this.setGenericTag(t,o)}async postFixPicture(t){if(t.data&&t.data.length>0){if(!t.format){let o=await qB(Uint8Array.from(t.data));if(o)t.format=o.mime;else return null}switch(t.format=t.format.toLocaleLowerCase(),t.format){case"image/jpg":t.format="image/jpeg"}return t}return this.addWarning("Empty picture tag found"),null}async toCommon(t,o,i){let e={id:o,value:i},a=this.tagMapper.mapTag(t,e,this);a&&await this.postMap(t,a)}setGenericTag(t,o){Fl(`common.${o.id} = ${o.value}`);let i=this.commonOrigin[o.id]||1e3,e=this.originPriority[t];if(Jte(o.id))if(e<=i)this.common[o.id]=o.value,this.commonOrigin[o.id]=e;else return Fl(`Ignore native tag (singleton): ${t}.${o.id} = ${o.value}`);else if(e===i)!qte(o.id)||this.common[o.id].indexOf(o.value)===-1?this.common[o.id].push(o.value):Fl(`Ignore duplicate value: ${t}.${o.id} = ${o.value}`);else if(e{Rt=class{constructor(t,o,i){this.metadata=t,this.tokenizer=o,this.options=i}}});var zJe,at,si=ue(()=>{_s();Ar();er();zJe=/^[\x21-\x7e©][\x20-\x7e\x00()]{3}/,at={len:4,get:(n,t)=>{let o=wr(n.subarray(t,t+at.len),"latin1");if(!o.match(zJe))throw new Vo(`FourCC contains invalid characters: ${Yte(o)} "${o}"`);return o},put:(n,t,o)=>{let i=tte(o,"latin1");if(i.length!==4)throw new vl("Invalid length");return n.set(i,t),t+4}}});function Ire(n){return{containsHeader:cO(n,31),containsFooter:cO(n,30),isHeader:cO(n,29),readOnly:cO(n,0),dataType:(n&6)>>1}}function cO(n,t){return(n&1<{DA();si();VB={text_utf8:0,binary:1,external_info:2,reserved:3},qL={len:52,get:(n,t)=>({ID:at.get(n,t),version:Ge.get(n,t+4)/1e3,descriptorBytes:Ge.get(n,t+8),headerBytes:Ge.get(n,t+12),seekTableBytes:Ge.get(n,t+16),headerDataBytes:Ge.get(n,t+20),apeFrameDataBytes:Ge.get(n,t+24),apeFrameDataBytesHigh:Ge.get(n,t+28),terminatingDataBytes:Ge.get(n,t+32),fileMD5:new Dt(16).get(n,t+36)})},cre={len:24,get:(n,t)=>({compressionLevel:SA.get(n,t),formatFlags:SA.get(n,t+2),blocksPerFrame:Ge.get(n,t+4),finalFrameBlocks:Ge.get(n,t+8),totalFrames:Ge.get(n,t+12),bitsPerSample:SA.get(n,t+16),channel:SA.get(n,t+18),sampleRate:Ge.get(n,t+20)})},Ki={len:32,get:(n,t)=>({ID:new ze(8,"ascii").get(n,t),version:Ge.get(n,t+8),size:Ge.get(n,t+12),fields:Ge.get(n,t+16),flags:Ire(Ge.get(n,t+20))})},IO={len:8,get:(n,t)=>({size:Ge.get(n,t),flags:Ire(Ge.get(n,t+4))})}});var Ere={};Pr(Ere,{APEv2Parser:()=>iI,ApeContentError:()=>Nh,tryParseApeHeader:()=>Ll});function Ll(n,t,o){return new iI(n,t,o).tryParseApeHeader()}var hre,aI,pre,dre,Nh,iI,Ul=ue(()=>{hre=Je(ct(),1);so();DA();Ar();Hi();lre();er();_s();aI=(0,hre.default)("music-metadata:parser:APEv2"),pre="APEv2",dre="APETAGEX",Nh=class extends Qt("APEv2"){};iI=class n extends Rt{constructor(){super(...arguments),this.ape={}}static calculateDuration(t){let o=t.totalFrames>1?t.blocksPerFrame*(t.totalFrames-1):0;return o+=t.finalFrameBlocks,o/t.sampleRate}static async findApeFooterOffset(t,o){let i=new Uint8Array(Ki.len),e=t.position;if(o<=Ki.len){aI(`Offset is too small to read APE footer: offset=${o}`);return}if(o>Ki.len){await t.readBuffer(i,{position:o-Ki.len}),t.setPosition(e);let a=Ki.get(i,0);if(a.ID==="APETAGEX")return a.flags.isHeader?aI(`APE Header found at offset=${o-Ki.len}`):(aI(`APE Footer found at offset=${o-Ki.len}`),o-=a.size),{footer:a,offset:o}}}static parseTagFooter(t,o,i){let e=Ki.get(o,o.length-Ki.len);if(e.ID!==dre)throw new Nh("Unexpected APEv2 Footer ID preamble value");return no(o),new n(t,no(o),i).parseTags(e)}async tryParseApeHeader(){if(this.tokenizer.fileInfo.size&&this.tokenizer.fileInfo.size-this.tokenizer.position0?this.parseDescriptorExpansion(o):this.parseHeader());return this.metadata.setAudioOnly(),await this.tokenizer.ignore(i.forwardBytes),this.tryParseApeHeader()}async parseTags(t){let o=new Uint8Array(256),i=t.size-Ki.len;aI(`Parse APE tags at offset=${this.tokenizer.position}, size=${i}`);for(let e=0;ethis.metadata.addTag(pre,r,c)));break}case VB.binary:if(this.options.skipCovers)await this.tokenizer.ignore(a.size);else{let s=new Uint8Array(a.size);await this.tokenizer.readBuffer(s),A=Gs(s);let g=wr(s.subarray(0,A),"utf-8"),c=s.subarray(A+1);await this.metadata.addTag(pre,r,{description:g,data:c})}break;case VB.external_info:aI(`Ignore external info ${r}`),await this.tokenizer.ignore(a.size);break;case VB.reserved:aI(`Ignore external info ${r}`),this.metadata.addWarning(`APEv2 header declares a reserved datatype for "${r}"`),await this.tokenizer.ignore(a.size);break}}}async parseDescriptorExpansion(t){return await this.tokenizer.ignore(t),this.parseHeader()}async parseHeader(){let t=await this.tokenizer.readToken(cre);if(this.metadata.setFormat("lossless",!0),this.metadata.setFormat("container","Monkey's Audio"),this.metadata.setFormat("bitsPerSample",t.bitsPerSample),this.metadata.setFormat("sampleRate",t.sampleRate),this.metadata.setFormat("numberOfChannels",t.channel),this.metadata.setFormat("duration",n.calculateDuration(t)),!this.ape.descriptor)throw new Nh("Missing APE descriptor");return{forwardBytes:this.ape.descriptor.seekTableBytes+this.ape.descriptor.headerDataBytes+this.ape.descriptor.apeFrameDataBytes+this.ape.descriptor.terminatingDataBytes}}}});async function ure(n){if(n.fileInfo.size>=128){let t=new Uint8Array(3),o=n.position;return await n.readBuffer(t,{position:n.fileInfo.size-128}),n.setPosition(o),wr(t,"latin1")==="TAG"}return!1}var Cre,lO,Rh,pO,oI,dO,WB=ue(()=>{Cre=Je(ct(),1);DA();Ar();Hi();Ul();_s();lO=(0,Cre.default)("music-metadata:parser:ID3v1"),Rh=["Blues","Classic Rock","Country","Dance","Disco","Funk","Grunge","Hip-Hop","Jazz","Metal","New Age","Oldies","Other","Pop","R&B","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death Metal","Pranks","Soundtrack","Euro-Techno","Ambient","Trip-Hop","Vocal","Jazz+Funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound Clip","Gospel","Noise","Alt. Rock","Bass","Soul","Punk","Space","Meditative","Instrumental Pop","Instrumental Rock","Ethnic","Gothic","Darkwave","Techno-Industrial","Electronic","Pop-Folk","Eurodance","Dream","Southern Rock","Comedy","Cult","Gangsta Rap","Top 40","Christian Rap","Pop/Funk","Jungle","Native American","Cabaret","New Wave","Psychedelic","Rave","Showtunes","Trailer","Lo-Fi","Tribal","Acid Punk","Acid Jazz","Polka","Retro","Musical","Rock & Roll","Hard Rock","Folk","Folk/Rock","National Folk","Swing","Fast-Fusion","Bebob","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic Rock","Progressive Rock","Psychedelic Rock","Symphonic Rock","Slow Rock","Big Band","Chorus","Easy Listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber Music","Sonata","Symphony","Booty Bass","Primus","Porn Groove","Satire","Slow Jam","Club","Tango","Samba","Folklore","Ballad","Power Ballad","Rhythmic Soul","Freestyle","Duet","Punk Rock","Drum Solo","A Cappella","Euro-House","Dance Hall","Goa","Drum & Bass","Club-House","Hardcore","Terror","Indie","BritPop","Negerpunk","Polsk Punk","Beat","Christian Gangsta Rap","Heavy Metal","Black Metal","Crossover","Contemporary Christian","Christian Rock","Merengue","Salsa","Thrash Metal","Anime","JPop","Synthpop","Abstract","Art Rock","Baroque","Bhangra","Big Beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math Rock","New Romantic","Nu-Breakz","Post-Punk","Post-Rock","Psytrance","Shoegaze","Space Rock","Trop Rock","World Music","Neoclassical","Audiobook","Audio Theatre","Neue Deutsche Welle","Podcast","Indie Rock","G-Funk","Dubstep","Garage Rock","Psybient"],pO={len:128,get:(n,t)=>{let o=new oI(3).get(n,t);return o==="TAG"?{header:o,title:new oI(30).get(n,t+3),artist:new oI(30).get(n,t+33),album:new oI(30).get(n,t+63),year:new oI(4).get(n,t+93),comment:new oI(28).get(n,t+97),zeroByte:fA.get(n,t+127),track:fA.get(n,t+126),genre:fA.get(n,t+127)}:null}},oI=class{constructor(t){this.len=t,this.stringType=new ze(t,"latin1")}get(t,o){let i=this.stringType.get(t,o);return i=WD(i),i=i.trim(),i.length>0?i:void 0}},dO=class n extends Rt{constructor(t,o,i){super(t,o,i),this.apeHeader=i.apeHeader}static getGenre(t){if(tt){lO("Already consumed the last 128 bytes");return}let o=await this.tokenizer.readToken(pO,t);if(o){lO("ID3v1 header found at: pos=%s",this.tokenizer.fileInfo.size-pO.len);let i=["title","artist","album","comment","track","year"];for(let a of i)o[a]&&o[a]!==""&&await this.addTag(a,o[a]);let e=n.getGenre(o.genre);e&&await this.addTag("genre",e)}else lO("ID3v1 header not found at: pos=%s",this.tokenizer.fileInfo.size-pO.len)}async addTag(t,o){await this.metadata.addTag("ID3v1",t,o)}}});var zL,Bre=ue(()=>{DA();zL={len:16,get:(n,t)=>{let o=Ue.get(n,t+8),i=Ue.get(n,t+12);return{startTime:Ue.get(n,t),endTime:Ue.get(n,t+4),startOffset:o===4294967295?void 0:o,endOffset:i===4294967295?void 0:i}}}});function ZB(n){switch(n){case 2:return 6;case 3:case 4:return 10;default:throw fre(n)}}function VJe(n,t){return t===3?{status:{tag_alter_preservation:vA(n,0,7),file_alter_preservation:vA(n,0,6),read_only:vA(n,0,5)},format:{compression:vA(n,1,7),encryption:vA(n,1,6),grouping_identity:vA(n,1,5),unsynchronisation:!1,data_length_indicator:!1}}:{status:{tag_alter_preservation:vA(n,0,6),file_alter_preservation:vA(n,0,5),read_only:vA(n,0,4)},format:{grouping_identity:vA(n,1,6),compression:vA(n,1,3),encryption:vA(n,1,2),unsynchronisation:vA(n,1,1),data_length_indicator:vA(n,1,0)}}}function XB(n,t,o){switch(t){case 2:return WJe(n,t,o);case 3:case 4:return ZJe(n,t,o);default:throw fre(t)}}function WJe(n,t,o){let i={id:wr(n.subarray(0,3),"ascii"),length:kr.get(n,3)};return i.id.match(/^[A-Z0-9]{3}$/)||o.addWarning(`Invalid ID3v2.${t} frame-header-ID: ${i.id}`),i}function ZJe(n,t,o){let i={id:wr(n.subarray(0,4),"ascii"),length:(t===4?xL:Ue).get(n,4),flags:VJe(n.subarray(8,10),t)};return i.id.match(/^[A-Z0-9]{4}$/)||o.addWarning(`Invalid ID3v2.${t} frame-header-ID: ${i.id}`),i}function fre(n){throw new nI(`Unexpected majorVer: ${n}`)}var VL=ue(()=>{DA();Ar();Ug();_s();WL()});function XJe(n){let t=[],o,i="";for(let e of n)if(typeof o=="string")if(e==="("&&o==="")i+="(",o=void 0;else if(e===")"){i!==""&&(t.push(i),i="");let a=Qre(o);a&&t.push(a),o=void 0}else o+=e;else e==="("?o="":i+=e;return i&&(t.length===0&&i.match(/^\d*$/)&&(i=Qre(i)),i&&t.push(i)),t}function Qre(n){if(n==="RX")return"Remix";if(n==="CR")return"Cover";if(n.match(/^\d*$/))return Rh[Number.parseInt(n,10)]}function $Je(n){throw new nI(`Unexpected majorVer: ${n}`)}var yre,hO,Xo,ZL,EO,nI,WL=ue(()=>{yre=Je(ct(),1);DA();Ar();Ug();WB();er();Ar();Bre();VL();hO=(0,yre.default)("music-metadata:id3v2:frame-parser"),Xo="latin1",ZL={encoding:Xo,bom:!1};EO=class n{constructor(t,o){this.major=t,this.warningCollector=o}readData(t,o,i){if(t.length===0){this.warningCollector.addWarning(`id3v2.${this.major} header has empty tag type=${o}`);return}let{encoding:e,bom:a}=_h.get(t,0),A=t.length,r=0,s=[],g=n.getNullTerminatorLength(e),c;switch(hO(`Parsing tag type=${o}, encoding=${e}, bom=${a}`),o!=="TXXX"&&o[0]==="T"?"T*":o){case"T*":case"GRP1":case"GP1":case"IPLS":case"MVIN":case"MVNM":case"PCS":case"PCST":{let I;try{I=n.trimNullPadding(la(t.subarray(1),e))}catch(d){if(d instanceof Error){this.warningCollector.addWarning(`id3v2.${this.major} type=${o} header has invalid string value: ${d.message}`);break}throw d}switch(o){case"TMCL":case"TIPL":case"IPLS":s=n.functionList(this.splitValue(o,I));break;case"TRK":case"TRCK":case"TPOS":case"TIT1":case"TIT2":case"TIT3":s=I;break;case"TCOM":case"TEXT":case"TOLY":case"TOPE":case"TPE1":case"TSRC":s=this.splitValue(o,I);break;case"TCO":case"TCON":s=this.splitValue(o,I).map(d=>XJe(d)).reduce((d,B)=>d.concat(B),[]);break;case"PCS":case"PCST":s=this.major>=4?this.splitValue(o,I):[I],s=Array.isArray(s)&&s[0]===""?1:0;break;default:s=this.major>=4?this.splitValue(o,I):[I]}break}case"TXXX":{let I=n.readIdentifierAndData(t.subarray(1),e);s={description:I.id,text:this.splitValue(o,la(I.data,e).replace(/\x00+$/,""))};break}case"PIC":case"APIC":if(i){let I={};switch(t=t.subarray(1),this.major){case 2:I.format=la(t.subarray(0,3),"latin1"),t=t.subarray(3);break;case 3:case 4:c=Gs(t,Xo),I.format=la(t.subarray(0,c),Xo),t=t.subarray(c+1);break;default:throw $Je(this.major)}I.format=n.fixPictureMimeType(I.format),I.type=Oh[t[0]],t=t.subarray(1),c=Gs(t,e),I.description=la(t.subarray(0,c),e),t=t.subarray(c+g),I.data=t,s=I}break;case"CNT":case"PCNT":s=KL(t);break;case"SYLT":{let I=jL.get(t,0);t=t.subarray(jL.len);let d={descriptor:"",language:I.language,contentType:I.contentType,timeStampFormat:I.timeStampFormat,syncText:[]},B=!1;for(;t.length>0;){let f=n.readNullTerminatedString(t,I.encoding);if(t=t.subarray(f.len),B){let Q=Ue.get(t,0);t=t.subarray(Ue.len),d.syncText.push({text:f.text,timestamp:Q})}else d.descriptor=f.text,B=!0}s=d;break}case"ULT":case"USLT":case"COM":case"COMM":{let I=ZD.get(t,r);r+=ZD.len;let d=n.readNullTerminatedString(t.subarray(r),I.encoding);r+=d.len;let B=n.readNullTerminatedString(t.subarray(r),I.encoding);s={language:I.language,descriptor:d.text,text:B.text};break}case"UFID":{let I=n.readIdentifierAndData(t,Xo);s={owner_identifier:I.id,identifier:I.data};break}case"PRIV":{let I=n.readIdentifierAndData(t,Xo);s={owner_identifier:I.id,data:I.data};break}case"POPM":{t=t.subarray(r);let I=n.readNullTerminatedString(t,ZL),d=I.text;if(t=t.subarray(I.len),t.length===0){this.warningCollector.addWarning(`id3v2.${this.major} type=${o} POPM frame missing rating byte`),s={email:d,rating:0,counter:void 0};break}let B=fA.get(t,0),f=t.subarray(fA.len);s={email:d,rating:B,counter:f.length>0?KL(f):void 0};break}case"GEOB":{let I=_h.get(t,0);t=t.subarray(1);let d=n.readNullTerminatedString(t,ZL),B=d.text;t=t.subarray(d.len);let f=n.readNullTerminatedString(t,I),Q=f.text;t=t.subarray(f.len);let y=n.readNullTerminatedString(t,I),m=y.text;t=t.subarray(y.len),s={type:B,filename:Q,description:m,data:t};break}case"WCOM":case"WCOP":case"WOAF":case"WOAR":case"WOAS":case"WORS":case"WPAY":case"WPUB":s=n.readNullTerminatedString(t,ZL).text;break;case"WXXX":{let I=_h.get(t,0);t=t.subarray(1);let d=n.readNullTerminatedString(t,I),B=d.text;t=t.subarray(d.len),s={description:B,url:n.trimNullPadding(la(t,Xo))};break}case"WFD":case"WFED":{let I=_h.get(t,0);t=t.subarray(1),s=n.readNullTerminatedString(t,I).text;break}case"MCDI":{s=t.subarray(0,A);break}case"CHAP":{hO("Reading CHAP"),c=Gs(t,Xo);let I={label:la(t.subarray(0,c),Xo),info:zL.get(t,c+1),frames:new Map};for(r+=c+1+zL.len;r=a.length)return{text:la(t,o.encoding),len:e};let r=t.subarray(0,i+A);return{text:la(r,o.encoding),len:i+A+n.getNullTerminatorLength(o.encoding)}}static fixPictureMimeType(t){switch(t=t.toLocaleLowerCase(),t){case"jpg":return"image/jpeg";case"png":return"image/png"}return t}static functionList(t){let o={};for(let i=0;i+11?this.warningCollector.addWarning(`ID3v2.${this.major} ${t} uses non standard null-separator.`):i=o.split(/\//g)):i=o.split(/\x00/g),n.trimArray(i)}static trimArray(t){return t.map(o=>n.trimNullPadding(o).trim())}static trimNullPadding(t){let o=t.length;for(;o>0&&t.charCodeAt(o-1)===0;)o--;return o===t.length?t:t.slice(0,o)}static readIdentifierAndData(t,o){let i=n.readNullTerminatedString(t,{encoding:o,bom:!1});return{id:i.text,data:t.subarray(i.len)}}static getNullTerminatorLength(t){return t.startsWith("utf-16")?2:1}},nI=class extends Qt("id3v2"){}});function eqe(n){throw new nI(`Unexpected majorVer: ${n}`)}var $o,kh=ue(()=>{DA();WL();Ug();VL();$o=class n{constructor(){this.tokenizer=void 0,this.id3Header=void 0,this.metadata=void 0,this.headerType=void 0,this.options=void 0}static removeUnsyncBytes(t){let o=0,i=0;for(;o0?this.parseExtendedHeaderData(o,t.size):this.parseId3Data(this.id3Header.size-t.size)}async parseExtendedHeaderData(t,o){return await this.tokenizer.ignore(t),this.parseId3Data(this.id3Header.size-o)}async parseId3Data(t){let o=await this.tokenizer.readToken(new Dt(t));for(let i of this.parseMetadata(o))switch(i.id){case"TXXX":i.value&&await this.handleTag(i,i.value.text,()=>i.value.description);break;default:await(Array.isArray(i.value)?Promise.all(i.value.map(e=>this.addTag(i.id,e))):this.addTag(i.id,i.value))}}async handleTag(t,o,i,e=a=>a){await Promise.all(o.map(a=>this.addTag(n.makeDescriptionTagName(t.id,i(a)),e(a))))}async addTag(t,o){await this.metadata.addTag(this.headerType,t,o)}parseMetadata(t){let o=0,i=[];for(;o!==t.length;){let e=ZB(this.id3Header.version.major);if(o+e>t.length){this.metadata.addWarning("Illegal ID3v2 tag length");break}let a=t.subarray(o,o+e);o+=e;let A=XB(a,this.id3Header.version.major,this.metadata),r=t.subarray(o,o+A.length);o+=A.length;let s=n.readFrameData(r,A,this.id3Header.version.major,!this.options.skipCovers,this.metadata);s&&i.push({id:A.id,value:s})}return i}static mapId3v2Chapters(t){if(!t)return;let o=t.filter(g=>g.id==="CHAP");if(!o?.length)return;let e=t.filter(g=>g.id==="CTOC")?.find(g=>g.value.flags?.topLevel),a=new Map;for(let g of o)a.set(g.value.label,g.value);let A=e?.value.childElementIds,r=[],s=A??[...a.keys()];for(let g of s){let c=a.get(g);if(!c)continue;let I=c.frames,d=I.get("TIT2");d&&r.push({id:g,title:d,url:I.get("WXXX"),start:c.info.startTime/1e3,end:c.info.endTime/1e3,image:I.get("APIC")})}return A||r.sort((g,c)=>g.start-c.start),r.length?r:void 0}}});var mre,XL,Fs,$B=ue(()=>{so();mre=Je(ct(),1);Ug();kh();WB();Hi();XL=(0,mre.default)("music-metadata:parser:ID3"),Fs=class extends Rt{constructor(){super(...arguments),this.id3parser=new $o}static async startsWithID3v2Header(t){return(await t.peekToken(Pl)).fileIdentifier==="ID3"}async parse(){try{await this.parseID3v2()}catch(t){if(t instanceof bA)XL("End-of-stream");else throw t}}finalize(){}async parseID3v2(){await this.tryReadId3v2Headers(),XL("End of ID3v2 header, go to MPEG-parser: pos=%s",this.tokenizer.position),await this.postId3v2Parse(),this.options.skipPostHeaders&&this.metadata.hasAny()?this.finalize():(await new dO(this.metadata,this.tokenizer,this.options).parse(),this.finalize())}async tryReadId3v2Headers(){if((await this.tokenizer.peekToken(Pl)).fileIdentifier==="ID3")return XL("Found ID3v2 header, pos=%s",this.tokenizer.position),await this.id3parser.parse(this.metadata,this.tokenizer,this.options),this.tryReadId3v2Headers()}}});var $L,Sre=ue(()=>{Ar();$L={len:2,get:(n,t)=>{let o=XA(n,t,0,3),i=XA(n,t,6,1),e=XA(n,t,7,9)/10;if(o>0)return{type:XA(n,t,0,3),origin:XA(n,t,3,3),adjustment:i?-e:e}}}});var wre,Dre=ue(()=>{DA();Ar();Sre();wre={len:27,get:(n,t)=>{let o=Ue.get(n,t+2);return{revision:XA(n,t,0,4),vbr_method:XA(n,t,4,4),lowpass_filter:100*fA.get(n,t+1),track_peak:o===0?null:o/2**23,track_gain:$L.get(n,6),album_gain:$L.get(n,8),music_length:Ue.get(n,t+20),music_crc:fA.get(n,t+24),header_crc:GA.get(n,t+24)}}}});async function Ore(n){let t=await n.readToken(Aqe),o={numFrames:null,streamSize:null,vbrScale:null};if(t.frames&&(o.numFrames=await n.readToken(Ue)),t.bytes&&(o.streamSize=await n.readToken(Ue)),t.toc&&(o.toc=new Uint8Array(100),await n.readBuffer(o.toc)),t.vbrScale&&(o.vbrScale=await n.readToken(Ue)),await n.peekToken(new ze(4,"ascii"))==="LAME"){await n.ignore(4),o.lame={version:await n.readToken(new ze(5,"ascii"))};let e=o.lame.version.match(/\d+.\d+/g);if(e!==null){let A=e[0].split(".").map(r=>Number.parseInt(r,10));A[0]>=3&&A[1]>=90&&(o.lame.extended=await n.readToken(wre))}}return o}var e2,CO,Aqe,bre=ue(()=>{DA();Ar();Dre();e2=new ze(4,"ascii"),CO=new ze(6,"ascii"),Aqe={len:4,get:(n,t)=>({frames:Da(n,t,31),bytes:Da(n,t,30),toc:Da(n,t,29),vbrScale:Da(n,t,28)})}});var Rre={};Pr(Rre,{MpegContentError:()=>Hl,MpegParser:()=>A2});function rqe(n){return`V${Math.floor((100-n)/10)}`}var Nre,go,Hl,Mre,_re,tqe,co,Tre,A2,kre=ue(()=>{DA();so();Nre=Je(ct(),1);Ar();$B();bre();er();go=(0,Nre.default)("music-metadata:parser:mpeg"),Hl=class extends Qt("MPEG"){},Mre=1024,_re={AudioObjectTypes:["AAC Main","AAC LC","AAC SSR","AAC LTP"],SamplingFrequencies:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350,null,null,null]},tqe=[void 0,["front-center"],["front-left","front-right"],["front-center","front-left","front-right"],["front-center","front-left","front-right","back-center"],["front-center","front-left","front-right","back-left","back-right"],["front-center","front-left","front-right","back-left","back-right","LFE-channel"],["front-center","front-left","front-right","side-left","side-right","back-left","back-right","LFE-channel"]],co=class n{constructor(t,o){this.bitrateIndex=null,this.sampRateFreqIndex=null,this.padding=null,this.privateBit=null,this.channelModeIndex=null,this.modeExtension=null,this.isOriginalMedia=null,this.version=null,this.bitrate=null,this.samplingRate=null,this.frameLength=0,this.versionIndex=XA(t,o+1,3,2),this.layer=n.LayerDescription[XA(t,o+1,5,2)],this.versionIndex>1&&this.layer===0?this.parseAdtsHeader(t,o):this.parseMpegHeader(t,o),this.isProtectedByCRC=!Da(t,o+1,7)}calcDuration(t){return this.samplingRate==null?null:t*this.calcSamplesPerFrame()/this.samplingRate}calcSamplesPerFrame(){return n.samplesInFrameTable[this.version===1?0:1][this.layer]}calculateSideInfoLength(){if(this.layer!==3)return 2;if(this.channelModeIndex===3){if(this.version===1)return 17;if(this.version===2||this.version===2.5)return 9}else{if(this.version===1)return 32;if(this.version===2||this.version===2.5)return 17}return null}calcSlotSize(){return[null,4,1,1][this.layer]}parseMpegHeader(t,o){this.container="MPEG",this.bitrateIndex=XA(t,o+2,0,4),this.sampRateFreqIndex=XA(t,o+2,4,2),this.padding=Da(t,o+2,6),this.privateBit=Da(t,o+2,7),this.channelModeIndex=XA(t,o+3,0,2),this.modeExtension=XA(t,o+3,2,2),this.isCopyrighted=Da(t,o+3,4),this.isOriginalMedia=Da(t,o+3,5),this.emphasis=XA(t,o+3,7,2),this.version=n.VersionID[this.versionIndex],this.channelMode=n.ChannelMode[this.channelModeIndex],this.codec=`MPEG ${this.version} Layer ${this.layer}`;let i=this.calcBitrate();if(!i)throw new Hl("Cannot determine bit-rate");if(this.bitrate=i*1e3,this.samplingRate=this.calcSamplingRate(),this.samplingRate==null)throw new Hl("Cannot determine sampling-rate")}parseAdtsHeader(t,o){go("layer=0 => ADTS"),this.version=this.versionIndex===2?4:2,this.container=`ADTS/MPEG-${this.version}`;let i=XA(t,o+2,0,2);this.codec="AAC",this.codecProfile=_re.AudioObjectTypes[i],go(`MPEG-4 audio-codec=${this.codec}`);let e=XA(t,o+2,2,4);this.samplingRate=_re.SamplingFrequencies[e],go(`sampling-rate=${this.samplingRate}`);let a=XA(t,o+2,7,3);this.mp4ChannelConfig=tqe[a],go(`channel-config=${this.mp4ChannelConfig?this.mp4ChannelConfig.join("+"):"?"}`),this.frameLength=XA(t,o+3,6,2)<<11}calcBitrate(){if(this.bitrateIndex===0||this.bitrateIndex===15)return null;if(this.version&&this.bitrateIndex){let t=10*Math.floor(this.version)+this.layer;return n.bitrate_index[this.bitrateIndex][t]}return null}calcSamplingRate(){return this.sampRateFreqIndex===3||this.version===null||this.sampRateFreqIndex==null?null:n.sampling_rate_freq_index[this.version][this.sampRateFreqIndex]}};co.SyncByte1=255;co.SyncByte2=224;co.VersionID=[2.5,null,2,1];co.LayerDescription=[0,3,2,1];co.ChannelMode=["stereo","joint_stereo","dual_channel","mono"];co.bitrate_index={1:{11:32,12:32,13:32,21:32,22:8,23:8},2:{11:64,12:48,13:40,21:48,22:16,23:16},3:{11:96,12:56,13:48,21:56,22:24,23:24},4:{11:128,12:64,13:56,21:64,22:32,23:32},5:{11:160,12:80,13:64,21:80,22:40,23:40},6:{11:192,12:96,13:80,21:96,22:48,23:48},7:{11:224,12:112,13:96,21:112,22:56,23:56},8:{11:256,12:128,13:112,21:128,22:64,23:64},9:{11:288,12:160,13:128,21:144,22:80,23:80},10:{11:320,12:192,13:160,21:160,22:96,23:96},11:{11:352,12:224,13:192,21:176,22:112,23:112},12:{11:384,12:256,13:224,21:192,22:128,23:128},13:{11:416,12:320,13:256,21:224,22:144,23:144},14:{11:448,12:384,13:320,21:256,22:160,23:160}};co.sampling_rate_freq_index={1:{0:44100,1:48e3,2:32e3},2:{0:22050,1:24e3,2:16e3},2.5:{0:11025,1:12e3,2:8e3}};co.samplesInFrameTable=[[0,384,1152,1152],[0,384,1152,576]];Tre={len:4,get:(n,t)=>new co(n,t)};A2=class extends Fs{constructor(){super(...arguments),this.frameCount=0,this.syncFrameCount=-1,this.totalDataLength=0,this.bitrates=[],this.offset=0,this.frame_size=0,this.calculateEofDuration=!1,this.samplesPerFrame=null,this.buf_frame_header=new Uint8Array(4),this.mpegOffset=null,this.syncPeek={buf:new Uint8Array(Mre),len:0}}async postId3v2Parse(){this.metadata.setFormat("lossless",!1),this.metadata.setAudioOnly();try{let t=!1;for(;!t;)await this.sync(),t=await this.parseCommonMpegHeader()}catch(t){if(t instanceof bA){if(go("End-of-stream"),this.calculateEofDuration&&this.samplesPerFrame!==null){let o=this.frameCount*this.samplesPerFrame;if(this.metadata.setFormat("numberOfSamples",o),this.metadata.format.sampleRate){let i=o/this.metadata.format.sampleRate;go(`Calculate duration at EOF: ${i} sec.`,i),this.metadata.setFormat("duration",i)}}}else throw t}}finalize(){let t=this.metadata.format,o=!!this.metadata.native.ID3v1;if(this.mpegOffset!==null){if(t.duration&&this.tokenizer.fileInfo.size){let i=this.tokenizer.fileInfo.size-this.mpegOffset-(o?128:0);t.codecProfile&&t.codecProfile[0]==="V"&&this.metadata.setFormat("bitrate",i*8/t.duration)}if(this.tokenizer.fileInfo.size&&t.codecProfile==="CBR"){let i=this.tokenizer.fileInfo.size-this.mpegOffset-(o?128:0);if(this.frame_size!==null&&this.samplesPerFrame!==null){let e=Math.round(i/this.frame_size)*this.samplesPerFrame;if(this.metadata.setFormat("numberOfSamples",e),t.sampleRate&&!t.duration){let a=e/t.sampleRate;go("Calculate CBR duration based on file size: %s",a),this.metadata.setFormat("duration",a)}}}}}async sync(){let t=!1;for(;;){let o=0;if(this.syncPeek.len=await this.tokenizer.peekBuffer(this.syncPeek.buf,{length:Mre,mayBeLess:!0}),this.syncPeek.len<=163)throw new bA;for(;;){if(t&&(this.syncPeek.buf[o]&224)===224){this.buf_frame_header[0]=co.SyncByte1,this.buf_frame_header[1]=this.syncPeek.buf[o],await this.tokenizer.ignore(o),go(`Sync at offset=${this.tokenizer.position-1}, frameCount=${this.frameCount}`),this.syncFrameCount===this.frameCount&&(go(`Re-synced MPEG stream, frameCount=${this.frameCount}`),this.frameCount=0,this.frame_size=0),this.syncFrameCount=this.frameCount;return}if(t=!1,o=this.syncPeek.buf.indexOf(co.SyncByte1,o),o===-1){if(this.syncPeek.len=2&&t.layer===0?this.parseAdts(t):this.parseAudioFrameHeader(t)}async parseAudioFrameHeader(t){this.metadata.setFormat("numberOfChannels",t.channelMode==="mono"?1:2),this.metadata.setFormat("bitrate",t.bitrate),this.frameCount<20*1e4&&go("offset=%s MP%s bitrate=%s sample-rate=%s",this.tokenizer.position-4,t.layer,t.bitrate,t.samplingRate);let o=t.calcSlotSize();if(o===null)throw new Hl("invalid slot_size");let i=t.calcSamplesPerFrame();go(`samples_per_frame=${i}`);let e=i/8;if(t.bitrate!==null&&t.samplingRate!=null){let a=e*t.bitrate/t.samplingRate+(t.padding?o:0);this.frame_size=Math.floor(a)}if(this.audioFrameHeader=t,t.bitrate!==null&&this.bitrates.push(t.bitrate),this.frameCount===1)return this.offset=Tre.len,await this.skipSideInformation(),!1;if(this.frameCount===4){if(this.areAllSame(this.bitrates)){if(this.samplesPerFrame=i,this.metadata.setFormat("codecProfile","CBR"),this.tokenizer.fileInfo.size)return!0}else if(this.metadata.format.duration)return!0;if(!this.options.duration)return!0}return this.options.duration&&this.frameCount===4&&(this.samplesPerFrame=i,this.calculateEofDuration=!0),this.offset=4,t.isProtectedByCRC?(await this.parseCrc(),!1):(await this.skipSideInformation(),!1)}async parseAdts(t){let o=new Uint8Array(3);if(await this.tokenizer.readBuffer(o),t.frameLength+=XA(o,0,0,11),this.totalDataLength+=t.frameLength,this.samplesPerFrame=1024,t.samplingRate!==null){let i=t.samplingRate/this.samplesPerFrame,a=8*(this.frameCount===0?0:this.totalDataLength/this.frameCount)*i+.5;this.metadata.setFormat("bitrate",a),go(`frame-count=${this.frameCount}, size=${t.frameLength} bytes, bit-rate=${a}`)}if(await this.tokenizer.ignore(t.frameLength>7?t.frameLength-7:1),this.frameCount===3)if(this.metadata.setFormat("codecProfile",t.codecProfile),t.mp4ChannelConfig&&this.metadata.setFormat("numberOfChannels",t.mp4ChannelConfig.length),this.options.duration)this.calculateEofDuration=!0;else return!0;return!1}async parseCrc(){return await this.tokenizer.ignore(qo.len),this.offset+=qo.len,this.skipSideInformation()}async skipSideInformation(){if(this.audioFrameHeader){let t=this.audioFrameHeader.calculateSideInfoLength();if(t!==null){await this.tokenizer.readToken(new Dt(t)),this.offset+=t,await this.readXtraInfoHeader();return}}}async readXtraInfoHeader(){let t=await this.tokenizer.readToken(e2);switch(this.offset+=e2.len,t){case"Info":return this.metadata.setFormat("codecProfile","CBR"),this.readXingInfoHeader();case"Xing":{let i=await this.readXingInfoHeader();if(i.vbrScale!==null){let e=rqe(i.vbrScale);this.metadata.setFormat("codecProfile",e)}return null}case"Xtra":break;case"LAME":{let i=await this.tokenizer.readToken(CO);if(this.frame_size!==null&&this.frame_size>=this.offset+CO.len)return this.offset+=CO.len,this.metadata.setFormat("tool",`LAME ${i}`),await this.skipFrameData(this.frame_size-this.offset),null;this.metadata.addWarning("Corrupt LAME header");break}}let o=this.frame_size-this.offset;return o<0?this.metadata.addWarning(`Frame ${this.frameCount}corrupt: negative frameDataLeft`):await this.skipFrameData(o),null}async readXingInfoHeader(){let t=this.tokenizer.position,o=await Ore(this.tokenizer);if(this.offset+=this.tokenizer.position-t,o.lame&&(this.metadata.setFormat("tool",`LAME ${Wo(o.lame.version)}`),o.lame.extended&&(this.metadata.setFormat("trackPeakLevel",o.lame.extended.track_peak),o.lame.extended.track_gain&&this.metadata.setFormat("trackGain",o.lame.extended.track_gain.adjustment),o.lame.extended.album_gain&&this.metadata.setFormat("albumGain",o.lame.extended.album_gain.adjustment),this.metadata.setFormat("duration",o.lame.extended.music_length/1e3))),o.streamSize&&this.audioFrameHeader&&o.numFrames!==null){let e=this.audioFrameHeader.calcDuration(o.numFrames);return this.metadata.setFormat("duration",e),go("Get duration from Xing header: %s",this.metadata.format.duration),o}let i=this.frame_size-this.offset;return await this.skipFrameData(i),o}async skipFrameData(t){if(t<0)throw new Hl("frame-data-left cannot be negative");await this.tokenizer.ignore(t)}areAllSame(t){let o=t[0];return t.every(i=>i===o)}}});var vre,Pre=ue(()=>{vre={parserType:"mpeg",extensions:[".mp2",".mp3",".m2a",".aac","aacp"],mimeTypes:["audio/mpeg","audio/mp3","audio/aacs","audio/aacp"],async load(){return(await Promise.resolve().then(()=>(kre(),Rre))).MpegParser}}});var Gre,Fre=ue(()=>{Gre={parserType:"apev2",extensions:[".ape"],mimeTypes:["audio/ape","audio/monkeys-audio"],async load(){return(await Promise.resolve().then(()=>(Ul(),Ere))).APEv2Parser}}});function t2(n){let t=n.trim();if(t.length!==36||t[8]!=="-"||t[13]!=="-"||t[18]!=="-"||t[23]!=="-")throw new Error(`Invalid GUID format: ${n}`);let o,i=new Uint8Array(16);o=parseInt(t.slice(0,8),16),i[0]=o&255,i[1]=o>>>8&255,i[2]=o>>>16&255,i[3]=o>>>24&255,o=parseInt(t.slice(9,13),16),i[4]=o&255,i[5]=o>>>8&255,o=parseInt(t.slice(14,18),16),i[6]=o&255,i[7]=o>>>8&255,o=parseInt(t.slice(19,23),16),i[8]=o>>>8&255,i[9]=o&255,o=parseInt(t.slice(24,32),16),i[10]=o>>>24&255,i[11]=o>>>16&255,i[12]=o>>>8&255,i[13]=o&255,o=parseInt(t.slice(32,36),16),i[14]=o>>>8&255,i[15]=o&255;for(let e=0;e<16;e++)if(!Number.isFinite(i[e]))throw new Error(`Invalid GUID format: ${n}`);if(!/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(t))throw new Error(`Invalid GUID format: ${n}`);return i}var uO,Lre=ue(()=>{uO=class n{constructor(t){if(t.length!==16)throw new Error("GUID must be exactly 16 bytes");this.bytes=t}static fromString(t){return new n(t2(t))}toString(){let t=this.bytes,o=s=>s.toString(16).padStart(2,"0"),i=o(t[3])+o(t[2])+o(t[1])+o(t[0]),e=o(t[5])+o(t[4]),a=o(t[7])+o(t[6]),A=o(t[8])+o(t[9]),r=o(t[10])+o(t[11])+o(t[12])+o(t[13])+o(t[14])+o(t[15]);return`${i}-${e}-${a}-${A}-${r}`.toUpperCase()}equals(t,o=0){if(o<0||t.length-o<16)return!1;let i=this.bytes;for(let e=0;e<16;e++)if(t[o+e]!==i[e])return!1;return!0}}});var xe,cr,r2=ue(()=>{Lre();xe=class n{static fromBin(t,o=0){return new n(n.decode(t,o))}static decode(t,o=0){return new uO(t.subarray(o,o+16)).toString()}static decodeMediaType(t){switch(t.str){case n.AudioMedia.str:return"audio";case n.VideoMedia.str:return"video";case n.CommandMedia.str:return"command";case n.Degradable_JPEG_Media.str:return"degradable-jpeg";case n.FileTransferMedia.str:return"file-transfer";case n.BinaryMedia.str:return"binary"}}static encode(t){return t2(t)}constructor(t){this.str=t}equals(t){return this.str===t.str}toBin(){return n.encode(this.str)}};xe.HeaderObject=new xe("75B22630-668E-11CF-A6D9-00AA0062CE6C");xe.DataObject=new xe("75B22636-668E-11CF-A6D9-00AA0062CE6C");xe.SimpleIndexObject=new xe("33000890-E5B1-11CF-89F4-00A0C90349CB");xe.IndexObject=new xe("D6E229D3-35DA-11D1-9034-00A0C90349BE");xe.MediaObjectIndexObject=new xe("FEB103F8-12AD-4C64-840F-2A1D2F7AD48C");xe.TimecodeIndexObject=new xe("3CB73FD0-0C4A-4803-953D-EDF7B6228F0C");xe.FilePropertiesObject=new xe("8CABDCA1-A947-11CF-8EE4-00C00C205365");xe.StreamPropertiesObject=new xe("B7DC0791-A9B7-11CF-8EE6-00C00C205365");xe.HeaderExtensionObject=new xe("5FBF03B5-A92E-11CF-8EE3-00C00C205365");xe.CodecListObject=new xe("86D15240-311D-11D0-A3A4-00A0C90348F6");xe.ScriptCommandObject=new xe("1EFB1A30-0B62-11D0-A39B-00A0C90348F6");xe.MarkerObject=new xe("F487CD01-A951-11CF-8EE6-00C00C205365");xe.BitrateMutualExclusionObject=new xe("D6E229DC-35DA-11D1-9034-00A0C90349BE");xe.ErrorCorrectionObject=new xe("75B22635-668E-11CF-A6D9-00AA0062CE6C");xe.ContentDescriptionObject=new xe("75B22633-668E-11CF-A6D9-00AA0062CE6C");xe.ExtendedContentDescriptionObject=new xe("D2D0A440-E307-11D2-97F0-00A0C95EA850");xe.ContentBrandingObject=new xe("2211B3FA-BD23-11D2-B4B7-00A0C955FC6E");xe.StreamBitratePropertiesObject=new xe("7BF875CE-468D-11D1-8D82-006097C9A2B2");xe.ContentEncryptionObject=new xe("2211B3FB-BD23-11D2-B4B7-00A0C955FC6E");xe.ExtendedContentEncryptionObject=new xe("298AE614-2622-4C17-B935-DAE07EE9289C");xe.DigitalSignatureObject=new xe("2211B3FC-BD23-11D2-B4B7-00A0C955FC6E");xe.PaddingObject=new xe("1806D474-CADF-4509-A4BA-9AABCB96AAE8");xe.ExtendedStreamPropertiesObject=new xe("14E6A5CB-C672-4332-8399-A96952065B5A");xe.AdvancedMutualExclusionObject=new xe("A08649CF-4775-4670-8A16-6E35357566CD");xe.GroupMutualExclusionObject=new xe("D1465A40-5A79-4338-B71B-E36B8FD6C249");xe.StreamPrioritizationObject=new xe("D4FED15B-88D3-454F-81F0-ED5C45999E24");xe.BandwidthSharingObject=new xe("A69609E6-517B-11D2-B6AF-00C04FD908E9");xe.LanguageListObject=new xe("7C4346A9-EFE0-4BFC-B229-393EDE415C85");xe.MetadataObject=new xe("C5F8CBEA-5BAF-4877-8467-AA8C44FA4CCA");xe.MetadataLibraryObject=new xe("44231C94-9498-49D1-A141-1D134E457054");xe.IndexParametersObject=new xe("D6E229DF-35DA-11D1-9034-00A0C90349BE");xe.MediaObjectIndexParametersObject=new xe("6B203BAD-3F11-48E4-ACA8-D7613DE2CFA7");xe.TimecodeIndexParametersObject=new xe("F55E496D-9797-4B5D-8C8B-604DFE9BFB24");xe.CompatibilityObject=new xe("26F18B5D-4584-47EC-9F5F-0E651F0452C9");xe.AdvancedContentEncryptionObject=new xe("43058533-6981-49E6-9B74-AD12CB86D58C");xe.AudioMedia=new xe("F8699E40-5B4D-11CF-A8FD-00805F5C442B");xe.VideoMedia=new xe("BC19EFC0-5B4D-11CF-A8FD-00805F5C442B");xe.CommandMedia=new xe("59DACFC0-59E6-11D0-A3AC-00A0C90348F6");xe.JFIF_Media=new xe("B61BE100-5B4E-11CF-A8FD-00805F5C442B");xe.Degradable_JPEG_Media=new xe("35907DE0-E415-11CF-A917-00805F5C442B");xe.FileTransferMedia=new xe("91BD222C-F21C-497A-8B6D-5AA86BFC0185");xe.BinaryMedia=new xe("3AFB65E2-47EF-40F2-AC2C-70A90D71D343");xe.ASF_Index_Placeholder_Object=new xe("D9AADE20-7C17-4F9C-BC28-8555DD98E2A2");cr=xe});function Hre(n){return aqe[n]}function ef(n){return Wo(la(n,"utf-16le"))}function Ure(n){return new Uint8Array(n)}function iqe(n,t=0){return Kre(n,t)===1}function oqe(n,t=0){return Ge.get(n,t)}function nqe(n,t=0){return Dr.get(n,t)}function Kre(n,t=0){return SA.get(n,t)}var aqe,xre=ue(()=>{DA();Ar();aqe=[ef,Ure,iqe,oqe,nqe,Kre,Ure]});async function Yre(n){let t=await n.readNumber(SA);return(await n.readToken(new ze(t*2,"utf-16le"))).replace("\0","")}async function jre(n,t){let o=new a2(n,t),i=await o.readToken(sqe),e=[];for(let a=0;a{DA();Ar();r2();xre();Ug();er();vr=class extends Qt("ASF"){},BO={len:30,get:(n,t)=>{let o=Yl.get(n,t);if(o.objectSize{let o=Dr.get(n,t+16);if(oBigInt(Number.MAX_SAFE_INTEGER))throw new vr(`Invalid ASF header object size: ${o}`);return{objectId:cr.fromBin(n,t),objectSize:Number(o)}}},sI=class{constructor(t){this.len=t.objectSize-Yl.len}postProcessTag(t,o,i,e){if(o==="WM/Picture")t.push({id:o,value:i2.fromBuffer(e)});else{let a=Hre(i);if(!a)throw new vr(`unexpected value headerType: ${i}`);t.push({id:o,value:a(e)})}}},vh=class extends sI{get(t,o){return{fileId:cr.fromBin(t,o),fileSize:Dr.get(t,o+16),creationDate:Dr.get(t,o+24),dataPacketsCount:Dr.get(t,o+32),playDuration:Dr.get(t,o+40),sendDuration:Dr.get(t,o+48),preroll:Dr.get(t,o+56),flags:{broadcast:vA(t,o+64,24),seekable:vA(t,o+64,25)},minimumDataPacketSize:Ge.get(t,o+68),maximumDataPacketSize:Ge.get(t,o+72),maximumBitrate:Ge.get(t,o+76)}}};vh.guid=cr.FilePropertiesObject;Ph=class extends sI{get(t,o){return{streamType:cr.decodeMediaType(cr.fromBin(t,o)),errorCorrectionType:cr.fromBin(t,o+8)}}};Ph.guid=cr.StreamPropertiesObject;Gh=class{constructor(){this.len=22}get(t,o){let i=new DataView(t.buffer,o);return{reserved1:cr.fromBin(t,o),reserved2:i.getUint16(16,!0),extensionDataSize:i.getUint32(18,!0)}}};Gh.guid=cr.HeaderExtensionObject;sqe={len:20,get:(n,t)=>({entryCount:new DataView(n.buffer,t).getUint16(16,!0)})},a2=class{constructor(t,o){this.tokenizer=t,this.remaining=o}async readToken(t){this.ensureAvailable(t.len);let o=await this.tokenizer.readToken(t);return this.remaining-=t.len,o}async readNumber(t){return this.readToken(t)}async readBuffer(t){this.ensureAvailable(t);let o=new Uint8Array(t);return await this.tokenizer.readBuffer(o),this.remaining-=t,o}async ignoreRemaining(){let t=await this.tokenizer.ignore(this.remaining);if(t!==this.remaining)throw new vr(`Unexpected end of ASF Codec List Object; missing ${this.remaining-t} bytes`);this.remaining=0}ensureAvailable(t){if(t>this.remaining)throw new vr(`ASF Codec List field size ${t} exceeds remaining object payload size ${this.remaining}`)}};Kl=class n extends sI{get(t,o){let i=[],e=new DataView(t.buffer,o),a=10;for(let A=0;A0){let s=n.contentDescTags[A],g=a+r;i.push({id:s,value:ef(t.subarray(o+a,o+g))}),a=g}}return i}};Kl.guid=cr.ContentDescriptionObject;Kl.contentDescTags=["Title","Author","Copyright","Description","Rating"];Fh=class extends sI{get(t,o){let i=[],e=new DataView(t.buffer,o),a=e.getUint16(0,!0),A=2;for(let r=0;rs2});var qre,n2,lqe,Jre,s2,Vre=ue(()=>{qre=Je(ct(),1);so();Gl();r2();o2();Hi();o2();n2=(0,qre.default)("music-metadata:parser:ASF"),lqe="asf",Jre=16*1024*1024,s2=class extends Rt{async parse(){let t=await this.tokenizer.readToken(BO);if(!t.objectId.equals(cr.HeaderObject))throw new vr(`expected asf header; but was not found; got: ${t.objectId.str}`);if(t.numberOfHeaderObjects<1||t.numberOfHeaderObjects>1e4)throw new vr(`Unrealistic number of ASF header objects: ${t.numberOfHeaderObjects}`);await this.parseObjectHeaders(t.numberOfHeaderObjects,t.objectSize-BO.len)}async parseObjectHeaders(t,o){let i;for(let e=0;e{this.metadata.addStreamInfo({type:g.type.videoCodec?Ia.video:Ia.audio,codecName:g.codecName})});let s=r.filter(g=>g.type.audioCodec).map(g=>g.codecName).join("/");this.metadata.setFormat("codec",s);break}case cr.StreamBitratePropertiesObject.str:await this.ignorePayload(A,"Stream Bitrate Properties Object");break;case cr.PaddingObject.str:n2("Padding: %s bytes",A),await this.ignorePayload(A,"Padding Object");break;default:this.metadata.addWarning(`Ignore ASF-Object-GUID: ${a.objectId.str}`),n2("Ignore ASF-Object-GUID: %s",a.objectId.str),await this.ignorePayload(A,`object ${a.objectId.str}`)}o-=a.objectSize}if(o!==0)throw new vr(`ASF header child objects leave ${o} payload byte(s) unaccounted`)}async addTags(t){await Promise.all(t.map(({id:o,value:i})=>this.metadata.addTag(lqe,o,i)))}async readObjectHeader(t,o){if(tt)throw new vr(`ASF ${o} object size ${i.objectSize} exceeds remaining ${o} payload size ${t}`);return{header:i,payloadSize:this.validatePayloadAvailability(i,`${o} object`)}}validatePayloadAvailability(t,o){let i=t.objectSize-Yl.len,e=this.tokenizer.fileInfo.size;if(e!==void 0){let a=e-this.tokenizer.position;if(i>a)throw new vr(`ASF ${o} payload size ${i} exceeds available input size ${a}`)}return i}validateAllocationSize(t,o){if(t>Jre)throw new vr(`ASF ${o} payload size ${t} exceeds allocation limit ${Jre}`)}async ignorePayload(t,o){let i;try{i=await this.tokenizer.ignore(t)}catch(e){throw e instanceof bA?new vr(`Unexpected end of ASF ${o}`):e}if(i!==t)throw new vr(`Unexpected end of ASF ${o}; missing ${t-i} bytes`)}async parseExtensionObject(t){for(;t>0;){let{header:o,payloadSize:i}=await this.readObjectHeader(t,"extension");switch(o.objectId.str){case Lh.guid.str:this.validateAllocationSize(i,"Extended Stream Properties Object"),await this.tokenizer.readToken(new Lh(o));break;case xl.guid.str:{this.validateAllocationSize(i,"Metadata Object");let e=await this.tokenizer.readToken(new xl(o));await this.addTags(e);break}case Uh.guid.str:{this.validateAllocationSize(i,"Metadata Library Object");let e=await this.tokenizer.readToken(new Uh(o));await this.addTags(e);break}case cr.PaddingObject.str:await this.ignorePayload(i,"extension Padding Object");break;case cr.CompatibilityObject.str:await this.ignorePayload(i,"Compatibility Object");break;case cr.ASF_Index_Placeholder_Object.str:await this.ignorePayload(i,"Index Placeholder Object");break;default:this.metadata.addWarning(`Ignore ASF-Object-GUID: ${o.objectId.str}`),await this.ignorePayload(i,`extension object ${o.objectId.str}`);break}t-=o.objectSize}}}});var Wre,Zre=ue(()=>{Wre={parserType:"asf",extensions:[".asf",".wma",".wmv"],mimeTypes:["audio/ms-wma","video/ms-wmv","audio/ms-asf","video/ms-asf","application/vnd.ms-asf"],async load(){return(await Promise.resolve().then(()=>(Vre(),zre))).AsfParser}}});var jl,Xre=ue(()=>{DA();si();jl={len:12,get:(n,t)=>({chunkID:at.get(n,t),chunkSize:bL.get(n,t+4)})}});var eae={};Pr(eae,{DsdiffContentParseError:()=>Hh,DsdiffParser:()=>g2});var $re,gi,Hh,g2,Aae=ue(()=>{DA();$re=Je(ct(),1);so();si();Hi();kh();Xre();er();gi=(0,$re.default)("music-metadata:parser:aiff"),Hh=class extends Qt("DSDIFF"){},g2=class extends Rt{async parse(){let t=await this.tokenizer.readToken(jl);if(t.chunkID!=="FRM8")throw new Hh("Unexpected chunk-ID");this.metadata.setAudioOnly();let o=(await this.tokenizer.readToken(at)).trim();switch(o){case"DSD":return this.metadata.setFormat("container",`DSDIFF/${o}`),this.metadata.setFormat("lossless",!0),this.readFmt8Chunks(t.chunkSize-BigInt(at.len));default:throw new Hh(`Unsupported DSDIFF type: ${o}`)}}async readFmt8Chunks(t){for(;t>=jl.len;){let o=await this.tokenizer.readToken(jl);gi(`Chunk id=${o.chunkID}`),await this.readData(o),t-=BigInt(jl.len)+o.chunkSize}}async readData(t){gi(`Reading data of chunk[ID=${t.chunkID}, size=${t.chunkSize}]`);let o=this.tokenizer.position;switch(t.chunkID.trim()){case"FVER":{let e=await this.tokenizer.readToken(Ge);gi(`DSDIFF version=${e}`);break}case"PROP":{if(await this.tokenizer.readToken(at)!=="SND ")throw new Hh("Unexpected PROP-chunk ID");await this.handleSoundPropertyChunks(t.chunkSize-BigInt(at.len));break}case"ID3":{let e=await this.tokenizer.readToken(new Dt(Number(t.chunkSize))),a=no(e);await new $o().parse(this.metadata,a,this.options);break}case"DSD":this.metadata.format.numberOfChannels&&this.metadata.setFormat("numberOfSamples",Number(t.chunkSize*BigInt(8)/BigInt(this.metadata.format.numberOfChannels))),this.metadata.format.numberOfSamples&&this.metadata.format.sampleRate&&this.metadata.setFormat("duration",this.metadata.format.numberOfSamples/this.metadata.format.sampleRate);break;default:gi(`Ignore chunk[ID=${t.chunkID}, size=${t.chunkSize}]`);break}let i=t.chunkSize-BigInt(this.tokenizer.position-o);i>0&&(gi(`After Parsing chunk, remaining ${i} bytes`),await this.tokenizer.ignore(Number(i)))}async handleSoundPropertyChunks(t){for(gi(`Parsing sound-property-chunks, remainingSize=${t}`);t>0;){let o=await this.tokenizer.readToken(jl);gi(`Sound-property-chunk[ID=${o.chunkID}, size=${o.chunkSize}]`);let i=this.tokenizer.position;switch(o.chunkID.trim()){case"FS":{let a=await this.tokenizer.readToken(Ue);this.metadata.setFormat("sampleRate",a);break}case"CHNL":{let a=await this.tokenizer.readToken(GA);this.metadata.setFormat("numberOfChannels",a),await this.handleChannelChunks(o.chunkSize-BigInt(GA.len));break}case"CMPR":{let a=(await this.tokenizer.readToken(at)).trim(),A=await this.tokenizer.readToken(fA),r=await this.tokenizer.readToken(new ze(A,"ascii"));a==="DSD"&&(this.metadata.setFormat("lossless",!0),this.metadata.setFormat("bitsPerSample",1)),this.metadata.setFormat("codec",`${a} (${r})`);break}case"ABSS":{let a=await this.tokenizer.readToken(GA),A=await this.tokenizer.readToken(fA),r=await this.tokenizer.readToken(fA),s=await this.tokenizer.readToken(Ue);gi(`ABSS ${a}:${A}:${r}.${s}`);break}case"LSCO":{let a=await this.tokenizer.readToken(GA);gi(`LSCO lsConfig=${a}`);break}default:gi(`Unknown sound-property-chunk[ID=${o.chunkID}, size=${o.chunkSize}]`),await this.tokenizer.ignore(Number(o.chunkSize))}let e=o.chunkSize-BigInt(this.tokenizer.position-i);e>0&&(gi(`After Parsing sound-property-chunk ${o.chunkSize}, remaining ${e} bytes`),await this.tokenizer.ignore(Number(e))),t-=BigInt(jl.len)+o.chunkSize,gi(`Parsing sound-property-chunks, remainingSize=${t}`)}if(this.metadata.format.lossless&&this.metadata.format.sampleRate&&this.metadata.format.numberOfChannels&&this.metadata.format.bitsPerSample){let o=this.metadata.format.sampleRate*this.metadata.format.numberOfChannels*this.metadata.format.bitsPerSample;this.metadata.setFormat("bitrate",o)}}async handleChannelChunks(t){gi(`Parsing channel-chunks, remainingSize=${t}`);let o=[];for(;t>=at.len;){let i=await this.tokenizer.readToken(at);gi(`Channel[ID=${i}]`),o.push(i),t-=BigInt(at.len)}return gi(`Channels: ${o.join(", ")}`),o}}});var tae,rae=ue(()=>{tae={parserType:"dsdiff",extensions:[".dff"],mimeTypes:["audio/dsf","audio/dsd"],async load(){return(await Promise.resolve().then(()=>(Aae(),eae))).DsdiffParser}}});var aae,gI,fO,c2=ue(()=>{DA();si();er();aae={NONE:"not compressed PCM Apple Computer",sowt:"PCM (byte swapped)",fl32:"32-bit floating point IEEE 32-bit float",fl64:"64-bit floating point IEEE 64-bit float Apple Computer",alaw:"ALaw 2:1 8-bit ITU-T G.711 A-law",ulaw:"\xB5Law 2:1 8-bit ITU-T G.711 \xB5-law Apple Computer",ULAW:"CCITT G.711 u-law 8-bit ITU-T G.711 \xB5-law",ALAW:"CCITT G.711 A-law 8-bit ITU-T G.711 A-law",FL32:"Float 32 IEEE 32-bit float "},gI=class extends Qt("AIFF"){},fO=class{constructor(t,o){this.isAifc=o;let i=o?22:18;if(t.chunkSize>Math.abs(i):e<22){let A=fA.get(t,o+22);if(A>0){let r=(A+1)%2;if(23+A+r===this.len)a.compressionName=new ze(A,"latin1").get(t,o+23);else throw new gI("Illegal pstring length")}else a.compressionName=void 0}}else a.compressionName="PCM";return a}}});var QO,iae=ue(()=>{DA();si();QO={len:8,get:(n,t)=>({chunkID:at.get(n,t),chunkSize:Number(BigInt(Ue.get(n,t+4)))})}});var nae={};Pr(nae,{AIFFParser:()=>l2});var oae,I2,l2,sae=ue(()=>{DA();oae=Je(ct(),1);so();kh();si();Hi();c2();c2();iae();I2=(0,oae.default)("music-metadata:parser:aiff"),l2=class extends Rt{constructor(){super(...arguments),this.isCompressed=null}async parse(){if((await this.tokenizer.readToken(QO)).chunkID!=="FORM")throw new gI("Invalid Chunk-ID, expected 'FORM'");let o=await this.tokenizer.readToken(at);switch(o){case"AIFF":this.metadata.setFormat("container",o),this.isCompressed=!1;break;case"AIFC":this.metadata.setFormat("container","AIFF-C"),this.isCompressed=!0;break;default:throw new gI(`Unsupported AIFF type: ${o}`)}this.metadata.setFormat("lossless",!this.isCompressed),this.metadata.setAudioOnly();try{for(;!this.tokenizer.fileInfo.size||this.tokenizer.fileInfo.size-this.tokenizer.position>=QO.len;){I2(`Reading AIFF chunk at offset=${this.tokenizer.position}`);let i=await this.tokenizer.readToken(QO),e=2*Math.round(i.chunkSize/2),a=await this.readData(i);await this.tokenizer.ignore(e-a)}}catch(i){if(i instanceof bA)I2("End-of-stream");else throw i}}async readData(t){switch(t.chunkID){case"COMM":{if(this.isCompressed===null)throw new gI("Failed to parse AIFF.COMM chunk when compression type is unknown");let o=await this.tokenizer.readToken(new fO(t,this.isCompressed));return this.metadata.setFormat("bitsPerSample",o.sampleSize),this.metadata.setFormat("sampleRate",o.sampleRate),this.metadata.setFormat("numberOfChannels",o.numChannels),this.metadata.setFormat("numberOfSamples",o.numSampleFrames),this.metadata.setFormat("duration",o.numSampleFrames/o.sampleRate),(o.compressionName||o.compressionType)&&this.metadata.setFormat("codec",o.compressionName??aae[o.compressionType]),t.chunkSize}case"ID3 ":{let o=await this.tokenizer.readToken(new Dt(t.chunkSize)),i=no(o);return await new $o().parse(this.metadata,i,this.options),t.chunkSize}case"SSND":return this.metadata.format.duration&&this.metadata.setFormat("bitrate",8*t.chunkSize/this.metadata.format.duration),0;case"NAME":case"AUTH":case"(c) ":case"ANNO":return this.readTextChunk(t);default:return I2(`Ignore chunk id=${t.chunkID}, size=${t.chunkSize}`),0}}async readTextChunk(t){let i=(await this.tokenizer.readToken(new ze(t.chunkSize,"ascii"))).split("\0").map(e=>e.trim()).filter(e=>e?.length);return await Promise.all(i.map(e=>this.metadata.addTag("AIFF",t.chunkID,e))),t.chunkSize}}});var gae,cae=ue(()=>{gae={parserType:"aiff",extensions:[".aif","aiff","aifc"],mimeTypes:["audio/aiff","audio/aif","audio/aifc","application/aiff"],async load(){return(await Promise.resolve().then(()=>(sae(),nae))).AIFFParser}}});var Af,p2,d2,Iae=ue(()=>{DA();si();Af={len:12,get:(n,t)=>({id:at.get(n,t),size:Dr.get(n,t+4)})},p2={len:16,get:(n,t)=>({fileSize:Dr.get(n,t),metadataPointer:Dr.get(n,t+8)})},d2={len:40,get:(n,t)=>({formatVersion:sr.get(n,t),formatID:sr.get(n,t+4),channelType:sr.get(n,t+8),channelNum:sr.get(n,t+12),samplingFrequency:sr.get(n,t+16),bitsPerSample:sr.get(n,t+20),sampleCount:OL.get(n,t+24),blockSizePerChannel:sr.get(n,t+32)})}});var pae={};Pr(pae,{DsdContentParseError:()=>Ls,DsfParser:()=>E2});var lae,h2,Ls,E2,dae=ue(()=>{lae=Je(ct(),1);$B();Iae();kh();er();Ug();h2=(0,lae.default)("music-metadata:parser:DSF"),Ls=class extends Qt("DSD"){},E2=class extends Fs{async postId3v2Parse(){let t=this.tokenizer.position,o=await this.tokenizer.readToken(Af);if(o.id!=="DSD ")throw new Ls("Invalid chunk signature");if(o.size!==BigInt(Af.len+p2.len))throw new Ls(`Invalid DSD chunk size: ${o.size}`);this.metadata.setFormat("container","DSF"),this.metadata.setFormat("lossless",!0),this.metadata.setAudioOnly();let i=await this.tokenizer.readToken(p2);if(i.fileSizeBigInt(Number.MAX_SAFE_INTEGER)||i.metadataPointer+BigInt(Pl.len)>i.fileSize)throw new Ls(`Invalid metadata pointer: ${i.metadataPointer}`);return await this.tokenizer.ignore(Number(e)),new $o().parse(this.metadata,this.tokenizer,this.options)}async parseChunks(t){let o=BigInt(Af.len);for(;t>=o;){let i=await this.tokenizer.readToken(Af);if(h2(`Parsing chunk name=${i.id} size=${i.size}`),i.sizet)throw new Ls(`${i.id} chunk exceeds remaining file size`);let e=i.size-o;switch(i.id){case"fmt ":{if(e{hae={parserType:"dsf",extensions:[".dsf"],mimeTypes:["audio/dsf"],async load(){return(await Promise.resolve().then(()=>(dae(),pae))).DsfParser}}});var cI,tf,Cae,yO=ue(()=>{DA();Ug();cI=class n{static fromBase64(t){return n.fromBuffer(Uint8Array.from(atob(t),o=>o.charCodeAt(0)))}static fromBuffer(t){return new n(t.length).get(t,0)}constructor(t){this.len=t}get(t,o){let i=Oh[Ue.get(t,o)];o+=4;let e=Ue.get(t,o);o+=4;let a=new ze(e,"utf-8").get(t,o);o+=e;let A=Ue.get(t,o);o+=4;let r=new ze(A,"utf-8").get(t,o);o+=A;let s=Ue.get(t,o);o+=4;let g=Ue.get(t,o);o+=4;let c=Ue.get(t,o);o+=4;let I=Ue.get(t,o);o+=4;let d=Ue.get(t,o);o+=4;let B=t.slice(o,o+d);return{type:i,format:a,description:r,width:s,height:g,colour_depth:c,indexed_color:I,data:B}}},tf={len:7,get:(n,t)=>({packetType:fA.get(n,t),vorbis:new ze(6,"ascii").get(n,t+1)})},Cae={len:23,get:(n,t)=>({version:Ge.get(n,t+0),channelMode:fA.get(n,t+4),sampleRate:Ge.get(n,t+5),bitrateMax:Ge.get(n,t+9),bitrateNominal:Ge.get(n,t+13),bitrateMin:Ge.get(n,t+17)})}});var Kh,C2=ue(()=>{DA();_s();Kh=class{constructor(t,o){this.data=t,this.offset=o}readInt32(){let t=Ge.get(this.data,this.offset);return this.offset+=4,t}readStringUtf8(){let t=this.readInt32(),o=wr(this.data.subarray(this.offset,this.offset+t),"utf-8");return this.offset+=t,o}parseUserComment(){let t=this.offset,o=this.readStringUtf8(),i=o.indexOf("=");return{key:o.substring(0,i).toUpperCase(),value:o.substring(i+1),len:this.offset-t}}}});var uae,xh,rf,Us,af=ue(()=>{DA();uae=Je(ct(),1);C2();yO();er();xh=(0,uae.default)("music-metadata:parser:ogg:vorbis1"),rf=class extends Qt("Vorbis"){},Us=class n{constructor(t,o){this.pageSegments=[],this.durationOnLastPage=!0,this.metadata=t,this.options=o}async parsePage(t,o){if(this.lastPageHeader=t,t.headerType.firstPage)this.parseFirstPage(t,o);else{if(t.headerType.continued){if(this.pageSegments.length===0)throw new rf("Cannot continue on previous page");this.pageSegments.push(o)}if(t.headerType.lastPage||!t.headerType.continued){if(this.pageSegments.length>0){let i=n.mergeUint8Arrays(this.pageSegments);await this.parseFullPage(i)}this.pageSegments=t.headerType.lastPage?[]:[o]}}}static mergeUint8Arrays(t){let o=t.reduce((e,a)=>e+a.length,0),i=new Uint8Array(o);return t.forEach((e,a,A)=>{let r=A.slice(0,a).reduce((s,g)=>s+g.length,0);i.set(e,r)}),i}async flush(){await this.parseFullPage(n.mergeUint8Arrays(this.pageSegments))}async parseUserComment(t,o){let e=new Kh(t,o).parseUserComment();return await this.addTag(e.key,e.value),e.len}async addTag(t,o){if(t==="METADATA_BLOCK_PICTURE"&&typeof o=="string"){if(this.options.skipCovers){xh("Ignore picture");return}o=cI.fromBase64(o),xh(`Push picture: id=${t}, format=${o.format}`)}else xh(`Push tag: id=${t}, value=${o}`);await this.metadata.addTag("vorbis",t,o)}calculateDuration(t){this.lastPageHeader&&(t||this.lastPageHeader.headerType.lastPage)&&this.metadata.format.sampleRate&&this.lastPageHeader.absoluteGranulePosition>=0&&(this.metadata.setFormat("numberOfSamples",this.lastPageHeader.absoluteGranulePosition),this.metadata.setFormat("duration",this.lastPageHeader.absoluteGranulePosition/this.metadata.format.sampleRate))}parseFirstPage(t,o){this.metadata.setFormat("codec","Vorbis I"),this.metadata.setFormat("hasAudio",!0),xh("Parse first page");let i=tf.get(o,0);if(i.vorbis!=="vorbis")throw new rf("Metadata does not look like Vorbis");if(i.packetType===1){let e=Cae.get(o,tf.len);this.metadata.setFormat("sampleRate",e.sampleRate),this.metadata.setFormat("bitrate",e.bitrateNominal),this.metadata.setFormat("numberOfChannels",e.channelMode),xh("sample-rate=%s[hz], bitrate=%s[b/s], channel-mode=%s",e.sampleRate,e.bitrateNominal,e.channelMode)}else throw new rf("First Ogg page should be type 1: the identification header")}async parseFullPage(t){let o=tf.get(t,0);switch(xh("Parse full page: type=%s, byteLength=%s",o.packetType,t.byteLength),o.packetType){case 3:return this.parseUserCommentList(t,tf.len);case 1:case 5:break}}async parseUserCommentList(t,o){let i=Ge.get(t,o);o+=4,o+=i;let e=Ge.get(t,o);for(o+=4;e-- >0;)o+=await this.parseUserComment(t,o)}}});var ci,of,nf,u2=ue(()=>{Ar();DA();ci={STREAMINFO:0,PADDING:1,APPLICATION:2,SEEKTABLE:3,VORBIS_COMMENT:4,CUESHEET:5,PICTURE:6},of={len:4,get:(n,t)=>({lastBlock:vA(n,t,7),type:XA(n,t,1,7),length:kr.get(n,t+1)})},nf={len:34,get:(n,t)=>({minimumBlockSize:GA.get(n,t),maximumBlockSize:GA.get(n,t+2)/1e3,minimumFrameSize:kr.get(n,t+4),maximumFrameSize:kr.get(n,t+7),sampleRate:kr.get(n,t+10)>>4,channels:XA(n,t+12,4,3)+1,bitsPerSample:XA(n,t+12,7,5)+1,totalSamples:XA(n,t+13,4,36),fileMD5:new Dt(16).get(n,t+18)})}});var Qae={};Pr(Qae,{FlacParser:()=>sf});var fae,hqe,mO,sf,B2=ue(()=>{fae=Je(ct(),1);DA();yO();$B();si();af();C2();er();u2();hqe=(0,fae.default)("music-metadata:parser:FLAC"),mO=class extends Qt("FLAC"){},sf=class extends Fs{constructor(){super(...arguments),this.vorbisParser=new Us(this.metadata,this.options)}async postId3v2Parse(){if((await this.tokenizer.readToken(at)).toString()!=="fLaC")throw new mO("Invalid FLAC preamble");let o;do o=await this.tokenizer.readToken(of),await this.parseDataBlock(o);while(!o.lastBlock);if(this.tokenizer.fileInfo.size&&this.metadata.format.duration){let i=this.tokenizer.fileInfo.size-this.tokenizer.position;this.metadata.setFormat("bitrate",8*i/this.metadata.format.duration)}}async parseDataBlock(t){switch(hqe(`blockHeader type=${t.type}, length=${t.length}`),t.type){case ci.STREAMINFO:return this.readBlockStreamInfo(t.length);case ci.PADDING:break;case ci.APPLICATION:break;case ci.SEEKTABLE:break;case ci.VORBIS_COMMENT:return this.readComment(t.length);case ci.CUESHEET:break;case ci.PICTURE:await this.parsePicture(t.length);return;default:this.metadata.addWarning(`Unknown block type: ${t.type}`)}return this.tokenizer.ignore(t.length).then()}async readBlockStreamInfo(t){if(t!==nf.len)throw new mO("Unexpected block-stream-info length");let o=await this.tokenizer.readToken(nf);this.metadata.setFormat("container","FLAC"),this.processsStreamInfo(o)}processsStreamInfo(t){this.metadata.setFormat("codec","FLAC"),this.metadata.setFormat("hasAudio",!0),this.metadata.setFormat("lossless",!0),this.metadata.setFormat("numberOfChannels",t.channels),this.metadata.setFormat("bitsPerSample",t.bitsPerSample),this.metadata.setFormat("sampleRate",t.sampleRate),t.totalSamples>0&&this.metadata.setFormat("duration",t.totalSamples/t.sampleRate)}async readComment(t){let o=await this.tokenizer.readToken(new Dt(t));return this.parseComment(o)}async parseComment(t){let o=new Kh(t,0),i=o.readStringUtf8();i.length>0&&this.metadata.setFormat("tool",i);let e=o.readInt32(),a=new Array(e);for(let A=0;A(A.key==="ENCODER"&&this.metadata.setFormat("tool",A.value),this.addTag(A.key,A.value))))}async parsePicture(t){return this.options.skipCovers?this.tokenizer.ignore(t):this.addPictureTag(await this.tokenizer.readToken(new cI(t)))}addPictureTag(t){return this.addTag("METADATA_BLOCK_PICTURE",t)}addTag(t,o){return this.vorbisParser.addTag(t,o)}}});var yae,mae=ue(()=>{yae={parserType:"flac",extensions:[".flac"],mimeTypes:["audio/flac"],async load(){return(await Promise.resolve().then(()=>(B2(),Qae))).FlacParser}}});var Te,f2=ue(()=>{Te={string:0,uint:1,uid:2,bool:3,binary:4,float:5}});var Sae,wae=ue(()=>{f2();Sae={name:"dtd",container:{440786851:{name:"ebml",container:{17030:{name:"ebmlVersion",value:Te.uint},17143:{name:"ebmlReadVersion",value:Te.uint},17138:{name:"ebmlMaxIDWidth",value:Te.uint},17139:{name:"ebmlMaxSizeWidth",value:Te.uint},17026:{name:"docType",value:Te.string},17031:{name:"docTypeVersion",value:Te.uint},17029:{name:"docTypeReadVersion",value:Te.uint}}},408125543:{name:"segment",container:{290298740:{name:"seekHead",container:{19899:{name:"seek",multiple:!0,container:{21419:{name:"id",value:Te.binary},21420:{name:"position",value:Te.uint}}}}},357149030:{name:"info",container:{29604:{name:"uid",value:Te.uid},29572:{name:"filename",value:Te.string},3979555:{name:"prevUID",value:Te.uid},3965867:{name:"prevFilename",value:Te.string},4110627:{name:"nextUID",value:Te.uid},4096955:{name:"nextFilename",value:Te.string},2807729:{name:"timecodeScale",value:Te.uint},17545:{name:"duration",value:Te.float},17505:{name:"dateUTC",value:Te.uint},31657:{name:"title",value:Te.string},19840:{name:"muxingApp",value:Te.string},22337:{name:"writingApp",value:Te.string}}},524531317:{name:"cluster",multiple:!0,container:{231:{name:"timecode",value:Te.uid},22743:{name:"silentTracks ",multiple:!0},167:{name:"position",value:Te.uid},171:{name:"prevSize",value:Te.uid},160:{name:"blockGroup"},163:{name:"simpleBlock"}}},374648427:{name:"tracks",container:{174:{name:"entries",multiple:!0,container:{215:{name:"trackNumber",value:Te.uint},29637:{name:"uid",value:Te.uid},131:{name:"trackType",value:Te.uint},185:{name:"flagEnabled",value:Te.bool},136:{name:"flagDefault",value:Te.bool},21930:{name:"flagForced",value:Te.bool},156:{name:"flagLacing",value:Te.bool},28135:{name:"minCache",value:Te.uint},28136:{name:"maxCache",value:Te.uint},2352003:{name:"defaultDuration",value:Te.uint},2306383:{name:"timecodeScale",value:Te.float},21358:{name:"name",value:Te.string},2274716:{name:"language",value:Te.string},134:{name:"codecID",value:Te.string},25506:{name:"codecPrivate",value:Te.binary},2459272:{name:"codecName",value:Te.string},3839639:{name:"codecSettings",value:Te.string},3883072:{name:"codecInfoUrl",value:Te.string},2536e3:{name:"codecDownloadUrl",value:Te.string},170:{name:"codecDecodeAll",value:Te.bool},28587:{name:"trackOverlay",value:Te.uint},224:{name:"video",container:{154:{name:"flagInterlaced",value:Te.bool},21432:{name:"stereoMode",value:Te.uint},176:{name:"pixelWidth",value:Te.uint},186:{name:"pixelHeight",value:Te.uint},21680:{name:"displayWidth",value:Te.uint},21690:{name:"displayHeight",value:Te.uint},21683:{name:"aspectRatioType",value:Te.uint},3061028:{name:"colourSpace",value:Te.uint},3126563:{name:"gammaValue",value:Te.float}}},225:{name:"audio",container:{181:{name:"samplingFrequency",value:Te.float},30901:{name:"outputSamplingFrequency",value:Te.float},159:{name:"channels",value:Te.uint},148:{name:"channels",value:Te.uint},32123:{name:"channelPositions",value:Te.binary},25188:{name:"bitDepth",value:Te.uint}}},28032:{name:"contentEncodings",container:{25152:{name:"contentEncoding",container:{20529:{name:"order",value:Te.uint},20530:{name:"scope",value:Te.bool},20531:{name:"type",value:Te.uint},20532:{name:"contentEncoding",container:{16980:{name:"contentCompAlgo",value:Te.uint},16981:{name:"contentCompSettings",value:Te.binary}}},20533:{name:"contentEncoding",container:{18401:{name:"contentEncAlgo",value:Te.uint},18402:{name:"contentEncKeyID",value:Te.binary},18403:{name:"contentSignature ",value:Te.binary},18404:{name:"ContentSigKeyID ",value:Te.binary},18405:{name:"contentSigAlgo ",value:Te.uint},18406:{name:"contentSigHashAlgo ",value:Te.uint}}},25188:{name:"bitDepth",value:Te.uint}}}}}}}}},475249515:{name:"cues",container:{187:{name:"cuePoint",container:{179:{name:"cueTime",value:Te.uid},183:{name:"positions",container:{247:{name:"track",value:Te.uint},241:{name:"clusterPosition",value:Te.uint},21368:{name:"blockNumber",value:Te.uint},234:{name:"codecState",value:Te.uint},219:{name:"reference",container:{150:{name:"time",value:Te.uint},151:{name:"cluster",value:Te.uint},21343:{name:"number",value:Te.uint},235:{name:"codecState",value:Te.uint}}},240:{name:"relativePosition",value:Te.uint}}}}}}},423732329:{name:"attachments",container:{24999:{name:"attachedFiles",multiple:!0,container:{18046:{name:"description",value:Te.string},18030:{name:"name",value:Te.string},18016:{name:"mimeType",value:Te.string},18012:{name:"data",value:Te.binary},18094:{name:"uid",value:Te.uid}}}}},272869232:{name:"chapters",container:{17849:{name:"editionEntry",container:{182:{name:"chapterAtom",container:{29636:{name:"uid",value:Te.uid},145:{name:"timeStart",value:Te.uint},146:{name:"timeEnd",value:Te.uid},152:{name:"hidden",value:Te.bool},17816:{name:"enabled",value:Te.uid},143:{name:"track",container:{137:{name:"trackNumber",value:Te.uid},128:{name:"display",container:{133:{name:"string",value:Te.string},17276:{name:"language ",value:Te.string},17278:{name:"country ",value:Te.string}}}}}}}}}}},307544935:{name:"tags",container:{29555:{name:"tag",multiple:!0,container:{25536:{name:"target",container:{25541:{name:"tagTrackUID",value:Te.uid},25540:{name:"tagChapterUID",value:Te.uint},25542:{name:"tagAttachmentUID",value:Te.uid},25546:{name:"targetType",value:Te.string},26826:{name:"targetTypeValue",value:Te.uint},25545:{name:"tagEditionUID",value:Te.uid}}},26568:{name:"simpleTags",multiple:!0,container:{17827:{name:"name",value:Te.string},17543:{name:"string",value:Te.string},17541:{name:"binary",value:Te.binary},17530:{name:"language",value:Te.string},17531:{name:"languageIETF",value:Te.string},17540:{name:"default",value:Te.bool}}}}}}}}}}}});function Q2(n,t){return Number(Eqe(n,t))}function Eqe(n,t){let o=new Uint8Array(8),i=n.subarray(0,t);try{return o.set(i,8-t),Rs.get(o,0)}catch{return BigInt(-1)}}function Oae(n){return n.container&&Object.keys(n.container).map(t=>{let o=n.container[t];return o.id=Number.parseInt(t,10),o}).forEach(t=>{t.parent=n,Oae(t)}),n}function Jl(n){let t="";return n.parent&&n.parent.name!=="dtd"&&(t+=`${Jl(n.parent)}/`),t+n.name}var Dae,Yh,SO,Hs,wO,bae=ue(()=>{DA();Dae=Je(ct(),1);so();f2();DA();er();Yh=(0,Dae.default)("music-metadata:parser:ebml"),SO=class extends Qt("EBML"){},Hs={ReadNext:0,IgnoreElement:2,SkipSiblings:3,TerminateParsing:4,SkipElement:5},wO=class{constructor(t){this.parserMap=new Map,this.ebmlMaxIDLength=4,this.ebmlMaxSizeLength=8,this.tokenizer=t,this.parserMap.set(Te.uint,o=>this.readUint(o)),this.parserMap.set(Te.string,o=>this.readString(o)),this.parserMap.set(Te.binary,o=>this.readBuffer(o)),this.parserMap.set(Te.uid,async o=>this.readBuffer(o)),this.parserMap.set(Te.bool,o=>this.readFlag(o)),this.parserMap.set(Te.float,o=>this.readFloat(o))}async iterate(t,o,i){return this.parseContainer(Oae(t),o,i)}async parseContainer(t,o,i){let e={};for(;this.tokenizer.position=0?this.tokenizer.position+a.len:-1,i);r.multiple?(e[r.name]||(e[r.name]=[]),e[r.name].push(g)):e[r.name]=g,await i.elementValue(r,g,A)}else{let g=this.parserMap.get(r.value);if(typeof g=="function"){let c=await g(a);e[r.name]=c,await i.elementValue(r,c,A)}}break;case Hs.SkipElement:Yh(`Go to next element: name=${Jl(r)}, element.id=0x${a.id}, container=${!!r.container} at position=${A}`);break;case Hs.IgnoreElement:Yh(`Ignore element: name=${Jl(r)}, element.id=0x${a.id}, container=${!!r.container} at position=${A}`),await this.tokenizer.ignore(a.len);break;case Hs.SkipSiblings:Yh(`Ignore remaining container, at: name=${Jl(r)}, element.id=0x${a.id}, container=${!!r.container} at position=${A}`),await this.tokenizer.ignore(o-this.tokenizer.position);break;case Hs.TerminateParsing:return Yh(`Terminate parsing at element: name=${Jl(r)}, element.id=0x${a.id}, container=${!!r.container} at position=${A}`),e}else switch(a.id){case 236:await this.tokenizer.ignore(a.len);break;default:Yh(`parseEbml: parent=${Jl(t)}, unknown child: id=${a.id.toString(16)} at position=${A}`),await this.tokenizer.ignore(a.len)}}return e}async readVintData(t){let o=await this.tokenizer.peekNumber(fA),i=128,e=1;for(;(o&i)===0;){if(e>t)throw new SO("VINT value exceeding maximum size");++e,i>>=1}let a=new Uint8Array(e);return await this.tokenizer.readBuffer(a),a}async readElement(){let t=await this.readVintData(this.ebmlMaxIDLength),o=await this.readVintData(this.ebmlMaxSizeLength);return o[0]^=128>>o.length-1,{id:Q2(t,t.length),len:Q2(o,o.length)}}async readFloat(t){switch(t.len){case 0:return 0;case 4:return this.tokenizer.readNumber(ML);case 8:return this.tokenizer.readNumber(xD);case 10:return this.tokenizer.readNumber(xD);default:throw new SO(`Invalid IEEE-754 float length: ${t.len}`)}}async readFlag(t){return await this.readUint(t)===1}async readUint(t){let o=await this.readBuffer(t);return Q2(o,t.len)}async readString(t){return(await this.tokenizer.readToken(new ze(t.len,"utf-8"))).replace(/\x00.*$/g,"")}async readBuffer(t){let o=new Uint8Array(t.len);return await this.tokenizer.readBuffer(o),o}}});var _ae={};Pr(_ae,{MatroskaParser:()=>y2});var Mae,DO,y2,Tae=ue(()=>{Mae=Je(ct(),1);Hi();wae();HL();bae();DO=(0,Mae.default)("music-metadata:parser:matroska"),y2=class extends Rt{constructor(){super(...arguments),this.seekHeadOffset=0,this.flagUseIndexToSkipClusters=this.options.mkvUseIndex??!1}async parse(){let t=this.tokenizer.fileInfo.size??Number.MAX_SAFE_INTEGER,o=new wO(this.tokenizer);DO("Initializing DTD end MatroskaIterator"),await o.iterate(Sae,t,{startNext:i=>{switch(i.id){case 475249515:return DO(`Skip element: name=${i.name}, id=0x${i.id.toString(16)}`),Hs.IgnoreElement;case 524531317:if(this.flagUseIndexToSkipClusters&&this.seekHead){let e=this.seekHead.seek.find(a=>a.position+this.seekHeadOffset>this.tokenizer.position);if(e){let a=e.position+this.seekHeadOffset-this.tokenizer.position;return DO(`Use index to go to next position, ignoring ${a} bytes`),this.tokenizer.ignore(a),Hs.SkipElement}}return Hs.IgnoreElement;default:return Hs.ReadNext}},elementValue:async(i,e,a)=>{switch(DO(`Received: name=${i.name}, value=${e}`),i.id){case 17026:this.metadata.setFormat("container",`EBML/${e}`);break;case 290298740:this.seekHead=e,this.seekHeadOffset=a;break;case 357149030:{let A=e,r=A.timecodeScale?A.timecodeScale:1e6;if(typeof A.duration=="number"){let s=A.duration*r/1e9;await this.addTag("segment:title",A.title),this.metadata.setFormat("duration",Number(s))}}break;case 374648427:{let A=e;if(A?.entries){A.entries.forEach(s=>{let g={codecName:s.codecID.replace("A_","").replace("V_",""),codecSettings:s.codecSettings,flagDefault:s.flagDefault,flagLacing:s.flagLacing,flagEnabled:s.flagEnabled,language:s.language,name:s.name,type:s.trackType,audio:s.audio,video:s.video};this.metadata.addStreamInfo(g)});let r=A.entries.filter(s=>s.trackType===Ia.audio).reduce((s,g)=>!s||g.flagDefault&&!s.flagDefault||g.trackNumber{let s=r.target,g=s?.targetTypeValue?Kte[s.targetTypeValue]:s?.targetType?s.targetType:"track";await Promise.all(r.simpleTags.map(async c=>{let I=c.string?c.string:c.binary;await this.addTag(`${g}:${c.name}`,I)}))}))}break;case 423732329:{let A=e;await Promise.all(A.attachedFiles.filter(r=>r.mimeType.startsWith("image/")).map(r=>this.addTag("picture",{data:r.data,format:r.mimeType,description:r.description,name:r.name})))}break}}})}async addTag(t,o){await this.metadata.addTag("matroska",t,o)}}});var Nae,Rae=ue(()=>{Nae={parserType:"matroska",extensions:[".mka",".mkv",".mk3d",".mks","webm"],mimeTypes:["audio/matroska","video/matroska","audio/webm","video/webm"],async load(){return(await Promise.resolve().then(()=>(Tae(),_ae))).MatroskaParser}}});function Gae(n,t,o,i,e){if(S2(`remainingLen=${i}, numberOfEntries=${e} * token-len=${t.len}`),i===0)return[];if(i!==e*t.len)throw new Kg("mismatch number-of-entries with remaining atom-length");let a=[];for(let A=0;A{DA();vae=Je(ct(),1);si();er();Ar();er();S2=(0,vae.default)("music-metadata:parser:MP4:atom"),Kg=class extends Qt("MP4"){},ql={len:8,get:(n,t)=>{let o=Ue.get(n,t);if(o<0)throw new Kg("Invalid atom header length");return{length:BigInt(o),name:new ze(4,"latin1").get(n,t+4)}},put:(n,t,o)=>(Ue.put(n,t,Number(o.length)),at.put(n,t+4,o.name))},Pae=Rs,w2={len:4,get:(n,t)=>({type:new ze(4,"ascii").get(n,t)})},OO=class{constructor(t,o,i){if(to&&S2(`Warning: atom ${i} expected to be ${o}, but was actually ${t} bytes long.`),this.len=t}},jh={len:4,get:(n,t)=>{let o=Ue.get(n,t)-2082844800;return new Date(o*1e3)}},Jh={len:8,get:(n,t)=>{let o=Number(Rs.get(n,t))-2082844800;return new Date(o*1e3)}},bO=class extends OO{constructor(t){super(t,24,"mdhd")}get(t,o){let i=fA.get(t,o+0),e=kr.get(t,o+1);switch(i){case 0:return{version:i,flags:e,creationTime:jh.get(t,o+4),modificationTime:jh.get(t,o+8),timeScale:Ue.get(t,o+12),duration:Ue.get(t,o+16),language:GA.get(t,o+20),quality:GA.get(t,o+22)};case 1:return{version:i,flags:e,creationTime:Jh.get(t,o+4),modificationTime:Jh.get(t,o+12),timeScale:Ue.get(t,o+20),duration:Number(Rs.get(t,o+24)),language:GA.get(t,o+32),quality:GA.get(t,o+34)};default:throw new Vo("Invalid mdhd version header")}}},MO=class extends OO{constructor(t){super(t,100,"mvhd")}get(t,o){let i=fA.get(t,o),e=kr.get(t,o+1);return i===1?{version:i,flags:e,creationTime:Jh.get(t,o+4),modificationTime:Jh.get(t,o+12),timeScale:Ue.get(t,o+20),duration:Number(Rs.get(t,o+24)),preferredRate:Ue.get(t,o+32),preferredVolume:GA.get(t,o+36),previewTime:Ue.get(t,o+84),previewDuration:Ue.get(t,o+88),posterTime:Ue.get(t,o+92),selectionTime:Ue.get(t,o+96),selectionDuration:Ue.get(t,o+100),currentTime:Ue.get(t,o+104),nextTrackID:Ue.get(t,o+108)}:{version:i,flags:e,creationTime:jh.get(t,o+4),modificationTime:jh.get(t,o+8),timeScale:Ue.get(t,o+12),duration:Ue.get(t,o+16),preferredRate:Ue.get(t,o+20),preferredVolume:GA.get(t,o+24),previewTime:Ue.get(t,o+72),previewDuration:Ue.get(t,o+76),posterTime:Ue.get(t,o+80),selectionTime:Ue.get(t,o+84),selectionDuration:Ue.get(t,o+88),currentTime:Ue.get(t,o+92),nextTrackID:Ue.get(t,o+96)}}},_O=class{constructor(t){this.len=t}get(t,o){return{type:{set:fA.get(t,o+0),type:kr.get(t,o+1)},locale:kr.get(t,o+4),value:new Dt(this.len-8).get(t,o+8)}}},TO=class{constructor(t){this.len=t}get(t,o){return{version:fA.get(t,o),flags:kr.get(t,o+1),name:new ze(this.len-4,"utf-8").get(t,o+4)}}},NO=class{constructor(t){this.len=t}get(t,o){let i=fA.get(t,o),e=kr.get(t,o+1);switch(i){case 0:return{version:i,flags:e,creationTime:jh.get(t,o+4),modificationTime:jh.get(t,o+8),trackId:Ue.get(t,o+12),duration:Ue.get(t,o+20),layer:GA.get(t,o+32),alternateGroup:GA.get(t,o+34),volume:GA.get(t,o+36)};case 1:return{version:i,flags:e,creationTime:Jh.get(t,o+4),modificationTime:Jh.get(t,o+12),trackId:Ue.get(t,o+20),duration:Number(Rs.get(t,o+28)),layer:GA.get(t,o+44),alternateGroup:GA.get(t,o+46),volume:GA.get(t,o+48)};default:throw new Vo("Invalid tkhd version header")}}},kae={len:8,get:(n,t)=>({version:fA.get(n,t),flags:kr.get(n,t+1),numberOfEntries:Ue.get(n,t+4)})},m2=class{constructor(t){this.len=t}get(t,o){let i=this.len-12;return{dataFormat:at.get(t,o),dataReferenceIndex:GA.get(t,o+10),description:i>0?new Dt(i).get(t,o+12):void 0}}},gf=class{constructor(t){this.len=t}get(t,o){let i=kae.get(t,o);o+=kae.len;let e=[];for(let a=0;a=this.len){S2("TrackRunBox size mismatch");break}let r={};e.flags.sampleDurationPresent&&(r.sampleDuration=Ue.get(t,a),a+=4),e.flags.sampleSizePresent&&(r.sampleSize=Ue.get(t,a),a+=4),e.flags.sampleFlagsPresent&&(r.sampleFlags=Ue.get(t,a),a+=4),e.flags.sampleCompositionTimeOffsetsPresent&&(r.sampleCompositionTimeOffset=Ue.get(t,a),a+=4),e.samples.push(r)}return e}},LO=class{constructor(t){this.len=t}get(t,o){let i=o+1,e=new ze(4,"utf-8");return{version:Ns.get(t,o),flags:kr.get(t,o+1),componentType:e.get(t,o+4),handlerType:e.get(t,o+8),componentName:new ze(this.len-28,"utf-8").get(t,o+28)}}},UO=class{constructor(t){this.len=t}get(t,o){let i=0,e=[];for(;i{Uae=Je(ct(),1);lf();lf();Lae=(0,Uae.default)("music-metadata:parser:MP4:Atom"),KO=class n{static async readAtom(t,o,i,e){let a=t.position;Lae(`Reading next token on offset=${a}...`);let A=await t.readToken(ql),r=A.length===1n;r&&(A.length=await t.readToken(Pae));let s=new n(A,r,i),g=s.getPayloadLength(e);return Lae(`parse atom name=${s.atomPath}, extended=${s.extended}, offset=${a}, len=${s.header.length}`),await s.readData(t,o,g),s}constructor(t,o,i){this.header=t,this.extended=o,this.parent=i,this.children=[],this.atomPath=(this.parent?`${this.parent.atomPath}.`:"")+this.header.name}getHeaderLength(){return this.extended?16:8}getPayloadLength(t){return(this.header.length===0n?t:Number(this.header.length))-this.getHeaderLength()}async readAtoms(t,o,i){for(;i>0;){let e=await n.readAtom(t,o,this,i);this.children.push(e),i-=e.header.length===0n?i:Number(e.header.length)}}async readData(t,o,i){switch(this.header.name){case"moov":case"udta":case"mdia":case"minf":case"stbl":case"":case"ilst":case"tref":case"moof":return this.readAtoms(t,o,this.getPayloadLength(i));case"meta":{let a=(await t.peekToken(ql)).name==="hdlr"?0:4;return await t.ignore(a),this.readAtoms(t,o,this.getPayloadLength(i)-a)}default:return o(this,i)}}}});var Jae={};Pr(Jae,{MP4Parser:()=>O2});function xae(n,t,o){return o.indexOf(n)===t}function Yae(n){let[t]=n.soundSampleDescription??[];return t?n.isAudio?n.isAudio():!!t.description&&t.description.numAudioChannels>0:!1}var jae,Ii,Bqe,Kae,O2,qae=ue(()=>{jae=Je(ct(),1);DA();Hi();WB();Hae();lf();lf();Gl();YB();_s();Ii=(0,jae.default)("music-metadata:parser:MP4"),Bqe="iTunes",Kae={raw:{lossy:!1,format:"raw"},MAC3:{lossy:!0,format:"MACE 3:1"},MAC6:{lossy:!0,format:"MACE 6:1"},ima4:{lossy:!0,format:"IMA 4:1"},ulaw:{lossy:!0,format:"uLaw 2:1"},alaw:{lossy:!0,format:"uLaw 2:1"},Qclp:{lossy:!0,format:"QUALCOMM PureVoice"},".mp3":{lossy:!0,format:"MPEG-1 layer 3"},alac:{lossy:!1,format:"ALAC"},"ac-3":{lossy:!0,format:"AC-3"},mp4a:{lossy:!0,format:"MPEG-4/AAC"},mp4s:{lossy:!0,format:"MP4S"},c608:{lossy:!0,format:"CEA-608"},c708:{lossy:!0,format:"CEA-708"}};O2=class n extends Rt{constructor(){super(...arguments),this.tracks=new Map,this.hasVideoTrack=!1,this.hasAudioTrack=!0,this.atomParsers={mvhd:async t=>{let o=await this.tokenizer.readToken(new MO(t));this.metadata.setFormat("creationTime",o.creationTime),this.metadata.setFormat("modificationTime",o.modificationTime)},chap:async t=>{let o=this.getTrackDescription(),i=[];for(;t>=Ue.len;)i.push(await this.tokenizer.readNumber(Ue)),t-=Ue.len;o.chapterList=i},mdat:async t=>{if(this.options.includeChapters){let o=[...this.tracks.values()].filter(i=>i.chapterList);if(o.length===1){let i=o[0].chapterList,e=[...this.tracks.values()].filter(a=>i.indexOf(a.header.trackId)!==-1);if(e.length===1)return this.parseChapterTrack(e[0],o[0],t)}}await this.tokenizer.ignore(t)},ftyp:async t=>{let o=[];for(;t>0;){let e=await this.tokenizer.readToken(w2);t-=w2.len;let a=e.type.replace(/\W/g,"");a.length>0&&o.push(a)}Ii(`ftyp: ${o.join("/")}`);let i=o.filter(xae).join("/");this.metadata.setFormat("container",i)},stsd:async t=>{let o=await this.tokenizer.readToken(new gf(t)),i=this.getTrackDescription();i.soundSampleDescription=o.table.map(e=>this.parseSoundSampleDescription(e))},stsz:async t=>{let o=await this.tokenizer.readToken(new If(t)),i=this.getTrackDescription();i.sampleSize=o.sampleSize,i.sampleSizeTable=o.entries},date:async t=>{let o=await this.tokenizer.readToken(new ze(t,"utf-8"));await this.addTag("date",o)}}}static read_BE_Integer(t,o){let i=(o?"INT":"UINT")+t.length*8+(t.length>1?"_BE":""),e=VA[i];if(!e)throw new Kg(`Token for integer type not found: "${i}"`);return Number(e.get(t,0))}async parse(){this.hasVideoTrack=!1,this.hasAudioTrack=!0,this.tracks.clear();let t=this.tokenizer.fileInfo.size||0;for(;!this.tokenizer.fileInfo.size||t>0;){try{if((await this.tokenizer.peekToken(ql)).name==="\0\0\0\0"){let A=`Error at offset=${this.tokenizer.position}: box.id=0`;Ii(A),this.addWarning(A);break}}catch(a){if(a instanceof Error){let A=`Error at offset=${this.tokenizer.position}: ${a.message}`;Ii(A),this.addWarning(A)}else throw a;break}let e=await KO.readAtom(this.tokenizer,(a,A)=>this.handleAtom(a,A),null,t);t-=e.header.length===BigInt(0)?t:Number(e.header.length)}let o=[];this.tracks.forEach(e=>{let a=[],A=Yae(e);e.soundSampleDescription.forEach(r=>{let s={},g=Kae[r.dataFormat];if(g?(a.push(g.format),s.codecName=g.format):s.codecName=`<${r.dataFormat}>`,A&&r.description){let{description:c}=r;c.sampleRate>0&&(s.type=Ia.audio,s.audio={samplingFrequency:c.sampleRate,bitDepth:c.sampleSize,channels:c.numAudioChannels})}this.metadata.addStreamInfo(s)}),a.length>=1&&o.push(a.join("/"))}),o.length>0&&this.metadata.setFormat("codec",o.filter(xae).join("+"));let i=[...this.tracks.values()].filter(Yae);for(let e of i){if(e.media.header&&e.media.header.timeScale>0)if(e.sampleRate=e.media.header.timeScale,e.media.header.duration>0&&(Ii("Using duration defined on audio track"),e.samples=e.media.header.duration,e.duration=e.samples/e.sampleRate),e.fragments.length>0){Ii("Calculate duration defined in track fragments");let r=0;e.sizeInBytes=0;for(let s of e.fragments)for(let g of s.trackRun.samples){let c=g.sampleDuration??s.header.defaultSampleDuration??0,I=g.sampleSize??s.header.defaultSampleSize??0;if(c===0)throw new Error("Missing sampleDuration and no defaultSampleDuration in track fragment header");if(I===0)throw new Error("Missing sampleSize and no defaultSampleSize in track fragment header");r+=c,e.sizeInBytes+=I}e.samples||(e.samples=r),e.duration||(e.duration=r/e.sampleRate)}else e.sampleSizeTable.length>0&&(e.sizeInBytes=e.sampleSizeTable.reduce((r,s)=>r+s,0));let a=e.soundSampleDescription[0];if(a.description&&e.media.header&&(this.metadata.setFormat("sampleRate",a.description.sampleRate),this.metadata.setFormat("bitsPerSample",a.description.sampleSize),this.metadata.setFormat("numberOfChannels",a.description.numAudioChannels),e.media.header.timeScale===0&&e.timeToSampleTable.length>0)){let r=e.timeToSampleTable.map(s=>s.count*s.duration).reduce((s,g)=>s+g);e.duration=r/a.description.sampleRate}let A=Kae[a.dataFormat];A&&this.metadata.setFormat("lossless",!A.lossy)}if(i.length>=1){let e=i[0];e.duration&&(this.metadata.setFormat("duration",e.duration),e.sizeInBytes&&this.metadata.setFormat("bitrate",8*e.sizeInBytes/e.duration))}this.metadata.setFormat("hasAudio",this.hasAudioTrack),this.metadata.setFormat("hasVideo",this.hasVideoTrack)}async handleAtom(t,o){if(t.parent)switch(t.parent.header.name){case"ilst":case"":return this.parseMetadataItemData(t);case"moov":switch(t.header.name){case"trak":return this.parseTrackBox(t);case"udta":return this.parseTrackBox(t)}break;case"moof":switch(t.header.name){case"traf":return this.parseTrackFragmentBox(t)}}if(this.atomParsers[t.header.name])return this.atomParsers[t.header.name](o);Ii(`No parser for atom path=${t.atomPath}, payload-len=${o}, ignoring atom`),await this.tokenizer.ignore(o)}getTrackDescription(){let t=[...this.tracks.values()];return t[t.length-1]}async addTag(t,o){await this.metadata.addTag(Bqe,t,o)}addWarning(t){Ii(`Warning: ${t}`),this.metadata.addWarning(t)}parseMetadataItemData(t){let o=t.header.name;return t.readAtoms(this.tokenizer,async(i,e)=>{let a=i.getPayloadLength(e);switch(i.header.name){case"data":return this.parseValueAtom(o,i);case"name":case"mean":case"rate":{let A=await this.tokenizer.readToken(new TO(a));o+=`:${A.name}`;break}default:{let A=await this.tokenizer.readToken(new Dt(a));this.addWarning(`Unsupported meta-item: ${o}[${i.header.name}] => value=${jD(A)} ascii=${wr(A,"ascii")}`)}}},t.getPayloadLength(0))}async parseValueAtom(t,o){let i=await this.tokenizer.readToken(new _O(Number(o.header.length)-ql.len));if(i.type.set!==0)throw new Kg(`Unsupported type-set != 0: ${i.type.set}`);switch(i.type.type){case 0:switch(t){case"trkn":case"disk":{let e=fA.get(i.value,3),a=fA.get(i.value,5);await this.addTag(t,`${e}/${a}`);break}case"gnre":{let e=fA.get(i.value,1),a=Rh[e-1];await this.addTag(t,a);break}case"rate":{let e=wr(i.value,"ascii");await this.addTag(t,e);break}default:Ii(`unknown proprietary value type for: ${o.atomPath}`)}break;case 1:case 18:await this.addTag(t,wr(i.value));break;case 13:if(this.options.skipCovers)break;await this.addTag(t,{format:"image/jpeg",data:Uint8Array.from(i.value)});break;case 14:if(this.options.skipCovers)break;await this.addTag(t,{format:"image/png",data:Uint8Array.from(i.value)});break;case 21:await this.addTag(t,n.read_BE_Integer(i.value,!0));break;case 22:await this.addTag(t,n.read_BE_Integer(i.value,!1));break;case 65:await this.addTag(t,fA.get(i.value,0));break;case 66:await this.addTag(t,GA.get(i.value,0));break;case 67:await this.addTag(t,Ue.get(i.value,0));break;default:this.addWarning(`atom key=${t}, has unknown well-known-type (data-type): ${i.type.type}`)}}async parseTrackBox(t){let o={media:{},fragments:[]};await t.readAtoms(this.tokenizer,async(i,e)=>{let a=i.getPayloadLength(e);switch(i.header.name){case"chap":{let A=await this.tokenizer.readToken(new UO(e));o.chapterList=A;break}case"tkhd":o.header=await this.tokenizer.readToken(new NO(a));break;case"hdlr":o.handler=await this.tokenizer.readToken(new LO(a)),o.isAudio=()=>o.handler.handlerType==="audi"||o.handler.handlerType==="soun",o.isVideo=()=>o.handler.handlerType==="vide",o.isAudio()?this.hasAudioTrack=!0:o.isVideo()&&(this.hasVideoTrack=!0);break;case"mdhd":{let A=await this.tokenizer.readToken(new bO(a));o.media.header=A;break}case"stco":{let A=await this.tokenizer.readToken(new vO(a));o.chunkOffsetTable=A.entries;break}case"stsc":{let A=await this.tokenizer.readToken(new kO(a));o.sampleToChunkTable=A.entries;break}case"stsd":{let A=await this.tokenizer.readToken(new gf(a));o.soundSampleDescription=A.table.map(r=>this.parseSoundSampleDescription(r));break}case"stts":{let A=await this.tokenizer.readToken(new RO(a));o.timeToSampleTable=A.entries;break}case"stsz":{let A=await this.tokenizer.readToken(new If(a));o.sampleSize=A.sampleSize,o.sampleSizeTable=A.entries;break}case"dinf":case"vmhd":case"smhd":Ii(`Ignoring: ${i.header.name}`),await this.tokenizer.ignore(a);break;default:Ii(`Unexpected track box: ${i.header.name}`),await this.tokenizer.ignore(a)}},t.getPayloadLength(0)),this.tracks.set(o.header.trackId,o)}parseTrackFragmentBox(t){let o;return t.readAtoms(this.tokenizer,async(i,e)=>{let a=i.getPayloadLength(e);switch(i.header.name){case"tfhd":{let A=new GO(i.getPayloadLength(e));o=await this.tokenizer.readToken(A);break}case"tfdt":await this.tokenizer.ignore(a);break;case"trun":{let A=new FO(a),r=await this.tokenizer.readToken(A);o&&this.tracks.get(o.trackId)?.fragments.push({header:o,trackRun:r});break}default:Ii(`Unexpected box: ${i.header.name}`),await this.tokenizer.ignore(a)}},t.getPayloadLength(0))}parseSoundSampleDescription(t){let o={dataFormat:t.dataFormat,dataReferenceIndex:t.dataReferenceIndex},i=0,{description:e}=t;if(e&&e.length>=HO.len){let a=HO.get(e,i);i+=HO.len,a.version===0||a.version===1?e.length>=i+D2.len?o.description=D2.get(e,i):Ii(`Warning: sound-sample-description too short: ${e.length} bytes`):Ii(`Warning: sound-sample-description ${a} not implemented`)}return o}async parseChapterTrack(t,o,i){if(!t.sampleSize&&t.chunkOffsetTable.length!==t.sampleSizeTable.length)throw new Error("Expected equal chunk-offset-table & sample-size-table length.");let e=[];for(let a=0;a0;++a){let A=t.timeToSampleTable.slice(0,a).reduce((d,B)=>d+B.duration,0),s=t.chunkOffsetTable[a]-this.tokenizer.position,g=t.sampleSize>0?t.sampleSize:t.sampleSizeTable[a];if(i-=s+g,i<0)throw new Kg("Chapter chunk exceeding token length");await this.tokenizer.ignore(s);let c=await this.tokenizer.readToken(new PO(g));Ii(`Chapter ${a+1}: ${c}`);let I={title:c,timeScale:t.media.header?t.media.header.timeScale:0,start:A,sampleOffset:this.findSampleOffset(o,this.tokenizer.position)};Ii(`Chapter title=${I.title}, offset=${I.sampleOffset}/${o.header.duration}`),e.push(I)}this.metadata.setFormat("chapters",e),await this.tokenizer.ignore(i)}findSampleOffset(t,o){let i=0;for(;i=o[i].firstChunk&&t{zae={parserType:"mp4",extensions:[".mp4",".m4a",".m4b",".m4pa","m4v","m4r","3gp",".mov",".movie",".qt"],mimeTypes:["audio/mp4","audio/m4a","video/m4v","video/mp4","video/quicktime"],async load(){return(await Promise.resolve().then(()=>(qae(),Jae))).MP4Parser}}});var $ae,Wae,fqe,Zae,Xae,xO,eie=ue(()=>{DA();$ae=Je(ct(),1);Ar();Wae=(0,$ae.default)("music-metadata:parser:musepack:sv8"),fqe=new ze(2,"latin1"),Zae={len:5,get:(n,t)=>({crc:Ge.get(n,t),streamVersion:fA.get(n,t+4)})},Xae={len:2,get:(n,t)=>({sampleFrequency:[44100,48e3,37800,32e3][XA(n,t,0,3)],maxUsedBands:XA(n,t,3,5),channelCount:XA(n,t+1,0,4)+1,msUsed:Da(n,t+1,4),audioBlockFrames:XA(n,t+1,5,3)})},xO=class{get tokenizer(){return this._tokenizer}set tokenizer(t){this._tokenizer=t}constructor(t){this._tokenizer=t}async readPacketHeader(){let t=await this.tokenizer.readToken(fqe),o=await this.readVariableSizeField();return{key:t,payloadLength:o.value-2-o.len}}async readStreamHeader(t){let o={};Wae(`Reading SH at offset=${this.tokenizer.position}`);let i=await this.tokenizer.readToken(Zae);t-=Zae.len,Object.assign(o,i),Wae(`SH.streamVersion = ${i.streamVersion}`);let e=await this.readVariableSizeField();t-=e.len,o.sampleCount=e.value;let a=await this.readVariableSizeField();t-=a.len,o.beginningOfSilence=a.value;let A=await this.tokenizer.readToken(Xae);return t-=Xae.len,Object.assign(o,A),await this.tokenizer.ignore(t),o}async readVariableSizeField(t=1,o=0){let i=await this.tokenizer.readNumber(fA);return(i&128)===0?{len:t,value:o+i}:(i&=127,i+=o,this.readVariableSizeField(t+1,i<<7))}}});var xg,YO=ue(()=>{er();xg=class extends Qt("Musepack"){}});var Aie,yqe,jO,tie=ue(()=>{Aie=Je(ct(),1);Hi();Ul();si();eie();YO();yqe=(0,Aie.default)("music-metadata:parser:musepack"),jO=class extends Rt{constructor(){super(...arguments),this.audioLength=0}async parse(){if(await this.tokenizer.readToken(at)!=="MPCK")throw new xg("Invalid Magic number");return this.metadata.setFormat("container","Musepack, SV8"),this.parsePacket()}async parsePacket(){let t=new xO(this.tokenizer);do{let o=await t.readPacketHeader();switch(yqe(`packet-header key=${o.key}, payloadLength=${o.payloadLength}`),o.key){case"SH":{let i=await t.readStreamHeader(o.payloadLength);this.metadata.setFormat("numberOfSamples",i.sampleCount),this.metadata.setFormat("sampleRate",i.sampleFrequency),this.metadata.setFormat("duration",i.sampleCount/i.sampleFrequency),this.metadata.setFormat("numberOfChannels",i.channelCount);break}case"AP":this.audioLength+=o.payloadLength,await this.tokenizer.ignore(o.payloadLength);break;case"RG":case"EI":case"SO":case"ST":case"CT":await this.tokenizer.ignore(o.payloadLength);break;case"SE":return this.metadata.format.duration&&this.metadata.setFormat("bitrate",this.audioLength*8/this.metadata.format.duration),Ll(this.metadata,this.tokenizer,this.options);default:throw new xg(`Unexpected header: ${o.key}`)}}while(!0)}}});var JO,rie=ue(()=>{DA();JO=class{constructor(t){this.pos=0,this.dword=null,this.tokenizer=t}async read(t){for(;this.dword===null;)this.dword=await this.tokenizer.readToken(Ge);let o=this.dword;return this.pos+=t,this.pos<32?(o>>>=32-this.pos,o&(1<>>32-this.pos),o&(1<0){let e=32-this.pos;this.dword=null,t-=e,this.pos=0}let o=t%32,i=(t-o)/32;return await this.tokenizer.ignore(i*4),this.read(o)}}});var aie,iie=ue(()=>{DA();Ar();_s();aie={len:24,get:(n,t)=>{let o={signature:wr(n.subarray(t,t+3),"latin1"),streamMinorVersion:XA(n,t+3,0,4),streamMajorVersion:XA(n,t+3,4,4),frameCount:Ge.get(n,t+4),maxLevel:SA.get(n,t+8),sampleFrequency:[44100,48e3,37800,32e3][XA(n,t+10,0,2)],link:XA(n,t+10,2,2),profile:XA(n,t+10,4,4),maxBand:XA(n,t+11,0,6),intensityStereo:Da(n,t+11,6),midSideStereo:Da(n,t+11,7),titlePeak:SA.get(n,t+12),titleGain:SA.get(n,t+14),albumPeak:SA.get(n,t+16),albumGain:SA.get(n,t+18),lastFrameLength:Ge.get(n,t+20)>>>20&2047,trueGapless:Da(n,t+23,0)};return o.lastFrameLength=o.trueGapless?Ge.get(n,20)>>>20&2047:0,o}}});var nie,oie,qO,sie=ue(()=>{nie=Je(ct(),1);Hi();Ul();rie();iie();YO();oie=(0,nie.default)("music-metadata:parser:musepack"),qO=class extends Rt{constructor(){super(...arguments),this.bitreader=null,this.audioLength=0,this.duration=null}async parse(){let t=await this.tokenizer.readToken(aie);if(t.signature!=="MP+")throw new xg("Unexpected magic number");oie(`stream-version=${t.streamMajorVersion}.${t.streamMinorVersion}`),this.metadata.setFormat("container","Musepack, SV7"),this.metadata.setFormat("sampleRate",t.sampleFrequency);let o=1152*(t.frameCount-1)+t.lastFrameLength;this.metadata.setFormat("numberOfSamples",o),this.duration=o/t.sampleFrequency,this.metadata.setFormat("duration",this.duration),this.bitreader=new JO(this.tokenizer),this.metadata.setFormat("numberOfChannels",t.midSideStereo||t.intensityStereo?2:1);let i=await this.bitreader.read(8);return this.metadata.setFormat("codec",(i/100).toFixed(2)),await this.skipAudioData(t.frameCount),oie(`End of audio stream, switching to APEv2, offset=${this.tokenizer.position}`),Ll(this.metadata,this.tokenizer,this.options)}async skipAudioData(t){for(;t-- >0;){let i=await this.bitreader.read(20);this.audioLength+=20+i,await this.bitreader.ignore(i)}let o=await this.bitreader.read(11);this.audioLength+=o,this.duration!==null&&this.metadata.setFormat("bitrate",this.audioLength/this.duration)}}});var Iie={};Pr(Iie,{MusepackParser:()=>b2});var cie,gie,b2,lie=ue(()=>{cie=Je(ct(),1);DA();$B();tie();sie();YO();gie=(0,cie.default)("music-metadata:parser:musepack"),b2=class extends Fs{async postId3v2Parse(){let t=await this.tokenizer.peekToken(new ze(3,"latin1")),o;switch(t){case"MP+":{gie("Stream-version 7"),o=new qO(this.metadata,this.tokenizer,this.options);break}case"MPC":{gie("Stream-version 8"),o=new jO(this.metadata,this.tokenizer,this.options);break}default:throw new xg("Invalid signature prefix")}return this.metadata.setAudioOnly(),o.parse()}}});var pie,die=ue(()=>{pie={parserType:"musepack",extensions:[".mpc"],mimeTypes:["audio/musepack"],async load(){return(await Promise.resolve().then(()=>(lie(),Iie))).MusepackParser}}});var pf,zO,M2=ue(()=>{DA();er();pf=class extends Qt("Opus"){},zO=class{constructor(t){if(t<19)throw new pf("ID-header-page 0 should be at least 19 bytes long");this.len=t}get(t,o){return{magicSignature:new ze(8,"ascii").get(t,o+0),version:fA.get(t,o+8),channelCount:fA.get(t,o+9),preSkip:SA.get(t,o+10),inputSampleRate:Ge.get(t,o+12),outputGain:SA.get(t,o+16),channelMapping:fA.get(t,o+18)}}}});var VO,hie=ue(()=>{DA();af();M2();M2();VO=class extends Us{constructor(t,o,i){super(t,o),this.idHeader=null,this.lastPos=-1,this.tokenizer=i,this.durationOnLastPage=!0}parseFirstPage(t,o){if(this.metadata.setFormat("codec","Opus"),this.idHeader=new zO(o.length).get(o,0),this.idHeader.magicSignature!=="OpusHead")throw new pf("Illegal ogg/Opus magic-signature");this.metadata.setFormat("sampleRate",this.idHeader.inputSampleRate),this.metadata.setFormat("numberOfChannels",this.idHeader.channelCount),this.metadata.setAudioOnly()}async parseFullPage(t){switch(new ze(8,"ascii").get(t,0)){case"OpusTags":await this.parseUserCommentList(t,8),this.lastPos=this.tokenizer.position-t.length;break;default:break}}calculateDuration(t){if(this.lastPageHeader&&(t||this.lastPageHeader.headerType.lastPage)&&this.metadata.format.sampleRate&&this.lastPageHeader.absoluteGranulePosition>=0){let o=this.lastPageHeader.absoluteGranulePosition-this.idHeader.preSkip;if(this.metadata.setFormat("numberOfSamples",o),this.metadata.setFormat("duration",o/48e3),this.lastPos!==-1&&this.tokenizer.fileInfo.size&&this.metadata.format.duration){let i=this.tokenizer.fileInfo.size-this.lastPos;this.metadata.setFormat("bitrate",8*i/this.metadata.format.duration)}}}}});var Eie,Cie=ue(()=>{DA();Ar();Eie={len:80,get:(n,t)=>({speex:new ze(8,"ascii").get(n,t+0),version:WD(new ze(20,"ascii").get(n,t+8)),version_id:sr.get(n,t+28),header_size:sr.get(n,t+32),rate:sr.get(n,t+36),mode:sr.get(n,t+40),mode_bitstream_version:sr.get(n,t+44),nb_channels:sr.get(n,t+48),bitrate:sr.get(n,t+52),frame_size:sr.get(n,t+56),vbr:sr.get(n,t+60),frames_per_packet:sr.get(n,t+64),extra_headers:sr.get(n,t+68),reserved1:sr.get(n,t+72),reserved2:sr.get(n,t+76)})}});var Bie,uie,WO,fie=ue(()=>{Bie=Je(ct(),1);af();Cie();uie=(0,Bie.default)("music-metadata:parser:ogg:speex"),WO=class extends Us{constructor(t,o,i){super(t,o),this.commentHeaderParsed=!1}parseFirstPage(t,o){uie("First Ogg/Speex page");let i=Eie.get(o,0);this.metadata.setFormat("codec",`Speex ${i.version}`),this.metadata.setFormat("numberOfChannels",i.nb_channels),this.metadata.setFormat("sampleRate",i.rate),i.bitrate!==-1&&this.metadata.setFormat("bitrate",i.bitrate),this.metadata.setAudioOnly()}async parseFullPage(t){this.commentHeaderParsed||(this.commentHeaderParsed=!0,uie("Parse Ogg/Speex comment header"),await this.parseUserCommentList(t,0))}}});var Qie,yie=ue(()=>{DA();Qie={len:42,get:(n,t)=>({id:new ze(7,"ascii").get(n,t),vmaj:fA.get(n,t+7),vmin:fA.get(n,t+8),vrev:fA.get(n,t+9),vmbw:GA.get(n,t+10),vmbh:GA.get(n,t+17),nombr:kr.get(n,t+37),nqual:fA.get(n,t+40)})}});var Sie,mie,ZO,wie=ue(()=>{Sie=Je(ct(),1);yie();mie=(0,Sie.default)("music-metadata:parser:ogg:theora"),ZO=class{constructor(t,o,i){this.durationOnLastPage=!1,this.metadata=t}async parsePage(t,o){t.headerType.firstPage&&await this.parseFirstPage(t,o)}calculateDuration(){mie("duration calculation not implemented")}async parseFirstPage(t,o){mie("First Ogg/Theora page"),this.metadata.setFormat("codec","Theora");let i=Qie.get(o,0);this.metadata.setFormat("bitrate",i.nombr),this.metadata.setFormat("hasVideo",!0)}flush(){return Promise.resolve()}}});var Die,XO,Oie=ue(()=>{DA();Ar();DA();Die={len:27,get:(n,t)=>({capturePattern:new ze(4,"latin1").get(n,t),version:fA.get(n,t+4),headerType:{continued:vA(n,t+5,0),firstPage:vA(n,t+5,1),lastPage:vA(n,t+5,2)},absoluteGranulePosition:Number(Dr.get(n,t+6)),streamSerialNumber:Ge.get(n,t+14),pageSequenceNo:Ge.get(n,t+18),pageChecksum:Ge.get(n,t+22),page_segments:fA.get(n,t+26)})},XO=class n{static sum(t,o,i){let e=new DataView(t.buffer,0),a=0;for(let A=o;A{bie=Je(ct(),1);u2();B2();si();yO();_2=(0,bie.default)("music-metadata:parser:ogg:theora"),$O=class{constructor(t,o,i){this.durationOnLastPage=!1,this.metadata=t,this.options=o,this.tokenizer=i,this.flacParser=new sf(this.metadata,this.tokenizer,o)}async parsePage(t,o){t.headerType.firstPage&&await this.parseFirstPage(t,o)}calculateDuration(){_2("duration calculation not implemented")}async parseFirstPage(t,o){if(_2("First Ogg/FLAC page"),(await at.get(o,9)).toString()!=="fLaC")throw new Error("Invalid FLAC preamble");let e=await of.get(o,13);await this.parseDataBlock(e,o.subarray(13+of.len))}async parseDataBlock(t,o){switch(_2(`blockHeader type=${t.type}, length=${t.length}`),t.type){case ci.STREAMINFO:{let i=nf.get(o,0);return this.flacParser.processsStreamInfo(i)}case ci.PADDING:break;case ci.APPLICATION:break;case ci.SEEKTABLE:break;case ci.VORBIS_COMMENT:return this.flacParser.parseComment(o);case ci.PICTURE:if(!this.options.skipCovers){let i=new cI(o.length).get(o,0);return this.flacParser.addPictureTag(i)}break;default:this.metadata.addWarning(`Unknown block type: ${t.type}`)}return this.tokenizer.ignore(t.length).then()}flush(){return Promise.resolve()}}});var Tie={};Pr(Tie,{OggContentError:()=>qh,OggParser:()=>N2});var _ie,qh,Ks,T2,N2,Nie=ue(()=>{DA();so();_ie=Je(ct(),1);Hi();af();hie();fie();wie();er();Oie();Mie();qh=class extends Qt("Ogg"){},Ks=(0,_ie.default)("music-metadata:parser:ogg"),T2=class{constructor(t,o,i){this.pageNumber=0,this.closed=!1,this.metadata=t,this.streamSerial=o,this.options=i}async parsePage(t,o){this.pageNumber=o.pageSequenceNo,Ks("serial=%s page#=%s, Ogg.id=%s",o.streamSerialNumber,o.pageSequenceNo,o.capturePattern);let i=await t.readToken(new XO(o));Ks("totalPageSize=%s",i.totalPageSize);let e=await t.readToken(new Dt(i.totalPageSize));if(Ks("firstPage=%s, lastPage=%s, continued=%s",o.headerType.firstPage,o.headerType.lastPage,o.headerType.continued),o.headerType.firstPage){this.metadata.setFormat("container","Ogg");let a=e.subarray(0,7),A=Array.from(a).filter(r=>r>=32&&r<=126).map(r=>String.fromCharCode(r)).join("");switch(A){case"vorbis":Ks(`Set Ogg stream serial ${o.streamSerialNumber}, codec=Vorbis`),this.pageConsumer=new Us(this.metadata,this.options);break;case"OpusHea":Ks("Set page consumer to Ogg/Opus"),this.pageConsumer=new VO(this.metadata,this.options,t);break;case"Speex ":Ks("Set page consumer to Ogg/Speex"),this.pageConsumer=new WO(this.metadata,this.options,t);break;case"fishead":case"theora":Ks("Set page consumer to Ogg/Theora"),this.pageConsumer=new ZO(this.metadata,this.options,t);break;case"FLAC":Ks("Set page consumer to Vorbis"),this.pageConsumer=new $O(this.metadata,this.options,t);break;default:throw new qh(`Ogg codec not recognized (id=${A}`)}}if(o.headerType.lastPage&&(this.closed=!0),this.pageConsumer)await this.pageConsumer.parsePage(o,e);else throw new Error("pageConsumer should be initialized")}},N2=class extends Rt{constructor(){super(...arguments),this.streams=new Map}async parse(){this.streams=new Map;let t=!1,o;try{do{if(o=await this.tokenizer.readToken(Die),o.capturePattern!=="OggS")throw new qh("Invalid Ogg capture pattern");let i=this.streams.get(o.streamSerialNumber);if(i||(i=new T2(this.metadata,o.streamSerialNumber,this.options),this.streams.set(o.streamSerialNumber,i)),await i.parsePage(this.tokenizer,o),i.pageNumber>12&&!(this.options.duration&&[...this.streams.values()].find(e=>e.pageConsumer?.durationOnLastPage))){Ks("Stop processing Ogg stream");break}}while(![...this.streams.values()].every(i=>i.closed))}catch(i){if(i instanceof bA)Ks("Reached end-of-stream"),t=!0;else if(i instanceof qh)this.metadata.addWarning(`Corrupt Ogg content at ${this.tokenizer.position}`);else throw i}for(let i of this.streams.values())i.closed||(this.metadata.addWarning(`End-of-stream reached before reaching last page in Ogg stream serial=${i.streamSerial}`),await i.pageConsumer?.flush()),i.pageConsumer?.calculateDuration(t)}}});var Rie,kie=ue(()=>{Rie={parserType:"ogg",extensions:[".ogg",".ogv",".oga",".ogm",".ogx",".opus",".spx"],mimeTypes:["audio/ogg","audio/opus","audio/speex","video/ogg"],async load(){return(await Promise.resolve().then(()=>(Nie(),Tie))).OggParser}}});function xs(n,t){return eb(n,t,1)===1}function eb(n,t,o){return n>>>t&4294967295>>>32-o}var Dqe,df,Ab,vie=ue(()=>{DA();si();Dqe=[6e3,8e3,9600,11025,12e3,16e3,22050,24e3,32e3,44100,48e3,64e3,88200,96e3,192e3,-1],df={len:32,get:(n,t)=>{let o=Ge.get(n,t+24),i={BlockID:at.get(n,t),blockSize:Ge.get(n,t+4),version:SA.get(n,t+8),totalSamples:Ge.get(n,t+12),blockIndex:Ge.get(n,t+16),blockSamples:Ge.get(n,t+20),flags:{bitsPerSample:(1+eb(o,0,2))*8,isMono:xs(o,2),isHybrid:xs(o,3),isJointStereo:xs(o,4),crossChannel:xs(o,5),hybridNoiseShaping:xs(o,6),floatingPoint:xs(o,7),samplingRate:Dqe[eb(o,23,4)],isDSD:xs(o,31)},crc:new Dt(4).get(n,t+28)};return i.flags.isDSD&&(i.totalSamples*=8),i}},Ab={len:1,get:(n,t)=>({functionId:eb(n[t],0,6),isOptional:xs(n[t],5),isOddSize:xs(n[t],6),largeBlock:xs(n[t],7)})}});var Gie={};Pr(Gie,{WavPackContentError:()=>zh,WavPackParser:()=>R2});var Pie,zl,zh,R2,Fie=ue(()=>{DA();Ul();si();Hi();vie();Pie=Je(ct(),1);YB();er();zl=(0,Pie.default)("music-metadata:parser:WavPack"),zh=class extends Qt("WavPack"){},R2=class extends Rt{constructor(){super(...arguments),this.audioDataSize=0}async parse(){return this.metadata.setAudioOnly(),this.audioDataSize=0,await this.parseWavPackBlocks(),Ll(this.metadata,this.tokenizer,this.options)}async parseWavPackBlocks(){do{if(await this.tokenizer.peekToken(at)!=="wvpk")break;let o=await this.tokenizer.readToken(df);if(o.BlockID!=="wvpk")throw new zh("Invalid WavPack Block-ID");zl(`WavPack header blockIndex=${o.blockIndex}, len=${df.len}`),o.blockIndex===0&&!this.metadata.format.container&&(this.metadata.setFormat("container","WavPack"),this.metadata.setFormat("lossless",!o.flags.isHybrid),this.metadata.setFormat("bitsPerSample",o.flags.bitsPerSample),o.flags.isDSD||(this.metadata.setFormat("sampleRate",o.flags.samplingRate),this.metadata.setFormat("duration",o.totalSamples/o.flags.samplingRate)),this.metadata.setFormat("numberOfChannels",o.flags.isMono?1:2),this.metadata.setFormat("numberOfSamples",o.totalSamples),this.metadata.setFormat("codec",o.flags.isDSD?"DSD":"PCM"));let i=o.blockSize-(df.len-8);await(o.blockIndex===0?this.parseMetadataSubBlock(o,i):this.tokenizer.ignore(i)),o.blockSamples>0&&(this.audioDataSize+=o.blockSize)}while(!this.tokenizer.fileInfo.size||this.tokenizer.fileInfo.size-this.tokenizer.position>=df.len);this.metadata.format.duration&&this.metadata.setFormat("bitrate",this.audioDataSize*8/this.metadata.format.duration)}async parseMetadataSubBlock(t,o){let i=o;for(;i>Ab.len;){let e=await this.tokenizer.readToken(Ab),a=await this.tokenizer.readNumber(e.largeBlock?HB:fA),A=new Uint8Array(a*2-(e.isOddSize?1:0));switch(await this.tokenizer.readBuffer(A),zl(`Metadata Sub-Blocks functionId=0x${e.functionId.toString(16)}, id.largeBlock=${e.largeBlock},data-size=${A.length}`),e.functionId){case 0:break;case 14:{zl("ID_DSD_BLOCK");let r=1<{Lie={parserType:"wavpack",extensions:[".wv",".wvp"],mimeTypes:["audio/wavpack"],async load(){return(await Promise.resolve().then(()=>(Fie(),Gie))).WavPackParser}}});var Vh,tb,Hie=ue(()=>{DA();Vh={len:8,get:(n,t)=>({chunkID:new ze(4,"latin1").get(n,t),chunkSize:Ge.get(n,t+4)})},tb=class{constructor(t){this.tagHeader=t,this.len=t.chunkSize,this.len+=this.len&1}get(t,o){return new ze(this.tagHeader.chunkSize,"utf8").get(t,o)}}});var Vl,pa,Kie,rb,ab,k2=ue(()=>{DA();er();Vl=class extends Qt("Wave"){},pa={PCM:1,ADPCM:2,IEEE_FLOAT:3,ALAW:6,MULAW:7,DVI_ADPCM:17,GSM610:49,MPEG_ADTS_AAC:5632,MPEG_LOAS:5634,RAW_AAC1:255,DOLBY_AC3_SPDIF:146,DVM:8192,RAW_SPORT:576,ESST_AC3:577,DRM:9,DTS2:8193,MPEG:80,MPEGLAYER3:85},Kie={[pa.PCM]:"PCM",[pa.ADPCM]:"ADPCM",[pa.IEEE_FLOAT]:"IEEE_FLOAT",[pa.ALAW]:"ALAW",[pa.MULAW]:"MULAW",[pa.DVI_ADPCM]:"DVI_ADPCM",[pa.GSM610]:"GSM610",[pa.MPEG_ADTS_AAC]:"MPEG_ADTS_AAC",[pa.MPEG_LOAS]:"MPEG_LOAS",[pa.RAW_AAC1]:"RAW_AAC1",[pa.DOLBY_AC3_SPDIF]:"DOLBY_AC3_SPDIF",[pa.DVM]:"DVM",[pa.RAW_SPORT]:"RAW_SPORT",[pa.ESST_AC3]:"ESST_AC3",[pa.DRM]:"DRM",[pa.DTS2]:"DTS2",[pa.MPEG]:"MPEG",[pa.MPEGLAYER3]:"MPEGLAYER3"},rb=class{constructor(t){if(t.chunkSize<16)throw new Vl("Invalid chunk size");this.len=t.chunkSize}get(t,o){return{wFormatTag:SA.get(t,o),nChannels:SA.get(t,o+2),nSamplesPerSec:Ge.get(t,o+4),nAvgBytesPerSec:Ge.get(t,o+8),nBlockAlign:SA.get(t,o+12),wBitsPerSample:SA.get(t,o+14)}}},ab=class{constructor(t){if(t.chunkSize<4)throw new Vl("Invalid fact chunk size.");this.len=t.chunkSize}get(t,o){return{dwSampleLength:Ge.get(t,o)}}}});var v2,xie=ue(()=>{DA();Ar();v2={len:420,get:(n,t)=>({description:Wo(new ze(256,"ascii").get(n,t)).trim(),originator:Wo(new ze(32,"ascii").get(n,t+256)).trim(),originatorReference:Wo(new ze(32,"ascii").get(n,t+288)).trim(),originationDate:Wo(new ze(10,"ascii").get(n,t+320)).trim(),originationTime:Wo(new ze(8,"ascii").get(n,t+330)).trim(),timeReferenceLow:Ge.get(n,t+338),timeReferenceHigh:Ge.get(n,t+342),version:SA.get(n,t+346),umid:new Dt(64).get(n,t+348),loudnessValue:SA.get(n,t+412),maxTruePeakLevel:SA.get(n,t+414),maxMomentaryLoudness:SA.get(n,t+416),maxShortTermLoudness:SA.get(n,t+418)})}});var jie={};Pr(jie,{WaveParser:()=>P2});var Yie,II,P2,Jie=ue(()=>{so();DA();Yie=Je(ct(),1);Hie();k2();kh();Ar();si();Hi();xie();k2();II=(0,Yie.default)("music-metadata:parser:RIFF"),P2=class extends Rt{constructor(){super(...arguments),this.blockAlign=0,this.avgBytesPerSec=0}async parse(){let t=await this.tokenizer.readToken(Vh);if(II(`pos=${this.tokenizer.position}, parse: chunkID=${t.chunkID}`),t.chunkID==="RIFF")return this.metadata.setAudioOnly(),this.parseRiffChunk(t.chunkSize).catch(o=>{if(!(o instanceof bA))throw o})}async parseRiffChunk(t){let o=await this.tokenizer.readToken(at);switch(this.metadata.setFormat("container",o),o){case"WAVE":return this.readWaveChunk(t-at.len);default:throw new Vl(`Unsupported RIFF format: RIFF/${o}`)}}async readWaveChunk(t){for(;t>=Vh.len;){let o=await this.tokenizer.readToken(Vh);switch(t-=Vh.len+o.chunkSize,o.chunkSize>t&&this.metadata.addWarning("Data chunk size exceeds file size"),this.header=o,II(`pos=${this.tokenizer.position}, readChunk: chunkID=RIFF/WAVE/${o.chunkID}`),o.chunkID){case"LIST":await this.parseListTag(o);break;case"fact":this.metadata.setFormat("lossless",!1),this.fact=await this.tokenizer.readToken(new ab(o));break;case"fmt ":{let i=await this.tokenizer.readToken(new rb(o)),e=Kie[i.wFormatTag];e||(II(`WAVE/non-PCM format=${i.wFormatTag}`),e=`non-PCM (${i.wFormatTag})`),this.metadata.setFormat("codec",e),this.metadata.setFormat("bitsPerSample",i.wBitsPerSample),this.metadata.setFormat("sampleRate",i.nSamplesPerSec),this.metadata.setFormat("numberOfChannels",i.nChannels),this.blockAlign=i.nBlockAlign,this.avgBytesPerSec=i.nAvgBytesPerSec;break}case"id3 ":case"ID3 ":{let i=await this.tokenizer.readToken(new Dt(o.chunkSize)),e=no(i);await new $o().parse(this.metadata,e,this.options);break}case"data":{this.metadata.format.lossless!==!1&&this.metadata.setFormat("lossless",!0);let i=o.chunkSize;if(this.tokenizer.fileInfo.size){let a=this.tokenizer.fileInfo.size-this.tokenizer.position;a0?this.metadata.setFormat("bitrate",this.avgBytesPerSec*8):this.metadata.format.duration&&this.metadata.setFormat("bitrate",i*8/this.metadata.format.duration),await this.tokenizer.ignore(o.chunkSize);break}case"bext":{let i=await this.tokenizer.readToken(v2);Object.keys(i).forEach(a=>{this.metadata.addTag("exif",`bext.${a}`,i[a])});let e=o.chunkSize-v2.len;await this.tokenizer.ignore(e);break}case"\0\0\0\0":II(`Ignore padding chunk: RIFF/${o.chunkID} of ${o.chunkSize} bytes`),this.metadata.addWarning(`Ignore chunk: RIFF/${o.chunkID}`),await this.tokenizer.ignore(o.chunkSize);break;default:II(`Ignore chunk: RIFF/${o.chunkID} of ${o.chunkSize} bytes`),this.metadata.addWarning(`Ignore chunk: RIFF/${o.chunkID}`),await this.tokenizer.ignore(o.chunkSize)}this.header.chunkSize%2===1&&(II("Read odd padding byte"),await this.tokenizer.ignore(1))}}async parseListTag(t){let o=await this.tokenizer.readToken(new ze(4,"latin1"));switch(II("pos=%s, parseListTag: chunkID=RIFF/WAVE/LIST/%s",this.tokenizer.position,o),o){case"INFO":return this.parseRiffInfoTags(t.chunkSize-4);default:return this.metadata.addWarning(`Ignore chunk: RIFF/WAVE/LIST/${o}`),II(`Ignoring chunkID=RIFF/WAVE/LIST/${o}`),this.tokenizer.ignore(t.chunkSize-4).then()}}async parseRiffInfoTags(t){for(;t>=8;){let o=await this.tokenizer.readToken(Vh),i=new tb(o),e=await this.tokenizer.readToken(i);this.addTag(o.chunkID,Wo(e)),t-=8+i.len}if(t!==0)throw new Vl(`Illegal remaining size: ${t}`)}addTag(t,o){this.metadata.addTag("exif",t,o)}}});var qie,zie=ue(()=>{qie={parserType:"riff",extensions:[".wav","wave",".bwf"],mimeTypes:["audio/vnd.wave","audio/wav","audio/wave"],async load(){return(await Promise.resolve().then(()=>(Jie(),jie))).WaveParser}}});function Mqe(n){let t=Vie.default.parse(n),o=Ute(t.type);return{type:o.type,subtype:o.subtype,suffix:o.suffix,parameters:t.parameters}}function _qe(n){let t=n.lastIndexOf(".");return t===-1?"":n.substring(t)}var Vie,Wie,Wl,Zl,G2=ue(()=>{PL();Vie=Je(Lte(),1);Hte();Wie=Je(ct(),1);gre();Gl();Pre();er();Fre();Zre();rae();cae();Eae();mae();Rae();Vae();die();kie();Uie();zie();ib();Wl=(0,Wie.default)("music-metadata:parser:factory");Zl=class{constructor(){this.parsers=[],[yae,vre,Gre,zae,Nae,qie,Rie,Wre,gae,Lie,pie,hae,tae].forEach(t=>{this.registerParser(t)})}registerParser(t){this.parsers.push(t)}async parse(t,o,i){if(t.supportsRandomAccess()?(Wl("tokenizer supports random-access, scanning for appending headers"),await F2(t,i)):Wl("tokenizer does not support random-access, cannot scan for appending headers"),!o){let r=new Uint8Array(4100);if(t.fileInfo.mimeType&&(o=this.findLoaderForContentType(t.fileInfo.mimeType)),!o&&t.fileInfo.path&&(o=this.findLoaderForExtension(t.fileInfo.path)),!o){Wl("Guess parser on content..."),await t.peekBuffer(r,{mayBeLess:!0});let s=await qB(r,{mpegOffsetTolerance:10});if(!s||!s.mime)throw new tI("Failed to determine audio format");if(Wl(`Guessed file type is mime=${s.mime}, extension=${s.ext}`),o=this.findLoaderForContentType(s.mime),!o)throw new rI(`Guessed MIME-type not supported: ${s.mime}`)}}Wl(`Loading ${o.parserType} parser...`);let e=new gO(i),a=await o.load(),A=new a(e,t,i??{});return Wl(`Parser ${o.parserType} loaded`),await A.parse(),e.format.trackInfo&&(e.format.hasAudio===void 0&&e.setFormat("hasAudio",!!e.format.trackInfo.find(r=>r.type===Ia.audio)),e.format.hasVideo===void 0&&e.setFormat("hasVideo",!!e.format.trackInfo.find(r=>r.type===Ia.video))),e.toCommonMetadata()}findLoaderForExtension(t){if(!t)return;let o=_qe(t).toLocaleLowerCase()||t;return this.parsers.find(i=>i.extensions.indexOf(o)!==-1)}findLoaderForContentType(t){let o;if(!t)return;try{o=Mqe(t)}catch{Wl(`Invalid HTTP Content-Type header value: ${t}`);return}let i=o.subtype.indexOf("x-")===0?o.subtype.substring(2):o.subtype;return this.parsers.find(e=>e.mimeTypes.find(a=>a.indexOf(`${o.type}/${i}`)!==-1))}getSupportedMimeTypes(){let t=new Set;return this.parsers.forEach(o=>{o.mimeTypes.forEach(i=>{t.add(i),t.add(i.replace("/","/x-"))})}),Array.from(t)}}});async function Zie(n){let t=n.fileInfo.size;if(t>=143){let o=new Uint8Array(15),i=n.position;await n.readBuffer(o,{position:t-143}),n.setPosition(i);let e=wr(o,"latin1");if(e.substring(6)===Tqe)return Number.parseInt(e.substring(0,6),10)+15}return 0}var Tqe,Xie=ue(()=>{_s();Tqe="LYRICS200"});async function Nqe(n,t={}){let o=FD(n);try{return await Wh(o,t)}finally{await o.close()}}async function Rqe(n,t,o={}){let i=GD(n,{fileInfo:typeof t=="string"?{mimeType:t}:t});try{return await Wh(i,o)}finally{await i.close()}}async function kqe(n,t,o={}){let i=no(n,{fileInfo:typeof t=="string"?{mimeType:t}:t});return Wh(i,o)}function Wh(n,t){return new Zl().parse(n,void 0,t)}function vqe(n){let t={};for(let{id:o,value:i}of n)(t[o]||(t[o]=[])).push(i);return t}function Pqe(n){return n===void 0?0:1+Math.round(n*4)}function Gqe(n){return n?n.reduce((t,o)=>o.name&&o.name.toLowerCase()in["front","cover","cover (front)"]?o:t):null}async function F2(n,t={}){let o=n.fileInfo.size;if(await ure(n)){o-=128;let i=await Zie(n);o-=i}t.apeHeader=await iI.findApeFooterOffset(n,o)}function Fqe(){return new Zl().getSupportedMimeTypes()}var ib=ue(()=>{so();G2();Ul();WB();Xie();Gl();er();er()});var Aoe={};Pr(Aoe,{CouldNotDetermineFileTypeError:()=>tI,FieldDecodingError:()=>Vo,InternalParserError:()=>vl,LyricsContentType:()=>bh,TimestampFormat:()=>Mh,UnexpectedFileContentError:()=>VD,UnsupportedFileTypeError:()=>rI,getSupportedMimeTypes:()=>Fqe,makeParseError:()=>Dh,makeUnexpectedFileContentError:()=>Qt,orderTags:()=>vqe,parseBlob:()=>Nqe,parseBuffer:()=>kqe,parseFile:()=>Uqe,parseFromTokenizer:()=>Wh,parseStream:()=>Lqe,parseWebStream:()=>Rqe,ratingToStars:()=>Pqe,scanAppendingHeaders:()=>F2,selectCover:()=>Gqe});async function Lqe(n,t,o={}){let i=await QL(n,{fileInfo:typeof t=="string"?{mimeType:t}:t});try{return await Wh(i,o)}finally{await i.close()}}async function Uqe(n,t={}){$ie(`parseFile: ${n}`);let o=await $Ae(n),i=new Zl;try{let e=i.findLoaderForExtension(n);e||$ie("Parser could not be determined by file extension");try{return await i.parse(o,e,t)}catch(a){throw(a instanceof tI||a instanceof rI)&&(a.message+=`: ${n}`),a}}finally{await o.close()}}var eoe,$ie,toe=ue(()=>{so();eoe=Je(ct(),1);ib();G2();ib();$ie=(0,eoe.default)("music-metadata:parser")});var Ene=$((f0A,uU)=>{"use strict";var V4e=Object.prototype.hasOwnProperty,li="~";function Of(){}Object.create&&(Of.prototype=Object.create(null),new Of().__proto__||(li=!1));function W4e(n,t,o){this.fn=n,this.context=t,this.once=o||!1}function hne(n,t,o,i,e){if(typeof o!="function")throw new TypeError("The listener must be a function");var a=new W4e(o,i||n,e),A=li?li+t:t;return n._events[A]?n._events[A].fn?n._events[A]=[n._events[A],a]:n._events[A].push(a):(n._events[A]=a,n._eventsCount++),n}function Bb(n,t){--n._eventsCount===0?n._events=new Of:delete n._events[t]}function Xa(){this._events=new Of,this._eventsCount=0}Xa.prototype.eventNames=function(){var t=[],o,i;if(this._eventsCount===0)return t;for(i in o=this._events)V4e.call(o,i)&&t.push(li?i.slice(1):i);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(o)):t};Xa.prototype.listeners=function(t){var o=li?li+t:t,i=this._events[o];if(!i)return[];if(i.fn)return[i.fn];for(var e=0,a=i.length,A=new Array(a);e{"use strict";var Tf=n=>n&&typeof n.message=="string",NU=n=>{if(!n)return;let t=n.cause;if(typeof t=="function"){let o=n.cause();return Tf(o)?o:void 0}else return Tf(t)?t:void 0},Yne=(n,t)=>{if(!Tf(n))return"";let o=n.stack||"";if(t.has(n))return o+` +`),syncText:o}}var JL,nre=ue(()=>{Gl();JL=/\[(\d{2}):(\d{2})\.(\d{2,3})]/});function qJe(n){return n.length>2?`${n.slice(0,n.length-1).join(", ")} & ${n[n.length-1]}`:n.join(" & ")}var sre,Fl,JJe,gO,gre=ue(()=>{Gl();sre=Je(ct(),1);zte();ire();Hg();Ar();PL();nre();Fl=(0,sre.default)("music-metadata:collector"),JJe=["matroska","APEv2","vorbis","ID3v2.4","ID3v2.3","ID3v2.2","exif","asf","iTunes","AIFF","ID3v1"],gO=class{constructor(t){this.format={tagTypes:[],trackInfo:[]},this.native={},this.common={track:{no:null,of:null},disk:{no:null,of:null},movementIndex:{no:null,of:null}},this.quality={warnings:[]},this.commonOrigin={},this.originPriority={},this.tagMapper=new sO,this.opts=t;let o=1;for(let i of JJe)this.originPriority[i]=o++;this.originPriority.artificial=500,this.originPriority.id3v1=600}hasAny(){return Object.keys(this.native).length>0}addStreamInfo(t){Fl(`streamInfo: type=${t.type?UL[t.type]:"?"}, codec=${t.codecName}`),this.format.trackInfo.push(t)}setFormat(t,o){Fl(`format: ${t} = ${o}`),this.format[t]=o,this.opts?.observer&&this.opts.observer({metadata:this,tag:{type:"format",id:t,value:o}})}setAudioOnly(){this.setFormat("hasAudio",!0),this.setFormat("hasVideo",!1)}async addTag(t,o,i){Fl(`tag ${t}.${o} = ${i}`),this.native[t]||(this.format.tagTypes.push(t),this.native[t]=[]),this.native[t].push({id:o,value:i}),await this.toCommon(t,o,i)}addWarning(t){this.quality.warnings.push({message:t})}async postMap(t,o){switch(o.id){case"artist":return this.handleSingularArtistTag(t,o,"artist","artists");case"albumartist":return this.handleSingularArtistTag(t,o,"albumartist","albumartists");case"artists":return this.handlePluralArtistTag(t,o,"artist","artists");case"albumartists":return this.handlePluralArtistTag(t,o,"albumartist","albumartists");case"picture":return this.postFixPicture(o.value).then(i=>{i!==null&&(o.value=i,this.setGenericTag(t,o))});case"totaltracks":this.common.track.of=gr.toIntOrNull(o.value);return;case"totaldiscs":this.common.disk.of=gr.toIntOrNull(o.value);return;case"movementTotal":this.common.movementIndex.of=gr.toIntOrNull(o.value);return;case"track":case"disk":case"movementIndex":{let i=this.common[o.id].of;this.common[o.id]=gr.normalizeTrack(o.value),this.common[o.id].of=i??this.common[o.id].of;return}case"bpm":case"year":case"originalyear":o.value=Number.parseInt(o.value,10);break;case"date":{let i=Number.parseInt(o.value.substr(0,4),10);Number.isNaN(i)||(this.common.year=i);break}case"discogs_label_id":case"discogs_release_id":case"discogs_master_release_id":case"discogs_artist_id":case"discogs_votes":o.value=typeof o.value=="string"?Number.parseInt(o.value,10):o.value;break;case"replaygain_track_gain":case"replaygain_track_peak":case"replaygain_album_gain":case"replaygain_album_peak":o.value=jte(o.value);break;case"replaygain_track_minmax":o.value=o.value.split(",").map(i=>Number.parseInt(i,10));break;case"replaygain_undo":{let i=o.value.split(",").map(e=>Number.parseInt(e,10));o.value={leftChannel:i[0],rightChannel:i[1]};break}case"gapless":case"compilation":case"podcast":case"showMovement":o.value=o.value==="1"||o.value===1;break;case"isrc":{let i=this.common[o.id];if(i&&i.indexOf(o.value)!==-1)return;break}case"comment":typeof o.value=="string"&&(o.value={text:o.value}),o.value.descriptor==="iTunPGAP"&&this.setGenericTag(t,{id:"gapless",value:o.value.text==="1"});break;case"lyrics":typeof o.value=="string"&&(o.value=ore(o.value));break;default:}o.value!==null&&this.setGenericTag(t,o)}toCommonMetadata(){return{format:this.format,native:this.native,quality:this.quality,common:this.common}}handleSingularArtistTag(t,o,i,e){if(this.commonOrigin[i]===this.originPriority[t])return this.postMap("artificial",{id:e,value:o.value});this.common[e]||this.setGenericTag("artificial",{id:e,value:o.value}),this.setGenericTag(t,o)}handlePluralArtistTag(t,o,i,e){if((!this.common[i]||this.commonOrigin[i]===this.originPriority.artificial)&&(!this.common[e]||this.common[e].indexOf(o.value)===-1)){let a=(this.common[e]||[]).concat([o.value]),A=qJe(a);this.setGenericTag("artificial",{id:i,value:A})}this.setGenericTag(t,o)}async postFixPicture(t){if(t.data&&t.data.length>0){if(!t.format){let o=await qB(Uint8Array.from(t.data));if(o)t.format=o.mime;else return null}switch(t.format=t.format.toLocaleLowerCase(),t.format){case"image/jpg":t.format="image/jpeg"}return t}return this.addWarning("Empty picture tag found"),null}async toCommon(t,o,i){let e={id:o,value:i},a=this.tagMapper.mapTag(t,e,this);a&&await this.postMap(t,a)}setGenericTag(t,o){Fl(`common.${o.id} = ${o.value}`);let i=this.commonOrigin[o.id]||1e3,e=this.originPriority[t];if(Jte(o.id))if(e<=i)this.common[o.id]=o.value,this.commonOrigin[o.id]=e;else return Fl(`Ignore native tag (singleton): ${t}.${o.id} = ${o.value}`);else if(e===i)!qte(o.id)||this.common[o.id].indexOf(o.value)===-1?this.common[o.id].push(o.value):Fl(`Ignore duplicate value: ${t}.${o.id} = ${o.value}`);else if(e{Rt=class{constructor(t,o,i){this.metadata=t,this.tokenizer=o,this.options=i}}});var zJe,at,si=ue(()=>{_s();Ar();er();zJe=/^[\x21-\x7e©][\x20-\x7e\x00()]{3}/,at={len:4,get:(n,t)=>{let o=wr(n.subarray(t,t+at.len),"latin1");if(!o.match(zJe))throw new Vo(`FourCC contains invalid characters: ${Yte(o)} "${o}"`);return o},put:(n,t,o)=>{let i=tte(o,"latin1");if(i.length!==4)throw new vl("Invalid length");return n.set(i,t),t+4}}});function Ire(n){return{containsHeader:cO(n,31),containsFooter:cO(n,30),isHeader:cO(n,29),readOnly:cO(n,0),dataType:(n&6)>>1}}function cO(n,t){return(n&1<{DA();si();VB={text_utf8:0,binary:1,external_info:2,reserved:3},qL={len:52,get:(n,t)=>({ID:at.get(n,t),version:Ge.get(n,t+4)/1e3,descriptorBytes:Ge.get(n,t+8),headerBytes:Ge.get(n,t+12),seekTableBytes:Ge.get(n,t+16),headerDataBytes:Ge.get(n,t+20),apeFrameDataBytes:Ge.get(n,t+24),apeFrameDataBytesHigh:Ge.get(n,t+28),terminatingDataBytes:Ge.get(n,t+32),fileMD5:new Dt(16).get(n,t+36)})},cre={len:24,get:(n,t)=>({compressionLevel:SA.get(n,t),formatFlags:SA.get(n,t+2),blocksPerFrame:Ge.get(n,t+4),finalFrameBlocks:Ge.get(n,t+8),totalFrames:Ge.get(n,t+12),bitsPerSample:SA.get(n,t+16),channel:SA.get(n,t+18),sampleRate:Ge.get(n,t+20)})},Ki={len:32,get:(n,t)=>({ID:new ze(8,"ascii").get(n,t),version:Ge.get(n,t+8),size:Ge.get(n,t+12),fields:Ge.get(n,t+16),flags:Ire(Ge.get(n,t+20))})},IO={len:8,get:(n,t)=>({size:Ge.get(n,t),flags:Ire(Ge.get(n,t+4))})}});var Ere={};Pr(Ere,{APEv2Parser:()=>iI,ApeContentError:()=>Nh,tryParseApeHeader:()=>Ll});function Ll(n,t,o){return new iI(n,t,o).tryParseApeHeader()}var hre,aI,pre,dre,Nh,iI,Ul=ue(()=>{hre=Je(ct(),1);so();DA();Ar();Hi();lre();er();_s();aI=(0,hre.default)("music-metadata:parser:APEv2"),pre="APEv2",dre="APETAGEX",Nh=class extends Qt("APEv2"){};iI=class n extends Rt{constructor(){super(...arguments),this.ape={}}static calculateDuration(t){let o=t.totalFrames>1?t.blocksPerFrame*(t.totalFrames-1):0;return o+=t.finalFrameBlocks,o/t.sampleRate}static async findApeFooterOffset(t,o){let i=new Uint8Array(Ki.len),e=t.position;if(o<=Ki.len){aI(`Offset is too small to read APE footer: offset=${o}`);return}if(o>Ki.len){await t.readBuffer(i,{position:o-Ki.len}),t.setPosition(e);let a=Ki.get(i,0);if(a.ID==="APETAGEX")return a.flags.isHeader?aI(`APE Header found at offset=${o-Ki.len}`):(aI(`APE Footer found at offset=${o-Ki.len}`),o-=a.size),{footer:a,offset:o}}}static parseTagFooter(t,o,i){let e=Ki.get(o,o.length-Ki.len);if(e.ID!==dre)throw new Nh("Unexpected APEv2 Footer ID preamble value");return no(o),new n(t,no(o),i).parseTags(e)}async tryParseApeHeader(){if(this.tokenizer.fileInfo.size&&this.tokenizer.fileInfo.size-this.tokenizer.position0?this.parseDescriptorExpansion(o):this.parseHeader());return this.metadata.setAudioOnly(),await this.tokenizer.ignore(i.forwardBytes),this.tryParseApeHeader()}async parseTags(t){let o=new Uint8Array(256),i=t.size-Ki.len;aI(`Parse APE tags at offset=${this.tokenizer.position}, size=${i}`);for(let e=0;ethis.metadata.addTag(pre,r,c)));break}case VB.binary:if(this.options.skipCovers)await this.tokenizer.ignore(a.size);else{let s=new Uint8Array(a.size);await this.tokenizer.readBuffer(s),A=Gs(s);let g=wr(s.subarray(0,A),"utf-8"),c=s.subarray(A+1);await this.metadata.addTag(pre,r,{description:g,data:c})}break;case VB.external_info:aI(`Ignore external info ${r}`),await this.tokenizer.ignore(a.size);break;case VB.reserved:aI(`Ignore external info ${r}`),this.metadata.addWarning(`APEv2 header declares a reserved datatype for "${r}"`),await this.tokenizer.ignore(a.size);break}}}async parseDescriptorExpansion(t){return await this.tokenizer.ignore(t),this.parseHeader()}async parseHeader(){let t=await this.tokenizer.readToken(cre);if(this.metadata.setFormat("lossless",!0),this.metadata.setFormat("container","Monkey's Audio"),this.metadata.setFormat("bitsPerSample",t.bitsPerSample),this.metadata.setFormat("sampleRate",t.sampleRate),this.metadata.setFormat("numberOfChannels",t.channel),this.metadata.setFormat("duration",n.calculateDuration(t)),!this.ape.descriptor)throw new Nh("Missing APE descriptor");return{forwardBytes:this.ape.descriptor.seekTableBytes+this.ape.descriptor.headerDataBytes+this.ape.descriptor.apeFrameDataBytes+this.ape.descriptor.terminatingDataBytes}}}});async function ure(n){if(n.fileInfo.size>=128){let t=new Uint8Array(3),o=n.position;return await n.readBuffer(t,{position:n.fileInfo.size-128}),n.setPosition(o),wr(t,"latin1")==="TAG"}return!1}var Cre,lO,Rh,pO,oI,dO,WB=ue(()=>{Cre=Je(ct(),1);DA();Ar();Hi();Ul();_s();lO=(0,Cre.default)("music-metadata:parser:ID3v1"),Rh=["Blues","Classic Rock","Country","Dance","Disco","Funk","Grunge","Hip-Hop","Jazz","Metal","New Age","Oldies","Other","Pop","R&B","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death Metal","Pranks","Soundtrack","Euro-Techno","Ambient","Trip-Hop","Vocal","Jazz+Funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound Clip","Gospel","Noise","Alt. Rock","Bass","Soul","Punk","Space","Meditative","Instrumental Pop","Instrumental Rock","Ethnic","Gothic","Darkwave","Techno-Industrial","Electronic","Pop-Folk","Eurodance","Dream","Southern Rock","Comedy","Cult","Gangsta Rap","Top 40","Christian Rap","Pop/Funk","Jungle","Native American","Cabaret","New Wave","Psychedelic","Rave","Showtunes","Trailer","Lo-Fi","Tribal","Acid Punk","Acid Jazz","Polka","Retro","Musical","Rock & Roll","Hard Rock","Folk","Folk/Rock","National Folk","Swing","Fast-Fusion","Bebob","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic Rock","Progressive Rock","Psychedelic Rock","Symphonic Rock","Slow Rock","Big Band","Chorus","Easy Listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber Music","Sonata","Symphony","Booty Bass","Primus","Porn Groove","Satire","Slow Jam","Club","Tango","Samba","Folklore","Ballad","Power Ballad","Rhythmic Soul","Freestyle","Duet","Punk Rock","Drum Solo","A Cappella","Euro-House","Dance Hall","Goa","Drum & Bass","Club-House","Hardcore","Terror","Indie","BritPop","Negerpunk","Polsk Punk","Beat","Christian Gangsta Rap","Heavy Metal","Black Metal","Crossover","Contemporary Christian","Christian Rock","Merengue","Salsa","Thrash Metal","Anime","JPop","Synthpop","Abstract","Art Rock","Baroque","Bhangra","Big Beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math Rock","New Romantic","Nu-Breakz","Post-Punk","Post-Rock","Psytrance","Shoegaze","Space Rock","Trop Rock","World Music","Neoclassical","Audiobook","Audio Theatre","Neue Deutsche Welle","Podcast","Indie Rock","G-Funk","Dubstep","Garage Rock","Psybient"],pO={len:128,get:(n,t)=>{let o=new oI(3).get(n,t);return o==="TAG"?{header:o,title:new oI(30).get(n,t+3),artist:new oI(30).get(n,t+33),album:new oI(30).get(n,t+63),year:new oI(4).get(n,t+93),comment:new oI(28).get(n,t+97),zeroByte:fA.get(n,t+127),track:fA.get(n,t+126),genre:fA.get(n,t+127)}:null}},oI=class{constructor(t){this.len=t,this.stringType=new ze(t,"latin1")}get(t,o){let i=this.stringType.get(t,o);return i=WD(i),i=i.trim(),i.length>0?i:void 0}},dO=class n extends Rt{constructor(t,o,i){super(t,o,i),this.apeHeader=i.apeHeader}static getGenre(t){if(tt){lO("Already consumed the last 128 bytes");return}let o=await this.tokenizer.readToken(pO,t);if(o){lO("ID3v1 header found at: pos=%s",this.tokenizer.fileInfo.size-pO.len);let i=["title","artist","album","comment","track","year"];for(let a of i)o[a]&&o[a]!==""&&await this.addTag(a,o[a]);let e=n.getGenre(o.genre);e&&await this.addTag("genre",e)}else lO("ID3v1 header not found at: pos=%s",this.tokenizer.fileInfo.size-pO.len)}async addTag(t,o){await this.metadata.addTag("ID3v1",t,o)}}});var zL,Bre=ue(()=>{DA();zL={len:16,get:(n,t)=>{let o=Ue.get(n,t+8),i=Ue.get(n,t+12);return{startTime:Ue.get(n,t),endTime:Ue.get(n,t+4),startOffset:o===4294967295?void 0:o,endOffset:i===4294967295?void 0:i}}}});function ZB(n){switch(n){case 2:return 6;case 3:case 4:return 10;default:throw fre(n)}}function VJe(n,t){return t===3?{status:{tag_alter_preservation:vA(n,0,7),file_alter_preservation:vA(n,0,6),read_only:vA(n,0,5)},format:{compression:vA(n,1,7),encryption:vA(n,1,6),grouping_identity:vA(n,1,5),unsynchronisation:!1,data_length_indicator:!1}}:{status:{tag_alter_preservation:vA(n,0,6),file_alter_preservation:vA(n,0,5),read_only:vA(n,0,4)},format:{grouping_identity:vA(n,1,6),compression:vA(n,1,3),encryption:vA(n,1,2),unsynchronisation:vA(n,1,1),data_length_indicator:vA(n,1,0)}}}function XB(n,t,o){switch(t){case 2:return WJe(n,t,o);case 3:case 4:return ZJe(n,t,o);default:throw fre(t)}}function WJe(n,t,o){let i={id:wr(n.subarray(0,3),"ascii"),length:kr.get(n,3)};return i.id.match(/^[A-Z0-9]{3}$/)||o.addWarning(`Invalid ID3v2.${t} frame-header-ID: ${i.id}`),i}function ZJe(n,t,o){let i={id:wr(n.subarray(0,4),"ascii"),length:(t===4?xL:Ue).get(n,4),flags:VJe(n.subarray(8,10),t)};return i.id.match(/^[A-Z0-9]{4}$/)||o.addWarning(`Invalid ID3v2.${t} frame-header-ID: ${i.id}`),i}function fre(n){throw new nI(`Unexpected majorVer: ${n}`)}var VL=ue(()=>{DA();Ar();Ug();_s();WL()});function XJe(n){let t=[],o,i="";for(let e of n)if(typeof o=="string")if(e==="("&&o==="")i+="(",o=void 0;else if(e===")"){i!==""&&(t.push(i),i="");let a=Qre(o);a&&t.push(a),o=void 0}else o+=e;else e==="("?o="":i+=e;return i&&(t.length===0&&i.match(/^\d*$/)&&(i=Qre(i)),i&&t.push(i)),t}function Qre(n){if(n==="RX")return"Remix";if(n==="CR")return"Cover";if(n.match(/^\d*$/))return Rh[Number.parseInt(n,10)]}function $Je(n){throw new nI(`Unexpected majorVer: ${n}`)}var yre,hO,Xo,ZL,EO,nI,WL=ue(()=>{yre=Je(ct(),1);DA();Ar();Ug();WB();er();Ar();Bre();VL();hO=(0,yre.default)("music-metadata:id3v2:frame-parser"),Xo="latin1",ZL={encoding:Xo,bom:!1};EO=class n{constructor(t,o){this.major=t,this.warningCollector=o}readData(t,o,i){if(t.length===0){this.warningCollector.addWarning(`id3v2.${this.major} header has empty tag type=${o}`);return}let{encoding:e,bom:a}=_h.get(t,0),A=t.length,r=0,s=[],g=n.getNullTerminatorLength(e),c;switch(hO(`Parsing tag type=${o}, encoding=${e}, bom=${a}`),o!=="TXXX"&&o[0]==="T"?"T*":o){case"T*":case"GRP1":case"GP1":case"IPLS":case"MVIN":case"MVNM":case"PCS":case"PCST":{let I;try{I=n.trimNullPadding(la(t.subarray(1),e))}catch(d){if(d instanceof Error){this.warningCollector.addWarning(`id3v2.${this.major} type=${o} header has invalid string value: ${d.message}`);break}throw d}switch(o){case"TMCL":case"TIPL":case"IPLS":s=n.functionList(this.splitValue(o,I));break;case"TRK":case"TRCK":case"TPOS":case"TIT1":case"TIT2":case"TIT3":s=I;break;case"TCOM":case"TEXT":case"TOLY":case"TOPE":case"TPE1":case"TSRC":s=this.splitValue(o,I);break;case"TCO":case"TCON":s=this.splitValue(o,I).map(d=>XJe(d)).reduce((d,B)=>d.concat(B),[]);break;case"PCS":case"PCST":s=this.major>=4?this.splitValue(o,I):[I],s=Array.isArray(s)&&s[0]===""?1:0;break;default:s=this.major>=4?this.splitValue(o,I):[I]}break}case"TXXX":{let I=n.readIdentifierAndData(t.subarray(1),e);s={description:I.id,text:this.splitValue(o,la(I.data,e).replace(/\x00+$/,""))};break}case"PIC":case"APIC":if(i){let I={};switch(t=t.subarray(1),this.major){case 2:I.format=la(t.subarray(0,3),"latin1"),t=t.subarray(3);break;case 3:case 4:c=Gs(t,Xo),I.format=la(t.subarray(0,c),Xo),t=t.subarray(c+1);break;default:throw $Je(this.major)}I.format=n.fixPictureMimeType(I.format),I.type=Oh[t[0]],t=t.subarray(1),c=Gs(t,e),I.description=la(t.subarray(0,c),e),t=t.subarray(c+g),I.data=t,s=I}break;case"CNT":case"PCNT":s=KL(t);break;case"SYLT":{let I=jL.get(t,0);t=t.subarray(jL.len);let d={descriptor:"",language:I.language,contentType:I.contentType,timeStampFormat:I.timeStampFormat,syncText:[]},B=!1;for(;t.length>0;){let f=n.readNullTerminatedString(t,I.encoding);if(t=t.subarray(f.len),B){let Q=Ue.get(t,0);t=t.subarray(Ue.len),d.syncText.push({text:f.text,timestamp:Q})}else d.descriptor=f.text,B=!0}s=d;break}case"ULT":case"USLT":case"COM":case"COMM":{let I=ZD.get(t,r);r+=ZD.len;let d=n.readNullTerminatedString(t.subarray(r),I.encoding);r+=d.len;let B=n.readNullTerminatedString(t.subarray(r),I.encoding);s={language:I.language,descriptor:d.text,text:B.text};break}case"UFID":{let I=n.readIdentifierAndData(t,Xo);s={owner_identifier:I.id,identifier:I.data};break}case"PRIV":{let I=n.readIdentifierAndData(t,Xo);s={owner_identifier:I.id,data:I.data};break}case"POPM":{t=t.subarray(r);let I=n.readNullTerminatedString(t,ZL),d=I.text;if(t=t.subarray(I.len),t.length===0){this.warningCollector.addWarning(`id3v2.${this.major} type=${o} POPM frame missing rating byte`),s={email:d,rating:0,counter:void 0};break}let B=fA.get(t,0),f=t.subarray(fA.len);s={email:d,rating:B,counter:f.length>0?KL(f):void 0};break}case"GEOB":{let I=_h.get(t,0);t=t.subarray(1);let d=n.readNullTerminatedString(t,ZL),B=d.text;t=t.subarray(d.len);let f=n.readNullTerminatedString(t,I),Q=f.text;t=t.subarray(f.len);let y=n.readNullTerminatedString(t,I),m=y.text;t=t.subarray(y.len),s={type:B,filename:Q,description:m,data:t};break}case"WCOM":case"WCOP":case"WOAF":case"WOAR":case"WOAS":case"WORS":case"WPAY":case"WPUB":s=n.readNullTerminatedString(t,ZL).text;break;case"WXXX":{let I=_h.get(t,0);t=t.subarray(1);let d=n.readNullTerminatedString(t,I),B=d.text;t=t.subarray(d.len),s={description:B,url:n.trimNullPadding(la(t,Xo))};break}case"WFD":case"WFED":{let I=_h.get(t,0);t=t.subarray(1),s=n.readNullTerminatedString(t,I).text;break}case"MCDI":{s=t.subarray(0,A);break}case"CHAP":{hO("Reading CHAP"),c=Gs(t,Xo);let I={label:la(t.subarray(0,c),Xo),info:zL.get(t,c+1),frames:new Map};for(r+=c+1+zL.len;r=a.length)return{text:la(t,o.encoding),len:e};let r=t.subarray(0,i+A);return{text:la(r,o.encoding),len:i+A+n.getNullTerminatorLength(o.encoding)}}static fixPictureMimeType(t){switch(t=t.toLocaleLowerCase(),t){case"jpg":return"image/jpeg";case"png":return"image/png"}return t}static functionList(t){let o={};for(let i=0;i+11?this.warningCollector.addWarning(`ID3v2.${this.major} ${t} uses non standard null-separator.`):i=o.split(/\//g)):i=o.split(/\x00/g),n.trimArray(i)}static trimArray(t){return t.map(o=>n.trimNullPadding(o).trim())}static trimNullPadding(t){let o=t.length;for(;o>0&&t.charCodeAt(o-1)===0;)o--;return o===t.length?t:t.slice(0,o)}static readIdentifierAndData(t,o){let i=n.readNullTerminatedString(t,{encoding:o,bom:!1});return{id:i.text,data:t.subarray(i.len)}}static getNullTerminatorLength(t){return t.startsWith("utf-16")?2:1}},nI=class extends Qt("id3v2"){}});function eqe(n){throw new nI(`Unexpected majorVer: ${n}`)}var $o,kh=ue(()=>{DA();WL();Ug();VL();$o=class n{constructor(){this.tokenizer=void 0,this.id3Header=void 0,this.metadata=void 0,this.headerType=void 0,this.options=void 0}static removeUnsyncBytes(t){let o=0,i=0;for(;o0?this.parseExtendedHeaderData(o,t.size):this.parseId3Data(this.id3Header.size-t.size)}async parseExtendedHeaderData(t,o){return await this.tokenizer.ignore(t),this.parseId3Data(this.id3Header.size-o)}async parseId3Data(t){let o=await this.tokenizer.readToken(new Dt(t));for(let i of this.parseMetadata(o))switch(i.id){case"TXXX":i.value&&await this.handleTag(i,i.value.text,()=>i.value.description);break;default:await(Array.isArray(i.value)?Promise.all(i.value.map(e=>this.addTag(i.id,e))):this.addTag(i.id,i.value))}}async handleTag(t,o,i,e=a=>a){await Promise.all(o.map(a=>this.addTag(n.makeDescriptionTagName(t.id,i(a)),e(a))))}async addTag(t,o){await this.metadata.addTag(this.headerType,t,o)}parseMetadata(t){let o=0,i=[];for(;o!==t.length;){let e=ZB(this.id3Header.version.major);if(o+e>t.length){this.metadata.addWarning("Illegal ID3v2 tag length");break}let a=t.subarray(o,o+e);o+=e;let A=XB(a,this.id3Header.version.major,this.metadata),r=t.subarray(o,o+A.length);o+=A.length;let s=n.readFrameData(r,A,this.id3Header.version.major,!this.options.skipCovers,this.metadata);s&&i.push({id:A.id,value:s})}return i}static mapId3v2Chapters(t){if(!t)return;let o=t.filter(g=>g.id==="CHAP");if(!o?.length)return;let e=t.filter(g=>g.id==="CTOC")?.find(g=>g.value.flags?.topLevel),a=new Map;for(let g of o)a.set(g.value.label,g.value);let A=e?.value.childElementIds,r=[],s=A??[...a.keys()];for(let g of s){let c=a.get(g);if(!c)continue;let I=c.frames,d=I.get("TIT2");d&&r.push({id:g,title:d,url:I.get("WXXX"),start:c.info.startTime/1e3,end:c.info.endTime/1e3,image:I.get("APIC")})}return A||r.sort((g,c)=>g.start-c.start),r.length?r:void 0}}});var mre,XL,Fs,$B=ue(()=>{so();mre=Je(ct(),1);Ug();kh();WB();Hi();XL=(0,mre.default)("music-metadata:parser:ID3"),Fs=class extends Rt{constructor(){super(...arguments),this.id3parser=new $o}static async startsWithID3v2Header(t){return(await t.peekToken(Pl)).fileIdentifier==="ID3"}async parse(){try{await this.parseID3v2()}catch(t){if(t instanceof bA)XL("End-of-stream");else throw t}}finalize(){}async parseID3v2(){await this.tryReadId3v2Headers(),XL("End of ID3v2 header, go to MPEG-parser: pos=%s",this.tokenizer.position),await this.postId3v2Parse(),this.options.skipPostHeaders&&this.metadata.hasAny()?this.finalize():(await new dO(this.metadata,this.tokenizer,this.options).parse(),this.finalize())}async tryReadId3v2Headers(){if((await this.tokenizer.peekToken(Pl)).fileIdentifier==="ID3")return XL("Found ID3v2 header, pos=%s",this.tokenizer.position),await this.id3parser.parse(this.metadata,this.tokenizer,this.options),this.tryReadId3v2Headers()}}});var $L,Sre=ue(()=>{Ar();$L={len:2,get:(n,t)=>{let o=XA(n,t,0,3),i=XA(n,t,6,1),e=XA(n,t,7,9)/10;if(o>0)return{type:XA(n,t,0,3),origin:XA(n,t,3,3),adjustment:i?-e:e}}}});var wre,Dre=ue(()=>{DA();Ar();Sre();wre={len:27,get:(n,t)=>{let o=Ue.get(n,t+2);return{revision:XA(n,t,0,4),vbr_method:XA(n,t,4,4),lowpass_filter:100*fA.get(n,t+1),track_peak:o===0?null:o/2**23,track_gain:$L.get(n,6),album_gain:$L.get(n,8),music_length:Ue.get(n,t+20),music_crc:fA.get(n,t+24),header_crc:GA.get(n,t+24)}}}});async function Ore(n){let t=await n.readToken(Aqe),o={numFrames:null,streamSize:null,vbrScale:null};if(t.frames&&(o.numFrames=await n.readToken(Ue)),t.bytes&&(o.streamSize=await n.readToken(Ue)),t.toc&&(o.toc=new Uint8Array(100),await n.readBuffer(o.toc)),t.vbrScale&&(o.vbrScale=await n.readToken(Ue)),await n.peekToken(new ze(4,"ascii"))==="LAME"){await n.ignore(4),o.lame={version:await n.readToken(new ze(5,"ascii"))};let e=o.lame.version.match(/\d+.\d+/g);if(e!==null){let A=e[0].split(".").map(r=>Number.parseInt(r,10));A[0]>=3&&A[1]>=90&&(o.lame.extended=await n.readToken(wre))}}return o}var e2,CO,Aqe,bre=ue(()=>{DA();Ar();Dre();e2=new ze(4,"ascii"),CO=new ze(6,"ascii"),Aqe={len:4,get:(n,t)=>({frames:Da(n,t,31),bytes:Da(n,t,30),toc:Da(n,t,29),vbrScale:Da(n,t,28)})}});var Rre={};Pr(Rre,{MpegContentError:()=>Hl,MpegParser:()=>A2});function rqe(n){return`V${Math.floor((100-n)/10)}`}var Nre,go,Hl,Mre,_re,tqe,co,Tre,A2,kre=ue(()=>{DA();so();Nre=Je(ct(),1);Ar();$B();bre();er();go=(0,Nre.default)("music-metadata:parser:mpeg"),Hl=class extends Qt("MPEG"){},Mre=1024,_re={AudioObjectTypes:["AAC Main","AAC LC","AAC SSR","AAC LTP"],SamplingFrequencies:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350,null,null,null]},tqe=[void 0,["front-center"],["front-left","front-right"],["front-center","front-left","front-right"],["front-center","front-left","front-right","back-center"],["front-center","front-left","front-right","back-left","back-right"],["front-center","front-left","front-right","back-left","back-right","LFE-channel"],["front-center","front-left","front-right","side-left","side-right","back-left","back-right","LFE-channel"]],co=class n{constructor(t,o){this.bitrateIndex=null,this.sampRateFreqIndex=null,this.padding=null,this.privateBit=null,this.channelModeIndex=null,this.modeExtension=null,this.isOriginalMedia=null,this.version=null,this.bitrate=null,this.samplingRate=null,this.frameLength=0,this.versionIndex=XA(t,o+1,3,2),this.layer=n.LayerDescription[XA(t,o+1,5,2)],this.versionIndex>1&&this.layer===0?this.parseAdtsHeader(t,o):this.parseMpegHeader(t,o),this.isProtectedByCRC=!Da(t,o+1,7)}calcDuration(t){return this.samplingRate==null?null:t*this.calcSamplesPerFrame()/this.samplingRate}calcSamplesPerFrame(){return n.samplesInFrameTable[this.version===1?0:1][this.layer]}calculateSideInfoLength(){if(this.layer!==3)return 2;if(this.channelModeIndex===3){if(this.version===1)return 17;if(this.version===2||this.version===2.5)return 9}else{if(this.version===1)return 32;if(this.version===2||this.version===2.5)return 17}return null}calcSlotSize(){return[null,4,1,1][this.layer]}parseMpegHeader(t,o){this.container="MPEG",this.bitrateIndex=XA(t,o+2,0,4),this.sampRateFreqIndex=XA(t,o+2,4,2),this.padding=Da(t,o+2,6),this.privateBit=Da(t,o+2,7),this.channelModeIndex=XA(t,o+3,0,2),this.modeExtension=XA(t,o+3,2,2),this.isCopyrighted=Da(t,o+3,4),this.isOriginalMedia=Da(t,o+3,5),this.emphasis=XA(t,o+3,7,2),this.version=n.VersionID[this.versionIndex],this.channelMode=n.ChannelMode[this.channelModeIndex],this.codec=`MPEG ${this.version} Layer ${this.layer}`;let i=this.calcBitrate();if(!i)throw new Hl("Cannot determine bit-rate");if(this.bitrate=i*1e3,this.samplingRate=this.calcSamplingRate(),this.samplingRate==null)throw new Hl("Cannot determine sampling-rate")}parseAdtsHeader(t,o){go("layer=0 => ADTS"),this.version=this.versionIndex===2?4:2,this.container=`ADTS/MPEG-${this.version}`;let i=XA(t,o+2,0,2);this.codec="AAC",this.codecProfile=_re.AudioObjectTypes[i],go(`MPEG-4 audio-codec=${this.codec}`);let e=XA(t,o+2,2,4);this.samplingRate=_re.SamplingFrequencies[e],go(`sampling-rate=${this.samplingRate}`);let a=XA(t,o+2,7,3);this.mp4ChannelConfig=tqe[a],go(`channel-config=${this.mp4ChannelConfig?this.mp4ChannelConfig.join("+"):"?"}`),this.frameLength=XA(t,o+3,6,2)<<11}calcBitrate(){if(this.bitrateIndex===0||this.bitrateIndex===15)return null;if(this.version&&this.bitrateIndex){let t=10*Math.floor(this.version)+this.layer;return n.bitrate_index[this.bitrateIndex][t]}return null}calcSamplingRate(){return this.sampRateFreqIndex===3||this.version===null||this.sampRateFreqIndex==null?null:n.sampling_rate_freq_index[this.version][this.sampRateFreqIndex]}};co.SyncByte1=255;co.SyncByte2=224;co.VersionID=[2.5,null,2,1];co.LayerDescription=[0,3,2,1];co.ChannelMode=["stereo","joint_stereo","dual_channel","mono"];co.bitrate_index={1:{11:32,12:32,13:32,21:32,22:8,23:8},2:{11:64,12:48,13:40,21:48,22:16,23:16},3:{11:96,12:56,13:48,21:56,22:24,23:24},4:{11:128,12:64,13:56,21:64,22:32,23:32},5:{11:160,12:80,13:64,21:80,22:40,23:40},6:{11:192,12:96,13:80,21:96,22:48,23:48},7:{11:224,12:112,13:96,21:112,22:56,23:56},8:{11:256,12:128,13:112,21:128,22:64,23:64},9:{11:288,12:160,13:128,21:144,22:80,23:80},10:{11:320,12:192,13:160,21:160,22:96,23:96},11:{11:352,12:224,13:192,21:176,22:112,23:112},12:{11:384,12:256,13:224,21:192,22:128,23:128},13:{11:416,12:320,13:256,21:224,22:144,23:144},14:{11:448,12:384,13:320,21:256,22:160,23:160}};co.sampling_rate_freq_index={1:{0:44100,1:48e3,2:32e3},2:{0:22050,1:24e3,2:16e3},2.5:{0:11025,1:12e3,2:8e3}};co.samplesInFrameTable=[[0,384,1152,1152],[0,384,1152,576]];Tre={len:4,get:(n,t)=>new co(n,t)};A2=class extends Fs{constructor(){super(...arguments),this.frameCount=0,this.syncFrameCount=-1,this.totalDataLength=0,this.bitrates=[],this.offset=0,this.frame_size=0,this.calculateEofDuration=!1,this.samplesPerFrame=null,this.buf_frame_header=new Uint8Array(4),this.mpegOffset=null,this.syncPeek={buf:new Uint8Array(Mre),len:0}}async postId3v2Parse(){this.metadata.setFormat("lossless",!1),this.metadata.setAudioOnly();try{let t=!1;for(;!t;)await this.sync(),t=await this.parseCommonMpegHeader()}catch(t){if(t instanceof bA){if(go("End-of-stream"),this.calculateEofDuration&&this.samplesPerFrame!==null){let o=this.frameCount*this.samplesPerFrame;if(this.metadata.setFormat("numberOfSamples",o),this.metadata.format.sampleRate){let i=o/this.metadata.format.sampleRate;go(`Calculate duration at EOF: ${i} sec.`,i),this.metadata.setFormat("duration",i)}}}else throw t}}finalize(){let t=this.metadata.format,o=!!this.metadata.native.ID3v1;if(this.mpegOffset!==null){if(t.duration&&this.tokenizer.fileInfo.size){let i=this.tokenizer.fileInfo.size-this.mpegOffset-(o?128:0);t.codecProfile&&t.codecProfile[0]==="V"&&this.metadata.setFormat("bitrate",i*8/t.duration)}if(this.tokenizer.fileInfo.size&&t.codecProfile==="CBR"){let i=this.tokenizer.fileInfo.size-this.mpegOffset-(o?128:0);if(this.frame_size!==null&&this.samplesPerFrame!==null){let e=Math.round(i/this.frame_size)*this.samplesPerFrame;if(this.metadata.setFormat("numberOfSamples",e),t.sampleRate&&!t.duration){let a=e/t.sampleRate;go("Calculate CBR duration based on file size: %s",a),this.metadata.setFormat("duration",a)}}}}}async sync(){let t=!1;for(;;){let o=0;if(this.syncPeek.len=await this.tokenizer.peekBuffer(this.syncPeek.buf,{length:Mre,mayBeLess:!0}),this.syncPeek.len<=163)throw new bA;for(;;){if(t&&(this.syncPeek.buf[o]&224)===224){this.buf_frame_header[0]=co.SyncByte1,this.buf_frame_header[1]=this.syncPeek.buf[o],await this.tokenizer.ignore(o),go(`Sync at offset=${this.tokenizer.position-1}, frameCount=${this.frameCount}`),this.syncFrameCount===this.frameCount&&(go(`Re-synced MPEG stream, frameCount=${this.frameCount}`),this.frameCount=0,this.frame_size=0),this.syncFrameCount=this.frameCount;return}if(t=!1,o=this.syncPeek.buf.indexOf(co.SyncByte1,o),o===-1){if(this.syncPeek.len=2&&t.layer===0?this.parseAdts(t):this.parseAudioFrameHeader(t)}async parseAudioFrameHeader(t){this.metadata.setFormat("numberOfChannels",t.channelMode==="mono"?1:2),this.metadata.setFormat("bitrate",t.bitrate),this.frameCount<20*1e4&&go("offset=%s MP%s bitrate=%s sample-rate=%s",this.tokenizer.position-4,t.layer,t.bitrate,t.samplingRate);let o=t.calcSlotSize();if(o===null)throw new Hl("invalid slot_size");let i=t.calcSamplesPerFrame();go(`samples_per_frame=${i}`);let e=i/8;if(t.bitrate!==null&&t.samplingRate!=null){let a=e*t.bitrate/t.samplingRate+(t.padding?o:0);this.frame_size=Math.floor(a)}if(this.audioFrameHeader=t,t.bitrate!==null&&this.bitrates.push(t.bitrate),this.frameCount===1)return this.offset=Tre.len,await this.skipSideInformation(),!1;if(this.frameCount===4){if(this.areAllSame(this.bitrates)){if(this.samplesPerFrame=i,this.metadata.setFormat("codecProfile","CBR"),this.tokenizer.fileInfo.size)return!0}else if(this.metadata.format.duration)return!0;if(!this.options.duration)return!0}return this.options.duration&&this.frameCount===4&&(this.samplesPerFrame=i,this.calculateEofDuration=!0),this.offset=4,t.isProtectedByCRC?(await this.parseCrc(),!1):(await this.skipSideInformation(),!1)}async parseAdts(t){let o=new Uint8Array(3);if(await this.tokenizer.readBuffer(o),t.frameLength+=XA(o,0,0,11),this.totalDataLength+=t.frameLength,this.samplesPerFrame=1024,t.samplingRate!==null){let i=t.samplingRate/this.samplesPerFrame,a=8*(this.frameCount===0?0:this.totalDataLength/this.frameCount)*i+.5;this.metadata.setFormat("bitrate",a),go(`frame-count=${this.frameCount}, size=${t.frameLength} bytes, bit-rate=${a}`)}if(await this.tokenizer.ignore(t.frameLength>7?t.frameLength-7:1),this.frameCount===3)if(this.metadata.setFormat("codecProfile",t.codecProfile),t.mp4ChannelConfig&&this.metadata.setFormat("numberOfChannels",t.mp4ChannelConfig.length),this.options.duration)this.calculateEofDuration=!0;else return!0;return!1}async parseCrc(){return await this.tokenizer.ignore(qo.len),this.offset+=qo.len,this.skipSideInformation()}async skipSideInformation(){if(this.audioFrameHeader){let t=this.audioFrameHeader.calculateSideInfoLength();if(t!==null){await this.tokenizer.readToken(new Dt(t)),this.offset+=t,await this.readXtraInfoHeader();return}}}async readXtraInfoHeader(){let t=await this.tokenizer.readToken(e2);switch(this.offset+=e2.len,t){case"Info":return this.metadata.setFormat("codecProfile","CBR"),this.readXingInfoHeader();case"Xing":{let i=await this.readXingInfoHeader();if(i.vbrScale!==null){let e=rqe(i.vbrScale);this.metadata.setFormat("codecProfile",e)}return null}case"Xtra":break;case"LAME":{let i=await this.tokenizer.readToken(CO);if(this.frame_size!==null&&this.frame_size>=this.offset+CO.len)return this.offset+=CO.len,this.metadata.setFormat("tool",`LAME ${i}`),await this.skipFrameData(this.frame_size-this.offset),null;this.metadata.addWarning("Corrupt LAME header");break}}let o=this.frame_size-this.offset;return o<0?this.metadata.addWarning(`Frame ${this.frameCount}corrupt: negative frameDataLeft`):await this.skipFrameData(o),null}async readXingInfoHeader(){let t=this.tokenizer.position,o=await Ore(this.tokenizer);if(this.offset+=this.tokenizer.position-t,o.lame&&(this.metadata.setFormat("tool",`LAME ${Wo(o.lame.version)}`),o.lame.extended&&(this.metadata.setFormat("trackPeakLevel",o.lame.extended.track_peak),o.lame.extended.track_gain&&this.metadata.setFormat("trackGain",o.lame.extended.track_gain.adjustment),o.lame.extended.album_gain&&this.metadata.setFormat("albumGain",o.lame.extended.album_gain.adjustment),this.metadata.setFormat("duration",o.lame.extended.music_length/1e3))),o.streamSize&&this.audioFrameHeader&&o.numFrames!==null){let e=this.audioFrameHeader.calcDuration(o.numFrames);return this.metadata.setFormat("duration",e),go("Get duration from Xing header: %s",this.metadata.format.duration),o}let i=this.frame_size-this.offset;return await this.skipFrameData(i),o}async skipFrameData(t){if(t<0)throw new Hl("frame-data-left cannot be negative");await this.tokenizer.ignore(t)}areAllSame(t){let o=t[0];return t.every(i=>i===o)}}});var vre,Pre=ue(()=>{vre={parserType:"mpeg",extensions:[".mp2",".mp3",".m2a",".aac","aacp"],mimeTypes:["audio/mpeg","audio/mp3","audio/aacs","audio/aacp"],async load(){return(await Promise.resolve().then(()=>(kre(),Rre))).MpegParser}}});var Gre,Fre=ue(()=>{Gre={parserType:"apev2",extensions:[".ape"],mimeTypes:["audio/ape","audio/monkeys-audio"],async load(){return(await Promise.resolve().then(()=>(Ul(),Ere))).APEv2Parser}}});function t2(n){let t=n.trim();if(t.length!==36||t[8]!=="-"||t[13]!=="-"||t[18]!=="-"||t[23]!=="-")throw new Error(`Invalid GUID format: ${n}`);let o,i=new Uint8Array(16);o=parseInt(t.slice(0,8),16),i[0]=o&255,i[1]=o>>>8&255,i[2]=o>>>16&255,i[3]=o>>>24&255,o=parseInt(t.slice(9,13),16),i[4]=o&255,i[5]=o>>>8&255,o=parseInt(t.slice(14,18),16),i[6]=o&255,i[7]=o>>>8&255,o=parseInt(t.slice(19,23),16),i[8]=o>>>8&255,i[9]=o&255,o=parseInt(t.slice(24,32),16),i[10]=o>>>24&255,i[11]=o>>>16&255,i[12]=o>>>8&255,i[13]=o&255,o=parseInt(t.slice(32,36),16),i[14]=o>>>8&255,i[15]=o&255;for(let e=0;e<16;e++)if(!Number.isFinite(i[e]))throw new Error(`Invalid GUID format: ${n}`);if(!/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(t))throw new Error(`Invalid GUID format: ${n}`);return i}var uO,Lre=ue(()=>{uO=class n{constructor(t){if(t.length!==16)throw new Error("GUID must be exactly 16 bytes");this.bytes=t}static fromString(t){return new n(t2(t))}toString(){let t=this.bytes,o=s=>s.toString(16).padStart(2,"0"),i=o(t[3])+o(t[2])+o(t[1])+o(t[0]),e=o(t[5])+o(t[4]),a=o(t[7])+o(t[6]),A=o(t[8])+o(t[9]),r=o(t[10])+o(t[11])+o(t[12])+o(t[13])+o(t[14])+o(t[15]);return`${i}-${e}-${a}-${A}-${r}`.toUpperCase()}equals(t,o=0){if(o<0||t.length-o<16)return!1;let i=this.bytes;for(let e=0;e<16;e++)if(t[o+e]!==i[e])return!1;return!0}}});var xe,cr,r2=ue(()=>{Lre();xe=class n{static fromBin(t,o=0){return new n(n.decode(t,o))}static decode(t,o=0){return new uO(t.subarray(o,o+16)).toString()}static decodeMediaType(t){switch(t.str){case n.AudioMedia.str:return"audio";case n.VideoMedia.str:return"video";case n.CommandMedia.str:return"command";case n.Degradable_JPEG_Media.str:return"degradable-jpeg";case n.FileTransferMedia.str:return"file-transfer";case n.BinaryMedia.str:return"binary"}}static encode(t){return t2(t)}constructor(t){this.str=t}equals(t){return this.str===t.str}toBin(){return n.encode(this.str)}};xe.HeaderObject=new xe("75B22630-668E-11CF-A6D9-00AA0062CE6C");xe.DataObject=new xe("75B22636-668E-11CF-A6D9-00AA0062CE6C");xe.SimpleIndexObject=new xe("33000890-E5B1-11CF-89F4-00A0C90349CB");xe.IndexObject=new xe("D6E229D3-35DA-11D1-9034-00A0C90349BE");xe.MediaObjectIndexObject=new xe("FEB103F8-12AD-4C64-840F-2A1D2F7AD48C");xe.TimecodeIndexObject=new xe("3CB73FD0-0C4A-4803-953D-EDF7B6228F0C");xe.FilePropertiesObject=new xe("8CABDCA1-A947-11CF-8EE4-00C00C205365");xe.StreamPropertiesObject=new xe("B7DC0791-A9B7-11CF-8EE6-00C00C205365");xe.HeaderExtensionObject=new xe("5FBF03B5-A92E-11CF-8EE3-00C00C205365");xe.CodecListObject=new xe("86D15240-311D-11D0-A3A4-00A0C90348F6");xe.ScriptCommandObject=new xe("1EFB1A30-0B62-11D0-A39B-00A0C90348F6");xe.MarkerObject=new xe("F487CD01-A951-11CF-8EE6-00C00C205365");xe.BitrateMutualExclusionObject=new xe("D6E229DC-35DA-11D1-9034-00A0C90349BE");xe.ErrorCorrectionObject=new xe("75B22635-668E-11CF-A6D9-00AA0062CE6C");xe.ContentDescriptionObject=new xe("75B22633-668E-11CF-A6D9-00AA0062CE6C");xe.ExtendedContentDescriptionObject=new xe("D2D0A440-E307-11D2-97F0-00A0C95EA850");xe.ContentBrandingObject=new xe("2211B3FA-BD23-11D2-B4B7-00A0C955FC6E");xe.StreamBitratePropertiesObject=new xe("7BF875CE-468D-11D1-8D82-006097C9A2B2");xe.ContentEncryptionObject=new xe("2211B3FB-BD23-11D2-B4B7-00A0C955FC6E");xe.ExtendedContentEncryptionObject=new xe("298AE614-2622-4C17-B935-DAE07EE9289C");xe.DigitalSignatureObject=new xe("2211B3FC-BD23-11D2-B4B7-00A0C955FC6E");xe.PaddingObject=new xe("1806D474-CADF-4509-A4BA-9AABCB96AAE8");xe.ExtendedStreamPropertiesObject=new xe("14E6A5CB-C672-4332-8399-A96952065B5A");xe.AdvancedMutualExclusionObject=new xe("A08649CF-4775-4670-8A16-6E35357566CD");xe.GroupMutualExclusionObject=new xe("D1465A40-5A79-4338-B71B-E36B8FD6C249");xe.StreamPrioritizationObject=new xe("D4FED15B-88D3-454F-81F0-ED5C45999E24");xe.BandwidthSharingObject=new xe("A69609E6-517B-11D2-B6AF-00C04FD908E9");xe.LanguageListObject=new xe("7C4346A9-EFE0-4BFC-B229-393EDE415C85");xe.MetadataObject=new xe("C5F8CBEA-5BAF-4877-8467-AA8C44FA4CCA");xe.MetadataLibraryObject=new xe("44231C94-9498-49D1-A141-1D134E457054");xe.IndexParametersObject=new xe("D6E229DF-35DA-11D1-9034-00A0C90349BE");xe.MediaObjectIndexParametersObject=new xe("6B203BAD-3F11-48E4-ACA8-D7613DE2CFA7");xe.TimecodeIndexParametersObject=new xe("F55E496D-9797-4B5D-8C8B-604DFE9BFB24");xe.CompatibilityObject=new xe("26F18B5D-4584-47EC-9F5F-0E651F0452C9");xe.AdvancedContentEncryptionObject=new xe("43058533-6981-49E6-9B74-AD12CB86D58C");xe.AudioMedia=new xe("F8699E40-5B4D-11CF-A8FD-00805F5C442B");xe.VideoMedia=new xe("BC19EFC0-5B4D-11CF-A8FD-00805F5C442B");xe.CommandMedia=new xe("59DACFC0-59E6-11D0-A3AC-00A0C90348F6");xe.JFIF_Media=new xe("B61BE100-5B4E-11CF-A8FD-00805F5C442B");xe.Degradable_JPEG_Media=new xe("35907DE0-E415-11CF-A917-00805F5C442B");xe.FileTransferMedia=new xe("91BD222C-F21C-497A-8B6D-5AA86BFC0185");xe.BinaryMedia=new xe("3AFB65E2-47EF-40F2-AC2C-70A90D71D343");xe.ASF_Index_Placeholder_Object=new xe("D9AADE20-7C17-4F9C-BC28-8555DD98E2A2");cr=xe});function Hre(n){return aqe[n]}function ef(n){return Wo(la(n,"utf-16le"))}function Ure(n){return new Uint8Array(n)}function iqe(n,t=0){return Kre(n,t)===1}function oqe(n,t=0){return Ge.get(n,t)}function nqe(n,t=0){return Dr.get(n,t)}function Kre(n,t=0){return SA.get(n,t)}var aqe,xre=ue(()=>{DA();Ar();aqe=[ef,Ure,iqe,oqe,nqe,Kre,Ure]});async function Yre(n){let t=await n.readNumber(SA);return(await n.readToken(new ze(t*2,"utf-16le"))).replace("\0","")}async function jre(n,t){let o=new a2(n,t),i=await o.readToken(sqe),e=[];for(let a=0;a{DA();Ar();r2();xre();Ug();er();vr=class extends Qt("ASF"){},BO={len:30,get:(n,t)=>{let o=Yl.get(n,t);if(o.objectSize{let o=Dr.get(n,t+16);if(oBigInt(Number.MAX_SAFE_INTEGER))throw new vr(`Invalid ASF header object size: ${o}`);return{objectId:cr.fromBin(n,t),objectSize:Number(o)}}},sI=class{constructor(t){this.len=t.objectSize-Yl.len}postProcessTag(t,o,i,e){if(o==="WM/Picture")t.push({id:o,value:i2.fromBuffer(e)});else{let a=Hre(i);if(!a)throw new vr(`unexpected value headerType: ${i}`);t.push({id:o,value:a(e)})}}},vh=class extends sI{get(t,o){return{fileId:cr.fromBin(t,o),fileSize:Dr.get(t,o+16),creationDate:Dr.get(t,o+24),dataPacketsCount:Dr.get(t,o+32),playDuration:Dr.get(t,o+40),sendDuration:Dr.get(t,o+48),preroll:Dr.get(t,o+56),flags:{broadcast:vA(t,o+64,24),seekable:vA(t,o+64,25)},minimumDataPacketSize:Ge.get(t,o+68),maximumDataPacketSize:Ge.get(t,o+72),maximumBitrate:Ge.get(t,o+76)}}};vh.guid=cr.FilePropertiesObject;Ph=class extends sI{get(t,o){return{streamType:cr.decodeMediaType(cr.fromBin(t,o)),errorCorrectionType:cr.fromBin(t,o+8)}}};Ph.guid=cr.StreamPropertiesObject;Gh=class{constructor(){this.len=22}get(t,o){let i=new DataView(t.buffer,o);return{reserved1:cr.fromBin(t,o),reserved2:i.getUint16(16,!0),extensionDataSize:i.getUint32(18,!0)}}};Gh.guid=cr.HeaderExtensionObject;sqe={len:20,get:(n,t)=>({entryCount:new DataView(n.buffer,t).getUint16(16,!0)})},a2=class{constructor(t,o){this.tokenizer=t,this.remaining=o}async readToken(t){this.ensureAvailable(t.len);let o=await this.tokenizer.readToken(t);return this.remaining-=t.len,o}async readNumber(t){return this.readToken(t)}async readBuffer(t){this.ensureAvailable(t);let o=new Uint8Array(t);return await this.tokenizer.readBuffer(o),this.remaining-=t,o}async ignoreRemaining(){let t=await this.tokenizer.ignore(this.remaining);if(t!==this.remaining)throw new vr(`Unexpected end of ASF Codec List Object; missing ${this.remaining-t} bytes`);this.remaining=0}ensureAvailable(t){if(t>this.remaining)throw new vr(`ASF Codec List field size ${t} exceeds remaining object payload size ${this.remaining}`)}};Kl=class n extends sI{get(t,o){let i=[],e=new DataView(t.buffer,o),a=10;for(let A=0;A0){let s=n.contentDescTags[A],g=a+r;i.push({id:s,value:ef(t.subarray(o+a,o+g))}),a=g}}return i}};Kl.guid=cr.ContentDescriptionObject;Kl.contentDescTags=["Title","Author","Copyright","Description","Rating"];Fh=class extends sI{get(t,o){let i=[],e=new DataView(t.buffer,o),a=e.getUint16(0,!0),A=2;for(let r=0;rs2});var qre,n2,lqe,Jre,s2,Vre=ue(()=>{qre=Je(ct(),1);so();Gl();r2();o2();Hi();o2();n2=(0,qre.default)("music-metadata:parser:ASF"),lqe="asf",Jre=16*1024*1024,s2=class extends Rt{async parse(){let t=await this.tokenizer.readToken(BO);if(!t.objectId.equals(cr.HeaderObject))throw new vr(`expected asf header; but was not found; got: ${t.objectId.str}`);if(t.numberOfHeaderObjects<1||t.numberOfHeaderObjects>1e4)throw new vr(`Unrealistic number of ASF header objects: ${t.numberOfHeaderObjects}`);await this.parseObjectHeaders(t.numberOfHeaderObjects,t.objectSize-BO.len)}async parseObjectHeaders(t,o){let i;for(let e=0;e{this.metadata.addStreamInfo({type:g.type.videoCodec?Ia.video:Ia.audio,codecName:g.codecName})});let s=r.filter(g=>g.type.audioCodec).map(g=>g.codecName).join("/");this.metadata.setFormat("codec",s);break}case cr.StreamBitratePropertiesObject.str:await this.ignorePayload(A,"Stream Bitrate Properties Object");break;case cr.PaddingObject.str:n2("Padding: %s bytes",A),await this.ignorePayload(A,"Padding Object");break;default:this.metadata.addWarning(`Ignore ASF-Object-GUID: ${a.objectId.str}`),n2("Ignore ASF-Object-GUID: %s",a.objectId.str),await this.ignorePayload(A,`object ${a.objectId.str}`)}o-=a.objectSize}if(o!==0)throw new vr(`ASF header child objects leave ${o} payload byte(s) unaccounted`)}async addTags(t){await Promise.all(t.map(({id:o,value:i})=>this.metadata.addTag(lqe,o,i)))}async readObjectHeader(t,o){if(tt)throw new vr(`ASF ${o} object size ${i.objectSize} exceeds remaining ${o} payload size ${t}`);return{header:i,payloadSize:this.validatePayloadAvailability(i,`${o} object`)}}validatePayloadAvailability(t,o){let i=t.objectSize-Yl.len,e=this.tokenizer.fileInfo.size;if(e!==void 0){let a=e-this.tokenizer.position;if(i>a)throw new vr(`ASF ${o} payload size ${i} exceeds available input size ${a}`)}return i}validateAllocationSize(t,o){if(t>Jre)throw new vr(`ASF ${o} payload size ${t} exceeds allocation limit ${Jre}`)}async ignorePayload(t,o){let i;try{i=await this.tokenizer.ignore(t)}catch(e){throw e instanceof bA?new vr(`Unexpected end of ASF ${o}`):e}if(i!==t)throw new vr(`Unexpected end of ASF ${o}; missing ${t-i} bytes`)}async parseExtensionObject(t){for(;t>0;){let{header:o,payloadSize:i}=await this.readObjectHeader(t,"extension");switch(o.objectId.str){case Lh.guid.str:this.validateAllocationSize(i,"Extended Stream Properties Object"),await this.tokenizer.readToken(new Lh(o));break;case xl.guid.str:{this.validateAllocationSize(i,"Metadata Object");let e=await this.tokenizer.readToken(new xl(o));await this.addTags(e);break}case Uh.guid.str:{this.validateAllocationSize(i,"Metadata Library Object");let e=await this.tokenizer.readToken(new Uh(o));await this.addTags(e);break}case cr.PaddingObject.str:await this.ignorePayload(i,"extension Padding Object");break;case cr.CompatibilityObject.str:await this.ignorePayload(i,"Compatibility Object");break;case cr.ASF_Index_Placeholder_Object.str:await this.ignorePayload(i,"Index Placeholder Object");break;default:this.metadata.addWarning(`Ignore ASF-Object-GUID: ${o.objectId.str}`),await this.ignorePayload(i,`extension object ${o.objectId.str}`);break}t-=o.objectSize}}}});var Wre,Zre=ue(()=>{Wre={parserType:"asf",extensions:[".asf",".wma",".wmv"],mimeTypes:["audio/ms-wma","video/ms-wmv","audio/ms-asf","video/ms-asf","application/vnd.ms-asf"],async load(){return(await Promise.resolve().then(()=>(Vre(),zre))).AsfParser}}});var jl,Xre=ue(()=>{DA();si();jl={len:12,get:(n,t)=>({chunkID:at.get(n,t),chunkSize:bL.get(n,t+4)})}});var eae={};Pr(eae,{DsdiffContentParseError:()=>Hh,DsdiffParser:()=>g2});var $re,gi,Hh,g2,Aae=ue(()=>{DA();$re=Je(ct(),1);so();si();Hi();kh();Xre();er();gi=(0,$re.default)("music-metadata:parser:aiff"),Hh=class extends Qt("DSDIFF"){},g2=class extends Rt{async parse(){let t=await this.tokenizer.readToken(jl);if(t.chunkID!=="FRM8")throw new Hh("Unexpected chunk-ID");this.metadata.setAudioOnly();let o=(await this.tokenizer.readToken(at)).trim();switch(o){case"DSD":return this.metadata.setFormat("container",`DSDIFF/${o}`),this.metadata.setFormat("lossless",!0),this.readFmt8Chunks(t.chunkSize-BigInt(at.len));default:throw new Hh(`Unsupported DSDIFF type: ${o}`)}}async readFmt8Chunks(t){for(;t>=jl.len;){let o=await this.tokenizer.readToken(jl);gi(`Chunk id=${o.chunkID}`),await this.readData(o),t-=BigInt(jl.len)+o.chunkSize}}async readData(t){gi(`Reading data of chunk[ID=${t.chunkID}, size=${t.chunkSize}]`);let o=this.tokenizer.position;switch(t.chunkID.trim()){case"FVER":{let e=await this.tokenizer.readToken(Ge);gi(`DSDIFF version=${e}`);break}case"PROP":{if(await this.tokenizer.readToken(at)!=="SND ")throw new Hh("Unexpected PROP-chunk ID");await this.handleSoundPropertyChunks(t.chunkSize-BigInt(at.len));break}case"ID3":{let e=await this.tokenizer.readToken(new Dt(Number(t.chunkSize))),a=no(e);await new $o().parse(this.metadata,a,this.options);break}case"DSD":this.metadata.format.numberOfChannels&&this.metadata.setFormat("numberOfSamples",Number(t.chunkSize*BigInt(8)/BigInt(this.metadata.format.numberOfChannels))),this.metadata.format.numberOfSamples&&this.metadata.format.sampleRate&&this.metadata.setFormat("duration",this.metadata.format.numberOfSamples/this.metadata.format.sampleRate);break;default:gi(`Ignore chunk[ID=${t.chunkID}, size=${t.chunkSize}]`);break}let i=t.chunkSize-BigInt(this.tokenizer.position-o);i>0&&(gi(`After Parsing chunk, remaining ${i} bytes`),await this.tokenizer.ignore(Number(i)))}async handleSoundPropertyChunks(t){for(gi(`Parsing sound-property-chunks, remainingSize=${t}`);t>0;){let o=await this.tokenizer.readToken(jl);gi(`Sound-property-chunk[ID=${o.chunkID}, size=${o.chunkSize}]`);let i=this.tokenizer.position;switch(o.chunkID.trim()){case"FS":{let a=await this.tokenizer.readToken(Ue);this.metadata.setFormat("sampleRate",a);break}case"CHNL":{let a=await this.tokenizer.readToken(GA);this.metadata.setFormat("numberOfChannels",a),await this.handleChannelChunks(o.chunkSize-BigInt(GA.len));break}case"CMPR":{let a=(await this.tokenizer.readToken(at)).trim(),A=await this.tokenizer.readToken(fA),r=await this.tokenizer.readToken(new ze(A,"ascii"));a==="DSD"&&(this.metadata.setFormat("lossless",!0),this.metadata.setFormat("bitsPerSample",1)),this.metadata.setFormat("codec",`${a} (${r})`);break}case"ABSS":{let a=await this.tokenizer.readToken(GA),A=await this.tokenizer.readToken(fA),r=await this.tokenizer.readToken(fA),s=await this.tokenizer.readToken(Ue);gi(`ABSS ${a}:${A}:${r}.${s}`);break}case"LSCO":{let a=await this.tokenizer.readToken(GA);gi(`LSCO lsConfig=${a}`);break}default:gi(`Unknown sound-property-chunk[ID=${o.chunkID}, size=${o.chunkSize}]`),await this.tokenizer.ignore(Number(o.chunkSize))}let e=o.chunkSize-BigInt(this.tokenizer.position-i);e>0&&(gi(`After Parsing sound-property-chunk ${o.chunkSize}, remaining ${e} bytes`),await this.tokenizer.ignore(Number(e))),t-=BigInt(jl.len)+o.chunkSize,gi(`Parsing sound-property-chunks, remainingSize=${t}`)}if(this.metadata.format.lossless&&this.metadata.format.sampleRate&&this.metadata.format.numberOfChannels&&this.metadata.format.bitsPerSample){let o=this.metadata.format.sampleRate*this.metadata.format.numberOfChannels*this.metadata.format.bitsPerSample;this.metadata.setFormat("bitrate",o)}}async handleChannelChunks(t){gi(`Parsing channel-chunks, remainingSize=${t}`);let o=[];for(;t>=at.len;){let i=await this.tokenizer.readToken(at);gi(`Channel[ID=${i}]`),o.push(i),t-=BigInt(at.len)}return gi(`Channels: ${o.join(", ")}`),o}}});var tae,rae=ue(()=>{tae={parserType:"dsdiff",extensions:[".dff"],mimeTypes:["audio/dsf","audio/dsd"],async load(){return(await Promise.resolve().then(()=>(Aae(),eae))).DsdiffParser}}});var aae,gI,fO,c2=ue(()=>{DA();si();er();aae={NONE:"not compressed PCM Apple Computer",sowt:"PCM (byte swapped)",fl32:"32-bit floating point IEEE 32-bit float",fl64:"64-bit floating point IEEE 64-bit float Apple Computer",alaw:"ALaw 2:1 8-bit ITU-T G.711 A-law",ulaw:"\xB5Law 2:1 8-bit ITU-T G.711 \xB5-law Apple Computer",ULAW:"CCITT G.711 u-law 8-bit ITU-T G.711 \xB5-law",ALAW:"CCITT G.711 A-law 8-bit ITU-T G.711 A-law",FL32:"Float 32 IEEE 32-bit float "},gI=class extends Qt("AIFF"){},fO=class{constructor(t,o){this.isAifc=o;let i=o?22:18;if(t.chunkSize>Math.abs(i):e<22){let A=fA.get(t,o+22);if(A>0){let r=(A+1)%2;if(23+A+r===this.len)a.compressionName=new ze(A,"latin1").get(t,o+23);else throw new gI("Illegal pstring length")}else a.compressionName=void 0}}else a.compressionName="PCM";return a}}});var QO,iae=ue(()=>{DA();si();QO={len:8,get:(n,t)=>({chunkID:at.get(n,t),chunkSize:Number(BigInt(Ue.get(n,t+4)))})}});var nae={};Pr(nae,{AIFFParser:()=>l2});var oae,I2,l2,sae=ue(()=>{DA();oae=Je(ct(),1);so();kh();si();Hi();c2();c2();iae();I2=(0,oae.default)("music-metadata:parser:aiff"),l2=class extends Rt{constructor(){super(...arguments),this.isCompressed=null}async parse(){if((await this.tokenizer.readToken(QO)).chunkID!=="FORM")throw new gI("Invalid Chunk-ID, expected 'FORM'");let o=await this.tokenizer.readToken(at);switch(o){case"AIFF":this.metadata.setFormat("container",o),this.isCompressed=!1;break;case"AIFC":this.metadata.setFormat("container","AIFF-C"),this.isCompressed=!0;break;default:throw new gI(`Unsupported AIFF type: ${o}`)}this.metadata.setFormat("lossless",!this.isCompressed),this.metadata.setAudioOnly();try{for(;!this.tokenizer.fileInfo.size||this.tokenizer.fileInfo.size-this.tokenizer.position>=QO.len;){I2(`Reading AIFF chunk at offset=${this.tokenizer.position}`);let i=await this.tokenizer.readToken(QO),e=2*Math.round(i.chunkSize/2),a=await this.readData(i);await this.tokenizer.ignore(e-a)}}catch(i){if(i instanceof bA)I2("End-of-stream");else throw i}}async readData(t){switch(t.chunkID){case"COMM":{if(this.isCompressed===null)throw new gI("Failed to parse AIFF.COMM chunk when compression type is unknown");let o=await this.tokenizer.readToken(new fO(t,this.isCompressed));return this.metadata.setFormat("bitsPerSample",o.sampleSize),this.metadata.setFormat("sampleRate",o.sampleRate),this.metadata.setFormat("numberOfChannels",o.numChannels),this.metadata.setFormat("numberOfSamples",o.numSampleFrames),this.metadata.setFormat("duration",o.numSampleFrames/o.sampleRate),(o.compressionName||o.compressionType)&&this.metadata.setFormat("codec",o.compressionName??aae[o.compressionType]),t.chunkSize}case"ID3 ":{let o=await this.tokenizer.readToken(new Dt(t.chunkSize)),i=no(o);return await new $o().parse(this.metadata,i,this.options),t.chunkSize}case"SSND":return this.metadata.format.duration&&this.metadata.setFormat("bitrate",8*t.chunkSize/this.metadata.format.duration),0;case"NAME":case"AUTH":case"(c) ":case"ANNO":return this.readTextChunk(t);default:return I2(`Ignore chunk id=${t.chunkID}, size=${t.chunkSize}`),0}}async readTextChunk(t){let i=(await this.tokenizer.readToken(new ze(t.chunkSize,"ascii"))).split("\0").map(e=>e.trim()).filter(e=>e?.length);return await Promise.all(i.map(e=>this.metadata.addTag("AIFF",t.chunkID,e))),t.chunkSize}}});var gae,cae=ue(()=>{gae={parserType:"aiff",extensions:[".aif","aiff","aifc"],mimeTypes:["audio/aiff","audio/aif","audio/aifc","application/aiff"],async load(){return(await Promise.resolve().then(()=>(sae(),nae))).AIFFParser}}});var Af,p2,d2,Iae=ue(()=>{DA();si();Af={len:12,get:(n,t)=>({id:at.get(n,t),size:Dr.get(n,t+4)})},p2={len:16,get:(n,t)=>({fileSize:Dr.get(n,t),metadataPointer:Dr.get(n,t+8)})},d2={len:40,get:(n,t)=>({formatVersion:sr.get(n,t),formatID:sr.get(n,t+4),channelType:sr.get(n,t+8),channelNum:sr.get(n,t+12),samplingFrequency:sr.get(n,t+16),bitsPerSample:sr.get(n,t+20),sampleCount:OL.get(n,t+24),blockSizePerChannel:sr.get(n,t+32)})}});var pae={};Pr(pae,{DsdContentParseError:()=>Ls,DsfParser:()=>E2});var lae,h2,Ls,E2,dae=ue(()=>{lae=Je(ct(),1);$B();Iae();kh();er();Ug();h2=(0,lae.default)("music-metadata:parser:DSF"),Ls=class extends Qt("DSD"){},E2=class extends Fs{async postId3v2Parse(){let t=this.tokenizer.position,o=await this.tokenizer.readToken(Af);if(o.id!=="DSD ")throw new Ls("Invalid chunk signature");if(o.size!==BigInt(Af.len+p2.len))throw new Ls(`Invalid DSD chunk size: ${o.size}`);this.metadata.setFormat("container","DSF"),this.metadata.setFormat("lossless",!0),this.metadata.setAudioOnly();let i=await this.tokenizer.readToken(p2);if(i.fileSizeBigInt(Number.MAX_SAFE_INTEGER)||i.metadataPointer+BigInt(Pl.len)>i.fileSize)throw new Ls(`Invalid metadata pointer: ${i.metadataPointer}`);return await this.tokenizer.ignore(Number(e)),new $o().parse(this.metadata,this.tokenizer,this.options)}async parseChunks(t){let o=BigInt(Af.len);for(;t>=o;){let i=await this.tokenizer.readToken(Af);if(h2(`Parsing chunk name=${i.id} size=${i.size}`),i.sizet)throw new Ls(`${i.id} chunk exceeds remaining file size`);let e=i.size-o;switch(i.id){case"fmt ":{if(e{hae={parserType:"dsf",extensions:[".dsf"],mimeTypes:["audio/dsf"],async load(){return(await Promise.resolve().then(()=>(dae(),pae))).DsfParser}}});var cI,tf,Cae,yO=ue(()=>{DA();Ug();cI=class n{static fromBase64(t){return n.fromBuffer(Uint8Array.from(atob(t),o=>o.charCodeAt(0)))}static fromBuffer(t){return new n(t.length).get(t,0)}constructor(t){this.len=t}get(t,o){let i=Oh[Ue.get(t,o)];o+=4;let e=Ue.get(t,o);o+=4;let a=new ze(e,"utf-8").get(t,o);o+=e;let A=Ue.get(t,o);o+=4;let r=new ze(A,"utf-8").get(t,o);o+=A;let s=Ue.get(t,o);o+=4;let g=Ue.get(t,o);o+=4;let c=Ue.get(t,o);o+=4;let I=Ue.get(t,o);o+=4;let d=Ue.get(t,o);o+=4;let B=t.slice(o,o+d);return{type:i,format:a,description:r,width:s,height:g,colour_depth:c,indexed_color:I,data:B}}},tf={len:7,get:(n,t)=>({packetType:fA.get(n,t),vorbis:new ze(6,"ascii").get(n,t+1)})},Cae={len:23,get:(n,t)=>({version:Ge.get(n,t+0),channelMode:fA.get(n,t+4),sampleRate:Ge.get(n,t+5),bitrateMax:Ge.get(n,t+9),bitrateNominal:Ge.get(n,t+13),bitrateMin:Ge.get(n,t+17)})}});var Kh,C2=ue(()=>{DA();_s();Kh=class{constructor(t,o){this.data=t,this.offset=o}readInt32(){let t=Ge.get(this.data,this.offset);return this.offset+=4,t}readStringUtf8(){let t=this.readInt32(),o=wr(this.data.subarray(this.offset,this.offset+t),"utf-8");return this.offset+=t,o}parseUserComment(){let t=this.offset,o=this.readStringUtf8(),i=o.indexOf("=");return{key:o.substring(0,i).toUpperCase(),value:o.substring(i+1),len:this.offset-t}}}});var uae,xh,rf,Us,af=ue(()=>{DA();uae=Je(ct(),1);C2();yO();er();xh=(0,uae.default)("music-metadata:parser:ogg:vorbis1"),rf=class extends Qt("Vorbis"){},Us=class n{constructor(t,o){this.pageSegments=[],this.durationOnLastPage=!0,this.metadata=t,this.options=o}async parsePage(t,o){if(this.lastPageHeader=t,t.headerType.firstPage)this.parseFirstPage(t,o);else{if(t.headerType.continued){if(this.pageSegments.length===0)throw new rf("Cannot continue on previous page");this.pageSegments.push(o)}if(t.headerType.lastPage||!t.headerType.continued){if(this.pageSegments.length>0){let i=n.mergeUint8Arrays(this.pageSegments);await this.parseFullPage(i)}this.pageSegments=t.headerType.lastPage?[]:[o]}}}static mergeUint8Arrays(t){let o=t.reduce((e,a)=>e+a.length,0),i=new Uint8Array(o);return t.forEach((e,a,A)=>{let r=A.slice(0,a).reduce((s,g)=>s+g.length,0);i.set(e,r)}),i}async flush(){await this.parseFullPage(n.mergeUint8Arrays(this.pageSegments))}async parseUserComment(t,o){let e=new Kh(t,o).parseUserComment();return await this.addTag(e.key,e.value),e.len}async addTag(t,o){if(t==="METADATA_BLOCK_PICTURE"&&typeof o=="string"){if(this.options.skipCovers){xh("Ignore picture");return}o=cI.fromBase64(o),xh(`Push picture: id=${t}, format=${o.format}`)}else xh(`Push tag: id=${t}, value=${o}`);await this.metadata.addTag("vorbis",t,o)}calculateDuration(t){this.lastPageHeader&&(t||this.lastPageHeader.headerType.lastPage)&&this.metadata.format.sampleRate&&this.lastPageHeader.absoluteGranulePosition>=0&&(this.metadata.setFormat("numberOfSamples",this.lastPageHeader.absoluteGranulePosition),this.metadata.setFormat("duration",this.lastPageHeader.absoluteGranulePosition/this.metadata.format.sampleRate))}parseFirstPage(t,o){this.metadata.setFormat("codec","Vorbis I"),this.metadata.setFormat("hasAudio",!0),xh("Parse first page");let i=tf.get(o,0);if(i.vorbis!=="vorbis")throw new rf("Metadata does not look like Vorbis");if(i.packetType===1){let e=Cae.get(o,tf.len);this.metadata.setFormat("sampleRate",e.sampleRate),this.metadata.setFormat("bitrate",e.bitrateNominal),this.metadata.setFormat("numberOfChannels",e.channelMode),xh("sample-rate=%s[hz], bitrate=%s[b/s], channel-mode=%s",e.sampleRate,e.bitrateNominal,e.channelMode)}else throw new rf("First Ogg page should be type 1: the identification header")}async parseFullPage(t){let o=tf.get(t,0);switch(xh("Parse full page: type=%s, byteLength=%s",o.packetType,t.byteLength),o.packetType){case 3:return this.parseUserCommentList(t,tf.len);case 1:case 5:break}}async parseUserCommentList(t,o){let i=Ge.get(t,o);o+=4,o+=i;let e=Ge.get(t,o);for(o+=4;e-- >0;)o+=await this.parseUserComment(t,o)}}});var ci,of,nf,u2=ue(()=>{Ar();DA();ci={STREAMINFO:0,PADDING:1,APPLICATION:2,SEEKTABLE:3,VORBIS_COMMENT:4,CUESHEET:5,PICTURE:6},of={len:4,get:(n,t)=>({lastBlock:vA(n,t,7),type:XA(n,t,1,7),length:kr.get(n,t+1)})},nf={len:34,get:(n,t)=>({minimumBlockSize:GA.get(n,t),maximumBlockSize:GA.get(n,t+2)/1e3,minimumFrameSize:kr.get(n,t+4),maximumFrameSize:kr.get(n,t+7),sampleRate:kr.get(n,t+10)>>4,channels:XA(n,t+12,4,3)+1,bitsPerSample:XA(n,t+12,7,5)+1,totalSamples:XA(n,t+13,4,36),fileMD5:new Dt(16).get(n,t+18)})}});var Qae={};Pr(Qae,{FlacParser:()=>sf});var fae,hqe,mO,sf,B2=ue(()=>{fae=Je(ct(),1);DA();yO();$B();si();af();C2();er();u2();hqe=(0,fae.default)("music-metadata:parser:FLAC"),mO=class extends Qt("FLAC"){},sf=class extends Fs{constructor(){super(...arguments),this.vorbisParser=new Us(this.metadata,this.options)}async postId3v2Parse(){if((await this.tokenizer.readToken(at)).toString()!=="fLaC")throw new mO("Invalid FLAC preamble");let o;do o=await this.tokenizer.readToken(of),await this.parseDataBlock(o);while(!o.lastBlock);if(this.tokenizer.fileInfo.size&&this.metadata.format.duration){let i=this.tokenizer.fileInfo.size-this.tokenizer.position;this.metadata.setFormat("bitrate",8*i/this.metadata.format.duration)}}async parseDataBlock(t){switch(hqe(`blockHeader type=${t.type}, length=${t.length}`),t.type){case ci.STREAMINFO:return this.readBlockStreamInfo(t.length);case ci.PADDING:break;case ci.APPLICATION:break;case ci.SEEKTABLE:break;case ci.VORBIS_COMMENT:return this.readComment(t.length);case ci.CUESHEET:break;case ci.PICTURE:await this.parsePicture(t.length);return;default:this.metadata.addWarning(`Unknown block type: ${t.type}`)}return this.tokenizer.ignore(t.length).then()}async readBlockStreamInfo(t){if(t!==nf.len)throw new mO("Unexpected block-stream-info length");let o=await this.tokenizer.readToken(nf);this.metadata.setFormat("container","FLAC"),this.processsStreamInfo(o)}processsStreamInfo(t){this.metadata.setFormat("codec","FLAC"),this.metadata.setFormat("hasAudio",!0),this.metadata.setFormat("lossless",!0),this.metadata.setFormat("numberOfChannels",t.channels),this.metadata.setFormat("bitsPerSample",t.bitsPerSample),this.metadata.setFormat("sampleRate",t.sampleRate),t.totalSamples>0&&this.metadata.setFormat("duration",t.totalSamples/t.sampleRate)}async readComment(t){let o=await this.tokenizer.readToken(new Dt(t));return this.parseComment(o)}async parseComment(t){let o=new Kh(t,0),i=o.readStringUtf8();i.length>0&&this.metadata.setFormat("tool",i);let e=o.readInt32(),a=new Array(e);for(let A=0;A(A.key==="ENCODER"&&this.metadata.setFormat("tool",A.value),this.addTag(A.key,A.value))))}async parsePicture(t){return this.options.skipCovers?this.tokenizer.ignore(t):this.addPictureTag(await this.tokenizer.readToken(new cI(t)))}addPictureTag(t){return this.addTag("METADATA_BLOCK_PICTURE",t)}addTag(t,o){return this.vorbisParser.addTag(t,o)}}});var yae,mae=ue(()=>{yae={parserType:"flac",extensions:[".flac"],mimeTypes:["audio/flac"],async load(){return(await Promise.resolve().then(()=>(B2(),Qae))).FlacParser}}});var Te,f2=ue(()=>{Te={string:0,uint:1,uid:2,bool:3,binary:4,float:5}});var Sae,wae=ue(()=>{f2();Sae={name:"dtd",container:{440786851:{name:"ebml",container:{17030:{name:"ebmlVersion",value:Te.uint},17143:{name:"ebmlReadVersion",value:Te.uint},17138:{name:"ebmlMaxIDWidth",value:Te.uint},17139:{name:"ebmlMaxSizeWidth",value:Te.uint},17026:{name:"docType",value:Te.string},17031:{name:"docTypeVersion",value:Te.uint},17029:{name:"docTypeReadVersion",value:Te.uint}}},408125543:{name:"segment",container:{290298740:{name:"seekHead",container:{19899:{name:"seek",multiple:!0,container:{21419:{name:"id",value:Te.binary},21420:{name:"position",value:Te.uint}}}}},357149030:{name:"info",container:{29604:{name:"uid",value:Te.uid},29572:{name:"filename",value:Te.string},3979555:{name:"prevUID",value:Te.uid},3965867:{name:"prevFilename",value:Te.string},4110627:{name:"nextUID",value:Te.uid},4096955:{name:"nextFilename",value:Te.string},2807729:{name:"timecodeScale",value:Te.uint},17545:{name:"duration",value:Te.float},17505:{name:"dateUTC",value:Te.uint},31657:{name:"title",value:Te.string},19840:{name:"muxingApp",value:Te.string},22337:{name:"writingApp",value:Te.string}}},524531317:{name:"cluster",multiple:!0,container:{231:{name:"timecode",value:Te.uid},22743:{name:"silentTracks ",multiple:!0},167:{name:"position",value:Te.uid},171:{name:"prevSize",value:Te.uid},160:{name:"blockGroup"},163:{name:"simpleBlock"}}},374648427:{name:"tracks",container:{174:{name:"entries",multiple:!0,container:{215:{name:"trackNumber",value:Te.uint},29637:{name:"uid",value:Te.uid},131:{name:"trackType",value:Te.uint},185:{name:"flagEnabled",value:Te.bool},136:{name:"flagDefault",value:Te.bool},21930:{name:"flagForced",value:Te.bool},156:{name:"flagLacing",value:Te.bool},28135:{name:"minCache",value:Te.uint},28136:{name:"maxCache",value:Te.uint},2352003:{name:"defaultDuration",value:Te.uint},2306383:{name:"timecodeScale",value:Te.float},21358:{name:"name",value:Te.string},2274716:{name:"language",value:Te.string},134:{name:"codecID",value:Te.string},25506:{name:"codecPrivate",value:Te.binary},2459272:{name:"codecName",value:Te.string},3839639:{name:"codecSettings",value:Te.string},3883072:{name:"codecInfoUrl",value:Te.string},2536e3:{name:"codecDownloadUrl",value:Te.string},170:{name:"codecDecodeAll",value:Te.bool},28587:{name:"trackOverlay",value:Te.uint},224:{name:"video",container:{154:{name:"flagInterlaced",value:Te.bool},21432:{name:"stereoMode",value:Te.uint},176:{name:"pixelWidth",value:Te.uint},186:{name:"pixelHeight",value:Te.uint},21680:{name:"displayWidth",value:Te.uint},21690:{name:"displayHeight",value:Te.uint},21683:{name:"aspectRatioType",value:Te.uint},3061028:{name:"colourSpace",value:Te.uint},3126563:{name:"gammaValue",value:Te.float}}},225:{name:"audio",container:{181:{name:"samplingFrequency",value:Te.float},30901:{name:"outputSamplingFrequency",value:Te.float},159:{name:"channels",value:Te.uint},148:{name:"channels",value:Te.uint},32123:{name:"channelPositions",value:Te.binary},25188:{name:"bitDepth",value:Te.uint}}},28032:{name:"contentEncodings",container:{25152:{name:"contentEncoding",container:{20529:{name:"order",value:Te.uint},20530:{name:"scope",value:Te.bool},20531:{name:"type",value:Te.uint},20532:{name:"contentEncoding",container:{16980:{name:"contentCompAlgo",value:Te.uint},16981:{name:"contentCompSettings",value:Te.binary}}},20533:{name:"contentEncoding",container:{18401:{name:"contentEncAlgo",value:Te.uint},18402:{name:"contentEncKeyID",value:Te.binary},18403:{name:"contentSignature ",value:Te.binary},18404:{name:"ContentSigKeyID ",value:Te.binary},18405:{name:"contentSigAlgo ",value:Te.uint},18406:{name:"contentSigHashAlgo ",value:Te.uint}}},25188:{name:"bitDepth",value:Te.uint}}}}}}}}},475249515:{name:"cues",container:{187:{name:"cuePoint",container:{179:{name:"cueTime",value:Te.uid},183:{name:"positions",container:{247:{name:"track",value:Te.uint},241:{name:"clusterPosition",value:Te.uint},21368:{name:"blockNumber",value:Te.uint},234:{name:"codecState",value:Te.uint},219:{name:"reference",container:{150:{name:"time",value:Te.uint},151:{name:"cluster",value:Te.uint},21343:{name:"number",value:Te.uint},235:{name:"codecState",value:Te.uint}}},240:{name:"relativePosition",value:Te.uint}}}}}}},423732329:{name:"attachments",container:{24999:{name:"attachedFiles",multiple:!0,container:{18046:{name:"description",value:Te.string},18030:{name:"name",value:Te.string},18016:{name:"mimeType",value:Te.string},18012:{name:"data",value:Te.binary},18094:{name:"uid",value:Te.uid}}}}},272869232:{name:"chapters",container:{17849:{name:"editionEntry",container:{182:{name:"chapterAtom",container:{29636:{name:"uid",value:Te.uid},145:{name:"timeStart",value:Te.uint},146:{name:"timeEnd",value:Te.uid},152:{name:"hidden",value:Te.bool},17816:{name:"enabled",value:Te.uid},143:{name:"track",container:{137:{name:"trackNumber",value:Te.uid},128:{name:"display",container:{133:{name:"string",value:Te.string},17276:{name:"language ",value:Te.string},17278:{name:"country ",value:Te.string}}}}}}}}}}},307544935:{name:"tags",container:{29555:{name:"tag",multiple:!0,container:{25536:{name:"target",container:{25541:{name:"tagTrackUID",value:Te.uid},25540:{name:"tagChapterUID",value:Te.uint},25542:{name:"tagAttachmentUID",value:Te.uid},25546:{name:"targetType",value:Te.string},26826:{name:"targetTypeValue",value:Te.uint},25545:{name:"tagEditionUID",value:Te.uid}}},26568:{name:"simpleTags",multiple:!0,container:{17827:{name:"name",value:Te.string},17543:{name:"string",value:Te.string},17541:{name:"binary",value:Te.binary},17530:{name:"language",value:Te.string},17531:{name:"languageIETF",value:Te.string},17540:{name:"default",value:Te.bool}}}}}}}}}}}});function Q2(n,t){return Number(Eqe(n,t))}function Eqe(n,t){let o=new Uint8Array(8),i=n.subarray(0,t);try{return o.set(i,8-t),Rs.get(o,0)}catch{return BigInt(-1)}}function Oae(n){return n.container&&Object.keys(n.container).map(t=>{let o=n.container[t];return o.id=Number.parseInt(t,10),o}).forEach(t=>{t.parent=n,Oae(t)}),n}function Jl(n){let t="";return n.parent&&n.parent.name!=="dtd"&&(t+=`${Jl(n.parent)}/`),t+n.name}var Dae,Yh,SO,Hs,wO,bae=ue(()=>{DA();Dae=Je(ct(),1);so();f2();DA();er();Yh=(0,Dae.default)("music-metadata:parser:ebml"),SO=class extends Qt("EBML"){},Hs={ReadNext:0,IgnoreElement:2,SkipSiblings:3,TerminateParsing:4,SkipElement:5},wO=class{constructor(t){this.parserMap=new Map,this.ebmlMaxIDLength=4,this.ebmlMaxSizeLength=8,this.tokenizer=t,this.parserMap.set(Te.uint,o=>this.readUint(o)),this.parserMap.set(Te.string,o=>this.readString(o)),this.parserMap.set(Te.binary,o=>this.readBuffer(o)),this.parserMap.set(Te.uid,async o=>this.readBuffer(o)),this.parserMap.set(Te.bool,o=>this.readFlag(o)),this.parserMap.set(Te.float,o=>this.readFloat(o))}async iterate(t,o,i){return this.parseContainer(Oae(t),o,i)}async parseContainer(t,o,i){let e={};for(;this.tokenizer.position=0?this.tokenizer.position+a.len:-1,i);r.multiple?(e[r.name]||(e[r.name]=[]),e[r.name].push(g)):e[r.name]=g,await i.elementValue(r,g,A)}else{let g=this.parserMap.get(r.value);if(typeof g=="function"){let c=await g(a);e[r.name]=c,await i.elementValue(r,c,A)}}break;case Hs.SkipElement:Yh(`Go to next element: name=${Jl(r)}, element.id=0x${a.id}, container=${!!r.container} at position=${A}`);break;case Hs.IgnoreElement:Yh(`Ignore element: name=${Jl(r)}, element.id=0x${a.id}, container=${!!r.container} at position=${A}`),await this.tokenizer.ignore(a.len);break;case Hs.SkipSiblings:Yh(`Ignore remaining container, at: name=${Jl(r)}, element.id=0x${a.id}, container=${!!r.container} at position=${A}`),await this.tokenizer.ignore(o-this.tokenizer.position);break;case Hs.TerminateParsing:return Yh(`Terminate parsing at element: name=${Jl(r)}, element.id=0x${a.id}, container=${!!r.container} at position=${A}`),e}else switch(a.id){case 236:await this.tokenizer.ignore(a.len);break;default:Yh(`parseEbml: parent=${Jl(t)}, unknown child: id=${a.id.toString(16)} at position=${A}`),await this.tokenizer.ignore(a.len)}}return e}async readVintData(t){let o=await this.tokenizer.peekNumber(fA),i=128,e=1;for(;(o&i)===0;){if(e>t)throw new SO("VINT value exceeding maximum size");++e,i>>=1}let a=new Uint8Array(e);return await this.tokenizer.readBuffer(a),a}async readElement(){let t=await this.readVintData(this.ebmlMaxIDLength),o=await this.readVintData(this.ebmlMaxSizeLength);return o[0]^=128>>o.length-1,{id:Q2(t,t.length),len:Q2(o,o.length)}}async readFloat(t){switch(t.len){case 0:return 0;case 4:return this.tokenizer.readNumber(ML);case 8:return this.tokenizer.readNumber(xD);case 10:return this.tokenizer.readNumber(xD);default:throw new SO(`Invalid IEEE-754 float length: ${t.len}`)}}async readFlag(t){return await this.readUint(t)===1}async readUint(t){let o=await this.readBuffer(t);return Q2(o,t.len)}async readString(t){return(await this.tokenizer.readToken(new ze(t.len,"utf-8"))).replace(/\x00.*$/g,"")}async readBuffer(t){let o=new Uint8Array(t.len);return await this.tokenizer.readBuffer(o),o}}});var _ae={};Pr(_ae,{MatroskaParser:()=>y2});var Mae,DO,y2,Tae=ue(()=>{Mae=Je(ct(),1);Hi();wae();HL();bae();DO=(0,Mae.default)("music-metadata:parser:matroska"),y2=class extends Rt{constructor(){super(...arguments),this.seekHeadOffset=0,this.flagUseIndexToSkipClusters=this.options.mkvUseIndex??!1}async parse(){let t=this.tokenizer.fileInfo.size??Number.MAX_SAFE_INTEGER,o=new wO(this.tokenizer);DO("Initializing DTD end MatroskaIterator"),await o.iterate(Sae,t,{startNext:i=>{switch(i.id){case 475249515:return DO(`Skip element: name=${i.name}, id=0x${i.id.toString(16)}`),Hs.IgnoreElement;case 524531317:if(this.flagUseIndexToSkipClusters&&this.seekHead){let e=this.seekHead.seek.find(a=>a.position+this.seekHeadOffset>this.tokenizer.position);if(e){let a=e.position+this.seekHeadOffset-this.tokenizer.position;return DO(`Use index to go to next position, ignoring ${a} bytes`),this.tokenizer.ignore(a),Hs.SkipElement}}return Hs.IgnoreElement;default:return Hs.ReadNext}},elementValue:async(i,e,a)=>{switch(DO(`Received: name=${i.name}, value=${e}`),i.id){case 17026:this.metadata.setFormat("container",`EBML/${e}`);break;case 290298740:this.seekHead=e,this.seekHeadOffset=a;break;case 357149030:{let A=e,r=A.timecodeScale?A.timecodeScale:1e6;if(typeof A.duration=="number"){let s=A.duration*r/1e9;await this.addTag("segment:title",A.title),this.metadata.setFormat("duration",Number(s))}}break;case 374648427:{let A=e;if(A?.entries){A.entries.forEach(s=>{let g={codecName:s.codecID.replace("A_","").replace("V_",""),codecSettings:s.codecSettings,flagDefault:s.flagDefault,flagLacing:s.flagLacing,flagEnabled:s.flagEnabled,language:s.language,name:s.name,type:s.trackType,audio:s.audio,video:s.video};this.metadata.addStreamInfo(g)});let r=A.entries.filter(s=>s.trackType===Ia.audio).reduce((s,g)=>!s||g.flagDefault&&!s.flagDefault||g.trackNumber{let s=r.target,g=s?.targetTypeValue?Kte[s.targetTypeValue]:s?.targetType?s.targetType:"track";await Promise.all(r.simpleTags.map(async c=>{let I=c.string?c.string:c.binary;await this.addTag(`${g}:${c.name}`,I)}))}))}break;case 423732329:{let A=e;await Promise.all(A.attachedFiles.filter(r=>r.mimeType.startsWith("image/")).map(r=>this.addTag("picture",{data:r.data,format:r.mimeType,description:r.description,name:r.name})))}break}}})}async addTag(t,o){await this.metadata.addTag("matroska",t,o)}}});var Nae,Rae=ue(()=>{Nae={parserType:"matroska",extensions:[".mka",".mkv",".mk3d",".mks","webm"],mimeTypes:["audio/matroska","video/matroska","audio/webm","video/webm"],async load(){return(await Promise.resolve().then(()=>(Tae(),_ae))).MatroskaParser}}});function Gae(n,t,o,i,e){if(S2(`remainingLen=${i}, numberOfEntries=${e} * token-len=${t.len}`),i===0)return[];if(i!==e*t.len)throw new Kg("mismatch number-of-entries with remaining atom-length");let a=[];for(let A=0;A{DA();vae=Je(ct(),1);si();er();Ar();er();S2=(0,vae.default)("music-metadata:parser:MP4:atom"),Kg=class extends Qt("MP4"){},ql={len:8,get:(n,t)=>{let o=Ue.get(n,t);if(o<0)throw new Kg("Invalid atom header length");return{length:BigInt(o),name:new ze(4,"latin1").get(n,t+4)}},put:(n,t,o)=>(Ue.put(n,t,Number(o.length)),at.put(n,t+4,o.name))},Pae=Rs,w2={len:4,get:(n,t)=>({type:new ze(4,"ascii").get(n,t)})},OO=class{constructor(t,o,i){if(to&&S2(`Warning: atom ${i} expected to be ${o}, but was actually ${t} bytes long.`),this.len=t}},jh={len:4,get:(n,t)=>{let o=Ue.get(n,t)-2082844800;return new Date(o*1e3)}},Jh={len:8,get:(n,t)=>{let o=Number(Rs.get(n,t))-2082844800;return new Date(o*1e3)}},bO=class extends OO{constructor(t){super(t,24,"mdhd")}get(t,o){let i=fA.get(t,o+0),e=kr.get(t,o+1);switch(i){case 0:return{version:i,flags:e,creationTime:jh.get(t,o+4),modificationTime:jh.get(t,o+8),timeScale:Ue.get(t,o+12),duration:Ue.get(t,o+16),language:GA.get(t,o+20),quality:GA.get(t,o+22)};case 1:return{version:i,flags:e,creationTime:Jh.get(t,o+4),modificationTime:Jh.get(t,o+12),timeScale:Ue.get(t,o+20),duration:Number(Rs.get(t,o+24)),language:GA.get(t,o+32),quality:GA.get(t,o+34)};default:throw new Vo("Invalid mdhd version header")}}},MO=class extends OO{constructor(t){super(t,100,"mvhd")}get(t,o){let i=fA.get(t,o),e=kr.get(t,o+1);return i===1?{version:i,flags:e,creationTime:Jh.get(t,o+4),modificationTime:Jh.get(t,o+12),timeScale:Ue.get(t,o+20),duration:Number(Rs.get(t,o+24)),preferredRate:Ue.get(t,o+32),preferredVolume:GA.get(t,o+36),previewTime:Ue.get(t,o+84),previewDuration:Ue.get(t,o+88),posterTime:Ue.get(t,o+92),selectionTime:Ue.get(t,o+96),selectionDuration:Ue.get(t,o+100),currentTime:Ue.get(t,o+104),nextTrackID:Ue.get(t,o+108)}:{version:i,flags:e,creationTime:jh.get(t,o+4),modificationTime:jh.get(t,o+8),timeScale:Ue.get(t,o+12),duration:Ue.get(t,o+16),preferredRate:Ue.get(t,o+20),preferredVolume:GA.get(t,o+24),previewTime:Ue.get(t,o+72),previewDuration:Ue.get(t,o+76),posterTime:Ue.get(t,o+80),selectionTime:Ue.get(t,o+84),selectionDuration:Ue.get(t,o+88),currentTime:Ue.get(t,o+92),nextTrackID:Ue.get(t,o+96)}}},_O=class{constructor(t){this.len=t}get(t,o){return{type:{set:fA.get(t,o+0),type:kr.get(t,o+1)},locale:kr.get(t,o+4),value:new Dt(this.len-8).get(t,o+8)}}},TO=class{constructor(t){this.len=t}get(t,o){return{version:fA.get(t,o),flags:kr.get(t,o+1),name:new ze(this.len-4,"utf-8").get(t,o+4)}}},NO=class{constructor(t){this.len=t}get(t,o){let i=fA.get(t,o),e=kr.get(t,o+1);switch(i){case 0:return{version:i,flags:e,creationTime:jh.get(t,o+4),modificationTime:jh.get(t,o+8),trackId:Ue.get(t,o+12),duration:Ue.get(t,o+20),layer:GA.get(t,o+32),alternateGroup:GA.get(t,o+34),volume:GA.get(t,o+36)};case 1:return{version:i,flags:e,creationTime:Jh.get(t,o+4),modificationTime:Jh.get(t,o+12),trackId:Ue.get(t,o+20),duration:Number(Rs.get(t,o+28)),layer:GA.get(t,o+44),alternateGroup:GA.get(t,o+46),volume:GA.get(t,o+48)};default:throw new Vo("Invalid tkhd version header")}}},kae={len:8,get:(n,t)=>({version:fA.get(n,t),flags:kr.get(n,t+1),numberOfEntries:Ue.get(n,t+4)})},m2=class{constructor(t){this.len=t}get(t,o){let i=this.len-12;return{dataFormat:at.get(t,o),dataReferenceIndex:GA.get(t,o+10),description:i>0?new Dt(i).get(t,o+12):void 0}}},gf=class{constructor(t){this.len=t}get(t,o){let i=kae.get(t,o);o+=kae.len;let e=[];for(let a=0;a=this.len){S2("TrackRunBox size mismatch");break}let r={};e.flags.sampleDurationPresent&&(r.sampleDuration=Ue.get(t,a),a+=4),e.flags.sampleSizePresent&&(r.sampleSize=Ue.get(t,a),a+=4),e.flags.sampleFlagsPresent&&(r.sampleFlags=Ue.get(t,a),a+=4),e.flags.sampleCompositionTimeOffsetsPresent&&(r.sampleCompositionTimeOffset=Ue.get(t,a),a+=4),e.samples.push(r)}return e}},LO=class{constructor(t){this.len=t}get(t,o){let i=o+1,e=new ze(4,"utf-8");return{version:Ns.get(t,o),flags:kr.get(t,o+1),componentType:e.get(t,o+4),handlerType:e.get(t,o+8),componentName:new ze(this.len-28,"utf-8").get(t,o+28)}}},UO=class{constructor(t){this.len=t}get(t,o){let i=0,e=[];for(;i{Uae=Je(ct(),1);lf();lf();Lae=(0,Uae.default)("music-metadata:parser:MP4:Atom"),KO=class n{static async readAtom(t,o,i,e){let a=t.position;Lae(`Reading next token on offset=${a}...`);let A=await t.readToken(ql),r=A.length===1n;r&&(A.length=await t.readToken(Pae));let s=new n(A,r,i),g=s.getPayloadLength(e);return Lae(`parse atom name=${s.atomPath}, extended=${s.extended}, offset=${a}, len=${s.header.length}`),await s.readData(t,o,g),s}constructor(t,o,i){this.header=t,this.extended=o,this.parent=i,this.children=[],this.atomPath=(this.parent?`${this.parent.atomPath}.`:"")+this.header.name}getHeaderLength(){return this.extended?16:8}getPayloadLength(t){return(this.header.length===0n?t:Number(this.header.length))-this.getHeaderLength()}async readAtoms(t,o,i){for(;i>0;){let e=await n.readAtom(t,o,this,i);this.children.push(e),i-=e.header.length===0n?i:Number(e.header.length)}}async readData(t,o,i){switch(this.header.name){case"moov":case"udta":case"mdia":case"minf":case"stbl":case"":case"ilst":case"tref":case"moof":return this.readAtoms(t,o,this.getPayloadLength(i));case"meta":{let a=(await t.peekToken(ql)).name==="hdlr"?0:4;return await t.ignore(a),this.readAtoms(t,o,this.getPayloadLength(i)-a)}default:return o(this,i)}}}});var Jae={};Pr(Jae,{MP4Parser:()=>O2});function xae(n,t,o){return o.indexOf(n)===t}function Yae(n){let[t]=n.soundSampleDescription??[];return t?n.isAudio?n.isAudio():!!t.description&&t.description.numAudioChannels>0:!1}var jae,Ii,Bqe,Kae,O2,qae=ue(()=>{jae=Je(ct(),1);DA();Hi();WB();Hae();lf();lf();Gl();YB();_s();Ii=(0,jae.default)("music-metadata:parser:MP4"),Bqe="iTunes",Kae={raw:{lossy:!1,format:"raw"},MAC3:{lossy:!0,format:"MACE 3:1"},MAC6:{lossy:!0,format:"MACE 6:1"},ima4:{lossy:!0,format:"IMA 4:1"},ulaw:{lossy:!0,format:"uLaw 2:1"},alaw:{lossy:!0,format:"uLaw 2:1"},Qclp:{lossy:!0,format:"QUALCOMM PureVoice"},".mp3":{lossy:!0,format:"MPEG-1 layer 3"},alac:{lossy:!1,format:"ALAC"},"ac-3":{lossy:!0,format:"AC-3"},mp4a:{lossy:!0,format:"MPEG-4/AAC"},mp4s:{lossy:!0,format:"MP4S"},c608:{lossy:!0,format:"CEA-608"},c708:{lossy:!0,format:"CEA-708"}};O2=class n extends Rt{constructor(){super(...arguments),this.tracks=new Map,this.hasVideoTrack=!1,this.hasAudioTrack=!0,this.atomParsers={mvhd:async t=>{let o=await this.tokenizer.readToken(new MO(t));this.metadata.setFormat("creationTime",o.creationTime),this.metadata.setFormat("modificationTime",o.modificationTime)},chap:async t=>{let o=this.getTrackDescription(),i=[];for(;t>=Ue.len;)i.push(await this.tokenizer.readNumber(Ue)),t-=Ue.len;o.chapterList=i},mdat:async t=>{if(this.options.includeChapters){let o=[...this.tracks.values()].filter(i=>i.chapterList);if(o.length===1){let i=o[0].chapterList,e=[...this.tracks.values()].filter(a=>i.indexOf(a.header.trackId)!==-1);if(e.length===1)return this.parseChapterTrack(e[0],o[0],t)}}await this.tokenizer.ignore(t)},ftyp:async t=>{let o=[];for(;t>0;){let e=await this.tokenizer.readToken(w2);t-=w2.len;let a=e.type.replace(/\W/g,"");a.length>0&&o.push(a)}Ii(`ftyp: ${o.join("/")}`);let i=o.filter(xae).join("/");this.metadata.setFormat("container",i)},stsd:async t=>{let o=await this.tokenizer.readToken(new gf(t)),i=this.getTrackDescription();i.soundSampleDescription=o.table.map(e=>this.parseSoundSampleDescription(e))},stsz:async t=>{let o=await this.tokenizer.readToken(new If(t)),i=this.getTrackDescription();i.sampleSize=o.sampleSize,i.sampleSizeTable=o.entries},date:async t=>{let o=await this.tokenizer.readToken(new ze(t,"utf-8"));await this.addTag("date",o)}}}static read_BE_Integer(t,o){let i=(o?"INT":"UINT")+t.length*8+(t.length>1?"_BE":""),e=VA[i];if(!e)throw new Kg(`Token for integer type not found: "${i}"`);return Number(e.get(t,0))}async parse(){this.hasVideoTrack=!1,this.hasAudioTrack=!0,this.tracks.clear();let t=this.tokenizer.fileInfo.size||0;for(;!this.tokenizer.fileInfo.size||t>0;){try{if((await this.tokenizer.peekToken(ql)).name==="\0\0\0\0"){let A=`Error at offset=${this.tokenizer.position}: box.id=0`;Ii(A),this.addWarning(A);break}}catch(a){if(a instanceof Error){let A=`Error at offset=${this.tokenizer.position}: ${a.message}`;Ii(A),this.addWarning(A)}else throw a;break}let e=await KO.readAtom(this.tokenizer,(a,A)=>this.handleAtom(a,A),null,t);t-=e.header.length===BigInt(0)?t:Number(e.header.length)}let o=[];this.tracks.forEach(e=>{let a=[],A=Yae(e);e.soundSampleDescription.forEach(r=>{let s={},g=Kae[r.dataFormat];if(g?(a.push(g.format),s.codecName=g.format):s.codecName=`<${r.dataFormat}>`,A&&r.description){let{description:c}=r;c.sampleRate>0&&(s.type=Ia.audio,s.audio={samplingFrequency:c.sampleRate,bitDepth:c.sampleSize,channels:c.numAudioChannels})}this.metadata.addStreamInfo(s)}),a.length>=1&&o.push(a.join("/"))}),o.length>0&&this.metadata.setFormat("codec",o.filter(xae).join("+"));let i=[...this.tracks.values()].filter(Yae);for(let e of i){if(e.media.header&&e.media.header.timeScale>0)if(e.sampleRate=e.media.header.timeScale,e.media.header.duration>0&&(Ii("Using duration defined on audio track"),e.samples=e.media.header.duration,e.duration=e.samples/e.sampleRate),e.fragments.length>0){Ii("Calculate duration defined in track fragments");let r=0;e.sizeInBytes=0;for(let s of e.fragments)for(let g of s.trackRun.samples){let c=g.sampleDuration??s.header.defaultSampleDuration??0,I=g.sampleSize??s.header.defaultSampleSize??0;if(c===0)throw new Error("Missing sampleDuration and no defaultSampleDuration in track fragment header");if(I===0)throw new Error("Missing sampleSize and no defaultSampleSize in track fragment header");r+=c,e.sizeInBytes+=I}e.samples||(e.samples=r),e.duration||(e.duration=r/e.sampleRate)}else e.sampleSizeTable.length>0&&(e.sizeInBytes=e.sampleSizeTable.reduce((r,s)=>r+s,0));let a=e.soundSampleDescription[0];if(a.description&&e.media.header&&(this.metadata.setFormat("sampleRate",a.description.sampleRate),this.metadata.setFormat("bitsPerSample",a.description.sampleSize),this.metadata.setFormat("numberOfChannels",a.description.numAudioChannels),e.media.header.timeScale===0&&e.timeToSampleTable.length>0)){let r=e.timeToSampleTable.map(s=>s.count*s.duration).reduce((s,g)=>s+g);e.duration=r/a.description.sampleRate}let A=Kae[a.dataFormat];A&&this.metadata.setFormat("lossless",!A.lossy)}if(i.length>=1){let e=i[0];e.duration&&(this.metadata.setFormat("duration",e.duration),e.sizeInBytes&&this.metadata.setFormat("bitrate",8*e.sizeInBytes/e.duration))}this.metadata.setFormat("hasAudio",this.hasAudioTrack),this.metadata.setFormat("hasVideo",this.hasVideoTrack)}async handleAtom(t,o){if(t.parent)switch(t.parent.header.name){case"ilst":case"":return this.parseMetadataItemData(t);case"moov":switch(t.header.name){case"trak":return this.parseTrackBox(t);case"udta":return this.parseTrackBox(t)}break;case"moof":switch(t.header.name){case"traf":return this.parseTrackFragmentBox(t)}}if(this.atomParsers[t.header.name])return this.atomParsers[t.header.name](o);Ii(`No parser for atom path=${t.atomPath}, payload-len=${o}, ignoring atom`),await this.tokenizer.ignore(o)}getTrackDescription(){let t=[...this.tracks.values()];return t[t.length-1]}async addTag(t,o){await this.metadata.addTag(Bqe,t,o)}addWarning(t){Ii(`Warning: ${t}`),this.metadata.addWarning(t)}parseMetadataItemData(t){let o=t.header.name;return t.readAtoms(this.tokenizer,async(i,e)=>{let a=i.getPayloadLength(e);switch(i.header.name){case"data":return this.parseValueAtom(o,i);case"name":case"mean":case"rate":{let A=await this.tokenizer.readToken(new TO(a));o+=`:${A.name}`;break}default:{let A=await this.tokenizer.readToken(new Dt(a));this.addWarning(`Unsupported meta-item: ${o}[${i.header.name}] => value=${jD(A)} ascii=${wr(A,"ascii")}`)}}},t.getPayloadLength(0))}async parseValueAtom(t,o){let i=await this.tokenizer.readToken(new _O(Number(o.header.length)-ql.len));if(i.type.set!==0)throw new Kg(`Unsupported type-set != 0: ${i.type.set}`);switch(i.type.type){case 0:switch(t){case"trkn":case"disk":{let e=fA.get(i.value,3),a=fA.get(i.value,5);await this.addTag(t,`${e}/${a}`);break}case"gnre":{let e=fA.get(i.value,1),a=Rh[e-1];await this.addTag(t,a);break}case"rate":{let e=wr(i.value,"ascii");await this.addTag(t,e);break}default:Ii(`unknown proprietary value type for: ${o.atomPath}`)}break;case 1:case 18:await this.addTag(t,wr(i.value));break;case 13:if(this.options.skipCovers)break;await this.addTag(t,{format:"image/jpeg",data:Uint8Array.from(i.value)});break;case 14:if(this.options.skipCovers)break;await this.addTag(t,{format:"image/png",data:Uint8Array.from(i.value)});break;case 21:await this.addTag(t,n.read_BE_Integer(i.value,!0));break;case 22:await this.addTag(t,n.read_BE_Integer(i.value,!1));break;case 65:await this.addTag(t,fA.get(i.value,0));break;case 66:await this.addTag(t,GA.get(i.value,0));break;case 67:await this.addTag(t,Ue.get(i.value,0));break;default:this.addWarning(`atom key=${t}, has unknown well-known-type (data-type): ${i.type.type}`)}}async parseTrackBox(t){let o={media:{},fragments:[]};await t.readAtoms(this.tokenizer,async(i,e)=>{let a=i.getPayloadLength(e);switch(i.header.name){case"chap":{let A=await this.tokenizer.readToken(new UO(e));o.chapterList=A;break}case"tkhd":o.header=await this.tokenizer.readToken(new NO(a));break;case"hdlr":o.handler=await this.tokenizer.readToken(new LO(a)),o.isAudio=()=>o.handler.handlerType==="audi"||o.handler.handlerType==="soun",o.isVideo=()=>o.handler.handlerType==="vide",o.isAudio()?this.hasAudioTrack=!0:o.isVideo()&&(this.hasVideoTrack=!0);break;case"mdhd":{let A=await this.tokenizer.readToken(new bO(a));o.media.header=A;break}case"stco":{let A=await this.tokenizer.readToken(new vO(a));o.chunkOffsetTable=A.entries;break}case"stsc":{let A=await this.tokenizer.readToken(new kO(a));o.sampleToChunkTable=A.entries;break}case"stsd":{let A=await this.tokenizer.readToken(new gf(a));o.soundSampleDescription=A.table.map(r=>this.parseSoundSampleDescription(r));break}case"stts":{let A=await this.tokenizer.readToken(new RO(a));o.timeToSampleTable=A.entries;break}case"stsz":{let A=await this.tokenizer.readToken(new If(a));o.sampleSize=A.sampleSize,o.sampleSizeTable=A.entries;break}case"dinf":case"vmhd":case"smhd":Ii(`Ignoring: ${i.header.name}`),await this.tokenizer.ignore(a);break;default:Ii(`Unexpected track box: ${i.header.name}`),await this.tokenizer.ignore(a)}},t.getPayloadLength(0)),this.tracks.set(o.header.trackId,o)}parseTrackFragmentBox(t){let o;return t.readAtoms(this.tokenizer,async(i,e)=>{let a=i.getPayloadLength(e);switch(i.header.name){case"tfhd":{let A=new GO(i.getPayloadLength(e));o=await this.tokenizer.readToken(A);break}case"tfdt":await this.tokenizer.ignore(a);break;case"trun":{let A=new FO(a),r=await this.tokenizer.readToken(A);o&&this.tracks.get(o.trackId)?.fragments.push({header:o,trackRun:r});break}default:Ii(`Unexpected box: ${i.header.name}`),await this.tokenizer.ignore(a)}},t.getPayloadLength(0))}parseSoundSampleDescription(t){let o={dataFormat:t.dataFormat,dataReferenceIndex:t.dataReferenceIndex},i=0,{description:e}=t;if(e&&e.length>=HO.len){let a=HO.get(e,i);i+=HO.len,a.version===0||a.version===1?e.length>=i+D2.len?o.description=D2.get(e,i):Ii(`Warning: sound-sample-description too short: ${e.length} bytes`):Ii(`Warning: sound-sample-description ${a} not implemented`)}return o}async parseChapterTrack(t,o,i){if(!t.sampleSize&&t.chunkOffsetTable.length!==t.sampleSizeTable.length)throw new Error("Expected equal chunk-offset-table & sample-size-table length.");let e=[];for(let a=0;a0;++a){let A=t.timeToSampleTable.slice(0,a).reduce((d,B)=>d+B.duration,0),s=t.chunkOffsetTable[a]-this.tokenizer.position,g=t.sampleSize>0?t.sampleSize:t.sampleSizeTable[a];if(i-=s+g,i<0)throw new Kg("Chapter chunk exceeding token length");await this.tokenizer.ignore(s);let c=await this.tokenizer.readToken(new PO(g));Ii(`Chapter ${a+1}: ${c}`);let I={title:c,timeScale:t.media.header?t.media.header.timeScale:0,start:A,sampleOffset:this.findSampleOffset(o,this.tokenizer.position)};Ii(`Chapter title=${I.title}, offset=${I.sampleOffset}/${o.header.duration}`),e.push(I)}this.metadata.setFormat("chapters",e),await this.tokenizer.ignore(i)}findSampleOffset(t,o){let i=0;for(;i=o[i].firstChunk&&t{zae={parserType:"mp4",extensions:[".mp4",".m4a",".m4b",".m4pa","m4v","m4r","3gp",".mov",".movie",".qt"],mimeTypes:["audio/mp4","audio/m4a","video/m4v","video/mp4","video/quicktime"],async load(){return(await Promise.resolve().then(()=>(qae(),Jae))).MP4Parser}}});var $ae,Wae,fqe,Zae,Xae,xO,eie=ue(()=>{DA();$ae=Je(ct(),1);Ar();Wae=(0,$ae.default)("music-metadata:parser:musepack:sv8"),fqe=new ze(2,"latin1"),Zae={len:5,get:(n,t)=>({crc:Ge.get(n,t),streamVersion:fA.get(n,t+4)})},Xae={len:2,get:(n,t)=>({sampleFrequency:[44100,48e3,37800,32e3][XA(n,t,0,3)],maxUsedBands:XA(n,t,3,5),channelCount:XA(n,t+1,0,4)+1,msUsed:Da(n,t+1,4),audioBlockFrames:XA(n,t+1,5,3)})},xO=class{get tokenizer(){return this._tokenizer}set tokenizer(t){this._tokenizer=t}constructor(t){this._tokenizer=t}async readPacketHeader(){let t=await this.tokenizer.readToken(fqe),o=await this.readVariableSizeField();return{key:t,payloadLength:o.value-2-o.len}}async readStreamHeader(t){let o={};Wae(`Reading SH at offset=${this.tokenizer.position}`);let i=await this.tokenizer.readToken(Zae);t-=Zae.len,Object.assign(o,i),Wae(`SH.streamVersion = ${i.streamVersion}`);let e=await this.readVariableSizeField();t-=e.len,o.sampleCount=e.value;let a=await this.readVariableSizeField();t-=a.len,o.beginningOfSilence=a.value;let A=await this.tokenizer.readToken(Xae);return t-=Xae.len,Object.assign(o,A),await this.tokenizer.ignore(t),o}async readVariableSizeField(t=1,o=0){let i=await this.tokenizer.readNumber(fA);return(i&128)===0?{len:t,value:o+i}:(i&=127,i+=o,this.readVariableSizeField(t+1,i<<7))}}});var xg,YO=ue(()=>{er();xg=class extends Qt("Musepack"){}});var Aie,yqe,jO,tie=ue(()=>{Aie=Je(ct(),1);Hi();Ul();si();eie();YO();yqe=(0,Aie.default)("music-metadata:parser:musepack"),jO=class extends Rt{constructor(){super(...arguments),this.audioLength=0}async parse(){if(await this.tokenizer.readToken(at)!=="MPCK")throw new xg("Invalid Magic number");return this.metadata.setFormat("container","Musepack, SV8"),this.parsePacket()}async parsePacket(){let t=new xO(this.tokenizer);do{let o=await t.readPacketHeader();switch(yqe(`packet-header key=${o.key}, payloadLength=${o.payloadLength}`),o.key){case"SH":{let i=await t.readStreamHeader(o.payloadLength);this.metadata.setFormat("numberOfSamples",i.sampleCount),this.metadata.setFormat("sampleRate",i.sampleFrequency),this.metadata.setFormat("duration",i.sampleCount/i.sampleFrequency),this.metadata.setFormat("numberOfChannels",i.channelCount);break}case"AP":this.audioLength+=o.payloadLength,await this.tokenizer.ignore(o.payloadLength);break;case"RG":case"EI":case"SO":case"ST":case"CT":await this.tokenizer.ignore(o.payloadLength);break;case"SE":return this.metadata.format.duration&&this.metadata.setFormat("bitrate",this.audioLength*8/this.metadata.format.duration),Ll(this.metadata,this.tokenizer,this.options);default:throw new xg(`Unexpected header: ${o.key}`)}}while(!0)}}});var JO,rie=ue(()=>{DA();JO=class{constructor(t){this.pos=0,this.dword=null,this.tokenizer=t}async read(t){for(;this.dword===null;)this.dword=await this.tokenizer.readToken(Ge);let o=this.dword;return this.pos+=t,this.pos<32?(o>>>=32-this.pos,o&(1<>>32-this.pos),o&(1<0){let e=32-this.pos;this.dword=null,t-=e,this.pos=0}let o=t%32,i=(t-o)/32;return await this.tokenizer.ignore(i*4),this.read(o)}}});var aie,iie=ue(()=>{DA();Ar();_s();aie={len:24,get:(n,t)=>{let o={signature:wr(n.subarray(t,t+3),"latin1"),streamMinorVersion:XA(n,t+3,0,4),streamMajorVersion:XA(n,t+3,4,4),frameCount:Ge.get(n,t+4),maxLevel:SA.get(n,t+8),sampleFrequency:[44100,48e3,37800,32e3][XA(n,t+10,0,2)],link:XA(n,t+10,2,2),profile:XA(n,t+10,4,4),maxBand:XA(n,t+11,0,6),intensityStereo:Da(n,t+11,6),midSideStereo:Da(n,t+11,7),titlePeak:SA.get(n,t+12),titleGain:SA.get(n,t+14),albumPeak:SA.get(n,t+16),albumGain:SA.get(n,t+18),lastFrameLength:Ge.get(n,t+20)>>>20&2047,trueGapless:Da(n,t+23,0)};return o.lastFrameLength=o.trueGapless?Ge.get(n,20)>>>20&2047:0,o}}});var nie,oie,qO,sie=ue(()=>{nie=Je(ct(),1);Hi();Ul();rie();iie();YO();oie=(0,nie.default)("music-metadata:parser:musepack"),qO=class extends Rt{constructor(){super(...arguments),this.bitreader=null,this.audioLength=0,this.duration=null}async parse(){let t=await this.tokenizer.readToken(aie);if(t.signature!=="MP+")throw new xg("Unexpected magic number");oie(`stream-version=${t.streamMajorVersion}.${t.streamMinorVersion}`),this.metadata.setFormat("container","Musepack, SV7"),this.metadata.setFormat("sampleRate",t.sampleFrequency);let o=1152*(t.frameCount-1)+t.lastFrameLength;this.metadata.setFormat("numberOfSamples",o),this.duration=o/t.sampleFrequency,this.metadata.setFormat("duration",this.duration),this.bitreader=new JO(this.tokenizer),this.metadata.setFormat("numberOfChannels",t.midSideStereo||t.intensityStereo?2:1);let i=await this.bitreader.read(8);return this.metadata.setFormat("codec",(i/100).toFixed(2)),await this.skipAudioData(t.frameCount),oie(`End of audio stream, switching to APEv2, offset=${this.tokenizer.position}`),Ll(this.metadata,this.tokenizer,this.options)}async skipAudioData(t){for(;t-- >0;){let i=await this.bitreader.read(20);this.audioLength+=20+i,await this.bitreader.ignore(i)}let o=await this.bitreader.read(11);this.audioLength+=o,this.duration!==null&&this.metadata.setFormat("bitrate",this.audioLength/this.duration)}}});var Iie={};Pr(Iie,{MusepackParser:()=>b2});var cie,gie,b2,lie=ue(()=>{cie=Je(ct(),1);DA();$B();tie();sie();YO();gie=(0,cie.default)("music-metadata:parser:musepack"),b2=class extends Fs{async postId3v2Parse(){let t=await this.tokenizer.peekToken(new ze(3,"latin1")),o;switch(t){case"MP+":{gie("Stream-version 7"),o=new qO(this.metadata,this.tokenizer,this.options);break}case"MPC":{gie("Stream-version 8"),o=new jO(this.metadata,this.tokenizer,this.options);break}default:throw new xg("Invalid signature prefix")}return this.metadata.setAudioOnly(),o.parse()}}});var pie,die=ue(()=>{pie={parserType:"musepack",extensions:[".mpc"],mimeTypes:["audio/musepack"],async load(){return(await Promise.resolve().then(()=>(lie(),Iie))).MusepackParser}}});var pf,zO,M2=ue(()=>{DA();er();pf=class extends Qt("Opus"){},zO=class{constructor(t){if(t<19)throw new pf("ID-header-page 0 should be at least 19 bytes long");this.len=t}get(t,o){return{magicSignature:new ze(8,"ascii").get(t,o+0),version:fA.get(t,o+8),channelCount:fA.get(t,o+9),preSkip:SA.get(t,o+10),inputSampleRate:Ge.get(t,o+12),outputGain:SA.get(t,o+16),channelMapping:fA.get(t,o+18)}}}});var VO,hie=ue(()=>{DA();af();M2();M2();VO=class extends Us{constructor(t,o,i){super(t,o),this.idHeader=null,this.lastPos=-1,this.tokenizer=i,this.durationOnLastPage=!0}parseFirstPage(t,o){if(this.metadata.setFormat("codec","Opus"),this.idHeader=new zO(o.length).get(o,0),this.idHeader.magicSignature!=="OpusHead")throw new pf("Illegal ogg/Opus magic-signature");this.metadata.setFormat("sampleRate",this.idHeader.inputSampleRate),this.metadata.setFormat("numberOfChannels",this.idHeader.channelCount),this.metadata.setAudioOnly()}async parseFullPage(t){switch(new ze(8,"ascii").get(t,0)){case"OpusTags":await this.parseUserCommentList(t,8),this.lastPos=this.tokenizer.position-t.length;break;default:break}}calculateDuration(t){if(this.lastPageHeader&&(t||this.lastPageHeader.headerType.lastPage)&&this.metadata.format.sampleRate&&this.lastPageHeader.absoluteGranulePosition>=0){let o=this.lastPageHeader.absoluteGranulePosition-this.idHeader.preSkip;if(this.metadata.setFormat("numberOfSamples",o),this.metadata.setFormat("duration",o/48e3),this.lastPos!==-1&&this.tokenizer.fileInfo.size&&this.metadata.format.duration){let i=this.tokenizer.fileInfo.size-this.lastPos;this.metadata.setFormat("bitrate",8*i/this.metadata.format.duration)}}}}});var Eie,Cie=ue(()=>{DA();Ar();Eie={len:80,get:(n,t)=>({speex:new ze(8,"ascii").get(n,t+0),version:WD(new ze(20,"ascii").get(n,t+8)),version_id:sr.get(n,t+28),header_size:sr.get(n,t+32),rate:sr.get(n,t+36),mode:sr.get(n,t+40),mode_bitstream_version:sr.get(n,t+44),nb_channels:sr.get(n,t+48),bitrate:sr.get(n,t+52),frame_size:sr.get(n,t+56),vbr:sr.get(n,t+60),frames_per_packet:sr.get(n,t+64),extra_headers:sr.get(n,t+68),reserved1:sr.get(n,t+72),reserved2:sr.get(n,t+76)})}});var Bie,uie,WO,fie=ue(()=>{Bie=Je(ct(),1);af();Cie();uie=(0,Bie.default)("music-metadata:parser:ogg:speex"),WO=class extends Us{constructor(t,o,i){super(t,o),this.commentHeaderParsed=!1}parseFirstPage(t,o){uie("First Ogg/Speex page");let i=Eie.get(o,0);this.metadata.setFormat("codec",`Speex ${i.version}`),this.metadata.setFormat("numberOfChannels",i.nb_channels),this.metadata.setFormat("sampleRate",i.rate),i.bitrate!==-1&&this.metadata.setFormat("bitrate",i.bitrate),this.metadata.setAudioOnly()}async parseFullPage(t){this.commentHeaderParsed||(this.commentHeaderParsed=!0,uie("Parse Ogg/Speex comment header"),await this.parseUserCommentList(t,0))}}});var Qie,yie=ue(()=>{DA();Qie={len:42,get:(n,t)=>({id:new ze(7,"ascii").get(n,t),vmaj:fA.get(n,t+7),vmin:fA.get(n,t+8),vrev:fA.get(n,t+9),vmbw:GA.get(n,t+10),vmbh:GA.get(n,t+17),nombr:kr.get(n,t+37),nqual:fA.get(n,t+40)})}});var Sie,mie,ZO,wie=ue(()=>{Sie=Je(ct(),1);yie();mie=(0,Sie.default)("music-metadata:parser:ogg:theora"),ZO=class{constructor(t,o,i){this.durationOnLastPage=!1,this.metadata=t}async parsePage(t,o){t.headerType.firstPage&&await this.parseFirstPage(t,o)}calculateDuration(){mie("duration calculation not implemented")}async parseFirstPage(t,o){mie("First Ogg/Theora page"),this.metadata.setFormat("codec","Theora");let i=Qie.get(o,0);this.metadata.setFormat("bitrate",i.nombr),this.metadata.setFormat("hasVideo",!0)}flush(){return Promise.resolve()}}});var Die,XO,Oie=ue(()=>{DA();Ar();DA();Die={len:27,get:(n,t)=>({capturePattern:new ze(4,"latin1").get(n,t),version:fA.get(n,t+4),headerType:{continued:vA(n,t+5,0),firstPage:vA(n,t+5,1),lastPage:vA(n,t+5,2)},absoluteGranulePosition:Number(Dr.get(n,t+6)),streamSerialNumber:Ge.get(n,t+14),pageSequenceNo:Ge.get(n,t+18),pageChecksum:Ge.get(n,t+22),page_segments:fA.get(n,t+26)})},XO=class n{static sum(t,o,i){let e=new DataView(t.buffer,0),a=0;for(let A=o;A{bie=Je(ct(),1);u2();B2();si();yO();_2=(0,bie.default)("music-metadata:parser:ogg:theora"),$O=class{constructor(t,o,i){this.durationOnLastPage=!1,this.metadata=t,this.options=o,this.tokenizer=i,this.flacParser=new sf(this.metadata,this.tokenizer,o)}async parsePage(t,o){t.headerType.firstPage&&await this.parseFirstPage(t,o)}calculateDuration(){_2("duration calculation not implemented")}async parseFirstPage(t,o){if(_2("First Ogg/FLAC page"),(await at.get(o,9)).toString()!=="fLaC")throw new Error("Invalid FLAC preamble");let e=await of.get(o,13);await this.parseDataBlock(e,o.subarray(13+of.len))}async parseDataBlock(t,o){switch(_2(`blockHeader type=${t.type}, length=${t.length}`),t.type){case ci.STREAMINFO:{let i=nf.get(o,0);return this.flacParser.processsStreamInfo(i)}case ci.PADDING:break;case ci.APPLICATION:break;case ci.SEEKTABLE:break;case ci.VORBIS_COMMENT:return this.flacParser.parseComment(o);case ci.PICTURE:if(!this.options.skipCovers){let i=new cI(o.length).get(o,0);return this.flacParser.addPictureTag(i)}break;default:this.metadata.addWarning(`Unknown block type: ${t.type}`)}return this.tokenizer.ignore(t.length).then()}flush(){return Promise.resolve()}}});var Tie={};Pr(Tie,{OggContentError:()=>qh,OggParser:()=>N2});var _ie,qh,Ks,T2,N2,Nie=ue(()=>{DA();so();_ie=Je(ct(),1);Hi();af();hie();fie();wie();er();Oie();Mie();qh=class extends Qt("Ogg"){},Ks=(0,_ie.default)("music-metadata:parser:ogg"),T2=class{constructor(t,o,i){this.pageNumber=0,this.closed=!1,this.metadata=t,this.streamSerial=o,this.options=i}async parsePage(t,o){this.pageNumber=o.pageSequenceNo,Ks("serial=%s page#=%s, Ogg.id=%s",o.streamSerialNumber,o.pageSequenceNo,o.capturePattern);let i=await t.readToken(new XO(o));Ks("totalPageSize=%s",i.totalPageSize);let e=await t.readToken(new Dt(i.totalPageSize));if(Ks("firstPage=%s, lastPage=%s, continued=%s",o.headerType.firstPage,o.headerType.lastPage,o.headerType.continued),o.headerType.firstPage){this.metadata.setFormat("container","Ogg");let a=e.subarray(0,7),A=Array.from(a).filter(r=>r>=32&&r<=126).map(r=>String.fromCharCode(r)).join("");switch(A){case"vorbis":Ks(`Set Ogg stream serial ${o.streamSerialNumber}, codec=Vorbis`),this.pageConsumer=new Us(this.metadata,this.options);break;case"OpusHea":Ks("Set page consumer to Ogg/Opus"),this.pageConsumer=new VO(this.metadata,this.options,t);break;case"Speex ":Ks("Set page consumer to Ogg/Speex"),this.pageConsumer=new WO(this.metadata,this.options,t);break;case"fishead":case"theora":Ks("Set page consumer to Ogg/Theora"),this.pageConsumer=new ZO(this.metadata,this.options,t);break;case"FLAC":Ks("Set page consumer to Vorbis"),this.pageConsumer=new $O(this.metadata,this.options,t);break;default:throw new qh(`Ogg codec not recognized (id=${A}`)}}if(o.headerType.lastPage&&(this.closed=!0),this.pageConsumer)await this.pageConsumer.parsePage(o,e);else throw new Error("pageConsumer should be initialized")}},N2=class extends Rt{constructor(){super(...arguments),this.streams=new Map}async parse(){this.streams=new Map;let t=!1,o;try{do{if(o=await this.tokenizer.readToken(Die),o.capturePattern!=="OggS")throw new qh("Invalid Ogg capture pattern");let i=this.streams.get(o.streamSerialNumber);if(i||(i=new T2(this.metadata,o.streamSerialNumber,this.options),this.streams.set(o.streamSerialNumber,i)),await i.parsePage(this.tokenizer,o),i.pageNumber>12&&!(this.options.duration&&[...this.streams.values()].find(e=>e.pageConsumer?.durationOnLastPage))){Ks("Stop processing Ogg stream");break}}while(![...this.streams.values()].every(i=>i.closed))}catch(i){if(i instanceof bA)Ks("Reached end-of-stream"),t=!0;else if(i instanceof qh)this.metadata.addWarning(`Corrupt Ogg content at ${this.tokenizer.position}`);else throw i}for(let i of this.streams.values())i.closed||(this.metadata.addWarning(`End-of-stream reached before reaching last page in Ogg stream serial=${i.streamSerial}`),await i.pageConsumer?.flush()),i.pageConsumer?.calculateDuration(t)}}});var Rie,kie=ue(()=>{Rie={parserType:"ogg",extensions:[".ogg",".ogv",".oga",".ogm",".ogx",".opus",".spx"],mimeTypes:["audio/ogg","audio/opus","audio/speex","video/ogg"],async load(){return(await Promise.resolve().then(()=>(Nie(),Tie))).OggParser}}});function xs(n,t){return eb(n,t,1)===1}function eb(n,t,o){return n>>>t&4294967295>>>32-o}var Dqe,df,Ab,vie=ue(()=>{DA();si();Dqe=[6e3,8e3,9600,11025,12e3,16e3,22050,24e3,32e3,44100,48e3,64e3,88200,96e3,192e3,-1],df={len:32,get:(n,t)=>{let o=Ge.get(n,t+24),i={BlockID:at.get(n,t),blockSize:Ge.get(n,t+4),version:SA.get(n,t+8),totalSamples:Ge.get(n,t+12),blockIndex:Ge.get(n,t+16),blockSamples:Ge.get(n,t+20),flags:{bitsPerSample:(1+eb(o,0,2))*8,isMono:xs(o,2),isHybrid:xs(o,3),isJointStereo:xs(o,4),crossChannel:xs(o,5),hybridNoiseShaping:xs(o,6),floatingPoint:xs(o,7),samplingRate:Dqe[eb(o,23,4)],isDSD:xs(o,31)},crc:new Dt(4).get(n,t+28)};return i.flags.isDSD&&(i.totalSamples*=8),i}},Ab={len:1,get:(n,t)=>({functionId:eb(n[t],0,6),isOptional:xs(n[t],5),isOddSize:xs(n[t],6),largeBlock:xs(n[t],7)})}});var Gie={};Pr(Gie,{WavPackContentError:()=>zh,WavPackParser:()=>R2});var Pie,zl,zh,R2,Fie=ue(()=>{DA();Ul();si();Hi();vie();Pie=Je(ct(),1);YB();er();zl=(0,Pie.default)("music-metadata:parser:WavPack"),zh=class extends Qt("WavPack"){},R2=class extends Rt{constructor(){super(...arguments),this.audioDataSize=0}async parse(){return this.metadata.setAudioOnly(),this.audioDataSize=0,await this.parseWavPackBlocks(),Ll(this.metadata,this.tokenizer,this.options)}async parseWavPackBlocks(){do{if(await this.tokenizer.peekToken(at)!=="wvpk")break;let o=await this.tokenizer.readToken(df);if(o.BlockID!=="wvpk")throw new zh("Invalid WavPack Block-ID");zl(`WavPack header blockIndex=${o.blockIndex}, len=${df.len}`),o.blockIndex===0&&!this.metadata.format.container&&(this.metadata.setFormat("container","WavPack"),this.metadata.setFormat("lossless",!o.flags.isHybrid),this.metadata.setFormat("bitsPerSample",o.flags.bitsPerSample),o.flags.isDSD||(this.metadata.setFormat("sampleRate",o.flags.samplingRate),this.metadata.setFormat("duration",o.totalSamples/o.flags.samplingRate)),this.metadata.setFormat("numberOfChannels",o.flags.isMono?1:2),this.metadata.setFormat("numberOfSamples",o.totalSamples),this.metadata.setFormat("codec",o.flags.isDSD?"DSD":"PCM"));let i=o.blockSize-(df.len-8);await(o.blockIndex===0?this.parseMetadataSubBlock(o,i):this.tokenizer.ignore(i)),o.blockSamples>0&&(this.audioDataSize+=o.blockSize)}while(!this.tokenizer.fileInfo.size||this.tokenizer.fileInfo.size-this.tokenizer.position>=df.len);this.metadata.format.duration&&this.metadata.setFormat("bitrate",this.audioDataSize*8/this.metadata.format.duration)}async parseMetadataSubBlock(t,o){let i=o;for(;i>Ab.len;){let e=await this.tokenizer.readToken(Ab),a=await this.tokenizer.readNumber(e.largeBlock?HB:fA),A=new Uint8Array(a*2-(e.isOddSize?1:0));switch(await this.tokenizer.readBuffer(A),zl(`Metadata Sub-Blocks functionId=0x${e.functionId.toString(16)}, id.largeBlock=${e.largeBlock},data-size=${A.length}`),e.functionId){case 0:break;case 14:{zl("ID_DSD_BLOCK");let r=1<{Lie={parserType:"wavpack",extensions:[".wv",".wvp"],mimeTypes:["audio/wavpack"],async load(){return(await Promise.resolve().then(()=>(Fie(),Gie))).WavPackParser}}});var Vh,tb,Hie=ue(()=>{DA();Vh={len:8,get:(n,t)=>({chunkID:new ze(4,"latin1").get(n,t),chunkSize:Ge.get(n,t+4)})},tb=class{constructor(t){this.tagHeader=t,this.len=t.chunkSize,this.len+=this.len&1}get(t,o){return new ze(this.tagHeader.chunkSize,"utf8").get(t,o)}}});var Vl,pa,Kie,rb,ab,k2=ue(()=>{DA();er();Vl=class extends Qt("Wave"){},pa={PCM:1,ADPCM:2,IEEE_FLOAT:3,ALAW:6,MULAW:7,DVI_ADPCM:17,GSM610:49,MPEG_ADTS_AAC:5632,MPEG_LOAS:5634,RAW_AAC1:255,DOLBY_AC3_SPDIF:146,DVM:8192,RAW_SPORT:576,ESST_AC3:577,DRM:9,DTS2:8193,MPEG:80,MPEGLAYER3:85},Kie={[pa.PCM]:"PCM",[pa.ADPCM]:"ADPCM",[pa.IEEE_FLOAT]:"IEEE_FLOAT",[pa.ALAW]:"ALAW",[pa.MULAW]:"MULAW",[pa.DVI_ADPCM]:"DVI_ADPCM",[pa.GSM610]:"GSM610",[pa.MPEG_ADTS_AAC]:"MPEG_ADTS_AAC",[pa.MPEG_LOAS]:"MPEG_LOAS",[pa.RAW_AAC1]:"RAW_AAC1",[pa.DOLBY_AC3_SPDIF]:"DOLBY_AC3_SPDIF",[pa.DVM]:"DVM",[pa.RAW_SPORT]:"RAW_SPORT",[pa.ESST_AC3]:"ESST_AC3",[pa.DRM]:"DRM",[pa.DTS2]:"DTS2",[pa.MPEG]:"MPEG",[pa.MPEGLAYER3]:"MPEGLAYER3"},rb=class{constructor(t){if(t.chunkSize<16)throw new Vl("Invalid chunk size");this.len=t.chunkSize}get(t,o){return{wFormatTag:SA.get(t,o),nChannels:SA.get(t,o+2),nSamplesPerSec:Ge.get(t,o+4),nAvgBytesPerSec:Ge.get(t,o+8),nBlockAlign:SA.get(t,o+12),wBitsPerSample:SA.get(t,o+14)}}},ab=class{constructor(t){if(t.chunkSize<4)throw new Vl("Invalid fact chunk size.");this.len=t.chunkSize}get(t,o){return{dwSampleLength:Ge.get(t,o)}}}});var v2,xie=ue(()=>{DA();Ar();v2={len:420,get:(n,t)=>({description:Wo(new ze(256,"ascii").get(n,t)).trim(),originator:Wo(new ze(32,"ascii").get(n,t+256)).trim(),originatorReference:Wo(new ze(32,"ascii").get(n,t+288)).trim(),originationDate:Wo(new ze(10,"ascii").get(n,t+320)).trim(),originationTime:Wo(new ze(8,"ascii").get(n,t+330)).trim(),timeReferenceLow:Ge.get(n,t+338),timeReferenceHigh:Ge.get(n,t+342),version:SA.get(n,t+346),umid:new Dt(64).get(n,t+348),loudnessValue:SA.get(n,t+412),maxTruePeakLevel:SA.get(n,t+414),maxMomentaryLoudness:SA.get(n,t+416),maxShortTermLoudness:SA.get(n,t+418)})}});var jie={};Pr(jie,{WaveParser:()=>P2});var Yie,II,P2,Jie=ue(()=>{so();DA();Yie=Je(ct(),1);Hie();k2();kh();Ar();si();Hi();xie();k2();II=(0,Yie.default)("music-metadata:parser:RIFF"),P2=class extends Rt{constructor(){super(...arguments),this.blockAlign=0,this.avgBytesPerSec=0}async parse(){let t=await this.tokenizer.readToken(Vh);if(II(`pos=${this.tokenizer.position}, parse: chunkID=${t.chunkID}`),t.chunkID==="RIFF")return this.metadata.setAudioOnly(),this.parseRiffChunk(t.chunkSize).catch(o=>{if(!(o instanceof bA))throw o})}async parseRiffChunk(t){let o=await this.tokenizer.readToken(at);switch(this.metadata.setFormat("container",o),o){case"WAVE":return this.readWaveChunk(t-at.len);default:throw new Vl(`Unsupported RIFF format: RIFF/${o}`)}}async readWaveChunk(t){for(;t>=Vh.len;){let o=await this.tokenizer.readToken(Vh);switch(t-=Vh.len+o.chunkSize,o.chunkSize>t&&this.metadata.addWarning("Data chunk size exceeds file size"),this.header=o,II(`pos=${this.tokenizer.position}, readChunk: chunkID=RIFF/WAVE/${o.chunkID}`),o.chunkID){case"LIST":await this.parseListTag(o);break;case"fact":this.metadata.setFormat("lossless",!1),this.fact=await this.tokenizer.readToken(new ab(o));break;case"fmt ":{let i=await this.tokenizer.readToken(new rb(o)),e=Kie[i.wFormatTag];e||(II(`WAVE/non-PCM format=${i.wFormatTag}`),e=`non-PCM (${i.wFormatTag})`),this.metadata.setFormat("codec",e),this.metadata.setFormat("bitsPerSample",i.wBitsPerSample),this.metadata.setFormat("sampleRate",i.nSamplesPerSec),this.metadata.setFormat("numberOfChannels",i.nChannels),this.blockAlign=i.nBlockAlign,this.avgBytesPerSec=i.nAvgBytesPerSec;break}case"id3 ":case"ID3 ":{let i=await this.tokenizer.readToken(new Dt(o.chunkSize)),e=no(i);await new $o().parse(this.metadata,e,this.options);break}case"data":{this.metadata.format.lossless!==!1&&this.metadata.setFormat("lossless",!0);let i=o.chunkSize;if(this.tokenizer.fileInfo.size){let a=this.tokenizer.fileInfo.size-this.tokenizer.position;a0?this.metadata.setFormat("bitrate",this.avgBytesPerSec*8):this.metadata.format.duration&&this.metadata.setFormat("bitrate",i*8/this.metadata.format.duration),await this.tokenizer.ignore(o.chunkSize);break}case"bext":{let i=await this.tokenizer.readToken(v2);Object.keys(i).forEach(a=>{this.metadata.addTag("exif",`bext.${a}`,i[a])});let e=o.chunkSize-v2.len;await this.tokenizer.ignore(e);break}case"\0\0\0\0":II(`Ignore padding chunk: RIFF/${o.chunkID} of ${o.chunkSize} bytes`),this.metadata.addWarning(`Ignore chunk: RIFF/${o.chunkID}`),await this.tokenizer.ignore(o.chunkSize);break;default:II(`Ignore chunk: RIFF/${o.chunkID} of ${o.chunkSize} bytes`),this.metadata.addWarning(`Ignore chunk: RIFF/${o.chunkID}`),await this.tokenizer.ignore(o.chunkSize)}this.header.chunkSize%2===1&&(II("Read odd padding byte"),await this.tokenizer.ignore(1))}}async parseListTag(t){let o=await this.tokenizer.readToken(new ze(4,"latin1"));switch(II("pos=%s, parseListTag: chunkID=RIFF/WAVE/LIST/%s",this.tokenizer.position,o),o){case"INFO":return this.parseRiffInfoTags(t.chunkSize-4);default:return this.metadata.addWarning(`Ignore chunk: RIFF/WAVE/LIST/${o}`),II(`Ignoring chunkID=RIFF/WAVE/LIST/${o}`),this.tokenizer.ignore(t.chunkSize-4).then()}}async parseRiffInfoTags(t){for(;t>=8;){let o=await this.tokenizer.readToken(Vh),i=new tb(o),e=await this.tokenizer.readToken(i);this.addTag(o.chunkID,Wo(e)),t-=8+i.len}if(t!==0)throw new Vl(`Illegal remaining size: ${t}`)}addTag(t,o){this.metadata.addTag("exif",t,o)}}});var qie,zie=ue(()=>{qie={parserType:"riff",extensions:[".wav","wave",".bwf"],mimeTypes:["audio/vnd.wave","audio/wav","audio/wave"],async load(){return(await Promise.resolve().then(()=>(Jie(),jie))).WaveParser}}});function Mqe(n){let t=Vie.default.parse(n),o=Ute(t.type);return{type:o.type,subtype:o.subtype,suffix:o.suffix,parameters:t.parameters}}function _qe(n){let t=n.lastIndexOf(".");return t===-1?"":n.substring(t)}var Vie,Wie,Wl,Zl,G2=ue(()=>{PL();Vie=Je(Lte(),1);Hte();Wie=Je(ct(),1);gre();Gl();Pre();er();Fre();Zre();rae();cae();Eae();mae();Rae();Vae();die();kie();Uie();zie();ib();Wl=(0,Wie.default)("music-metadata:parser:factory");Zl=class{constructor(){this.parsers=[],[yae,vre,Gre,zae,Nae,qie,Rie,Wre,gae,Lie,pie,hae,tae].forEach(t=>{this.registerParser(t)})}registerParser(t){this.parsers.push(t)}async parse(t,o,i){if(t.supportsRandomAccess()?(Wl("tokenizer supports random-access, scanning for appending headers"),await F2(t,i)):Wl("tokenizer does not support random-access, cannot scan for appending headers"),!o){let r=new Uint8Array(4100);if(t.fileInfo.mimeType&&(o=this.findLoaderForContentType(t.fileInfo.mimeType)),!o&&t.fileInfo.path&&(o=this.findLoaderForExtension(t.fileInfo.path)),!o){Wl("Guess parser on content..."),await t.peekBuffer(r,{mayBeLess:!0});let s=await qB(r,{mpegOffsetTolerance:10});if(!s||!s.mime)throw new tI("Failed to determine audio format");if(Wl(`Guessed file type is mime=${s.mime}, extension=${s.ext}`),o=this.findLoaderForContentType(s.mime),!o)throw new rI(`Guessed MIME-type not supported: ${s.mime}`)}}Wl(`Loading ${o.parserType} parser...`);let e=new gO(i),a=await o.load(),A=new a(e,t,i??{});return Wl(`Parser ${o.parserType} loaded`),await A.parse(),e.format.trackInfo&&(e.format.hasAudio===void 0&&e.setFormat("hasAudio",!!e.format.trackInfo.find(r=>r.type===Ia.audio)),e.format.hasVideo===void 0&&e.setFormat("hasVideo",!!e.format.trackInfo.find(r=>r.type===Ia.video))),e.toCommonMetadata()}findLoaderForExtension(t){if(!t)return;let o=_qe(t).toLocaleLowerCase()||t;return this.parsers.find(i=>i.extensions.indexOf(o)!==-1)}findLoaderForContentType(t){let o;if(!t)return;try{o=Mqe(t)}catch{Wl(`Invalid HTTP Content-Type header value: ${t}`);return}let i=o.subtype.indexOf("x-")===0?o.subtype.substring(2):o.subtype;return this.parsers.find(e=>e.mimeTypes.find(a=>a.indexOf(`${o.type}/${i}`)!==-1))}getSupportedMimeTypes(){let t=new Set;return this.parsers.forEach(o=>{o.mimeTypes.forEach(i=>{t.add(i),t.add(i.replace("/","/x-"))})}),Array.from(t)}}});async function Zie(n){let t=n.fileInfo.size;if(t>=143){let o=new Uint8Array(15),i=n.position;await n.readBuffer(o,{position:t-143}),n.setPosition(i);let e=wr(o,"latin1");if(e.substring(6)===Tqe)return Number.parseInt(e.substring(0,6),10)+15}return 0}var Tqe,Xie=ue(()=>{_s();Tqe="LYRICS200"});async function Nqe(n,t={}){let o=FD(n);try{return await Wh(o,t)}finally{await o.close()}}async function Rqe(n,t,o={}){let i=GD(n,{fileInfo:typeof t=="string"?{mimeType:t}:t});try{return await Wh(i,o)}finally{await i.close()}}async function kqe(n,t,o={}){let i=no(n,{fileInfo:typeof t=="string"?{mimeType:t}:t});return Wh(i,o)}function Wh(n,t){return new Zl().parse(n,void 0,t)}function vqe(n){let t={};for(let{id:o,value:i}of n)(t[o]||(t[o]=[])).push(i);return t}function Pqe(n){return n===void 0?0:1+Math.round(n*4)}function Gqe(n){return n?n.reduce((t,o)=>o.name&&o.name.toLowerCase()in["front","cover","cover (front)"]?o:t):null}async function F2(n,t={}){let o=n.fileInfo.size;if(await ure(n)){o-=128;let i=await Zie(n);o-=i}t.apeHeader=await iI.findApeFooterOffset(n,o)}function Fqe(){return new Zl().getSupportedMimeTypes()}var ib=ue(()=>{so();G2();Ul();WB();Xie();Gl();er();er()});var Aoe={};Pr(Aoe,{CouldNotDetermineFileTypeError:()=>tI,FieldDecodingError:()=>Vo,InternalParserError:()=>vl,LyricsContentType:()=>bh,TimestampFormat:()=>Mh,UnexpectedFileContentError:()=>VD,UnsupportedFileTypeError:()=>rI,getSupportedMimeTypes:()=>Fqe,makeParseError:()=>Dh,makeUnexpectedFileContentError:()=>Qt,orderTags:()=>vqe,parseBlob:()=>Nqe,parseBuffer:()=>kqe,parseFile:()=>Uqe,parseFromTokenizer:()=>Wh,parseStream:()=>Lqe,parseWebStream:()=>Rqe,ratingToStars:()=>Pqe,scanAppendingHeaders:()=>F2,selectCover:()=>Gqe});async function Lqe(n,t,o={}){let i=await QL(n,{fileInfo:typeof t=="string"?{mimeType:t}:t});try{return await Wh(i,o)}finally{await i.close()}}async function Uqe(n,t={}){$ie(`parseFile: ${n}`);let o=await $Ae(n),i=new Zl;try{let e=i.findLoaderForExtension(n);e||$ie("Parser could not be determined by file extension");try{return await i.parse(o,e,t)}catch(a){throw(a instanceof tI||a instanceof rI)&&(a.message+=`: ${n}`),a}}finally{await o.close()}}var eoe,$ie,toe=ue(()=>{so();eoe=Je(ct(),1);ib();G2();ib();$ie=(0,eoe.default)("music-metadata:parser")});var Ene=$((f0A,uU)=>{"use strict";var V4e=Object.prototype.hasOwnProperty,li="~";function Of(){}Object.create&&(Of.prototype=Object.create(null),new Of().__proto__||(li=!1));function W4e(n,t,o){this.fn=n,this.context=t,this.once=o||!1}function hne(n,t,o,i,e){if(typeof o!="function")throw new TypeError("The listener must be a function");var a=new W4e(o,i||n,e),A=li?li+t:t;return n._events[A]?n._events[A].fn?n._events[A]=[n._events[A],a]:n._events[A].push(a):(n._events[A]=a,n._eventsCount++),n}function Bb(n,t){--n._eventsCount===0?n._events=new Of:delete n._events[t]}function Xa(){this._events=new Of,this._eventsCount=0}Xa.prototype.eventNames=function(){var t=[],o,i;if(this._eventsCount===0)return t;for(i in o=this._events)V4e.call(o,i)&&t.push(li?i.slice(1):i);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(o)):t};Xa.prototype.listeners=function(t){var o=li?li+t:t,i=this._events[o];if(!i)return[];if(i.fn)return[i.fn];for(var e=0,a=i.length,A=new Array(a);e{"use strict";var Tf=n=>n&&typeof n.message=="string",NU=n=>{if(!n)return;let t=n.cause;if(typeof t=="function"){let o=n.cause();return Tf(o)?o:void 0}else return Tf(t)?t:void 0},Yne=(n,t)=>{if(!Tf(n))return"";let o=n.stack||"";if(t.has(n))return o+` causes have become circular...`;let i=NU(n);return i?(t.add(n),o+` caused by: `+Yne(i,t)):o},N8e=n=>Yne(n,new Set),jne=(n,t,o)=>{if(!Tf(n))return"";let i=o?"":n.message||"";if(t.has(n))return i+": ...";let e=NU(n);if(e){t.add(n);let a=typeof n.cause=="function";return i+(a?"":": ")+jne(e,t,a)}else return i},R8e=n=>jne(n,new Set);Jne.exports={isErrorLike:Tf,getErrorCause:NU,stackWithCauses:N8e,messageWithCauses:R8e}});var kU=$((VRA,zne)=>{"use strict";var k8e=Symbol("circular-ref-tag"),Tb=Symbol("pino-raw-err-ref"),qne=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[Tb]},set:function(n){this[Tb]=n}}});Object.defineProperty(qne,Tb,{writable:!0,value:{}});zne.exports={pinoErrProto:qne,pinoErrorSymbols:{seen:k8e,rawSymbol:Tb}}});var Zne=$((WRA,Wne)=>{"use strict";Wne.exports=PU;var{messageWithCauses:v8e,stackWithCauses:P8e,isErrorLike:Vne}=RU(),{pinoErrProto:G8e,pinoErrorSymbols:F8e}=kU(),{seen:vU}=F8e,{toString:L8e}=Object.prototype;function PU(n){if(!Vne(n))return n;n[vU]=void 0;let t=Object.create(G8e);t.type=L8e.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,t.message=v8e(n),t.stack=P8e(n),Array.isArray(n.errors)&&(t.aggregateErrors=n.errors.map(o=>PU(o)));for(let o in n)if(t[o]===void 0){let i=n[o];Vne(i)?o!=="cause"&&!Object.prototype.hasOwnProperty.call(i,vU)&&(t[o]=PU(i)):t[o]=i}return delete n[vU],t.raw=n,t}});var $ne=$((ZRA,Xne)=>{"use strict";Xne.exports=Rb;var{isErrorLike:GU}=RU(),{pinoErrProto:U8e,pinoErrorSymbols:H8e}=kU(),{seen:Nb}=H8e,{toString:K8e}=Object.prototype;function Rb(n){if(!GU(n))return n;n[Nb]=void 0;let t=Object.create(U8e);t.type=K8e.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,t.message=n.message,t.stack=n.stack,Array.isArray(n.errors)&&(t.aggregateErrors=n.errors.map(o=>Rb(o))),GU(n.cause)&&!Object.prototype.hasOwnProperty.call(n.cause,Nb)&&(t.cause=Rb(n.cause));for(let o in n)if(t[o]===void 0){let i=n[o];GU(i)?Object.prototype.hasOwnProperty.call(i,Nb)||(t[o]=Rb(i)):t[o]=i}return delete n[Nb],t.raw=n,t}});var rse=$((XRA,tse)=>{"use strict";tse.exports={mapHttpRequest:x8e,reqSerializer:Ase};var FU=Symbol("pino-raw-req-ref"),ese=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[FU]},set:function(n){this[FU]=n}}});Object.defineProperty(ese,FU,{writable:!0,value:{}});function Ase(n){let t=n.info||n.socket,o=Object.create(ese);if(o.id=typeof n.id=="function"?n.id():n.id||(n.info?n.info.id:void 0),o.method=n.method,n.originalUrl)o.url=n.originalUrl;else{let i=n.path;o.url=typeof i=="string"?i:n.url?n.url.path||n.url:void 0}return n.query&&(o.query=n.query),n.params&&(o.params=n.params),o.headers=n.headers,o.remoteAddress=t&&t.remoteAddress,o.remotePort=t&&t.remotePort,o.raw=n.raw||n,o}function x8e(n){return{req:Ase(n)}}});var nse=$(($RA,ose)=>{"use strict";ose.exports={mapHttpResponse:Y8e,resSerializer:ise};var LU=Symbol("pino-raw-res-ref"),ase=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[LU]},set:function(n){this[LU]=n}}});Object.defineProperty(ase,LU,{writable:!0,value:{}});function ise(n){let t=Object.create(ase);return t.statusCode=n.headersSent?n.statusCode:null,t.headers=n.getHeaders?n.getHeaders():n._headers,t.raw=n,t}function Y8e(n){return{res:ise(n)}}});var HU=$((ekA,sse)=>{"use strict";var UU=Zne(),j8e=$ne(),kb=rse(),vb=nse();sse.exports={err:UU,errWithCause:j8e,mapHttpRequest:kb.mapHttpRequest,mapHttpResponse:vb.mapHttpResponse,req:kb.reqSerializer,res:vb.resSerializer,wrapErrorSerializer:function(t){return t===UU?t:function(i){return t(UU(i))}},wrapRequestSerializer:function(t){return t===kb.reqSerializer?t:function(i){return t(kb.reqSerializer(i))}},wrapResponseSerializer:function(t){return t===vb.resSerializer?t:function(i){return t(vb.resSerializer(i))}}}});var KU=$((AkA,gse)=>{"use strict";function J8e(n,t){return t}gse.exports=function(){let t=Error.prepareStackTrace;Error.prepareStackTrace=J8e;let o=new Error().stack;if(Error.prepareStackTrace=t,!Array.isArray(o))return;let i=o.slice(2),e=[];for(let a of i)a&&e.push(a.getFileName());return e}});var Ise=$((tkA,cse)=>{"use strict";cse.exports=q8e;function q8e(n={}){let{ERR_PATHS_MUST_BE_STRINGS:t=()=>"fast-redact - Paths must be (non-empty) strings",ERR_INVALID_PATH:o=i=>`fast-redact \u2013 Invalid path (${i})`}=n;return function({paths:e}){e.forEach(a=>{if(typeof a!="string")throw Error(t());try{if(/〇/.test(a))throw Error();let A=(a[0]==="["?"":".")+a.replace(/^\*/,"\u3007").replace(/\.\*/g,".\u3007").replace(/\[\*\]/g,"[\u3007]");if(/\n|\r|;/.test(A)||/\/\*/.test(A))throw Error();Function(` 'use strict' @@ -112,7 +112,7 @@ caused by: `+Yne(i,t)):o},N8e=n=>Yne(n,new Set),jne=(n,t,o)=>{if(!Tf(n))return"" var s = this.serialize(o) this.restore(o) return s - `}function Aze(n,t){return n===!0?"throw Error('fast-redact: primitives cannot be redacted')":t===!1?"return o":"return this.serialize(o)"}});var YU=$((okA,Bse)=>{"use strict";Bse.exports={groupRedact:rze,groupRestore:tze,nestedRedact:ize,nestedRestore:aze};function tze({keys:n,values:t,target:o}){if(o==null||typeof o=="string")return;let i=n.length;for(var e=0;e0;A--)a=a[i[A]];a[i[0]]=e}}function ize(n,t,o,i,e,a,A){let r=Cse(t,o);if(r==null)return;let s=Object.keys(r),g=s.length;for(var c=0;c{"use strict";var{groupRestore:sze,nestedRestore:gze}=YU();fse.exports=cze;function cze(){return function(){if(this.restore){this.restore.state.secret=this.secret;return}let{secret:t,wcLen:o}=this,i=Object.keys(t),e=Ize(t,i),a=o>0,A=a?{secret:t,groupRestore:sze,nestedRestore:gze}:{secret:t};this.restore=Function("o",lze(e,i,a)).bind(A),this.restore.state=A}}function Ize(n,t){return t.map(o=>{let{circle:i,escPath:e,leadingBracket:a}=n[o],r=i?`o.${i} = secret[${e}].val`:`o${a?"":"."}${o} = secret[${e}].val`,s=`secret[${e}].val = undefined`;return` + `}function Aze(n,t){return n===!0?"throw Error('fast-redact: primitives cannot be redacted')":t===!1?"return o":"return this.serialize(o)"}});var YU=$((okA,Bse)=>{"use strict";Bse.exports={groupRedact:rze,groupRestore:tze,nestedRedact:ize,nestedRestore:aze};function tze({keys:n,values:t,target:o}){if(o==null||typeof o=="string")return;let i=n.length;for(var e=0;e0;A--)a=a[i[A]];a[i[0]]=e}}function ize(n,t,o,i,e,a,A){let r=Cse(t,o);if(r==null)return;let s=Object.keys(r),g=s.length;for(var c=0;c{"use strict";var{groupRestore:sze,nestedRestore:gze}=YU();fse.exports=cze;function cze(){return function(){if(this.restore){this.restore.state.secret=this.secret;return}let{secret:t,wcLen:o}=this,i=Object.keys(t),e=Ize(t,i),a=o>0,A=a?{secret:t,groupRestore:sze,nestedRestore:gze}:{secret:t};this.restore=Function("o",lze(e,i,a)).bind(A),this.restore.state=A}}function Ize(n,t){return t.map(o=>{let{circle:i,escPath:e,leadingBracket:a}=n[o],r=i?`o.${i} = secret[${e}].val`:`o${a?"":"."}${o} = secret[${e}].val`,s=`secret[${e}].val = undefined`;return` if (secret[${e}].val !== undefined) { try { ${r} } catch (e) {} ${s} @@ -134,27 +134,27 @@ caused by: `+Yne(i,t)):o},N8e=n=>Yne(n,new Set),jne=(n,t,o)=>{if(!Tf(n))return"" `:""} ${n} return o - `}});var mse=$((skA,yse)=>{"use strict";yse.exports=pze;function pze(n){let{secret:t,censor:o,compileRestore:i,serialize:e,groupRedact:a,nestedRedact:A,wildcards:r,wcLen:s}=n,g=[{secret:t,censor:o,compileRestore:i}];return e!==!1&&g.push({serialize:e}),s>0&&g.push({groupRedact:a,nestedRedact:A,wildcards:r,wcLen:s}),Object.assign(...g)}});var Dse=$((gkA,wse)=>{"use strict";var Sse=Ise(),dze=dse(),hze=Ese(),Eze=Qse(),{groupRedact:Cze,nestedRedact:uze}=YU(),Bze=mse(),fze=Pb(),Qze=Sse(),jU=n=>n;jU.restore=jU;var yze="[REDACTED]";JU.rx=fze;JU.validator=Sse;wse.exports=JU;function JU(n={}){let t=Array.from(new Set(n.paths||[])),o="serialize"in n&&(n.serialize===!1||typeof n.serialize=="function")?n.serialize:JSON.stringify,i=n.remove;if(i===!0&&o!==JSON.stringify)throw Error("fast-redact \u2013 remove option may only be set when serializer is JSON.stringify");let e=i===!0?void 0:"censor"in n?n.censor:yze,a=typeof e=="function",A=a&&e.length>1;if(t.length===0)return o||jU;Qze({paths:t,serialize:o,censor:e});let{wildcards:r,wcLen:s,secret:g}=dze({paths:t,censor:e}),c=Eze(),I="strict"in n?n.strict:!0;return hze({secret:g,wcLen:s,serialize:o,strict:I,isCensorFct:a,censorFctTakesPath:A},Bze({secret:g,censor:e,compileRestore:c,serialize:o,groupRedact:Cze,nestedRedact:uze,wildcards:r,wcLen:s}))}});var gE=$((ckA,Ose)=>{"use strict";var mze=Symbol("pino.setLevel"),Sze=Symbol("pino.getLevel"),wze=Symbol("pino.levelVal"),Dze=Symbol("pino.levelComp"),Oze=Symbol("pino.useLevelLabels"),bze=Symbol("pino.useOnlyCustomLevels"),Mze=Symbol("pino.mixin"),_ze=Symbol("pino.lsCache"),Tze=Symbol("pino.chindings"),Nze=Symbol("pino.asJson"),Rze=Symbol("pino.write"),kze=Symbol("pino.redactFmt"),vze=Symbol("pino.time"),Pze=Symbol("pino.timeSliceIndex"),Gze=Symbol("pino.stream"),Fze=Symbol("pino.stringify"),Lze=Symbol("pino.stringifySafe"),Uze=Symbol("pino.stringifiers"),Hze=Symbol("pino.end"),Kze=Symbol("pino.formatOpts"),xze=Symbol("pino.messageKey"),Yze=Symbol("pino.errorKey"),jze=Symbol("pino.nestedKey"),Jze=Symbol("pino.nestedKeyStr"),qze=Symbol("pino.mixinMergeStrategy"),zze=Symbol("pino.msgPrefix"),Vze=Symbol("pino.wildcardFirst"),Wze=Symbol.for("pino.serializers"),Zze=Symbol.for("pino.formatters"),Xze=Symbol.for("pino.hooks"),$ze=Symbol.for("pino.metadata");Ose.exports={setLevelSym:mze,getLevelSym:Sze,levelValSym:wze,levelCompSym:Dze,useLevelLabelsSym:Oze,mixinSym:Mze,lsCacheSym:_ze,chindingsSym:Tze,asJsonSym:Nze,writeSym:Rze,serializersSym:Wze,redactFmtSym:kze,timeSym:vze,timeSliceIndexSym:Pze,streamSym:Gze,stringifySym:Fze,stringifySafeSym:Lze,stringifiersSym:Uze,endSym:Hze,formatOptsSym:Kze,messageKeySym:xze,errorKeySym:Yze,nestedKeySym:jze,wildcardFirstSym:Vze,needsMetadataGsym:$ze,useOnlyCustomLevelsSym:bze,formattersSym:Zze,hooksSym:Xze,nestedKeyStrSym:Jze,mixinMergeStrategySym:qze,msgPrefixSym:zze}});var VU=$((IkA,Tse)=>{"use strict";var zU=Dse(),{redactFmtSym:eVe,wildcardFirstSym:Gb}=gE(),{rx:qU,validator:AVe}=zU,bse=AVe({ERR_PATHS_MUST_BE_STRINGS:()=>"pino \u2013 redacted paths must be strings",ERR_INVALID_PATH:n=>`pino \u2013 redact paths array contains an invalid path (${n})`}),Mse="[Redacted]",_se=!1;function tVe(n,t){let{paths:o,censor:i}=rVe(n),e=o.reduce((r,s)=>{qU.lastIndex=0;let g=qU.exec(s),c=qU.exec(s),I=g[1]!==void 0?g[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):g[0];if(I==="*"&&(I=Gb),c===null)return r[I]=null,r;if(r[I]===null)return r;let{index:d}=c,B=`${s.substr(d,s.length-1)}`;return r[I]=r[I]||[],I!==Gb&&r[I].length===0&&r[I].push(...r[Gb]||[]),I===Gb&&Object.keys(r).forEach(function(f){r[f]&&r[f].push(B)}),r[I].push(B),r},{}),a={[eVe]:zU({paths:o,censor:i,serialize:t,strict:_se})},A=(...r)=>t(typeof i=="function"?i(...r):i);return[...Object.keys(e),...Object.getOwnPropertySymbols(e)].reduce((r,s)=>{if(e[s]===null)r[s]=g=>A(g,[s]);else{let g=typeof i=="function"?(c,I)=>i(c,[s,...I]):i;r[s]=zU({paths:e[s],censor:g,serialize:t,strict:_se})}return r},a)}function rVe(n){if(Array.isArray(n))return n={paths:n,censor:Mse},bse(n),n;let{paths:t,censor:o=Mse,remove:i}=n;if(Array.isArray(t)===!1)throw Error("pino \u2013 redact must contain an array of strings");return i===!0&&(o=void 0),bse({paths:t,censor:o}),{paths:t,censor:o}}Tse.exports=tVe});var Rse=$((lkA,Nse)=>{"use strict";var aVe=()=>"",iVe=()=>`,"time":${Date.now()}`,oVe=()=>`,"time":${Math.round(Date.now()/1e3)}`,nVe=()=>`,"time":"${new Date(Date.now()).toISOString()}"`;Nse.exports={nullTime:aVe,epochTime:iVe,unixTime:oVe,isoTime:nVe}});var vse=$((pkA,kse)=>{"use strict";function sVe(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}kse.exports=gVe;function gVe(n,t,o){var i=o&&o.stringify||sVe,e=1;if(typeof n=="object"&&n!==null){var a=t.length+e;if(a===1)return n;var A=new Array(a);A[0]=i(n);for(var r=1;r-1?I:0,n.charCodeAt(B+1)){case 100:case 102:if(c>=s||t[c]==null)break;I=s||t[c]==null)break;I=s||t[c]===void 0)break;I",I=B+2,B++;break}g+=i(t[c]),I=B+2,B++;break;case 115:if(c>=s)break;I{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let t=function(o){if((o>0&&o<1/0)===!1)throw typeof o!="number"&&typeof o!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(n,0,0,Number(o))},n=new Int32Array(new SharedArrayBuffer(4));WU.exports=t}else{let n=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let i=Date.now()+Number(t);for(;i>Date.now(););};WU.exports=n}});var xse=$((hkA,Kse)=>{"use strict";var qt=$e("fs"),cVe=$e("events"),IVe=$e("util").inherits,Pse=$e("path"),$U=ZU(),lVe=$e("assert"),Fb=100,Lb=Buffer.allocUnsafe(0),pVe=16*1024,Gse="buffer",Fse="utf8",[dVe,hVe]=(process.versions.node||"0.0").split(".").map(Number),EVe=dVe>=22&&hVe>=7;function Lse(n,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function o(a,A){if(a){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount("error")>0&&t.emit("error",a)}):t.emit("error",a);return}let r=t._reopening;t.fd=A,t.file=n,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit("ready")):t.emit("ready"),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():r&&process.nextTick(()=>t.emit("drain")))}let i=t.append?"a":"w",e=t.mode;if(t.sync)try{t.mkdir&&qt.mkdirSync(Pse.dirname(n),{recursive:!0});let a=qt.openSync(n,i,e);o(null,a)}catch(a){throw o(a),a}else t.mkdir?qt.mkdir(Pse.dirname(n),{recursive:!0},a=>{if(a)return o(a);qt.open(n,i,e,o)}):qt.open(n,i,e,o)}function Ln(n){if(!(this instanceof Ln))return new Ln(n);let{fd:t,dest:o,minLength:i,maxLength:e,maxWrite:a,periodicFlush:A,sync:r,append:s=!0,mkdir:g,retryEAGAIN:c,fsync:I,contentMode:d,mode:B}=n||{};t=t||o,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=e||0,this.maxWrite=a||pVe,this._periodicFlush=A||0,this._periodicFlushTimer=void 0,this.sync=r||!1,this.writable=!0,this._fsync=I||!1,this.append=s||!1,this.mode=B,this.retryEAGAIN=c||(()=>!0),this.mkdir=g||!1;let f,Q;if(d===Gse)this._writingBuf=Lb,this.write=BVe,this.flush=QVe,this.flushSync=mVe,this._actualWrite=wVe,f=()=>qt.writeSync(this.fd,this._writingBuf),Q=()=>qt.write(this.fd,this._writingBuf,this.release);else if(d===void 0||d===Fse)this._writingBuf="",this.write=uVe,this.flush=fVe,this.flushSync=yVe,this._actualWrite=SVe,f=()=>Buffer.isBuffer(this._writingBuf)?qt.writeSync(this.fd,this._writingBuf):qt.writeSync(this.fd,this._writingBuf,"utf8"),Q=()=>Buffer.isBuffer(this._writingBuf)?qt.write(this.fd,this._writingBuf,this.release):qt.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Fse}" and "${Gse}", but passed ${d}`);if(typeof t=="number")this.fd=t,process.nextTick(()=>this.emit("ready"));else if(typeof t=="string")Lse(t,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(y,m)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{$U(Fb),this.release(void 0,0)}catch(R){this.release(R)}else setTimeout(Q,Fb);else this._writing=!1,this.emit("error",y);return}this.emit("write",m);let _=XU(this._writingBuf,this._len,m);if(this._len=_.len,this._writingBuf=_.writingBuf,this._writingBuf.length){if(!this.sync){Q();return}try{do{let R=f(),F=XU(this._writingBuf,this._len,R);this._len=F.len,this._writingBuf=F.writingBuf}while(this._writingBuf.length)}catch(R){this.release(R);return}}this._fsync&&qt.fsyncSync(this.fd);let T=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):T>this.minLength?this._actualWrite():this._ending?T>0?this._actualWrite():(this._writing=!1,Ub(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(CVe,this)):this.emit("drain"))},this.on("newListener",function(y){y==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function XU(n,t,o){return typeof n=="string"&&(n=Buffer.from(n)),t=Math.max(t-o,0),n=n.subarray(o),{writingBuf:n,len:t}}function CVe(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}IVe(Ln,cVe);function Use(n,t){return n.length===0?Lb:n.length===1?n[0]:Buffer.concat(n,t)}function uVe(n){if(this.destroyed)throw new Error("SonicBoom destroyed");n=""+n;let t=Buffer.byteLength(n),o=this._len+t,i=this._bufs;return this.maxLength&&o>this.maxLength?(this.emit("drop",n),this._lenthis.maxWrite?i.push(n):i[i.length-1]+=n,this._len=o,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._lenthis.maxLength?(this.emit("drop",n),this._lenthis.maxWrite?(o.push([n]),i.push(n.length)):(o[o.length-1].push(n),i[i.length-1]+=n.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len{if(this._fsync)this._flushPending=!1,n();else try{qt.fsync(this.fd,i=>{this._flushPending=!1,n(i)})}catch(i){n(i)}this.off("error",o)},o=i=>{this._flushPending=!1,n(i),this.off("drain",t)};this.once("drain",t),this.once("error",o)}function fVe(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(n){n(t);return}throw t}if(this.minLength<=0){n?.();return}n&&Hse.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function QVe(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(n){n(t);return}throw t}if(this.minLength<=0){n?.();return}n&&Hse.call(this,n),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}Ln.prototype.reopen=function(n){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(n)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(n&&(this.file=n),this._reopening=!0,this._writing)return;let t=this.fd;this.once("ready",()=>{t!==this.fd&&qt.close(t,o=>{if(o)return this.emit("error",o)})}),Lse(this.file,this)};Ln.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():Ub(this)))};function yVe(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let n="";for(;this._bufs.length||n.length;){n.length<=0&&(n=this._bufs[0]);try{let t=Buffer.isBuffer(n)?qt.writeSync(this.fd,n):qt.writeSync(this.fd,n,"utf8"),o=XU(n,this._len,t);n=o.writingBuf,this._len=o.len,n.length<=0&&this._bufs.shift()}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,n.length,this._len-n.length))throw t;$U(Fb)}}try{qt.fsyncSync(this.fd)}catch{}}function mVe(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Lb);let n=Lb;for(;this._bufs.length||n.length;){n.length<=0&&(n=Use(this._bufs[0],this._lens[0]));try{let t=qt.writeSync(this.fd,n);n=n.subarray(t),this._len=Math.max(this._len-t,0),n.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,n.length,this._len-n.length))throw t;$U(Fb)}}}Ln.prototype.destroy=function(){this.destroyed||Ub(this)};function SVe(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let t=Buffer.isBuffer(this._writingBuf)?qt.writeSync(this.fd,this._writingBuf):qt.writeSync(this.fd,this._writingBuf,"utf8");n(null,t)}catch(t){n(t)}else qt.write(this.fd,this._writingBuf,n)}function wVe(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Use(this._bufs.shift(),this._lens.shift()),this.sync)try{let t=qt.writeSync(this.fd,this._writingBuf);n(null,t)}catch(t){n(t)}else EVe&&(this._writingBuf=Buffer.from(this._writingBuf)),qt.write(this.fd,this._writingBuf,n)}function Ub(n){if(n.fd===-1){n.once("ready",Ub.bind(null,n));return}n._periodicFlushTimer!==void 0&&clearInterval(n._periodicFlushTimer),n.destroyed=!0,n._bufs=[],n._lens=[],lVe(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{qt.fsync(n.fd,t)}catch{}function t(){n.fd!==1&&n.fd!==2?qt.close(n.fd,o):o()}function o(i){if(i){n.emit("error",i);return}n._ending&&!n._writing&&n.emit("finish"),n.emit("close")}}Ln.SonicBoom=Ln;Ln.default=Ln;Kse.exports=Ln});var eH=$((EkA,zse)=>{"use strict";var Un={exit:[],beforeExit:[]},Yse={exit:bVe,beforeExit:MVe},cE;function DVe(){cE===void 0&&(cE=new FinalizationRegistry(_Ve))}function OVe(n){Un[n].length>0||process.on(n,Yse[n])}function jse(n){Un[n].length>0||(process.removeListener(n,Yse[n]),Un.exit.length===0&&Un.beforeExit.length===0&&(cE=void 0))}function bVe(){Jse("exit")}function MVe(){Jse("beforeExit")}function Jse(n){for(let t of Un[n]){let o=t.deref(),i=t.fn;o!==void 0&&i(o,n)}Un[n]=[]}function _Ve(n){for(let t of["exit","beforeExit"]){let o=Un[t].indexOf(n);Un[t].splice(o,o+1),jse(t)}}function qse(n,t,o){if(t===void 0)throw new Error("the object can't be undefined");OVe(n);let i=new WeakRef(t);i.fn=o,DVe(),cE.register(t,i),Un[n].push(i)}function TVe(n,t){qse("exit",n,t)}function NVe(n,t){qse("beforeExit",n,t)}function RVe(n){if(cE!==void 0){cE.unregister(n);for(let t of["exit","beforeExit"])Un[t]=Un[t].filter(o=>{let i=o.deref();return i&&i!==n}),jse(t)}}zse.exports={register:TVe,registerBeforeExit:NVe,unregister:RVe}});var Vse=$((CkA,kVe)=>{kVe.exports={name:"thread-stream",version:"3.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",dependencies:{"real-require":"^0.2.0"},devDependencies:{"@types/node":"^20.1.0","@types/tap":"^15.0.0","@yao-pkg/pkg":"^5.11.5",desm:"^1.3.0",fastbench:"^1.0.1",husky:"^9.0.6","pino-elasticsearch":"^8.0.0","sonic-boom":"^4.0.1",standard:"^17.0.0",tap:"^16.2.0","ts-node":"^10.8.0",typescript:"^5.3.2","why-is-node-running":"^2.2.2"},scripts:{build:"tsc --noEmit",test:'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts',"test:ci":"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts","test:ci:js":'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"',"test:ci:ts":'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"',"test:yarn":'npm run transpile && tap "test/**/*.test.js" --no-check-coverage',transpile:"sh ./test/ts/transpile.sh",prepare:"husky install"},standard:{ignore:["test/ts/**/*","test/syntax-error.mjs"]},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina ",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var Zse=$((ukA,Wse)=>{"use strict";function vVe(n,t,o,i,e){let a=Date.now()+i,A=Atomics.load(n,t);if(A===o){e(null,"ok");return}let r=A,s=g=>{Date.now()>a?e(null,"timed-out"):setTimeout(()=>{r=A,A=Atomics.load(n,t),A===r?s(g>=1e3?1e3:g*2):A===o?e(null,"ok"):e(null,"not-equal")},g)};s(1)}function PVe(n,t,o,i,e){let a=Date.now()+i,A=Atomics.load(n,t);if(A!==o){e(null,"ok");return}let r=s=>{Date.now()>a?e(null,"timed-out"):setTimeout(()=>{A=Atomics.load(n,t),A!==o?e(null,"ok"):r(s>=1e3?1e3:s*2)},s)};r(1)}Wse.exports={wait:vVe,waitDiff:PVe}});var $se=$((BkA,Xse)=>{"use strict";Xse.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var age=$((fkA,rge)=>{"use strict";var{version:GVe}=Vse(),{EventEmitter:FVe}=$e("events"),{Worker:LVe}=$e("worker_threads"),{join:UVe}=$e("path"),{pathToFileURL:HVe}=$e("url"),{wait:KVe}=Zse(),{WRITE_INDEX:An,READ_INDEX:xi,SEQ_INDEX:AH}=$se(),xVe=$e("buffer"),YVe=$e("assert"),Ne=Symbol("kImpl"),jVe=xVe.constants.MAX_STRING_LENGTH;function IE(n,t){Atomics.add(n[Ne].state,AH,1),t(),Atomics.add(n[Ne].state,AH,1),Atomics.notify(n[Ne].state,AH)}var Rf=class{constructor(t){this._value=t}deref(){return this._value}},Kb=class{register(){}unregister(){}},JVe=process.env.NODE_V8_COVERAGE?Kb:global.FinalizationRegistry||Kb,qVe=process.env.NODE_V8_COVERAGE?Rf:global.WeakRef||Rf,ege=new JVe(n=>{n.exited||n.terminate()});function zVe(n,t){let{filename:o,workerData:i}=t,a=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||UVe(__dirname,"lib","worker.js"),A=new LVe(a,{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:o.indexOf("file://")===0?o:HVe(o).href,dataBuf:n[Ne].dataBuf,stateBuf:n[Ne].stateBuf,workerData:{$context:{threadStreamVersion:GVe},...i}}});return A.stream=new Rf(n),A.on("message",VVe),A.on("exit",tge),ege.register(n,A),A}function Age(n){YVe(!n[Ne].sync),n[Ne].needDrain&&(n[Ne].needDrain=!1,n.emit("drain"))}function Hb(n){let t=Atomics.load(n[Ne].state,An),o=n[Ne].data.length-t;if(o>0){if(n[Ne].buf.length===0){n[Ne].flushing=!1,n[Ne].ending?oH(n):n[Ne].needDrain&&process.nextTick(Age,n);return}let i=n[Ne].buf.slice(0,o),e=Buffer.byteLength(i);e<=o?(n[Ne].buf=n[Ne].buf.slice(o),xb(n,i,Hb.bind(null,n))):n.flush(()=>{if(!n.destroyed){for(IE(n,()=>{Atomics.store(n[Ne].state,xi,0),Atomics.store(n[Ne].state,An,0)}),Atomics.notify(n[Ne].state,xi);e>n[Ne].data.length;)o=o/2,i=n[Ne].buf.slice(0,o),e=Buffer.byteLength(i);n[Ne].buf=n[Ne].buf.slice(o),xb(n,i,Hb.bind(null,n))}})}else if(o===0){if(t===0&&n[Ne].buf.length===0)return;n.flush(()=>{IE(n,()=>{Atomics.store(n[Ne].state,xi,0),Atomics.store(n[Ne].state,An,0)}),Atomics.notify(n[Ne].state,xi),Hb(n)})}else qs(n,new Error("overwritten"))}function VVe(n){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}if(n?.code!=null)switch(n.code){case"READY":this.stream=new qVe(t),t.flush(()=>{t[Ne].ready=!0,t.emit("ready")});break;case"ERROR":qs(t,n.err);break;case"EVENT":Array.isArray(n.args)?t.emit(n.name,...n.args):t.emit(n.name,n.args);break;case"WARNING":process.emitWarning(n.err);break;default:qs(t,new Error("this should not happen: "+n.code))}}function tge(n){let t=this.stream.deref();t!==void 0&&(ege.unregister(t),t.worker.exited=!0,t.worker.off("exit",tge),qs(t,n!==0?new Error("the worker thread exited"):null))}var rH=class extends FVe{constructor(t={}){if(super(),t.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[Ne]={},this[Ne].stateBuf=new SharedArrayBuffer(128),this[Ne].state=new Int32Array(this[Ne].stateBuf),this[Ne].dataBuf=new SharedArrayBuffer(t.bufferSize||4*1024*1024),this[Ne].data=Buffer.from(this[Ne].dataBuf),this[Ne].sync=t.sync||!1,this[Ne].ending=!1,this[Ne].ended=!1,this[Ne].needDrain=!1,this[Ne].destroyed=!1,this[Ne].flushing=!1,this[Ne].ready=!1,this[Ne].finished=!1,this[Ne].errored=null,this[Ne].closed=!1,this[Ne].buf="",this.worker=zVe(this,t),this.on("message",(o,i)=>{this.worker.postMessage(o,i)})}write(t){if(this[Ne].destroyed)return aH(this,new Error("the worker has exited")),!1;if(this[Ne].ending)return aH(this,new Error("the worker is ending")),!1;if(this[Ne].flushing&&this[Ne].buf.length+t.length>=jVe)try{tH(this),this[Ne].flushing=!0}catch(o){return qs(this,o),!1}if(this[Ne].buf+=t,this[Ne].sync)try{return tH(this),!0}catch(o){return qs(this,o),!1}return this[Ne].flushing||(this[Ne].flushing=!0,setImmediate(Hb,this)),this[Ne].needDrain=this[Ne].data.length-this[Ne].buf.length-Atomics.load(this[Ne].state,An)<=0,!this[Ne].needDrain}end(){this[Ne].destroyed||(this[Ne].ending=!0,oH(this))}flush(t){if(this[Ne].destroyed){typeof t=="function"&&process.nextTick(t,new Error("the worker has exited"));return}let o=Atomics.load(this[Ne].state,An);KVe(this[Ne].state,xi,o,1/0,(i,e)=>{if(i){qs(this,i),process.nextTick(t,i);return}if(e==="not-equal"){this.flush(t);return}process.nextTick(t)})}flushSync(){this[Ne].destroyed||(tH(this),iH(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[Ne].ready}get destroyed(){return this[Ne].destroyed}get closed(){return this[Ne].closed}get writable(){return!this[Ne].destroyed&&!this[Ne].ending}get writableEnded(){return this[Ne].ending}get writableFinished(){return this[Ne].finished}get writableNeedDrain(){return this[Ne].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[Ne].errored}};function aH(n,t){setImmediate(()=>{n.emit("error",t)})}function qs(n,t){n[Ne].destroyed||(n[Ne].destroyed=!0,t&&(n[Ne].errored=t,aH(n,t)),n.worker.exited?setImmediate(()=>{n[Ne].closed=!0,n.emit("close")}):n.worker.terminate().catch(()=>{}).then(()=>{n[Ne].closed=!0,n.emit("close")}))}function xb(n,t,o){let i=Atomics.load(n[Ne].state,An),e=Buffer.byteLength(t);return n[Ne].data.write(t,i),IE(n,()=>{Atomics.store(n[Ne].state,An,i+e)}),o(),!0}function oH(n){if(!(n[Ne].ended||!n[Ne].ending||n[Ne].flushing)){n[Ne].ended=!0;try{n.flushSync();let t=Atomics.load(n[Ne].state,xi);IE(n,()=>{Atomics.store(n[Ne].state,An,-1)});let o=0;for(;t!==-1;){if(Atomics.wait(n[Ne].state,xi,t,1e3),t=Atomics.load(n[Ne].state,xi),t===-2){qs(n,new Error("end() failed"));return}if(++o===10){qs(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[Ne].finished=!0,n.emit("finish")})}catch(t){qs(n,t)}}}function tH(n){let t=()=>{n[Ne].ending?oH(n):n[Ne].needDrain&&process.nextTick(Age,n)};for(n[Ne].flushing=!1;n[Ne].buf.length!==0;){let o=Atomics.load(n[Ne].state,An),i=n[Ne].data.length-o;if(i===0){iH(n),IE(n,()=>{Atomics.store(n[Ne].state,xi,0),Atomics.store(n[Ne].state,An,0)}),Atomics.notify(n[Ne].state,xi);continue}else if(i<0)throw new Error("overwritten");let e=n[Ne].buf.slice(0,i),a=Buffer.byteLength(e);if(a<=i)n[Ne].buf=n[Ne].buf.slice(i),xb(n,e,t);else{for(iH(n),IE(n,()=>{Atomics.store(n[Ne].state,xi,0),Atomics.store(n[Ne].state,An,0)}),Atomics.notify(n[Ne].state,xi);a>n[Ne].buf.length;)i=i/2,e=n[Ne].buf.slice(0,i),a=Buffer.byteLength(e);n[Ne].buf=n[Ne].buf.slice(i),xb(n,e,t)}}}function iH(n){if(n[Ne].flushing)throw new Error("unable to flush while flushing");let t=Atomics.load(n[Ne].state,An),o=0;for(;;){let i=Atomics.load(n[Ne].state,xi);if(i===-2)throw Error("_flushSync failed");if(i!==t)Atomics.wait(n[Ne].state,xi,i,1e3);else break;if(++o===10)throw new Error("_flushSync took too long (10s)")}}rge.exports=rH});var gH=$((QkA,ige)=>{"use strict";var{createRequire:WVe}=$e("module"),ZVe=KU(),{join:nH,isAbsolute:XVe,sep:$Ve}=$e("node:path"),eWe=ZU(),sH=eH(),AWe=age();function tWe(n){sH.register(n,aWe),sH.registerBeforeExit(n,iWe),n.on("close",function(){sH.unregister(n)})}function rWe(n,t,o,i){let e=new AWe({filename:n,workerData:t,workerOpts:o,sync:i});e.on("ready",a),e.on("close",function(){process.removeListener("exit",A)}),process.on("exit",A);function a(){process.removeListener("exit",A),e.unref(),o.autoEnd!==!1&&tWe(e)}function A(){e.closed||(e.flushSync(),eWe(100),e.end())}return e}function aWe(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function iWe(n){n.flushSync()}function oWe(n){let{pipeline:t,targets:o,levels:i,dedupe:e,worker:a={},caller:A=ZVe(),sync:r=!1}=n,s={...n.options},g=typeof A=="string"?[A]:A,c="__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{},I=n.target;if(I&&o)throw new Error("only one of target or targets can be specified");return o?(I=c["pino-worker"]||nH(__dirname,"worker.js"),s.targets=o.filter(B=>B.target).map(B=>({...B,target:d(B.target)})),s.pipelines=o.filter(B=>B.pipeline).map(B=>B.pipeline.map(f=>({...f,level:B.level,target:d(f.target)})))):t&&(I=c["pino-worker"]||nH(__dirname,"worker.js"),s.pipelines=[t.map(B=>({...B,target:d(B.target)}))]),i&&(s.levels=i),e&&(s.dedupe=e),s.pinoWillSendConfig=!0,rWe(d(I),s,a,r);function d(B){if(B=c[B]||B,XVe(B)||B.indexOf("file://")===0)return B;if(B==="pino/file")return nH(__dirname,"..","file.js");let f;for(let Q of g)try{let y=Q==="node:repl"?process.cwd()+$Ve:Q;f=WVe(y).resolve(B);break}catch{continue}if(!f)throw new Error(`unable to determine transport target for "${B}"`);return f}}ige.exports=oWe});var Jb=$((ykA,Ege)=>{"use strict";var oge=vse(),{mapHttpRequest:nWe,mapHttpResponse:sWe}=HU(),IH=xse(),nge=eH(),{lsCacheSym:gWe,chindingsSym:cge,writeSym:sge,serializersSym:Ige,formatOptsSym:gge,endSym:cWe,stringifiersSym:lge,stringifySym:pge,stringifySafeSym:lH,wildcardFirstSym:dge,nestedKeySym:IWe,formattersSym:hge,messageKeySym:lWe,errorKeySym:pWe,nestedKeyStrSym:dWe,msgPrefixSym:Yb}=gE(),{isMainThread:hWe}=$e("worker_threads"),EWe=gH();function lE(){}function CWe(n,t){if(!t)return o;return function(...e){t.call(this,e,o,n)};function o(i,...e){if(typeof i=="object"){let a=i;i!==null&&(i.method&&i.headers&&i.socket?i=nWe(i):typeof i.setHeader=="function"&&(i=sWe(i)));let A;a===null&&e.length===0?A=[null]:(a=e.shift(),A=e),typeof this[Yb]=="string"&&a!==void 0&&a!==null&&(a=this[Yb]+a),this[sge](i,oge(a,A,this[gge]),n)}else{let a=i===void 0?e.shift():i;typeof this[Yb]=="string"&&a!==void 0&&a!==null&&(a=this[Yb]+a),this[sge](null,oge(a,e,this[gge]),n)}}}function cH(n){let t="",o=0,i=!1,e=255,a=n.length;if(a>100)return JSON.stringify(n);for(var A=0;A=32;A++)e=n.charCodeAt(A),(e===34||e===92)&&(t+=n.slice(o,A)+"\\",o=A,i=!0);return i?t+=n.slice(o):t=n,e<32?JSON.stringify(n):'"'+t+'"'}function uWe(n,t,o,i){let e=this[pge],a=this[lH],A=this[lge],r=this[cWe],s=this[cge],g=this[Ige],c=this[hge],I=this[lWe],d=this[pWe],B=this[gWe][o]+i;B=B+s;let f;c.log&&(n=c.log(n));let Q=A[dge],y="";for(let _ in n)if(f=n[_],Object.prototype.hasOwnProperty.call(n,_)&&f!==void 0){g[_]?f=g[_](f):_===d&&g.err&&(f=g.err(f));let T=A[_]||Q;switch(typeof f){case"undefined":case"function":continue;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":T&&(f=T(f));break;case"string":f=(T||cH)(f);break;default:f=(T||e)(f,a)}if(f===void 0)continue;let R=cH(_);y+=","+R+":"+f}let m="";if(t!==void 0){f=g[I]?g[I](t):t;let _=A[I]||Q;switch(typeof f){case"function":break;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":_&&(f=_(f)),m=',"'+I+'":'+f;break;case"string":f=(_||cH)(f),m=',"'+I+'":'+f;break;default:f=(_||e)(f,a),m=',"'+I+'":'+f}}return this[IWe]&&y?B+this[dWe]+y.slice(1)+"}"+m+r:B+y+m+r}function BWe(n,t){let o,i=n[cge],e=n[pge],a=n[lH],A=n[lge],r=A[dge],s=n[Ige],g=n[hge].bindings;t=g(t);for(let c in t)if(o=t[c],(c!=="level"&&c!=="serializers"&&c!=="formatters"&&c!=="customLevels"&&t.hasOwnProperty(c)&&o!==void 0)===!0){if(o=s[c]?s[c](o):o,o=(A[c]||r||e)(o,a),o===void 0)continue;i+=',"'+c+'":'+o}return i}function fWe(n){return n.write!==n.constructor.prototype.write}var QWe=process.env.NODE_V8_COVERAGE||process.env.V8_COVERAGE;function jb(n){let t=new IH(n);return t.on("error",o),!QWe&&!n.sync&&hWe&&(nge.register(t,yWe),t.on("close",function(){nge.unregister(t)})),t;function o(i){if(i.code==="EPIPE"){t.write=lE,t.end=lE,t.flushSync=lE,t.destroy=lE;return}t.removeListener("error",o),t.emit("error",i)}}function yWe(n,t){n.destroyed||(t==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function mWe(n){return function(o,i,e={},a){if(typeof e=="string")a=jb({dest:e}),e={};else if(typeof a=="string"){if(e&&e.transport)throw Error("only one of option.transport or stream can be specified");a=jb({dest:a})}else if(e instanceof IH||e.writable||e._writableState)a=e,e={};else if(e.transport){if(e.transport instanceof IH||e.transport.writable||e.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(e.transport.targets&&e.transport.targets.length&&e.formatters&&typeof e.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let s;e.customLevels&&(s=e.useOnlyCustomLevels?e.customLevels:Object.assign({},e.levels,e.customLevels)),a=EWe({caller:i,...e.transport,levels:s})}if(e=Object.assign({},n,e),e.serializers=Object.assign({},n.serializers,e.serializers),e.formatters=Object.assign({},n.formatters,e.formatters),e.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:A,onChild:r}=e;return A===!1&&(e.level="silent"),r||(e.onChild=lE),a||(fWe(process.stdout)?a=process.stdout:a=jb({fd:process.stdout.fd||1})),{opts:e,stream:a}}}function SWe(n,t){try{return JSON.stringify(n)}catch{try{return(t||this[lH])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function wWe(n,t,o){return{level:n,bindings:t,log:o}}function DWe(n){let t=Number(n);return typeof n=="string"&&Number.isFinite(t)?t:n===void 0?1:n}Ege.exports={noop:lE,buildSafeSonicBoom:jb,asChindings:BWe,asJson:uWe,genLog:CWe,createArgsNormalizer:mWe,stringify:SWe,buildFormatters:wWe,normalizeDestFileDescriptor:DWe}});var qb=$((mkA,Cge)=>{var OWe={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},bWe={ASC:"ASC",DESC:"DESC"};Cge.exports={DEFAULT_LEVELS:OWe,SORTING_ORDER:bWe}});var hH=$((SkA,Qge)=>{"use strict";var{lsCacheSym:MWe,levelValSym:pH,useOnlyCustomLevelsSym:_We,streamSym:TWe,formattersSym:NWe,hooksSym:RWe,levelCompSym:uge}=gE(),{noop:kWe,genLog:op}=Jb(),{DEFAULT_LEVELS:zs,SORTING_ORDER:Bge}=qb(),fge={fatal:n=>{let t=op(zs.fatal,n);return function(...o){let i=this[TWe];if(t.call(this,...o),typeof i.flushSync=="function")try{i.flushSync()}catch{}}},error:n=>op(zs.error,n),warn:n=>op(zs.warn,n),info:n=>op(zs.info,n),debug:n=>op(zs.debug,n),trace:n=>op(zs.trace,n)},dH=Object.keys(zs).reduce((n,t)=>(n[zs[t]]=t,n),{}),vWe=Object.keys(dH).reduce((n,t)=>(n[t]='{"level":'+Number(t),n),{});function PWe(n){let t=n[NWe].level,{labels:o}=n.levels,i={};for(let e in o){let a=t(o[e],Number(e));i[e]=JSON.stringify(a).slice(0,-1)}return n[MWe]=i,n}function GWe(n,t){if(t)return!1;switch(n){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function FWe(n){let{labels:t,values:o}=this.levels;if(typeof n=="number"){if(t[n]===void 0)throw Error("unknown level value"+n);n=t[n]}if(o[n]===void 0)throw Error("unknown level "+n);let i=this[pH],e=this[pH]=o[n],a=this[_We],A=this[uge],r=this[RWe].logMethod;for(let s in o){if(A(o[s],e)===!1){this[s]=kWe;continue}this[s]=GWe(s,a)?fge[s](r):op(o[s],r)}this.emit("level-change",n,e,t[i],i,this)}function LWe(n){let{levels:t,levelVal:o}=this;return t&&t.labels?t.labels[o]:""}function UWe(n){let{values:t}=this.levels,o=t[n];return o!==void 0&&this[uge](o,this[pH])}function HWe(n,t,o){return n===Bge.DESC?t<=o:t>=o}function KWe(n){return typeof n=="string"?HWe.bind(null,n):n}function xWe(n=null,t=!1){let o=n?Object.keys(n).reduce((a,A)=>(a[n[A]]=A,a),{}):null,i=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),t?null:dH,o),e=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:zs,n);return{labels:i,values:e}}function YWe(n,t,o){if(typeof n=="number"){if(![].concat(Object.keys(t||{}).map(a=>t[a]),o?[]:Object.keys(dH).map(a=>+a),1/0).includes(n))throw Error(`default level:${n} must be included in custom levels`);return}let i=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),o?null:zs,t);if(!(n in i))throw Error(`default level:${n} must be included in custom levels`)}function jWe(n,t){let{labels:o,values:i}=n;for(let e in t){if(e in i)throw Error("levels cannot be overridden");if(t[e]in o)throw Error("pre-existing level values cannot be used for new levels")}}function JWe(n){if(typeof n!="function"&&!(typeof n=="string"&&Object.values(Bge).includes(n)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Qge.exports={initialLsCache:vWe,genLsCache:PWe,levelMethods:fge,getLevel:LWe,setLevel:FWe,isLevelEnabled:UWe,mappings:xWe,assertNoLevelCollisions:jWe,assertDefaultLevelFound:YWe,genLevelComparison:KWe,assertLevelComparison:JWe}});var EH=$((wkA,yge)=>{"use strict";yge.exports={version:"9.6.0"}});var Rge=$((OkA,Nge)=>{"use strict";var{EventEmitter:qWe}=$e("node:events"),{lsCacheSym:zWe,levelValSym:VWe,setLevelSym:uH,getLevelSym:mge,chindingsSym:BH,parsedChindingsSym:WWe,mixinSym:ZWe,asJsonSym:bge,writeSym:XWe,mixinMergeStrategySym:$We,timeSym:e6e,timeSliceIndexSym:A6e,streamSym:Mge,serializersSym:np,formattersSym:CH,errorKeySym:t6e,messageKeySym:r6e,useOnlyCustomLevelsSym:a6e,needsMetadataGsym:i6e,redactFmtSym:o6e,stringifySym:n6e,formatOptsSym:s6e,stringifiersSym:g6e,msgPrefixSym:Sge,hooksSym:c6e}=gE(),{getLevel:I6e,setLevel:l6e,isLevelEnabled:p6e,mappings:d6e,initialLsCache:h6e,genLsCache:E6e,assertNoLevelCollisions:C6e}=hH(),{asChindings:_ge,asJson:u6e,buildFormatters:wge,stringify:Dge}=Jb(),{version:B6e}=EH(),f6e=VU(),Q6e=class{},Tge={constructor:Q6e,child:y6e,bindings:m6e,setBindings:S6e,flush:b6e,isLevelEnabled:p6e,version:B6e,get level(){return this[mge]()},set level(n){this[uH](n)},get levelVal(){return this[VWe]},set levelVal(n){throw Error("levelVal is read-only")},[zWe]:h6e,[XWe]:D6e,[bge]:u6e,[mge]:I6e,[uH]:l6e};Object.setPrototypeOf(Tge,qWe.prototype);Nge.exports=function(){return Object.create(Tge)};var Oge=n=>n;function y6e(n,t){if(!n)throw Error("missing bindings for child Pino");t=t||{};let o=this[np],i=this[CH],e=Object.create(this);if(t.hasOwnProperty("serializers")===!0){e[np]=Object.create(null);for(let c in o)e[np][c]=o[c];let s=Object.getOwnPropertySymbols(o);for(var a=0;a{"use strict";var{hasOwnProperty:kf}=Object.prototype,gp=yH();gp.configure=yH;gp.stringify=gp;gp.default=gp;mH.stringify=gp;mH.configure=yH;Pge.exports=gp;var M6e=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function EI(n){return n.length<5e3&&!M6e.test(n)?`"${n}"`:JSON.stringify(n)}function fH(n,t){if(n.length>200||t)return n.sort(t);for(let o=1;oi;)n[e]=n[e-1],e--;n[e]=i}return n}var _6e=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function QH(n){return _6e.call(n)!==void 0&&n.length!==0}function kge(n,t,o){n.length= 1`)}return o===void 0?1/0:o}function sp(n){return n===1?"1 item":`${n} items`}function k6e(n){let t=new Set;for(let o of n)(typeof o=="string"||typeof o=="number")&&t.add(String(o));return t}function v6e(n){if(kf.call(n,"strict")){let t=n.strict;if(typeof t!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(t)return o=>{let i=`Object can not safely be stringified. Received type ${typeof o}`;throw typeof o!="function"&&(i+=` (${o.toString()})`),new Error(i)}}}function yH(n){n={...n};let t=v6e(n);t&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let o=T6e(n),i=R6e(n,"bigint"),e=N6e(n),a=typeof e=="function"?e:void 0,A=vge(n,"maximumDepth"),r=vge(n,"maximumBreadth");function s(B,f,Q,y,m,_){let T=f[B];switch(typeof T=="object"&&T!==null&&typeof T.toJSON=="function"&&(T=T.toJSON(B)),T=y.call(f,B,T),typeof T){case"string":return EI(T);case"object":{if(T===null)return"null";if(Q.indexOf(T)!==-1)return o;let R="",F=",",K=_;if(Array.isArray(T)){if(T.length===0)return"[]";if(Ar){let k=T.length-r-1;R+=`${F}"... ${sp(k)} not stringified"`}return m!==""&&(R+=` -${K}`),Q.pop(),`[${R}]`}let L=Object.keys(T),q=L.length;if(q===0)return"{}";if(Ar){let J=q-r;R+=`${j}"...":${z}"${sp(J)} not stringified"`,j=F}return m!==""&&j.length>1&&(R=` + `}});var mse=$((skA,yse)=>{"use strict";yse.exports=pze;function pze(n){let{secret:t,censor:o,compileRestore:i,serialize:e,groupRedact:a,nestedRedact:A,wildcards:r,wcLen:s}=n,g=[{secret:t,censor:o,compileRestore:i}];return e!==!1&&g.push({serialize:e}),s>0&&g.push({groupRedact:a,nestedRedact:A,wildcards:r,wcLen:s}),Object.assign(...g)}});var Dse=$((gkA,wse)=>{"use strict";var Sse=Ise(),dze=dse(),hze=Ese(),Eze=Qse(),{groupRedact:Cze,nestedRedact:uze}=YU(),Bze=mse(),fze=Pb(),Qze=Sse(),jU=n=>n;jU.restore=jU;var yze="[REDACTED]";JU.rx=fze;JU.validator=Sse;wse.exports=JU;function JU(n={}){let t=Array.from(new Set(n.paths||[])),o="serialize"in n&&(n.serialize===!1||typeof n.serialize=="function")?n.serialize:JSON.stringify,i=n.remove;if(i===!0&&o!==JSON.stringify)throw Error("fast-redact \u2013 remove option may only be set when serializer is JSON.stringify");let e=i===!0?void 0:"censor"in n?n.censor:yze,a=typeof e=="function",A=a&&e.length>1;if(t.length===0)return o||jU;Qze({paths:t,serialize:o,censor:e});let{wildcards:r,wcLen:s,secret:g}=dze({paths:t,censor:e}),c=Eze(),I="strict"in n?n.strict:!0;return hze({secret:g,wcLen:s,serialize:o,strict:I,isCensorFct:a,censorFctTakesPath:A},Bze({secret:g,censor:e,compileRestore:c,serialize:o,groupRedact:Cze,nestedRedact:uze,wildcards:r,wcLen:s}))}});var gE=$((ckA,Ose)=>{"use strict";var mze=Symbol("pino.setLevel"),Sze=Symbol("pino.getLevel"),wze=Symbol("pino.levelVal"),Dze=Symbol("pino.levelComp"),Oze=Symbol("pino.useLevelLabels"),bze=Symbol("pino.useOnlyCustomLevels"),Mze=Symbol("pino.mixin"),_ze=Symbol("pino.lsCache"),Tze=Symbol("pino.chindings"),Nze=Symbol("pino.asJson"),Rze=Symbol("pino.write"),kze=Symbol("pino.redactFmt"),vze=Symbol("pino.time"),Pze=Symbol("pino.timeSliceIndex"),Gze=Symbol("pino.stream"),Fze=Symbol("pino.stringify"),Lze=Symbol("pino.stringifySafe"),Uze=Symbol("pino.stringifiers"),Hze=Symbol("pino.end"),Kze=Symbol("pino.formatOpts"),xze=Symbol("pino.messageKey"),Yze=Symbol("pino.errorKey"),jze=Symbol("pino.nestedKey"),Jze=Symbol("pino.nestedKeyStr"),qze=Symbol("pino.mixinMergeStrategy"),zze=Symbol("pino.msgPrefix"),Vze=Symbol("pino.wildcardFirst"),Wze=Symbol.for("pino.serializers"),Zze=Symbol.for("pino.formatters"),Xze=Symbol.for("pino.hooks"),$ze=Symbol.for("pino.metadata");Ose.exports={setLevelSym:mze,getLevelSym:Sze,levelValSym:wze,levelCompSym:Dze,useLevelLabelsSym:Oze,mixinSym:Mze,lsCacheSym:_ze,chindingsSym:Tze,asJsonSym:Nze,writeSym:Rze,serializersSym:Wze,redactFmtSym:kze,timeSym:vze,timeSliceIndexSym:Pze,streamSym:Gze,stringifySym:Fze,stringifySafeSym:Lze,stringifiersSym:Uze,endSym:Hze,formatOptsSym:Kze,messageKeySym:xze,errorKeySym:Yze,nestedKeySym:jze,wildcardFirstSym:Vze,needsMetadataGsym:$ze,useOnlyCustomLevelsSym:bze,formattersSym:Zze,hooksSym:Xze,nestedKeyStrSym:Jze,mixinMergeStrategySym:qze,msgPrefixSym:zze}});var VU=$((IkA,Tse)=>{"use strict";var zU=Dse(),{redactFmtSym:eVe,wildcardFirstSym:Gb}=gE(),{rx:qU,validator:AVe}=zU,bse=AVe({ERR_PATHS_MUST_BE_STRINGS:()=>"pino \u2013 redacted paths must be strings",ERR_INVALID_PATH:n=>`pino \u2013 redact paths array contains an invalid path (${n})`}),Mse="[Redacted]",_se=!1;function tVe(n,t){let{paths:o,censor:i}=rVe(n),e=o.reduce((r,s)=>{qU.lastIndex=0;let g=qU.exec(s),c=qU.exec(s),I=g[1]!==void 0?g[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):g[0];if(I==="*"&&(I=Gb),c===null)return r[I]=null,r;if(r[I]===null)return r;let{index:d}=c,B=`${s.substr(d,s.length-1)}`;return r[I]=r[I]||[],I!==Gb&&r[I].length===0&&r[I].push(...r[Gb]||[]),I===Gb&&Object.keys(r).forEach(function(f){r[f]&&r[f].push(B)}),r[I].push(B),r},{}),a={[eVe]:zU({paths:o,censor:i,serialize:t,strict:_se})},A=(...r)=>t(typeof i=="function"?i(...r):i);return[...Object.keys(e),...Object.getOwnPropertySymbols(e)].reduce((r,s)=>{if(e[s]===null)r[s]=g=>A(g,[s]);else{let g=typeof i=="function"?(c,I)=>i(c,[s,...I]):i;r[s]=zU({paths:e[s],censor:g,serialize:t,strict:_se})}return r},a)}function rVe(n){if(Array.isArray(n))return n={paths:n,censor:Mse},bse(n),n;let{paths:t,censor:o=Mse,remove:i}=n;if(Array.isArray(t)===!1)throw Error("pino \u2013 redact must contain an array of strings");return i===!0&&(o=void 0),bse({paths:t,censor:o}),{paths:t,censor:o}}Tse.exports=tVe});var Rse=$((lkA,Nse)=>{"use strict";var aVe=()=>"",iVe=()=>`,"time":${Date.now()}`,oVe=()=>`,"time":${Math.round(Date.now()/1e3)}`,nVe=()=>`,"time":"${new Date(Date.now()).toISOString()}"`;Nse.exports={nullTime:aVe,epochTime:iVe,unixTime:oVe,isoTime:nVe}});var vse=$((pkA,kse)=>{"use strict";function sVe(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}kse.exports=gVe;function gVe(n,t,o){var i=o&&o.stringify||sVe,e=1;if(typeof n=="object"&&n!==null){var a=t.length+e;if(a===1)return n;var A=new Array(a);A[0]=i(n);for(var r=1;r-1?I:0,n.charCodeAt(B+1)){case 100:case 102:if(c>=s||t[c]==null)break;I=s||t[c]==null)break;I=s||t[c]===void 0)break;I",I=B+2,B++;break}g+=i(t[c]),I=B+2,B++;break;case 115:if(c>=s)break;I{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let t=function(o){if((o>0&&o<1/0)===!1)throw typeof o!="number"&&typeof o!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(n,0,0,Number(o))},n=new Int32Array(new SharedArrayBuffer(4));WU.exports=t}else{let n=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let i=Date.now()+Number(t);for(;i>Date.now(););};WU.exports=n}});var xse=$((hkA,Kse)=>{"use strict";var qt=$e("fs"),cVe=$e("events"),IVe=$e("util").inherits,Pse=$e("path"),$U=ZU(),lVe=$e("assert"),Fb=100,Lb=Buffer.allocUnsafe(0),pVe=16*1024,Gse="buffer",Fse="utf8",[dVe,hVe]=(process.versions.node||"0.0").split(".").map(Number),EVe=dVe>=22&&hVe>=7;function Lse(n,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function o(a,A){if(a){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount("error")>0&&t.emit("error",a)}):t.emit("error",a);return}let r=t._reopening;t.fd=A,t.file=n,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit("ready")):t.emit("ready"),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():r&&process.nextTick(()=>t.emit("drain")))}let i=t.append?"a":"w",e=t.mode;if(t.sync)try{t.mkdir&&qt.mkdirSync(Pse.dirname(n),{recursive:!0});let a=qt.openSync(n,i,e);o(null,a)}catch(a){throw o(a),a}else t.mkdir?qt.mkdir(Pse.dirname(n),{recursive:!0},a=>{if(a)return o(a);qt.open(n,i,e,o)}):qt.open(n,i,e,o)}function Ln(n){if(!(this instanceof Ln))return new Ln(n);let{fd:t,dest:o,minLength:i,maxLength:e,maxWrite:a,periodicFlush:A,sync:r,append:s=!0,mkdir:g,retryEAGAIN:c,fsync:I,contentMode:d,mode:B}=n||{};t=t||o,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=e||0,this.maxWrite=a||pVe,this._periodicFlush=A||0,this._periodicFlushTimer=void 0,this.sync=r||!1,this.writable=!0,this._fsync=I||!1,this.append=s||!1,this.mode=B,this.retryEAGAIN=c||(()=>!0),this.mkdir=g||!1;let f,Q;if(d===Gse)this._writingBuf=Lb,this.write=BVe,this.flush=QVe,this.flushSync=mVe,this._actualWrite=wVe,f=()=>qt.writeSync(this.fd,this._writingBuf),Q=()=>qt.write(this.fd,this._writingBuf,this.release);else if(d===void 0||d===Fse)this._writingBuf="",this.write=uVe,this.flush=fVe,this.flushSync=yVe,this._actualWrite=SVe,f=()=>Buffer.isBuffer(this._writingBuf)?qt.writeSync(this.fd,this._writingBuf):qt.writeSync(this.fd,this._writingBuf,"utf8"),Q=()=>Buffer.isBuffer(this._writingBuf)?qt.write(this.fd,this._writingBuf,this.release):qt.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Fse}" and "${Gse}", but passed ${d}`);if(typeof t=="number")this.fd=t,process.nextTick(()=>this.emit("ready"));else if(typeof t=="string")Lse(t,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(y,m)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{$U(Fb),this.release(void 0,0)}catch(R){this.release(R)}else setTimeout(Q,Fb);else this._writing=!1,this.emit("error",y);return}this.emit("write",m);let _=XU(this._writingBuf,this._len,m);if(this._len=_.len,this._writingBuf=_.writingBuf,this._writingBuf.length){if(!this.sync){Q();return}try{do{let R=f(),L=XU(this._writingBuf,this._len,R);this._len=L.len,this._writingBuf=L.writingBuf}while(this._writingBuf.length)}catch(R){this.release(R);return}}this._fsync&&qt.fsyncSync(this.fd);let T=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):T>this.minLength?this._actualWrite():this._ending?T>0?this._actualWrite():(this._writing=!1,Ub(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(CVe,this)):this.emit("drain"))},this.on("newListener",function(y){y==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function XU(n,t,o){return typeof n=="string"&&(n=Buffer.from(n)),t=Math.max(t-o,0),n=n.subarray(o),{writingBuf:n,len:t}}function CVe(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}IVe(Ln,cVe);function Use(n,t){return n.length===0?Lb:n.length===1?n[0]:Buffer.concat(n,t)}function uVe(n){if(this.destroyed)throw new Error("SonicBoom destroyed");n=""+n;let t=Buffer.byteLength(n),o=this._len+t,i=this._bufs;return this.maxLength&&o>this.maxLength?(this.emit("drop",n),this._lenthis.maxWrite?i.push(n):i[i.length-1]+=n,this._len=o,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._lenthis.maxLength?(this.emit("drop",n),this._lenthis.maxWrite?(o.push([n]),i.push(n.length)):(o[o.length-1].push(n),i[i.length-1]+=n.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len{if(this._fsync)this._flushPending=!1,n();else try{qt.fsync(this.fd,i=>{this._flushPending=!1,n(i)})}catch(i){n(i)}this.off("error",o)},o=i=>{this._flushPending=!1,n(i),this.off("drain",t)};this.once("drain",t),this.once("error",o)}function fVe(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(n){n(t);return}throw t}if(this.minLength<=0){n?.();return}n&&Hse.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function QVe(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(n){n(t);return}throw t}if(this.minLength<=0){n?.();return}n&&Hse.call(this,n),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}Ln.prototype.reopen=function(n){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(n)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(n&&(this.file=n),this._reopening=!0,this._writing)return;let t=this.fd;this.once("ready",()=>{t!==this.fd&&qt.close(t,o=>{if(o)return this.emit("error",o)})}),Lse(this.file,this)};Ln.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():Ub(this)))};function yVe(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let n="";for(;this._bufs.length||n.length;){n.length<=0&&(n=this._bufs[0]);try{let t=Buffer.isBuffer(n)?qt.writeSync(this.fd,n):qt.writeSync(this.fd,n,"utf8"),o=XU(n,this._len,t);n=o.writingBuf,this._len=o.len,n.length<=0&&this._bufs.shift()}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,n.length,this._len-n.length))throw t;$U(Fb)}}try{qt.fsyncSync(this.fd)}catch{}}function mVe(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Lb);let n=Lb;for(;this._bufs.length||n.length;){n.length<=0&&(n=Use(this._bufs[0],this._lens[0]));try{let t=qt.writeSync(this.fd,n);n=n.subarray(t),this._len=Math.max(this._len-t,0),n.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,n.length,this._len-n.length))throw t;$U(Fb)}}}Ln.prototype.destroy=function(){this.destroyed||Ub(this)};function SVe(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let t=Buffer.isBuffer(this._writingBuf)?qt.writeSync(this.fd,this._writingBuf):qt.writeSync(this.fd,this._writingBuf,"utf8");n(null,t)}catch(t){n(t)}else qt.write(this.fd,this._writingBuf,n)}function wVe(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Use(this._bufs.shift(),this._lens.shift()),this.sync)try{let t=qt.writeSync(this.fd,this._writingBuf);n(null,t)}catch(t){n(t)}else EVe&&(this._writingBuf=Buffer.from(this._writingBuf)),qt.write(this.fd,this._writingBuf,n)}function Ub(n){if(n.fd===-1){n.once("ready",Ub.bind(null,n));return}n._periodicFlushTimer!==void 0&&clearInterval(n._periodicFlushTimer),n.destroyed=!0,n._bufs=[],n._lens=[],lVe(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{qt.fsync(n.fd,t)}catch{}function t(){n.fd!==1&&n.fd!==2?qt.close(n.fd,o):o()}function o(i){if(i){n.emit("error",i);return}n._ending&&!n._writing&&n.emit("finish"),n.emit("close")}}Ln.SonicBoom=Ln;Ln.default=Ln;Kse.exports=Ln});var eH=$((EkA,zse)=>{"use strict";var Un={exit:[],beforeExit:[]},Yse={exit:bVe,beforeExit:MVe},cE;function DVe(){cE===void 0&&(cE=new FinalizationRegistry(_Ve))}function OVe(n){Un[n].length>0||process.on(n,Yse[n])}function jse(n){Un[n].length>0||(process.removeListener(n,Yse[n]),Un.exit.length===0&&Un.beforeExit.length===0&&(cE=void 0))}function bVe(){Jse("exit")}function MVe(){Jse("beforeExit")}function Jse(n){for(let t of Un[n]){let o=t.deref(),i=t.fn;o!==void 0&&i(o,n)}Un[n]=[]}function _Ve(n){for(let t of["exit","beforeExit"]){let o=Un[t].indexOf(n);Un[t].splice(o,o+1),jse(t)}}function qse(n,t,o){if(t===void 0)throw new Error("the object can't be undefined");OVe(n);let i=new WeakRef(t);i.fn=o,DVe(),cE.register(t,i),Un[n].push(i)}function TVe(n,t){qse("exit",n,t)}function NVe(n,t){qse("beforeExit",n,t)}function RVe(n){if(cE!==void 0){cE.unregister(n);for(let t of["exit","beforeExit"])Un[t]=Un[t].filter(o=>{let i=o.deref();return i&&i!==n}),jse(t)}}zse.exports={register:TVe,registerBeforeExit:NVe,unregister:RVe}});var Vse=$((CkA,kVe)=>{kVe.exports={name:"thread-stream",version:"3.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",dependencies:{"real-require":"^0.2.0"},devDependencies:{"@types/node":"^20.1.0","@types/tap":"^15.0.0","@yao-pkg/pkg":"^5.11.5",desm:"^1.3.0",fastbench:"^1.0.1",husky:"^9.0.6","pino-elasticsearch":"^8.0.0","sonic-boom":"^4.0.1",standard:"^17.0.0",tap:"^16.2.0","ts-node":"^10.8.0",typescript:"^5.3.2","why-is-node-running":"^2.2.2"},scripts:{build:"tsc --noEmit",test:'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts',"test:ci":"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts","test:ci:js":'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"',"test:ci:ts":'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"',"test:yarn":'npm run transpile && tap "test/**/*.test.js" --no-check-coverage',transpile:"sh ./test/ts/transpile.sh",prepare:"husky install"},standard:{ignore:["test/ts/**/*","test/syntax-error.mjs"]},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina ",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var Zse=$((ukA,Wse)=>{"use strict";function vVe(n,t,o,i,e){let a=Date.now()+i,A=Atomics.load(n,t);if(A===o){e(null,"ok");return}let r=A,s=g=>{Date.now()>a?e(null,"timed-out"):setTimeout(()=>{r=A,A=Atomics.load(n,t),A===r?s(g>=1e3?1e3:g*2):A===o?e(null,"ok"):e(null,"not-equal")},g)};s(1)}function PVe(n,t,o,i,e){let a=Date.now()+i,A=Atomics.load(n,t);if(A!==o){e(null,"ok");return}let r=s=>{Date.now()>a?e(null,"timed-out"):setTimeout(()=>{A=Atomics.load(n,t),A!==o?e(null,"ok"):r(s>=1e3?1e3:s*2)},s)};r(1)}Wse.exports={wait:vVe,waitDiff:PVe}});var $se=$((BkA,Xse)=>{"use strict";Xse.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var age=$((fkA,rge)=>{"use strict";var{version:GVe}=Vse(),{EventEmitter:FVe}=$e("events"),{Worker:LVe}=$e("worker_threads"),{join:UVe}=$e("path"),{pathToFileURL:HVe}=$e("url"),{wait:KVe}=Zse(),{WRITE_INDEX:An,READ_INDEX:xi,SEQ_INDEX:AH}=$se(),xVe=$e("buffer"),YVe=$e("assert"),Ne=Symbol("kImpl"),jVe=xVe.constants.MAX_STRING_LENGTH;function IE(n,t){Atomics.add(n[Ne].state,AH,1),t(),Atomics.add(n[Ne].state,AH,1),Atomics.notify(n[Ne].state,AH)}var Rf=class{constructor(t){this._value=t}deref(){return this._value}},Kb=class{register(){}unregister(){}},JVe=process.env.NODE_V8_COVERAGE?Kb:global.FinalizationRegistry||Kb,qVe=process.env.NODE_V8_COVERAGE?Rf:global.WeakRef||Rf,ege=new JVe(n=>{n.exited||n.terminate()});function zVe(n,t){let{filename:o,workerData:i}=t,a=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||UVe(__dirname,"lib","worker.js"),A=new LVe(a,{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:o.indexOf("file://")===0?o:HVe(o).href,dataBuf:n[Ne].dataBuf,stateBuf:n[Ne].stateBuf,workerData:{$context:{threadStreamVersion:GVe},...i}}});return A.stream=new Rf(n),A.on("message",VVe),A.on("exit",tge),ege.register(n,A),A}function Age(n){YVe(!n[Ne].sync),n[Ne].needDrain&&(n[Ne].needDrain=!1,n.emit("drain"))}function Hb(n){let t=Atomics.load(n[Ne].state,An),o=n[Ne].data.length-t;if(o>0){if(n[Ne].buf.length===0){n[Ne].flushing=!1,n[Ne].ending?oH(n):n[Ne].needDrain&&process.nextTick(Age,n);return}let i=n[Ne].buf.slice(0,o),e=Buffer.byteLength(i);e<=o?(n[Ne].buf=n[Ne].buf.slice(o),xb(n,i,Hb.bind(null,n))):n.flush(()=>{if(!n.destroyed){for(IE(n,()=>{Atomics.store(n[Ne].state,xi,0),Atomics.store(n[Ne].state,An,0)}),Atomics.notify(n[Ne].state,xi);e>n[Ne].data.length;)o=o/2,i=n[Ne].buf.slice(0,o),e=Buffer.byteLength(i);n[Ne].buf=n[Ne].buf.slice(o),xb(n,i,Hb.bind(null,n))}})}else if(o===0){if(t===0&&n[Ne].buf.length===0)return;n.flush(()=>{IE(n,()=>{Atomics.store(n[Ne].state,xi,0),Atomics.store(n[Ne].state,An,0)}),Atomics.notify(n[Ne].state,xi),Hb(n)})}else qs(n,new Error("overwritten"))}function VVe(n){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}if(n?.code!=null)switch(n.code){case"READY":this.stream=new qVe(t),t.flush(()=>{t[Ne].ready=!0,t.emit("ready")});break;case"ERROR":qs(t,n.err);break;case"EVENT":Array.isArray(n.args)?t.emit(n.name,...n.args):t.emit(n.name,n.args);break;case"WARNING":process.emitWarning(n.err);break;default:qs(t,new Error("this should not happen: "+n.code))}}function tge(n){let t=this.stream.deref();t!==void 0&&(ege.unregister(t),t.worker.exited=!0,t.worker.off("exit",tge),qs(t,n!==0?new Error("the worker thread exited"):null))}var rH=class extends FVe{constructor(t={}){if(super(),t.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[Ne]={},this[Ne].stateBuf=new SharedArrayBuffer(128),this[Ne].state=new Int32Array(this[Ne].stateBuf),this[Ne].dataBuf=new SharedArrayBuffer(t.bufferSize||4*1024*1024),this[Ne].data=Buffer.from(this[Ne].dataBuf),this[Ne].sync=t.sync||!1,this[Ne].ending=!1,this[Ne].ended=!1,this[Ne].needDrain=!1,this[Ne].destroyed=!1,this[Ne].flushing=!1,this[Ne].ready=!1,this[Ne].finished=!1,this[Ne].errored=null,this[Ne].closed=!1,this[Ne].buf="",this.worker=zVe(this,t),this.on("message",(o,i)=>{this.worker.postMessage(o,i)})}write(t){if(this[Ne].destroyed)return aH(this,new Error("the worker has exited")),!1;if(this[Ne].ending)return aH(this,new Error("the worker is ending")),!1;if(this[Ne].flushing&&this[Ne].buf.length+t.length>=jVe)try{tH(this),this[Ne].flushing=!0}catch(o){return qs(this,o),!1}if(this[Ne].buf+=t,this[Ne].sync)try{return tH(this),!0}catch(o){return qs(this,o),!1}return this[Ne].flushing||(this[Ne].flushing=!0,setImmediate(Hb,this)),this[Ne].needDrain=this[Ne].data.length-this[Ne].buf.length-Atomics.load(this[Ne].state,An)<=0,!this[Ne].needDrain}end(){this[Ne].destroyed||(this[Ne].ending=!0,oH(this))}flush(t){if(this[Ne].destroyed){typeof t=="function"&&process.nextTick(t,new Error("the worker has exited"));return}let o=Atomics.load(this[Ne].state,An);KVe(this[Ne].state,xi,o,1/0,(i,e)=>{if(i){qs(this,i),process.nextTick(t,i);return}if(e==="not-equal"){this.flush(t);return}process.nextTick(t)})}flushSync(){this[Ne].destroyed||(tH(this),iH(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[Ne].ready}get destroyed(){return this[Ne].destroyed}get closed(){return this[Ne].closed}get writable(){return!this[Ne].destroyed&&!this[Ne].ending}get writableEnded(){return this[Ne].ending}get writableFinished(){return this[Ne].finished}get writableNeedDrain(){return this[Ne].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[Ne].errored}};function aH(n,t){setImmediate(()=>{n.emit("error",t)})}function qs(n,t){n[Ne].destroyed||(n[Ne].destroyed=!0,t&&(n[Ne].errored=t,aH(n,t)),n.worker.exited?setImmediate(()=>{n[Ne].closed=!0,n.emit("close")}):n.worker.terminate().catch(()=>{}).then(()=>{n[Ne].closed=!0,n.emit("close")}))}function xb(n,t,o){let i=Atomics.load(n[Ne].state,An),e=Buffer.byteLength(t);return n[Ne].data.write(t,i),IE(n,()=>{Atomics.store(n[Ne].state,An,i+e)}),o(),!0}function oH(n){if(!(n[Ne].ended||!n[Ne].ending||n[Ne].flushing)){n[Ne].ended=!0;try{n.flushSync();let t=Atomics.load(n[Ne].state,xi);IE(n,()=>{Atomics.store(n[Ne].state,An,-1)});let o=0;for(;t!==-1;){if(Atomics.wait(n[Ne].state,xi,t,1e3),t=Atomics.load(n[Ne].state,xi),t===-2){qs(n,new Error("end() failed"));return}if(++o===10){qs(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[Ne].finished=!0,n.emit("finish")})}catch(t){qs(n,t)}}}function tH(n){let t=()=>{n[Ne].ending?oH(n):n[Ne].needDrain&&process.nextTick(Age,n)};for(n[Ne].flushing=!1;n[Ne].buf.length!==0;){let o=Atomics.load(n[Ne].state,An),i=n[Ne].data.length-o;if(i===0){iH(n),IE(n,()=>{Atomics.store(n[Ne].state,xi,0),Atomics.store(n[Ne].state,An,0)}),Atomics.notify(n[Ne].state,xi);continue}else if(i<0)throw new Error("overwritten");let e=n[Ne].buf.slice(0,i),a=Buffer.byteLength(e);if(a<=i)n[Ne].buf=n[Ne].buf.slice(i),xb(n,e,t);else{for(iH(n),IE(n,()=>{Atomics.store(n[Ne].state,xi,0),Atomics.store(n[Ne].state,An,0)}),Atomics.notify(n[Ne].state,xi);a>n[Ne].buf.length;)i=i/2,e=n[Ne].buf.slice(0,i),a=Buffer.byteLength(e);n[Ne].buf=n[Ne].buf.slice(i),xb(n,e,t)}}}function iH(n){if(n[Ne].flushing)throw new Error("unable to flush while flushing");let t=Atomics.load(n[Ne].state,An),o=0;for(;;){let i=Atomics.load(n[Ne].state,xi);if(i===-2)throw Error("_flushSync failed");if(i!==t)Atomics.wait(n[Ne].state,xi,i,1e3);else break;if(++o===10)throw new Error("_flushSync took too long (10s)")}}rge.exports=rH});var gH=$((QkA,ige)=>{"use strict";var{createRequire:WVe}=$e("module"),ZVe=KU(),{join:nH,isAbsolute:XVe,sep:$Ve}=$e("node:path"),eWe=ZU(),sH=eH(),AWe=age();function tWe(n){sH.register(n,aWe),sH.registerBeforeExit(n,iWe),n.on("close",function(){sH.unregister(n)})}function rWe(n,t,o,i){let e=new AWe({filename:n,workerData:t,workerOpts:o,sync:i});e.on("ready",a),e.on("close",function(){process.removeListener("exit",A)}),process.on("exit",A);function a(){process.removeListener("exit",A),e.unref(),o.autoEnd!==!1&&tWe(e)}function A(){e.closed||(e.flushSync(),eWe(100),e.end())}return e}function aWe(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function iWe(n){n.flushSync()}function oWe(n){let{pipeline:t,targets:o,levels:i,dedupe:e,worker:a={},caller:A=ZVe(),sync:r=!1}=n,s={...n.options},g=typeof A=="string"?[A]:A,c="__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{},I=n.target;if(I&&o)throw new Error("only one of target or targets can be specified");return o?(I=c["pino-worker"]||nH(__dirname,"worker.js"),s.targets=o.filter(B=>B.target).map(B=>({...B,target:d(B.target)})),s.pipelines=o.filter(B=>B.pipeline).map(B=>B.pipeline.map(f=>({...f,level:B.level,target:d(f.target)})))):t&&(I=c["pino-worker"]||nH(__dirname,"worker.js"),s.pipelines=[t.map(B=>({...B,target:d(B.target)}))]),i&&(s.levels=i),e&&(s.dedupe=e),s.pinoWillSendConfig=!0,rWe(d(I),s,a,r);function d(B){if(B=c[B]||B,XVe(B)||B.indexOf("file://")===0)return B;if(B==="pino/file")return nH(__dirname,"..","file.js");let f;for(let Q of g)try{let y=Q==="node:repl"?process.cwd()+$Ve:Q;f=WVe(y).resolve(B);break}catch{continue}if(!f)throw new Error(`unable to determine transport target for "${B}"`);return f}}ige.exports=oWe});var Jb=$((ykA,Ege)=>{"use strict";var oge=vse(),{mapHttpRequest:nWe,mapHttpResponse:sWe}=HU(),IH=xse(),nge=eH(),{lsCacheSym:gWe,chindingsSym:cge,writeSym:sge,serializersSym:Ige,formatOptsSym:gge,endSym:cWe,stringifiersSym:lge,stringifySym:pge,stringifySafeSym:lH,wildcardFirstSym:dge,nestedKeySym:IWe,formattersSym:hge,messageKeySym:lWe,errorKeySym:pWe,nestedKeyStrSym:dWe,msgPrefixSym:Yb}=gE(),{isMainThread:hWe}=$e("worker_threads"),EWe=gH();function lE(){}function CWe(n,t){if(!t)return o;return function(...e){t.call(this,e,o,n)};function o(i,...e){if(typeof i=="object"){let a=i;i!==null&&(i.method&&i.headers&&i.socket?i=nWe(i):typeof i.setHeader=="function"&&(i=sWe(i)));let A;a===null&&e.length===0?A=[null]:(a=e.shift(),A=e),typeof this[Yb]=="string"&&a!==void 0&&a!==null&&(a=this[Yb]+a),this[sge](i,oge(a,A,this[gge]),n)}else{let a=i===void 0?e.shift():i;typeof this[Yb]=="string"&&a!==void 0&&a!==null&&(a=this[Yb]+a),this[sge](null,oge(a,e,this[gge]),n)}}}function cH(n){let t="",o=0,i=!1,e=255,a=n.length;if(a>100)return JSON.stringify(n);for(var A=0;A=32;A++)e=n.charCodeAt(A),(e===34||e===92)&&(t+=n.slice(o,A)+"\\",o=A,i=!0);return i?t+=n.slice(o):t=n,e<32?JSON.stringify(n):'"'+t+'"'}function uWe(n,t,o,i){let e=this[pge],a=this[lH],A=this[lge],r=this[cWe],s=this[cge],g=this[Ige],c=this[hge],I=this[lWe],d=this[pWe],B=this[gWe][o]+i;B=B+s;let f;c.log&&(n=c.log(n));let Q=A[dge],y="";for(let _ in n)if(f=n[_],Object.prototype.hasOwnProperty.call(n,_)&&f!==void 0){g[_]?f=g[_](f):_===d&&g.err&&(f=g.err(f));let T=A[_]||Q;switch(typeof f){case"undefined":case"function":continue;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":T&&(f=T(f));break;case"string":f=(T||cH)(f);break;default:f=(T||e)(f,a)}if(f===void 0)continue;let R=cH(_);y+=","+R+":"+f}let m="";if(t!==void 0){f=g[I]?g[I](t):t;let _=A[I]||Q;switch(typeof f){case"function":break;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":_&&(f=_(f)),m=',"'+I+'":'+f;break;case"string":f=(_||cH)(f),m=',"'+I+'":'+f;break;default:f=(_||e)(f,a),m=',"'+I+'":'+f}}return this[IWe]&&y?B+this[dWe]+y.slice(1)+"}"+m+r:B+y+m+r}function BWe(n,t){let o,i=n[cge],e=n[pge],a=n[lH],A=n[lge],r=A[dge],s=n[Ige],g=n[hge].bindings;t=g(t);for(let c in t)if(o=t[c],(c!=="level"&&c!=="serializers"&&c!=="formatters"&&c!=="customLevels"&&t.hasOwnProperty(c)&&o!==void 0)===!0){if(o=s[c]?s[c](o):o,o=(A[c]||r||e)(o,a),o===void 0)continue;i+=',"'+c+'":'+o}return i}function fWe(n){return n.write!==n.constructor.prototype.write}var QWe=process.env.NODE_V8_COVERAGE||process.env.V8_COVERAGE;function jb(n){let t=new IH(n);return t.on("error",o),!QWe&&!n.sync&&hWe&&(nge.register(t,yWe),t.on("close",function(){nge.unregister(t)})),t;function o(i){if(i.code==="EPIPE"){t.write=lE,t.end=lE,t.flushSync=lE,t.destroy=lE;return}t.removeListener("error",o),t.emit("error",i)}}function yWe(n,t){n.destroyed||(t==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function mWe(n){return function(o,i,e={},a){if(typeof e=="string")a=jb({dest:e}),e={};else if(typeof a=="string"){if(e&&e.transport)throw Error("only one of option.transport or stream can be specified");a=jb({dest:a})}else if(e instanceof IH||e.writable||e._writableState)a=e,e={};else if(e.transport){if(e.transport instanceof IH||e.transport.writable||e.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(e.transport.targets&&e.transport.targets.length&&e.formatters&&typeof e.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let s;e.customLevels&&(s=e.useOnlyCustomLevels?e.customLevels:Object.assign({},e.levels,e.customLevels)),a=EWe({caller:i,...e.transport,levels:s})}if(e=Object.assign({},n,e),e.serializers=Object.assign({},n.serializers,e.serializers),e.formatters=Object.assign({},n.formatters,e.formatters),e.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:A,onChild:r}=e;return A===!1&&(e.level="silent"),r||(e.onChild=lE),a||(fWe(process.stdout)?a=process.stdout:a=jb({fd:process.stdout.fd||1})),{opts:e,stream:a}}}function SWe(n,t){try{return JSON.stringify(n)}catch{try{return(t||this[lH])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function wWe(n,t,o){return{level:n,bindings:t,log:o}}function DWe(n){let t=Number(n);return typeof n=="string"&&Number.isFinite(t)?t:n===void 0?1:n}Ege.exports={noop:lE,buildSafeSonicBoom:jb,asChindings:BWe,asJson:uWe,genLog:CWe,createArgsNormalizer:mWe,stringify:SWe,buildFormatters:wWe,normalizeDestFileDescriptor:DWe}});var qb=$((mkA,Cge)=>{var OWe={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},bWe={ASC:"ASC",DESC:"DESC"};Cge.exports={DEFAULT_LEVELS:OWe,SORTING_ORDER:bWe}});var hH=$((SkA,Qge)=>{"use strict";var{lsCacheSym:MWe,levelValSym:pH,useOnlyCustomLevelsSym:_We,streamSym:TWe,formattersSym:NWe,hooksSym:RWe,levelCompSym:uge}=gE(),{noop:kWe,genLog:op}=Jb(),{DEFAULT_LEVELS:zs,SORTING_ORDER:Bge}=qb(),fge={fatal:n=>{let t=op(zs.fatal,n);return function(...o){let i=this[TWe];if(t.call(this,...o),typeof i.flushSync=="function")try{i.flushSync()}catch{}}},error:n=>op(zs.error,n),warn:n=>op(zs.warn,n),info:n=>op(zs.info,n),debug:n=>op(zs.debug,n),trace:n=>op(zs.trace,n)},dH=Object.keys(zs).reduce((n,t)=>(n[zs[t]]=t,n),{}),vWe=Object.keys(dH).reduce((n,t)=>(n[t]='{"level":'+Number(t),n),{});function PWe(n){let t=n[NWe].level,{labels:o}=n.levels,i={};for(let e in o){let a=t(o[e],Number(e));i[e]=JSON.stringify(a).slice(0,-1)}return n[MWe]=i,n}function GWe(n,t){if(t)return!1;switch(n){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function FWe(n){let{labels:t,values:o}=this.levels;if(typeof n=="number"){if(t[n]===void 0)throw Error("unknown level value"+n);n=t[n]}if(o[n]===void 0)throw Error("unknown level "+n);let i=this[pH],e=this[pH]=o[n],a=this[_We],A=this[uge],r=this[RWe].logMethod;for(let s in o){if(A(o[s],e)===!1){this[s]=kWe;continue}this[s]=GWe(s,a)?fge[s](r):op(o[s],r)}this.emit("level-change",n,e,t[i],i,this)}function LWe(n){let{levels:t,levelVal:o}=this;return t&&t.labels?t.labels[o]:""}function UWe(n){let{values:t}=this.levels,o=t[n];return o!==void 0&&this[uge](o,this[pH])}function HWe(n,t,o){return n===Bge.DESC?t<=o:t>=o}function KWe(n){return typeof n=="string"?HWe.bind(null,n):n}function xWe(n=null,t=!1){let o=n?Object.keys(n).reduce((a,A)=>(a[n[A]]=A,a),{}):null,i=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),t?null:dH,o),e=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:zs,n);return{labels:i,values:e}}function YWe(n,t,o){if(typeof n=="number"){if(![].concat(Object.keys(t||{}).map(a=>t[a]),o?[]:Object.keys(dH).map(a=>+a),1/0).includes(n))throw Error(`default level:${n} must be included in custom levels`);return}let i=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),o?null:zs,t);if(!(n in i))throw Error(`default level:${n} must be included in custom levels`)}function jWe(n,t){let{labels:o,values:i}=n;for(let e in t){if(e in i)throw Error("levels cannot be overridden");if(t[e]in o)throw Error("pre-existing level values cannot be used for new levels")}}function JWe(n){if(typeof n!="function"&&!(typeof n=="string"&&Object.values(Bge).includes(n)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Qge.exports={initialLsCache:vWe,genLsCache:PWe,levelMethods:fge,getLevel:LWe,setLevel:FWe,isLevelEnabled:UWe,mappings:xWe,assertNoLevelCollisions:jWe,assertDefaultLevelFound:YWe,genLevelComparison:KWe,assertLevelComparison:JWe}});var EH=$((wkA,yge)=>{"use strict";yge.exports={version:"9.6.0"}});var Rge=$((OkA,Nge)=>{"use strict";var{EventEmitter:qWe}=$e("node:events"),{lsCacheSym:zWe,levelValSym:VWe,setLevelSym:uH,getLevelSym:mge,chindingsSym:BH,parsedChindingsSym:WWe,mixinSym:ZWe,asJsonSym:bge,writeSym:XWe,mixinMergeStrategySym:$We,timeSym:e6e,timeSliceIndexSym:A6e,streamSym:Mge,serializersSym:np,formattersSym:CH,errorKeySym:t6e,messageKeySym:r6e,useOnlyCustomLevelsSym:a6e,needsMetadataGsym:i6e,redactFmtSym:o6e,stringifySym:n6e,formatOptsSym:s6e,stringifiersSym:g6e,msgPrefixSym:Sge,hooksSym:c6e}=gE(),{getLevel:I6e,setLevel:l6e,isLevelEnabled:p6e,mappings:d6e,initialLsCache:h6e,genLsCache:E6e,assertNoLevelCollisions:C6e}=hH(),{asChindings:_ge,asJson:u6e,buildFormatters:wge,stringify:Dge}=Jb(),{version:B6e}=EH(),f6e=VU(),Q6e=class{},Tge={constructor:Q6e,child:y6e,bindings:m6e,setBindings:S6e,flush:b6e,isLevelEnabled:p6e,version:B6e,get level(){return this[mge]()},set level(n){this[uH](n)},get levelVal(){return this[VWe]},set levelVal(n){throw Error("levelVal is read-only")},[zWe]:h6e,[XWe]:D6e,[bge]:u6e,[mge]:I6e,[uH]:l6e};Object.setPrototypeOf(Tge,qWe.prototype);Nge.exports=function(){return Object.create(Tge)};var Oge=n=>n;function y6e(n,t){if(!n)throw Error("missing bindings for child Pino");t=t||{};let o=this[np],i=this[CH],e=Object.create(this);if(t.hasOwnProperty("serializers")===!0){e[np]=Object.create(null);for(let c in o)e[np][c]=o[c];let s=Object.getOwnPropertySymbols(o);for(var a=0;a{"use strict";var{hasOwnProperty:kf}=Object.prototype,gp=yH();gp.configure=yH;gp.stringify=gp;gp.default=gp;mH.stringify=gp;mH.configure=yH;Pge.exports=gp;var M6e=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function EI(n){return n.length<5e3&&!M6e.test(n)?`"${n}"`:JSON.stringify(n)}function fH(n,t){if(n.length>200||t)return n.sort(t);for(let o=1;oi;)n[e]=n[e-1],e--;n[e]=i}return n}var _6e=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function QH(n){return _6e.call(n)!==void 0&&n.length!==0}function kge(n,t,o){n.length= 1`)}return o===void 0?1/0:o}function sp(n){return n===1?"1 item":`${n} items`}function k6e(n){let t=new Set;for(let o of n)(typeof o=="string"||typeof o=="number")&&t.add(String(o));return t}function v6e(n){if(kf.call(n,"strict")){let t=n.strict;if(typeof t!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(t)return o=>{let i=`Object can not safely be stringified. Received type ${typeof o}`;throw typeof o!="function"&&(i+=` (${o.toString()})`),new Error(i)}}}function yH(n){n={...n};let t=v6e(n);t&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let o=T6e(n),i=R6e(n,"bigint"),e=N6e(n),a=typeof e=="function"?e:void 0,A=vge(n,"maximumDepth"),r=vge(n,"maximumBreadth");function s(B,f,Q,y,m,_){let T=f[B];switch(typeof T=="object"&&T!==null&&typeof T.toJSON=="function"&&(T=T.toJSON(B)),T=y.call(f,B,T),typeof T){case"string":return EI(T);case"object":{if(T===null)return"null";if(Q.indexOf(T)!==-1)return o;let R="",L=",",U=_;if(Array.isArray(T)){if(T.length===0)return"[]";if(Ar){let k=T.length-r-1;R+=`${L}"... ${sp(k)} not stringified"`}return m!==""&&(R+=` +${U}`),Q.pop(),`[${R}]`}let F=Object.keys(T),q=F.length;if(q===0)return"{}";if(Ar){let J=q-r;R+=`${j}"...":${z}"${sp(J)} not stringified"`,j=L}return m!==""&&j.length>1&&(R=` ${_}${R} -${K}`),Q.pop(),`{${R}}`}case"number":return isFinite(T)?String(T):t?t(T):"null";case"boolean":return T===!0?"true":"false";case"undefined":return;case"bigint":if(i)return String(T);default:return t?t(T):void 0}}function g(B,f,Q,y,m,_){switch(typeof f=="object"&&f!==null&&typeof f.toJSON=="function"&&(f=f.toJSON(B)),typeof f){case"string":return EI(f);case"object":{if(f===null)return"null";if(Q.indexOf(f)!==-1)return o;let T=_,R="",F=",";if(Array.isArray(f)){if(f.length===0)return"[]";if(Ar){let P=f.length-r-1;R+=`${F}"... ${sp(P)} not stringified"`}return m!==""&&(R+=` -${T}`),Q.pop(),`[${R}]`}Q.push(f);let K="";m!==""&&(_+=m,F=`, -${_}`,K=" ");let L="";for(let q of y){let z=g(q,f[q],Q,y,m,_);z!==void 0&&(R+=`${L}${EI(q)}:${K}${z}`,L=F)}return m!==""&&L.length>1&&(R=` +${U}`),Q.pop(),`{${R}}`}case"number":return isFinite(T)?String(T):t?t(T):"null";case"boolean":return T===!0?"true":"false";case"undefined":return;case"bigint":if(i)return String(T);default:return t?t(T):void 0}}function g(B,f,Q,y,m,_){switch(typeof f=="object"&&f!==null&&typeof f.toJSON=="function"&&(f=f.toJSON(B)),typeof f){case"string":return EI(f);case"object":{if(f===null)return"null";if(Q.indexOf(f)!==-1)return o;let T=_,R="",L=",";if(Array.isArray(f)){if(f.length===0)return"[]";if(Ar){let P=f.length-r-1;R+=`${L}"... ${sp(P)} not stringified"`}return m!==""&&(R+=` +${T}`),Q.pop(),`[${R}]`}Q.push(f);let U="";m!==""&&(_+=m,L=`, +${_}`,U=" ");let F="";for(let q of y){let z=g(q,f[q],Q,y,m,_);z!==void 0&&(R+=`${F}${EI(q)}:${U}${z}`,F=L)}return m!==""&&F.length>1&&(R=` ${_}${R} ${T}`),Q.pop(),`{${R}}`}case"number":return isFinite(f)?String(f):t?t(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(i)return String(f);default:return t?t(f):void 0}}function c(B,f,Q,y,m){switch(typeof f){case"string":return EI(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(B),typeof f!="object")return c(B,f,Q,y,m);if(f===null)return"null"}if(Q.indexOf(f)!==-1)return o;let _=m;if(Array.isArray(f)){if(f.length===0)return"[]";if(Ar){let N=f.length-r-1;z+=`${j}"... ${sp(N)} not stringified"`}return z+=` -${_}`,Q.pop(),`[${z}]`}let T=Object.keys(f),R=T.length;if(R===0)return"{}";if(Ar){let z=R-r;K+=`${L}"...": "${sp(z)} not stringified"`,L=F}return L!==""&&(K=` -${m}${K} -${_}`),Q.pop(),`{${K}}`}case"number":return isFinite(f)?String(f):t?t(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(i)return String(f);default:return t?t(f):void 0}}function I(B,f,Q){switch(typeof f){case"string":return EI(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(B),typeof f!="object")return I(B,f,Q);if(f===null)return"null"}if(Q.indexOf(f)!==-1)return o;let y="",m=f.length!==void 0;if(m&&Array.isArray(f)){if(f.length===0)return"[]";if(Ar){let z=f.length-r-1;y+=`,"... ${sp(z)} not stringified"`}return Q.pop(),`[${y}]`}let _=Object.keys(f),T=_.length;if(T===0)return"{}";if(Ar){let K=T-r;y+=`${R}"...":"${sp(K)} not stringified"`}return Q.pop(),`{${y}}`}case"number":return isFinite(f)?String(f):t?t(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(i)return String(f);default:return t?t(f):void 0}}function d(B,f,Q){if(arguments.length>1){let y="";if(typeof Q=="number"?y=" ".repeat(Math.min(Q,10)):typeof Q=="string"&&(y=Q.slice(0,10)),f!=null){if(typeof f=="function")return s("",{"":B},[],f,y,"");if(Array.isArray(f))return g("",B,[],k6e(f),y,"")}if(y.length!==0)return c("",B,[],y,"")}return I("",B,[])}return d}});var Uge=$((bkA,Lge)=>{"use strict";var SH=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Fge}=qb(),P6e=Fge.info;function G6e(n,t){let o=0;n=n||[],t=t||{dedupe:!1};let i=Object.create(Fge);i.silent=1/0,t.levels&&typeof t.levels=="object"&&Object.keys(t.levels).forEach(I=>{i[I]=t.levels[I]});let e={write:a,add:s,emit:A,flushSync:r,end:g,minLevel:0,streams:[],clone:c,[SH]:!0,streamLevels:i};return Array.isArray(n)?n.forEach(s,e):s.call(e,n),n=null,e;function a(I){let d,B=this.lastLevel,{streams:f}=this,Q=0,y;for(let m=L6e(f.length,t.dedupe);H6e(m,f.length,t.dedupe);m=U6e(m,t.dedupe))if(d=f[m],d.level<=B){if(Q!==0&&Q!==d.level)break;if(y=d.stream,y[SH]){let{lastTime:_,lastMsg:T,lastObj:R,lastLogger:F}=this;y.lastLevel=B,y.lastTime=_,y.lastMsg=T,y.lastObj=R,y.lastLogger=F}y.write(I),t.dedupe&&(Q=d.level)}else if(!t.dedupe)break}function A(...I){for(let{stream:d}of this.streams)typeof d.emit=="function"&&d.emit(...I)}function r(){for(let{stream:I}of this.streams)typeof I.flushSync=="function"&&I.flushSync()}function s(I){if(!I)return e;let d=typeof I.write=="function"||I.stream,B=I.write?I:I.stream;if(!d)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:f,streamLevels:Q}=this,y;typeof I.levelVal=="number"?y=I.levelVal:typeof I.level=="string"?y=Q[I.level]:typeof I.level=="number"?y=I.level:y=P6e;let m={stream:B,level:y,levelVal:void 0,id:o++};return f.unshift(m),f.sort(F6e),this.minLevel=f[0].level,e}function g(){for(let{stream:I}of this.streams)typeof I.flushSync=="function"&&I.flushSync(),I.end()}function c(I){let d=new Array(this.streams.length);for(let B=0;B=0:n{"use strict";var K6e=$e("node:os"),zge=HU(),x6e=KU(),Y6e=VU(),Vge=Rse(),j6e=Rge(),Wge=gE(),{configure:J6e}=Gge(),{assertDefaultLevelFound:q6e,mappings:Zge,genLsCache:z6e,genLevelComparison:V6e,assertLevelComparison:W6e}=hH(),{DEFAULT_LEVELS:Xge,SORTING_ORDER:Z6e}=qb(),{createArgsNormalizer:X6e,asChindings:$6e,buildSafeSonicBoom:Hge,buildFormatters:e5e,stringify:wH,normalizeDestFileDescriptor:Kge,noop:A5e}=Jb(),{version:t5e}=EH(),{chindingsSym:xge,redactFmtSym:r5e,serializersSym:Yge,timeSym:a5e,timeSliceIndexSym:i5e,streamSym:o5e,stringifySym:jge,stringifySafeSym:DH,stringifiersSym:Jge,setLevelSym:n5e,endSym:s5e,formatOptsSym:g5e,messageKeySym:c5e,errorKeySym:I5e,nestedKeySym:l5e,mixinSym:p5e,levelCompSym:d5e,useOnlyCustomLevelsSym:h5e,formattersSym:qge,hooksSym:E5e,nestedKeyStrSym:C5e,mixinMergeStrategySym:u5e,msgPrefixSym:B5e}=Wge,{epochTime:$ge,nullTime:f5e}=Vge,{pid:Q5e}=process,y5e=K6e.hostname(),m5e=zge.err,S5e={level:"info",levelComparison:Z6e.ASC,levels:Xge,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Q5e,hostname:y5e},serializers:Object.assign(Object.create(null),{err:m5e}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:$ge,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},w5e=X6e(S5e),D5e=Object.assign(Object.create(null),zge);function OH(...n){let t={},{opts:o,stream:i}=w5e(t,x6e(),...n);o.level&&typeof o.level=="string"&&Xge[o.level.toLowerCase()]!==void 0&&(o.level=o.level.toLowerCase());let{redact:e,crlf:a,serializers:A,timestamp:r,messageKey:s,errorKey:g,nestedKey:c,base:I,name:d,level:B,customLevels:f,levelComparison:Q,mixin:y,mixinMergeStrategy:m,useOnlyCustomLevels:_,formatters:T,hooks:R,depthLimit:F,edgeLimit:K,onChild:L,msgPrefix:q}=o,z=J6e({maximumDepth:F,maximumBreadth:K}),j=e5e(T.level,T.bindings,T.log),P=wH.bind({[DH]:z}),J=e?Y6e(e,P):{},U=e?{stringify:J[r5e]}:{stringify:P},N="}"+(a?`\r +${m}`,P=Math.min(f.length,r),J=0;for(;Jr){let N=f.length-r-1;z+=`${j}"... ${sp(N)} not stringified"`}return z+=` +${_}`,Q.pop(),`[${z}]`}let T=Object.keys(f),R=T.length;if(R===0)return"{}";if(Ar){let z=R-r;U+=`${F}"...": "${sp(z)} not stringified"`,F=L}return F!==""&&(U=` +${m}${U} +${_}`),Q.pop(),`{${U}}`}case"number":return isFinite(f)?String(f):t?t(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(i)return String(f);default:return t?t(f):void 0}}function I(B,f,Q){switch(typeof f){case"string":return EI(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(B),typeof f!="object")return I(B,f,Q);if(f===null)return"null"}if(Q.indexOf(f)!==-1)return o;let y="",m=f.length!==void 0;if(m&&Array.isArray(f)){if(f.length===0)return"[]";if(Ar){let z=f.length-r-1;y+=`,"... ${sp(z)} not stringified"`}return Q.pop(),`[${y}]`}let _=Object.keys(f),T=_.length;if(T===0)return"{}";if(Ar){let U=T-r;y+=`${R}"...":"${sp(U)} not stringified"`}return Q.pop(),`{${y}}`}case"number":return isFinite(f)?String(f):t?t(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(i)return String(f);default:return t?t(f):void 0}}function d(B,f,Q){if(arguments.length>1){let y="";if(typeof Q=="number"?y=" ".repeat(Math.min(Q,10)):typeof Q=="string"&&(y=Q.slice(0,10)),f!=null){if(typeof f=="function")return s("",{"":B},[],f,y,"");if(Array.isArray(f))return g("",B,[],k6e(f),y,"")}if(y.length!==0)return c("",B,[],y,"")}return I("",B,[])}return d}});var Uge=$((bkA,Lge)=>{"use strict";var SH=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Fge}=qb(),P6e=Fge.info;function G6e(n,t){let o=0;n=n||[],t=t||{dedupe:!1};let i=Object.create(Fge);i.silent=1/0,t.levels&&typeof t.levels=="object"&&Object.keys(t.levels).forEach(I=>{i[I]=t.levels[I]});let e={write:a,add:s,emit:A,flushSync:r,end:g,minLevel:0,streams:[],clone:c,[SH]:!0,streamLevels:i};return Array.isArray(n)?n.forEach(s,e):s.call(e,n),n=null,e;function a(I){let d,B=this.lastLevel,{streams:f}=this,Q=0,y;for(let m=L6e(f.length,t.dedupe);H6e(m,f.length,t.dedupe);m=U6e(m,t.dedupe))if(d=f[m],d.level<=B){if(Q!==0&&Q!==d.level)break;if(y=d.stream,y[SH]){let{lastTime:_,lastMsg:T,lastObj:R,lastLogger:L}=this;y.lastLevel=B,y.lastTime=_,y.lastMsg=T,y.lastObj=R,y.lastLogger=L}y.write(I),t.dedupe&&(Q=d.level)}else if(!t.dedupe)break}function A(...I){for(let{stream:d}of this.streams)typeof d.emit=="function"&&d.emit(...I)}function r(){for(let{stream:I}of this.streams)typeof I.flushSync=="function"&&I.flushSync()}function s(I){if(!I)return e;let d=typeof I.write=="function"||I.stream,B=I.write?I:I.stream;if(!d)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:f,streamLevels:Q}=this,y;typeof I.levelVal=="number"?y=I.levelVal:typeof I.level=="string"?y=Q[I.level]:typeof I.level=="number"?y=I.level:y=P6e;let m={stream:B,level:y,levelVal:void 0,id:o++};return f.unshift(m),f.sort(F6e),this.minLevel=f[0].level,e}function g(){for(let{stream:I}of this.streams)typeof I.flushSync=="function"&&I.flushSync(),I.end()}function c(I){let d=new Array(this.streams.length);for(let B=0;B=0:n{"use strict";var K6e=$e("node:os"),zge=HU(),x6e=KU(),Y6e=VU(),Vge=Rse(),j6e=Rge(),Wge=gE(),{configure:J6e}=Gge(),{assertDefaultLevelFound:q6e,mappings:Zge,genLsCache:z6e,genLevelComparison:V6e,assertLevelComparison:W6e}=hH(),{DEFAULT_LEVELS:Xge,SORTING_ORDER:Z6e}=qb(),{createArgsNormalizer:X6e,asChindings:$6e,buildSafeSonicBoom:Hge,buildFormatters:e5e,stringify:wH,normalizeDestFileDescriptor:Kge,noop:A5e}=Jb(),{version:t5e}=EH(),{chindingsSym:xge,redactFmtSym:r5e,serializersSym:Yge,timeSym:a5e,timeSliceIndexSym:i5e,streamSym:o5e,stringifySym:jge,stringifySafeSym:DH,stringifiersSym:Jge,setLevelSym:n5e,endSym:s5e,formatOptsSym:g5e,messageKeySym:c5e,errorKeySym:I5e,nestedKeySym:l5e,mixinSym:p5e,levelCompSym:d5e,useOnlyCustomLevelsSym:h5e,formattersSym:qge,hooksSym:E5e,nestedKeyStrSym:C5e,mixinMergeStrategySym:u5e,msgPrefixSym:B5e}=Wge,{epochTime:$ge,nullTime:f5e}=Vge,{pid:Q5e}=process,y5e=K6e.hostname(),m5e=zge.err,S5e={level:"info",levelComparison:Z6e.ASC,levels:Xge,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Q5e,hostname:y5e},serializers:Object.assign(Object.create(null),{err:m5e}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:$ge,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},w5e=X6e(S5e),D5e=Object.assign(Object.create(null),zge);function OH(...n){let t={},{opts:o,stream:i}=w5e(t,x6e(),...n);o.level&&typeof o.level=="string"&&Xge[o.level.toLowerCase()]!==void 0&&(o.level=o.level.toLowerCase());let{redact:e,crlf:a,serializers:A,timestamp:r,messageKey:s,errorKey:g,nestedKey:c,base:I,name:d,level:B,customLevels:f,levelComparison:Q,mixin:y,mixinMergeStrategy:m,useOnlyCustomLevels:_,formatters:T,hooks:R,depthLimit:L,edgeLimit:U,onChild:F,msgPrefix:q}=o,z=J6e({maximumDepth:L,maximumBreadth:U}),j=e5e(T.level,T.bindings,T.log),P=wH.bind({[DH]:z}),J=e?Y6e(e,P):{},H=e?{stringify:J[r5e]}:{stringify:P},N="}"+(a?`\r `:` -`),k=$6e.bind(null,{[xge]:"",[Yge]:A,[Jge]:J,[jge]:wH,[DH]:z,[qge]:j}),V="";I!==null&&(d===void 0?V=k(I):V=k(Object.assign({},I,{name:d})));let Ae=r instanceof Function?r:r?$ge:f5e,ie=Ae().indexOf(":")+1;if(_&&!f)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(y&&typeof y!="function")throw Error(`Unknown mixin type "${typeof y}" - expected "function"`);if(q&&typeof q!="string")throw Error(`Unknown msgPrefix type "${typeof q}" - expected "string"`);q6e(B,f,_);let De=Zge(f,_);typeof i.emit=="function"&&i.emit("message",{code:"PINO_CONFIG",config:{levels:De,messageKey:s,errorKey:g}}),W6e(Q);let fe=V6e(Q);return Object.assign(t,{levels:De,[d5e]:fe,[h5e]:_,[o5e]:i,[a5e]:Ae,[i5e]:ie,[jge]:wH,[DH]:z,[Jge]:J,[s5e]:N,[g5e]:U,[c5e]:s,[I5e]:g,[l5e]:c,[C5e]:c?`,${JSON.stringify(c)}:{`:"",[Yge]:A,[p5e]:y,[u5e]:m,[xge]:V,[qge]:j,[E5e]:R,silent:A5e,onChild:L,[B5e]:q}),Object.setPrototypeOf(t,j6e()),z6e(t),t[n5e](B),t}tn.exports=OH;tn.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=Kge(n.dest||process.stdout.fd),Hge(n)):Hge({dest:Kge(n),minLength:0});tn.exports.transport=gH();tn.exports.multistream=Uge();tn.exports.levels=Zge();tn.exports.stdSerializers=D5e;tn.exports.stdTimeFunctions=Object.assign({},Vge);tn.exports.symbols=Wge;tn.exports.version=t5e;tn.exports.default=OH;tn.exports.pino=OH});import{unlink as iCe}from"node:fs/promises";import{homedir as oCe}from"node:os";import{join as UE,resolve as bI}from"node:path";import{createHash as jIe,randomUUID as YK}from"node:crypto";import{mkdir as JIe,readFile as qIe,rename as zIe,unlink as xK,writeFile as VIe}from"node:fs/promises";import{dirname as WIe}from"node:path";var OK={"\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002":"This question has already been answered from another client; no further reply is needed.","\u4EFB\u52A1\u5DF2\u5B8C\u6210\u3002":"Task completed.",\u7ED3\u679C\u6587\u4EF6:"result file","\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u7684\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002":'The delivery result of the result file "{name}" could not be confirmed. Please check whether it already arrived in the chat before retrying.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 Slack \u5E94\u7528\u7F3A\u5C11 files:write \u6743\u9650\u3002\u8BF7\u66F4\u65B0 Manifest\u3001\u91CD\u65B0\u5B89\u88C5\u5E94\u7528\u5E76\u91CD\u65B0\u8FDE\u63A5\u673A\u5668\u4EBA\u540E\u91CD\u8BD5\u3002":'The result file "{name}" was generated, but the Slack app is missing the files:write permission. Please update the Manifest, reinstall the app, reconnect the bot, and try again.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11 Discord \u7684 Send Messages\u3001Attach Files \u6216 Read Message History \u6743\u9650\u3002":'The result file "{name}" was generated, but the bot is missing the Discord Send Messages, Attach Files, or Read Message History permission.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 Telegram \u4E0D\u5141\u8BB8\u673A\u5668\u4EBA\u5728\u5F53\u524D\u804A\u5929\u53D1\u9001\u6587\u6863\uFF0C\u8BF7\u68C0\u67E5\u804A\u5929\u6743\u9650\u3002":'The result file "{name}" was generated, but Telegram does not allow the bot to send documents in this chat. Please check the chat permissions.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u673A\u5668\u4EBA\u6CA1\u6709\u6587\u4EF6\u53D1\u9001\u6743\u9650\uFF0C\u8BF7\u68C0\u67E5\u6E20\u9053\u6743\u9650\u3002":'The result file "{name}" was generated, but the bot does not have permission to send files. Please check the channel permissions.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u6E20\u9053\u5927\u5C0F\u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002":'The result file "{name}" exceeds the size limit of this channel and was not sent.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u672A\u53D1\u9001\u3002":'The result file "{name}" is empty and was not sent.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002":'The result file "{name}" cannot be read or prepared for sending right now. Please make sure the file is still accessible and try again.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u5F53\u524D\u6E20\u9053\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":'The result file "{name}" was temporarily rate-limited by this channel and could not be sent. Please try again later.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002":'The result file "{name}" was generated, but this channel rejected the file or file message.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":'The result file "{name}" was generated, but this channel could not send it right now. Please try again later.',"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Failed to process the message. Please try again later.","\u5361\u7247\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u67E5\u770B\u540E\u7EED\u6D88\u606F\u3002":"This card has ended. Please check the next message.","\u5DE5\u5177\u8C03\u7528\u300C{name}\u300D\u672A\u6210\u529F\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u5177\u914D\u7F6E\u6216\u7A0D\u540E\u91CD\u8BD5\u3002":'Tool call "{name}" did not succeed. Check the tool configuration or try again later.',"\u65E0\u6CD5\u8FDE\u63A5\u5904\u7406\u670D\u52A1\uFF0C\u6D88\u606F\u5C1A\u672A\u63D0\u4EA4\u3002\u8BF7\u786E\u8BA4 DeepSeek Harness \u6B63\u5728\u8FD0\u884C\u540E\u91CD\u8BD5\u3002":"Could not connect to the processing service, so the message was not submitted. Make sure DeepSeek Harness is running, then try again.","\u5904\u7406\u670D\u52A1\u54CD\u5E94\u8D85\u65F6\uFF0C\u6D88\u606F\u5C1A\u672A\u5F00\u59CB\u5904\u7406\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The processing service timed out before the message started. Please try again later.","\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u4EFB\u52A1\u72B6\u6001\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u7ECF\u5F00\u59CB\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"The task status could not be confirmed and the task may have started. Wait or send /stop before submitting it again.","\u6D88\u606F\u63D0\u4EA4\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u7ECF\u5F00\u59CB\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /status \u67E5\u770B\u72B6\u6001\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"The message submission could not be confirmed and the task may have started. Wait or send /status before submitting it again.","\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4EFB\u52A1\u8FDB\u5EA6\uFF0C\u4EFB\u52A1\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Task progress is temporarily unavailable and the task may still be running. Wait or send /stop before submitting it again.","\u5904\u7406\u670D\u52A1\u62D2\u7EDD\u4E86\u673A\u5668\u4EBA\u8FDE\u63A5\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5 Harness \u5730\u5740\u3001\u4EE3\u7406\u6216\u8BBF\u95EE\u914D\u7F6E\u540E\u91CD\u8BD5\u3002":"The processing service rejected the bot connection. Ask an administrator to check the Harness address, proxy, or access settings.","\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u7684\u63A5\u53E3\u4E0D\u517C\u5BB9\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5 Harness \u5730\u5740\u5E76\u66F4\u65B0\u76F8\u5173\u7248\u672C\u3002":"The bot and DeepSeek Harness use incompatible APIs. Ask an administrator to check the Harness address and update the related components.","DeepSeek Harness \u6682\u65F6\u65E0\u6CD5\u5B8C\u6210\u8BF7\u6C42\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"DeepSeek Harness could not complete the request. Please try again later.","\u7B49\u5F85\u6A21\u578B\u56DE\u590D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Waiting for the model reply timed out and the task may still be running. Wait or send /stop before submitting it again.","\u6A21\u578B\u51ED\u636E\u7F3A\u5931\u6216\u5DF2\u5931\u6548\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5\u6A21\u578B\u914D\u7F6E\u540E\u91CD\u8BD5\u3002":"The model credentials are missing or invalid. Ask an administrator to check the model settings.","\u6A21\u578B\u989D\u5EA6\u6216\u4F59\u989D\u4E0D\u8DB3\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7BA1\u7406\u5458\u8865\u5145\u989D\u5EA6\u6216\u5207\u6362\u6A21\u578B\u540E\u91CD\u8BD5\u3002":"The model quota or balance is insufficient. Ask an administrator to add quota or switch models, then try again.","\u6A21\u578B\u670D\u52A1\u6B63\u5728\u9650\u6D41\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is rate-limiting requests. Please try again later.","\u5F53\u524D\u4F1A\u8BDD\u5185\u5BB9\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\u3002\u8BF7\u53D1\u9001 /compact \u6216 /new \u540E\u91CD\u8BD5\u3002":"This conversation exceeds the model context limit. Send /compact or /new, then try again.","\u5F53\u524D\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u53D1\u9001 /models \u67E5\u770B\u5E76\u4F7F\u7528 /model \u5207\u6362\u6A21\u578B\u3002":"The current model does not exist or is unavailable. Send /models and use /model to switch models.","\u5F53\u524D\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u4E0D\u652F\u6301\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u53D1\u9001 /models\uFF0C\u5E76\u4F7F\u7528 /model \u91CD\u65B0\u9009\u62E9\u3002":"The current model does not exist or does not support the selected settings. Send /models and use /model to choose again.","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u8FD9\u7C7B\u5185\u5BB9\u6216\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u8C03\u6574\u5185\u5BB9\u3001\u6A21\u578B\u6216\u63A8\u7406\u7B49\u7EA7\u540E\u91CD\u8BD5\u3002":"The current model does not support this content or the selected settings. Adjust the content, model, or reasoning effort and try again.","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u5207\u6362\u6A21\u578B\u6216\u63A8\u7406\u7B49\u7EA7\u540E\u91CD\u8BD5\u3002":"The current model does not support the selected settings. Switch the model or reasoning effort, then try again.","\u6A21\u578B\u670D\u52A1\u54CD\u5E94\u8D85\u65F6\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service timed out and the task did not finish. Please try again later.","\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u6A21\u578B\u670D\u52A1\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is temporarily unreachable and the task did not finish. Please try again later.","\u6A21\u578B\u670D\u52A1\u6682\u65F6\u5F02\u5E38\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is temporarily unavailable and the task did not finish. Please try again later.","\u6A21\u578B\u56DE\u590D\u4E2D\u65AD\u6216\u683C\u5F0F\u5F02\u5E38\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u91CD\u8BD5\u3002":"The model reply was interrupted or malformed, so the task did not finish. Please try again.","\u6A21\u578B\u6CA1\u6709\u8FD4\u56DE\u53EF\u663E\u793A\u7684\u5185\u5BB9\u3002\u8BF7\u91CD\u8BD5\uFF1B\u82E5\u6301\u7EED\u53D1\u751F\uFF0C\u8BF7\u5207\u6362\u6A21\u578B\u3002":"The model returned no displayable content. Try again, or switch models if this keeps happening.","\u6A21\u578B\u62D2\u7EDD\u5904\u7406\u5F53\u524D\u5185\u5BB9\u3002\u8BF7\u8C03\u6574\u95EE\u9898\u5185\u5BB9\u540E\u91CD\u8BD5\u3002":"The model rejected the current content. Revise the request and try again.","\u6A21\u578B\u8FBE\u5230\u8F93\u51FA\u957F\u5EA6\u4E0A\u9650\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u7ED3\u679C\u3002\u8BF7\u7F29\u5C0F\u4EFB\u52A1\u8303\u56F4\u540E\u91CD\u8BD5\u3002":"The model reached its output limit without producing a displayable result. Reduce the task scope and try again.","\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u65E0\u6CD5\u5728\u5F53\u524D\u6E20\u9053\u5B8C\u6210\u7684\u64CD\u4F5C\u3002\u8BF7\u5728 DeepSeek Harness \u4E2D\u5904\u7406\u540E\u518D\u8BD5\u3002":"The task is waiting for an action that cannot be completed in this channel. Handle it in DeepSeek Harness, then try again.","\u4EFB\u52A1\u88AB\u610F\u5916\u4E2D\u65AD\uFF0C\u672C\u6B21\u672A\u5B8C\u6210\u3002\u8BF7\u91CD\u8BD5\u3002":"The task was unexpectedly interrupted and did not finish. Please try again.","\u5F53\u524D\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\u3002\u8BF7\u53D1\u9001 /new \u521B\u5EFA\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002":"The current Session no longer exists. Send /new to create one, then try again.","\u5F53\u524D\u4F1A\u8BDD\u4ECD\u5728\u5904\u7406\u4E0A\u4E00\u9879\u4EFB\u52A1\u3002\u8BF7\u7B49\u5F85\u5B8C\u6210\uFF0C\u6216\u53D1\u9001 /stop \u540E\u91CD\u8BD5\u3002":"The current Session is still processing the previous task. Wait for it to finish, or send /stop before trying again.","\u5DE5\u4F5C\u533A\u6216\u4F1A\u8BDD\u72B6\u6001\u521A\u521A\u53D1\u751F\u53D8\u5316\u3002\u8BF7\u91CD\u65B0\u53D1\u9001\u8FD9\u6761\u6D88\u606F\u3002":"The Workspace or Session state just changed. Please send this message again.","\u5F53\u524D\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u91CD\u65B0\u9009\u62E9\u5DE5\u4F5C\u533A\u540E\u91CD\u8BD5\u3002":"The current Workspace does not exist or is unavailable. Select another Workspace and try again.","\u5F53\u524D Agent Preset \u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u53D1\u9001 /presetlist \u540E\u91CD\u65B0\u9009\u62E9\u3002":"The current Agent Preset does not exist or is unavailable. Send /presetlist and select another one.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u6CA1\u6709\u53D1\u9001\u6743\u9650\u3002\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u68C0\u67E5\u6E20\u9053\u6743\u9650\u6216\u91CD\u65B0\u7ED1\u5B9A\u673A\u5668\u4EBA\u3002":"The reply was generated, but the bot cannot send it. Ask an administrator to check channel permissions or reconnect the bot.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6B63\u5728\u9650\u6D41\uFF0C\u6682\u65F6\u65E0\u6CD5\u53D1\u9001\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The reply was generated, but this channel is rate-limiting messages. Please try again later.","\u56DE\u590D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\u3002\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u7ECF\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Reply delivery could not be confirmed. Check whether it already arrived before submitting the task again.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u65E0\u6CD5\u53D1\u9001\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The reply was generated, but this channel could not send it. Please try again later.","\u5F53\u524D\u6D88\u606F\u5305\u542B\u65E0\u6CD5\u5904\u7406\u7684\u56FE\u7247\u6216\u6587\u4EF6\u3002\u8BF7\u8C03\u6574\u540E\u91CD\u65B0\u53D1\u9001\u3002":"This message contains an image or file that cannot be processed. Adjust it and send it again.","\u4EFB\u52A1\u672A\u5B8C\u6210\uFF0C\u6682\u65F6\u65E0\u6CD5\u786E\u5B9A\u539F\u56E0\u3002\u8BF7\u91CD\u8BD5\uFF1B\u82E5\u6301\u7EED\u53D1\u751F\uFF0C\u8BF7\u5C06\u53C2\u8003\u53F7\u63D0\u4F9B\u7ED9\u7BA1\u7406\u5458\u3002":"The task did not finish and the cause could not be determined. Try again; if it persists, give the reference ID to an administrator.","\u9519\u8BEF\u7801\uFF1A{code}\uFF1B\u53C2\u8003\u53F7\uFF1A{referenceId}":"Error code: {code}; reference: {referenceId}","{label}\u673A\u5668\u4EBA":"{label} bot","\u76EE\u524D\u652F\u6301\u6587\u5B57\u548C\u56FE\u7247\u6D88\u606F\u3002":"Only text and image messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002":"Only text, image, and file messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002":"Only text, image, file, and voice-transcription messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\uFF0C\u4EE5\u53CA\u5FAE\u4FE1\u5DF2\u8F6C\u6210\u6587\u5B57\u7684\u8BED\u97F3\u6D88\u606F\u3002":"Only text, image, file, and voice messages already transcribed to text by WeChat are supported at the moment.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u6216\u56FE\u7247\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text or an image directly to continue the current session.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text, an image, or a file directly to continue the current session.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u6216\u5E26\u6587\u5B57\u8BC6\u522B\u7ED3\u679C\u7684\u8BED\u97F3\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text, an image, a file, or a voice message already transcribed to text to continue the current session.","{label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002":"The {label} bot is connected to DeepSeek Harness.","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD":"/new Start a brand-new session","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587":"/compact Compact the earlier context of the current session","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A":"/workspace Switch workspace","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84":"/workspacelist List absolute workspace paths","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898":"/sessionlist [workspace index or absolute path] List session IDs and titles","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898":"/sessionlist or /sessions [workspace index or absolute path] List session IDs and titles","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD":"/session Bind this chat to the specified session","/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B":"/models List all available models by index","/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7":"/reasoninglist or /reasonings List reasoning efforts for the current model by index","/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7":"/reasoning [index, effort ID, or --default] Show or switch the current reasoning effort","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B":"/model [index or full model ID] Show or switch the model of the current session","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B":"/model [index or full model ID] [reasoning effort ID] Show or switch the current Session model","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2":"Example: send /models first, then /model 2","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]":"Example: send /models first, then /model 2 [reasoning effort ID]","/presetlist \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset":"/presetlist List available Agent Presets by index","/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset":"/presetlist or /presets List available Agent Presets by index","/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset":"/preset [index or full ID] Show or set the Agent Preset of this bot","\u7EAF\u6570\u5B57 ID\uFF1A/preset id:":"Numeric-only ID: /preset id:","/preset --default \u8DDF\u968F Host \u9ED8\u8BA4":"/preset --default Follow the Host default","/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1":"/stop Stop the current task","/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1":"/steer Steer the current task","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001":"/status Check the connection status","/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C":"/version Show the plugin version","/help \u663E\u793A\u672C\u5E2E\u52A9":"/help Show this help","{label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002":"The {label} bot is connected to DeepSeek Harness and working normally.","{label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002":"{label} bot credentials are missing. Remove the bot and connect it again.","{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002":"The {label} connection is not ready yet. The plugin will retry automatically.","{label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002":"The {label} bot is connected, but its message connection is not ready yet.","{label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The {label} connection is still not ready. Please try again later.","{label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5":"The {label} bot is not connected yet","{name}\uFF08{id}\uFF09":"{name} ({id})","{label}{connectionLabel}\u8FD0\u884C\u6B63\u5E38":"The {label}{connectionLabel} is running normally","{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"The {label} connection is not ready. The plugin will retry automatically","{label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF":"The {label} connection is currently offline","\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002":"A new session has started. Please send your question.","\u6B63\u5728\u4F7F\u7528{name}\u2026":"Using {name}\u2026","\u5DF2\u505C\u6B62\u3002":"Stopped.","\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002":"Please answer the current question with text.","{label}\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002":"Failed to send the {label} interaction question.","\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002":"Failed to submit the answer.","\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002":"Failed to submit the answer. Please resend your answer to the current question.","\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002":"A pending question left over in this Session was detected. It has been safely cancelled, and your latest message is being processed."};var bK={"\u7528\u6CD5\uFF1A/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7\uFF08/session N\uFF09":"Usage: /session Session ID or the session index in the current Workspace (/session N)","\u7528\u6CD5\uFF1A\n/sessionlist \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u4F1A\u8BDD\n/sessionlist \u5DE5\u4F5C\u533A\u5E8F\u53F7 \u6309 /workspacelist \u5E8F\u53F7\u5217\u51FA\u4F1A\u8BDD\n/sessionlist \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5217\u51FA\u6307\u5B9A\u5DE5\u4F5C\u533A\u4F1A\u8BDD":`Usage: +`),k=$6e.bind(null,{[xge]:"",[Yge]:A,[Jge]:J,[jge]:wH,[DH]:z,[qge]:j}),V="";I!==null&&(d===void 0?V=k(I):V=k(Object.assign({},I,{name:d})));let Ae=r instanceof Function?r:r?$ge:f5e,ie=Ae().indexOf(":")+1;if(_&&!f)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(y&&typeof y!="function")throw Error(`Unknown mixin type "${typeof y}" - expected "function"`);if(q&&typeof q!="string")throw Error(`Unknown msgPrefix type "${typeof q}" - expected "string"`);q6e(B,f,_);let De=Zge(f,_);typeof i.emit=="function"&&i.emit("message",{code:"PINO_CONFIG",config:{levels:De,messageKey:s,errorKey:g}}),W6e(Q);let fe=V6e(Q);return Object.assign(t,{levels:De,[d5e]:fe,[h5e]:_,[o5e]:i,[a5e]:Ae,[i5e]:ie,[jge]:wH,[DH]:z,[Jge]:J,[s5e]:N,[g5e]:H,[c5e]:s,[I5e]:g,[l5e]:c,[C5e]:c?`,${JSON.stringify(c)}:{`:"",[Yge]:A,[p5e]:y,[u5e]:m,[xge]:V,[qge]:j,[E5e]:R,silent:A5e,onChild:F,[B5e]:q}),Object.setPrototypeOf(t,j6e()),z6e(t),t[n5e](B),t}tn.exports=OH;tn.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=Kge(n.dest||process.stdout.fd),Hge(n)):Hge({dest:Kge(n),minLength:0});tn.exports.transport=gH();tn.exports.multistream=Uge();tn.exports.levels=Zge();tn.exports.stdSerializers=D5e;tn.exports.stdTimeFunctions=Object.assign({},Vge);tn.exports.symbols=Wge;tn.exports.version=t5e;tn.exports.default=OH;tn.exports.pino=OH});import{unlink as iCe}from"node:fs/promises";import{homedir as oCe}from"node:os";import{join as UE,resolve as bI}from"node:path";import{createHash as jIe,randomUUID as YK}from"node:crypto";import{mkdir as JIe,readFile as qIe,rename as zIe,unlink as xK,writeFile as VIe}from"node:fs/promises";import{dirname as WIe}from"node:path";var OK={"\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002":"This question has already been answered from another client; no further reply is needed.","\u4EFB\u52A1\u5DF2\u5B8C\u6210\u3002":"Task completed.",\u7ED3\u679C\u6587\u4EF6:"result file","\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u7684\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002":'The delivery result of the result file "{name}" could not be confirmed. Please check whether it already arrived in the chat before retrying.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 Slack \u5E94\u7528\u7F3A\u5C11 files:write \u6743\u9650\u3002\u8BF7\u66F4\u65B0 Manifest\u3001\u91CD\u65B0\u5B89\u88C5\u5E94\u7528\u5E76\u91CD\u65B0\u8FDE\u63A5\u673A\u5668\u4EBA\u540E\u91CD\u8BD5\u3002":'The result file "{name}" was generated, but the Slack app is missing the files:write permission. Please update the Manifest, reinstall the app, reconnect the bot, and try again.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11 Discord \u7684 Send Messages\u3001Attach Files \u6216 Read Message History \u6743\u9650\u3002":'The result file "{name}" was generated, but the bot is missing the Discord Send Messages, Attach Files, or Read Message History permission.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 Telegram \u4E0D\u5141\u8BB8\u673A\u5668\u4EBA\u5728\u5F53\u524D\u804A\u5929\u53D1\u9001\u6587\u6863\uFF0C\u8BF7\u68C0\u67E5\u804A\u5929\u6743\u9650\u3002":'The result file "{name}" was generated, but Telegram does not allow the bot to send documents in this chat. Please check the chat permissions.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u673A\u5668\u4EBA\u6CA1\u6709\u6587\u4EF6\u53D1\u9001\u6743\u9650\uFF0C\u8BF7\u68C0\u67E5\u6E20\u9053\u6743\u9650\u3002":'The result file "{name}" was generated, but the bot does not have permission to send files. Please check the channel permissions.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u6E20\u9053\u5927\u5C0F\u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002":'The result file "{name}" exceeds the size limit of this channel and was not sent.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u672A\u53D1\u9001\u3002":'The result file "{name}" is empty and was not sent.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002":'The result file "{name}" cannot be read or prepared for sending right now. Please make sure the file is still accessible and try again.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u5F53\u524D\u6E20\u9053\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":'The result file "{name}" was temporarily rate-limited by this channel and could not be sent. Please try again later.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002":'The result file "{name}" was generated, but this channel rejected the file or file message.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":'The result file "{name}" was generated, but this channel could not send it right now. Please try again later.',"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Failed to process the message. Please try again later.","\u5361\u7247\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u67E5\u770B\u540E\u7EED\u6D88\u606F\u3002":"This card has ended. Please check the next message.","\u5DE5\u5177\u8C03\u7528\u300C{name}\u300D\u672A\u6210\u529F\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u5177\u914D\u7F6E\u6216\u7A0D\u540E\u91CD\u8BD5\u3002":'Tool call "{name}" did not succeed. Check the tool configuration or try again later.',"\u65E0\u6CD5\u8FDE\u63A5\u5904\u7406\u670D\u52A1\uFF0C\u6D88\u606F\u5C1A\u672A\u63D0\u4EA4\u3002\u8BF7\u786E\u8BA4 DeepSeek Harness \u6B63\u5728\u8FD0\u884C\u540E\u91CD\u8BD5\u3002":"Could not connect to the processing service, so the message was not submitted. Make sure DeepSeek Harness is running, then try again.","\u5904\u7406\u670D\u52A1\u54CD\u5E94\u8D85\u65F6\uFF0C\u6D88\u606F\u5C1A\u672A\u5F00\u59CB\u5904\u7406\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The processing service timed out before the message started. Please try again later.","\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u4EFB\u52A1\u72B6\u6001\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u7ECF\u5F00\u59CB\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"The task status could not be confirmed and the task may have started. Wait or send /stop before submitting it again.","\u6D88\u606F\u63D0\u4EA4\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u7ECF\u5F00\u59CB\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /status \u67E5\u770B\u72B6\u6001\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"The message submission could not be confirmed and the task may have started. Wait or send /status before submitting it again.","\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4EFB\u52A1\u8FDB\u5EA6\uFF0C\u4EFB\u52A1\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Task progress is temporarily unavailable and the task may still be running. Wait or send /stop before submitting it again.","\u5904\u7406\u670D\u52A1\u62D2\u7EDD\u4E86\u673A\u5668\u4EBA\u8FDE\u63A5\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5 Harness \u5730\u5740\u3001\u4EE3\u7406\u6216\u8BBF\u95EE\u914D\u7F6E\u540E\u91CD\u8BD5\u3002":"The processing service rejected the bot connection. Ask an administrator to check the Harness address, proxy, or access settings.","\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u7684\u63A5\u53E3\u4E0D\u517C\u5BB9\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5 Harness \u5730\u5740\u5E76\u66F4\u65B0\u76F8\u5173\u7248\u672C\u3002":"The bot and DeepSeek Harness use incompatible APIs. Ask an administrator to check the Harness address and update the related components.","DeepSeek Harness \u6682\u65F6\u65E0\u6CD5\u5B8C\u6210\u8BF7\u6C42\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"DeepSeek Harness could not complete the request. Please try again later.","\u7B49\u5F85\u6A21\u578B\u56DE\u590D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Waiting for the model reply timed out and the task may still be running. Wait or send /stop before submitting it again.","\u6A21\u578B\u51ED\u636E\u7F3A\u5931\u6216\u5DF2\u5931\u6548\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5\u6A21\u578B\u914D\u7F6E\u540E\u91CD\u8BD5\u3002":"The model credentials are missing or invalid. Ask an administrator to check the model settings.","\u6A21\u578B\u989D\u5EA6\u6216\u4F59\u989D\u4E0D\u8DB3\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7BA1\u7406\u5458\u8865\u5145\u989D\u5EA6\u6216\u5207\u6362\u6A21\u578B\u540E\u91CD\u8BD5\u3002":"The model quota or balance is insufficient. Ask an administrator to add quota or switch models, then try again.","\u6A21\u578B\u670D\u52A1\u6B63\u5728\u9650\u6D41\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is rate-limiting requests. Please try again later.","\u5F53\u524D\u4F1A\u8BDD\u5185\u5BB9\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\u3002\u8BF7\u53D1\u9001 /compact \u6216 /new \u540E\u91CD\u8BD5\u3002":"This conversation exceeds the model context limit. Send /compact or /new, then try again.","\u5F53\u524D\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u53D1\u9001 /models \u67E5\u770B\u5E76\u4F7F\u7528 /model \u5207\u6362\u6A21\u578B\u3002":"The current model does not exist or is unavailable. Send /models and use /model to switch models.","\u5F53\u524D\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u4E0D\u652F\u6301\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u53D1\u9001 /models\uFF0C\u5E76\u4F7F\u7528 /model \u91CD\u65B0\u9009\u62E9\u3002":"The current model does not exist or does not support the selected settings. Send /models and use /model to choose again.","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u8FD9\u7C7B\u5185\u5BB9\u6216\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u8C03\u6574\u5185\u5BB9\u3001\u6A21\u578B\u6216\u63A8\u7406\u7B49\u7EA7\u540E\u91CD\u8BD5\u3002":"The current model does not support this content or the selected settings. Adjust the content, model, or reasoning effort and try again.","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u5207\u6362\u6A21\u578B\u6216\u63A8\u7406\u7B49\u7EA7\u540E\u91CD\u8BD5\u3002":"The current model does not support the selected settings. Switch the model or reasoning effort, then try again.","\u6A21\u578B\u670D\u52A1\u54CD\u5E94\u8D85\u65F6\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service timed out and the task did not finish. Please try again later.","\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u6A21\u578B\u670D\u52A1\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is temporarily unreachable and the task did not finish. Please try again later.","\u6A21\u578B\u670D\u52A1\u6682\u65F6\u5F02\u5E38\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is temporarily unavailable and the task did not finish. Please try again later.","\u6A21\u578B\u56DE\u590D\u4E2D\u65AD\u6216\u683C\u5F0F\u5F02\u5E38\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u91CD\u8BD5\u3002":"The model reply was interrupted or malformed, so the task did not finish. Please try again.","\u6A21\u578B\u6CA1\u6709\u8FD4\u56DE\u53EF\u663E\u793A\u7684\u5185\u5BB9\u3002\u8BF7\u91CD\u8BD5\uFF1B\u82E5\u6301\u7EED\u53D1\u751F\uFF0C\u8BF7\u5207\u6362\u6A21\u578B\u3002":"The model returned no displayable content. Try again, or switch models if this keeps happening.","\u6A21\u578B\u62D2\u7EDD\u5904\u7406\u5F53\u524D\u5185\u5BB9\u3002\u8BF7\u8C03\u6574\u95EE\u9898\u5185\u5BB9\u540E\u91CD\u8BD5\u3002":"The model rejected the current content. Revise the request and try again.","\u6A21\u578B\u8FBE\u5230\u8F93\u51FA\u957F\u5EA6\u4E0A\u9650\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u7ED3\u679C\u3002\u8BF7\u7F29\u5C0F\u4EFB\u52A1\u8303\u56F4\u540E\u91CD\u8BD5\u3002":"The model reached its output limit without producing a displayable result. Reduce the task scope and try again.","\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u65E0\u6CD5\u5728\u5F53\u524D\u6E20\u9053\u5B8C\u6210\u7684\u64CD\u4F5C\u3002\u8BF7\u5728 DeepSeek Harness \u4E2D\u5904\u7406\u540E\u518D\u8BD5\u3002":"The task is waiting for an action that cannot be completed in this channel. Handle it in DeepSeek Harness, then try again.","\u4EFB\u52A1\u88AB\u610F\u5916\u4E2D\u65AD\uFF0C\u672C\u6B21\u672A\u5B8C\u6210\u3002\u8BF7\u91CD\u8BD5\u3002":"The task was unexpectedly interrupted and did not finish. Please try again.","\u5F53\u524D\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\u3002\u8BF7\u53D1\u9001 /new \u521B\u5EFA\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002":"The current Session no longer exists. Send /new to create one, then try again.","\u5F53\u524D\u4F1A\u8BDD\u4ECD\u5728\u5904\u7406\u4E0A\u4E00\u9879\u4EFB\u52A1\u3002\u8BF7\u7B49\u5F85\u5B8C\u6210\uFF0C\u6216\u53D1\u9001 /stop \u540E\u91CD\u8BD5\u3002":"The current Session is still processing the previous task. Wait for it to finish, or send /stop before trying again.","\u5DE5\u4F5C\u533A\u6216\u4F1A\u8BDD\u72B6\u6001\u521A\u521A\u53D1\u751F\u53D8\u5316\u3002\u8BF7\u91CD\u65B0\u53D1\u9001\u8FD9\u6761\u6D88\u606F\u3002":"The Workspace or Session state just changed. Please send this message again.","\u5F53\u524D\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u91CD\u65B0\u9009\u62E9\u5DE5\u4F5C\u533A\u540E\u91CD\u8BD5\u3002":"The current Workspace does not exist or is unavailable. Select another Workspace and try again.","\u5F53\u524D Agent Preset \u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u53D1\u9001 /presetlist \u540E\u91CD\u65B0\u9009\u62E9\u3002":"The current Agent Preset does not exist or is unavailable. Send /presetlist and select another one.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u6CA1\u6709\u53D1\u9001\u6743\u9650\u3002\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u68C0\u67E5\u6E20\u9053\u6743\u9650\u6216\u91CD\u65B0\u7ED1\u5B9A\u673A\u5668\u4EBA\u3002":"The reply was generated, but the bot cannot send it. Ask an administrator to check channel permissions or reconnect the bot.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6B63\u5728\u9650\u6D41\uFF0C\u6682\u65F6\u65E0\u6CD5\u53D1\u9001\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The reply was generated, but this channel is rate-limiting messages. Please try again later.","\u56DE\u590D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\u3002\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u7ECF\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Reply delivery could not be confirmed. Check whether it already arrived before submitting the task again.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u65E0\u6CD5\u53D1\u9001\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The reply was generated, but this channel could not send it. Please try again later.","\u5F53\u524D\u6D88\u606F\u5305\u542B\u65E0\u6CD5\u5904\u7406\u7684\u56FE\u7247\u6216\u6587\u4EF6\u3002\u8BF7\u8C03\u6574\u540E\u91CD\u65B0\u53D1\u9001\u3002":"This message contains an image or file that cannot be processed. Adjust it and send it again.","\u4EFB\u52A1\u672A\u5B8C\u6210\uFF0C\u6682\u65F6\u65E0\u6CD5\u786E\u5B9A\u539F\u56E0\u3002\u8BF7\u91CD\u8BD5\uFF1B\u82E5\u6301\u7EED\u53D1\u751F\uFF0C\u8BF7\u5C06\u53C2\u8003\u53F7\u63D0\u4F9B\u7ED9\u7BA1\u7406\u5458\u3002":"The task did not finish and the cause could not be determined. Try again; if it persists, give the reference ID to an administrator.","\u9519\u8BEF\u7801\uFF1A{code}\uFF1B\u53C2\u8003\u53F7\uFF1A{referenceId}":"Error code: {code}; reference: {referenceId}","{label}\u673A\u5668\u4EBA":"{label} bot","\u76EE\u524D\u652F\u6301\u6587\u5B57\u548C\u56FE\u7247\u6D88\u606F\u3002":"Only text and image messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002":"Only text, image, and file messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002":"Only text, image, file, and voice-transcription messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\uFF0C\u4EE5\u53CA\u5FAE\u4FE1\u5DF2\u8F6C\u6210\u6587\u5B57\u7684\u8BED\u97F3\u6D88\u606F\u3002":"Only text, image, file, and voice messages already transcribed to text by WeChat are supported at the moment.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u6216\u56FE\u7247\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text or an image directly to continue the current session.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text, an image, or a file directly to continue the current session.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u6216\u5E26\u6587\u5B57\u8BC6\u522B\u7ED3\u679C\u7684\u8BED\u97F3\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text, an image, a file, or a voice message already transcribed to text to continue the current session.","{label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002":"The {label} bot is connected to DeepSeek Harness.","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD":"/new Start a brand-new session","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587":"/compact Compact the earlier context of the current session","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A":"/workspace Switch workspace","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84":"/workspacelist List absolute workspace paths","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898":"/sessionlist [workspace index or absolute path] List session IDs and titles","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898":"/sessionlist or /sessions [workspace index or absolute path] List session IDs and titles","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD":"/session Bind this chat to the specified session","/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B":"/models List all available models by index","/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7":"/reasoninglist or /reasonings List reasoning efforts for the current model by index","/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7":"/reasoning [index, effort ID, or --default] Show or switch the current reasoning effort","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B":"/model [index or full model ID] Show or switch the model of the current session","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B":"/model [index or full model ID] [reasoning effort ID] Show or switch the current Session model","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2":"Example: send /models first, then /model 2","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]":"Example: send /models first, then /model 2 [reasoning effort ID]","/presetlist \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset":"/presetlist List available Agent Presets by index","/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset":"/presetlist or /presets List available Agent Presets by index","/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset":"/preset [index or full ID] Show or set the Agent Preset of this bot","\u7EAF\u6570\u5B57 ID\uFF1A/preset id:":"Numeric-only ID: /preset id:","/preset --default \u8DDF\u968F Host \u9ED8\u8BA4":"/preset --default Follow the Host default","/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1":"/stop Stop the current task","/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1":"/steer Steer the current task","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001":"/status Check the connection status","/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C":"/version Show the plugin version","/help \u663E\u793A\u672C\u5E2E\u52A9":"/help Show this help","{label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002":"The {label} bot is connected to DeepSeek Harness and working normally.","{label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002":"{label} bot credentials are missing. Remove the bot and connect it again.","{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002":"The {label} connection is not ready yet. The plugin will retry automatically.","{label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002":"The {label} bot is connected, but its message connection is not ready yet.","{label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The {label} connection is still not ready. Please try again later.","{label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5":"The {label} bot is not connected yet","{name}\uFF08{id}\uFF09":"{name} ({id})","{label}{connectionLabel}\u8FD0\u884C\u6B63\u5E38":"The {label}{connectionLabel} is running normally","{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"The {label} connection is not ready. The plugin will retry automatically","{label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF":"The {label} connection is currently offline","\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002":"A new session has started. Please send your question.","\u6B63\u5728\u4F7F\u7528{name}\u2026":"Using {name}\u2026","\u5DF2\u505C\u6B62\u3002":"Stopped.","\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002":"Please answer the current question with text.","{label}\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002":"Failed to send the {label} interaction question.","\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002":"Failed to submit the answer.","\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002":"Failed to submit the answer. Please resend your answer to the current question.","\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002":"A pending question left over in this Session was detected. It has been safely cancelled, and your latest message is being processed."};var bK={"\u7528\u6CD5\uFF1A/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7\uFF08/session N\uFF09":"Usage: /session Session ID or the session index in the current Workspace (/session N)","\u7528\u6CD5\uFF1A\n/sessionlist \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u4F1A\u8BDD\n/sessionlist \u5DE5\u4F5C\u533A\u5E8F\u53F7 \u6309 /workspacelist \u5E8F\u53F7\u5217\u51FA\u4F1A\u8BDD\n/sessionlist \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5217\u51FA\u6307\u5B9A\u5DE5\u4F5C\u533A\u4F1A\u8BDD":`Usage: /sessionlist List Sessions in the current Workspace /sessionlist Workspace index List Sessions by /workspacelist index /sessionlist Workspace absolute path List Sessions in the given Workspace`,"\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002\n{usage}":`The Workspace must be an absolute path. @@ -222,7 +222,7 @@ ${n}`:n)}function RM(n,t,o){return{cardParamMap:{flowStatus:t,msgContent:bE(n,o) `):"").split(` `),i=!1;return o.map((e,a)=>{let A=/^\s{0,3}```/.test(e),r=i;return A&&(i=!i),a===o.length-1?e:r||A||i||!e||!o[a+1]?`${e} `:/^\s{0,3}(?:[-*+] |\d+[.)] |#{1,6} |\||> )/.test(o[a+1])?`${e} -`:`${e}
`}).join("")}function kM(n,t){if(!n||typeof n!="object"||n.errcode!==0)throw new gt("registration-rejected",`\u9489\u9489\u626B\u7801${t}\u5931\u8D25\u3002`);return n}function vM(n,t){let o=Number(n);return Number.isFinite(o)&&o>0?o:t}function dx({fetchImpl:n=fetch,registrationBaseUrl:t=process.env.DINGTALK_REGISTRATION_BASE_URL||nx,registrationSource:o=process.env.DINGTALK_REGISTRATION_SOURCE||Tle,now:i=()=>Date.now(),cardMinIntervalMs:e=50,cardBackoffMs:a=1e3,delay:A=Hle}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");if(typeof i!="function")throw new TypeError("now must be a function");if(!Number.isFinite(e)||e<0)throw new TypeError("cardMinIntervalMs must be a non-negative number");if(!Number.isFinite(a)||a<0)throw new TypeError("cardBackoffMs must be a non-negative number");if(typeof A!="function")throw new TypeError("delay must be a function");let r=PM(t,{label:"\u9489\u9489\u6CE8\u518C\u670D\u52A1",requireSubdomain:!1}),s=new URL(_le),g=ZA(o);if(!g)throw new TypeError("registrationSource is required");let c=new Map,I=new Map,d=new Map,B=Promise.resolve(),f=0,Q=(L,q)=>new URL(q.replace(/^\//,""),L);async function y({clientId:L,clientSecret:q,signal:z,requestKind:j="normal"}){let P=ZA(L),J=ZA(q);if(!P||!J)throw new TypeError("clientId and clientSecret are required");let U=c.get(P);if(U&&U.expiresAt>i())return U.token;let N=j==="reaction"?d:I;if(N.has(P))return N.get(P);let V=(async()=>{let Ae=await cn(n,Q(s,"v1.0/oauth2/accessToken"),{body:{appKey:P,appSecret:J},signal:z,action:"\u9274\u6743"}),ie=ZA(Ae?.accessToken);if(!ie)throw new gt("invalid-access-token","\u9489\u9489\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u8BBF\u95EE\u4EE4\u724C\u3002");let De=vM(Ae?.expireIn??Ae?.expiresIn,7200),fe=Math.max(1e3,(De-60)*1e3);return c.set(P,{token:ie,expiresAt:i()+fe}),ie})().finally(()=>N.delete(P));return N.set(P,V),V}async function m({clientId:L,clientSecret:q,robotCode:z,messageId:j,conversationId:P,reactionName:J=yI,signal:U},N){let k=ZA(L),V=ZA(q),Ae=ZA(z)??k,ie=ZA(j),De=ZA(P),fe=ZA(J);if(!k||!V)throw new TypeError("clientId and clientSecret are required");if(!Ae)throw new TypeError("robotCode is required");if(!ie||!De)throw new TypeError("messageId and conversationId are required");if(!fe)throw new TypeError("reactionName is required");let _e=await y({clientId:k,clientSecret:V,signal:U,requestKind:"reaction"}),Ee=await cn(n,Q(s,`v1.0/robot/emotion/${N}`),{body:{robotCode:Ae,openMsgId:ie,openConversationId:De,emotionType:2,emotionName:fe,textEmotion:{emotionId:vle,emotionName:fe,text:fe,backgroundId:Ple}},headers:{"x-acs-dingtalk-access-token":_e},signal:U,timeoutMs:kle,action:N==="reply"?"\u6D88\u606F\u72B6\u6001\u6DFB\u52A0":"\u6D88\u606F\u72B6\u6001\u64A4\u56DE"}),Qe=Ee?.success===!1?ME(Ee?.code??Ee?.errcode)??"rejected":nQ(Ee);if(Qe)throw new gt("reaction-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u6D88\u606F\u72B6\u6001\u8BF7\u6C42\u3002",{providerCode:Qe});return!0}async function _({clientId:L,clientSecret:q,robotCode:z,downloadCode:j,signal:P,kind:J}){let U=ZA(z),N=ZA(j);if(!U||!N)throw new TypeError("robotCode and downloadCode are required");let k=await y({clientId:L,clientSecret:q,signal:P}),V;try{V=await cn(n,Q(s,"v1.0/robot/messageFiles/download"),{body:{downloadCode:N,robotCode:U},headers:{"x-acs-dingtalk-access-token":k},signal:P,action:`${J==="image"?"\u56FE\u7247":"\u6587\u4EF6"}\u4E0B\u8F7D\u5730\u5740`})}catch(ie){throw P?.aborted?ie:new gt(`${J}-download-address-failed`,`\u9489\u9489${J==="image"?"\u56FE\u7247":"\u6587\u4EF6"}\u4E0B\u8F7D\u5730\u5740\u83B7\u53D6\u5931\u8D25\u3002`,{cause:ie,status:ie?.status,providerCode:ie?.providerCode})}let Ae=ZA(V?.downloadUrl??V?.download_url);if(!Ae)throw new gt(`invalid-${J}-download`,`\u9489\u9489\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE${J==="image"?"\u56FE\u7247":"\u6587\u4EF6"}\u4E0B\u8F7D\u5730\u5740\u3002`);return Ule(Ae)}function T(L){let q=async()=>{let j=Math.max(0,f-i());j>0&&await A(j,L),f=Math.max(f,i())+e},z=B.then(q,q);return B=z.catch(()=>{}),z}async function R(L,q){await T(q.signal);try{return await cn(n,Q(s,L),q)}catch(z){if(!(z instanceof gt)||z.status!==403)throw z;return await A(a,q.signal),await T(q.signal),cn(n,Q(s,L),q)}}async function F({clientId:L,clientSecret:q,cardInstanceId:z,text:j,target:P,signal:J}){let U=ZA(z),N=ZA(j);if(!U)throw new TypeError("cardInstanceId is required");if(!N)throw new TypeError("text is required");let V={"x-acs-dingtalk-access-token":await y({clientId:L,clientSecret:q,signal:J})},Ae=[R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:U,guid:DE(),key:"msgContent",content:bE(N,P),isFull:!0,isFinalize:!1,isError:!0},headers:V,signal:J,action:"AI Card \u5931\u8D25\u6536\u53E3"}),R("v1.0/card/instances",{method:"PUT",body:{outTrackId:U,cardData:RM(N,"5",P),cardUpdateOptions:{updateCardDataByKey:!0}},headers:V,signal:J,action:"AI Card \u5931\u8D25\u72B6\u6001"})],ie=await Promise.allSettled(Ae);if(ie.every(({status:De})=>De==="rejected"))throw ie[0].reason;return!0}async function K({clientId:L,clientSecret:q,target:z,file:j,signal:P},{uploadType:J,messageKey:U,createMessageParams:N}){if(!j||typeof j!="object"||typeof j.fileName!="string"||!j.fileName||!Buffer.isBuffer(j.bytes))throw new TypeError("A DingTalk file is required");let k=gx(z),V;try{V=await y({clientId:L,clientSecret:q,signal:P})}catch(aA){if(P?.aborted)throw jn(P);let He=Number(aA?.status),ce=aA?.code==="http-error"&&He>=400&&He<500?"artifact-provider-rejected":"artifact-provider-failed";throw OE(aA,{fallback:ce})}let Ae=new URL("media/upload",nx);Ae.searchParams.set("access_token",V),Ae.searchParams.set("type",J);let ie=new FormData;ie.append("media",new Blob([j.bytes],{type:j.mediaType??"application/octet-stream"}),j.fileName);let De;try{De=await Kle(n,Ae,{body:ie,signal:P})}catch(aA){if(P?.aborted)throw jn(P);let He=Number(aA?.status),ce=aA?.code==="http-error"&&He>=400&&He<500?"artifact-provider-rejected":"artifact-provider-failed";throw OE(aA,{fallback:ce})}let fe=nQ(De),_e=ZA(De?.media_id);if(fe||!_e)throw OE(new gt("upload-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u4E0A\u4F20\u3002",{providerCode:fe??"missing-media-id"}));P?.throwIfAborted();let Ee={robotCode:k.robotCode,msgKey:U,msgParam:JSON.stringify(N(_e,j)),...k.type==="group"?{openConversationId:k.openConversationId}:{userIds:[k.userId]}},Qe=k.type==="group"?"v1.0/robot/groupMessages/send":"v1.0/robot/oToMessages/batchSend",Le;try{Le=await cn(n,Q(s,Qe),{body:Ee,headers:{"x-acs-dingtalk-access-token":V},signal:P,action:"\u6587\u4EF6\u6D88\u606F\u53D1\u9001"})}catch(aA){throw Lle(aA,P)}let AA=nQ(Le);if(AA)throw OE(new gt("send-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u6D88\u606F\u3002",{providerCode:AA}));return Le}return Object.freeze({async beginRegistration({signal:L}={}){let q=kM(await cn(n,Q(r,"app/registration/init"),{body:{source:g},signal:L,action:"\u521D\u59CB\u5316"}),"\u521D\u59CB\u5316"),z=ZA(q.nonce);if(!z)throw new gt("invalid-registration","\u9489\u9489\u626B\u7801\u521D\u59CB\u5316\u7F3A\u5C11 nonce\u3002");let j=kM(await cn(n,Q(r,"app/registration/begin"),{body:{nonce:z},signal:L,action:"\u521B\u5EFA"}),"\u521B\u5EFA"),P=ZA(j.device_code),J=ZA(j.verification_uri_complete);if(!P||!J)throw new gt("invalid-registration","\u9489\u9489\u626B\u7801\u670D\u52A1\u8FD4\u56DE\u7684\u4FE1\u606F\u4E0D\u5B8C\u6574\u3002");let U=PM(J,{label:"\u9489\u9489\u626B\u7801",requireSubdomain:!1}).toString();return{deviceCode:P,userCode:ZA(j.user_code)??void 0,verificationUri:ZA(j.verification_uri)??void 0,verificationUriComplete:U,expiresInSeconds:vM(j.expires_in,7200),intervalSeconds:vM(j.interval,5)}},async pollRegistration({deviceCode:L,signal:q}={}){let z=ZA(L);if(!z)throw new TypeError("deviceCode is required");let j=kM(await cn(n,Q(r,"app/registration/poll"),{body:{device_code:z},signal:q,action:"\u72B6\u6001\u67E5\u8BE2"}),"\u72B6\u6001\u67E5\u8BE2"),P=ZA(j.status)?.toUpperCase();if(!P||!Gle.has(P))throw new gt("invalid-registration-status","\u9489\u9489\u626B\u7801\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u72B6\u6001\u3002");let J={status:P,failReason:ZA(j.fail_reason)??void 0};if(P==="SUCCESS"&&(J.clientId=ZA(j.client_id)??void 0,J.clientSecret=ZA(j.client_secret)??void 0,!J.clientId||!J.clientSecret))throw new gt("missing-credentials","\u9489\u9489\u626B\u7801\u5DF2\u786E\u8BA4\uFF0C\u4F46\u6CA1\u6709\u8FD4\u56DE\u673A\u5668\u4EBA\u51ED\u636E\u3002");return J},accessToken:y,async addReaction(L){return m(L,"reply")},async recallReaction(L){return m(L,"recall")},async addThinkingReaction(L){return m({...L,reactionName:yI},"reply")},async recallThinkingReaction(L){return m({...L,reactionName:yI},"recall")},async downloadImage({clientId:L,clientSecret:q,robotCode:z,downloadCode:j,signal:P,maxBytes:J}){let U=await _({clientId:L,clientSecret:q,robotCode:z,downloadCode:j,signal:P,kind:"image"});try{return await uo(U,{fetchImpl:n,signal:P,maxBytes:J})}catch(N){throw P?.aborted||N instanceof Bt?N:new gt("image-content-download-failed","\u9489\u9489\u56FE\u7247\u5185\u5BB9\u4E0B\u8F7D\u5931\u8D25\u3002",{cause:N})}},async downloadFile({clientId:L,clientSecret:q,robotCode:z,downloadCode:j,signal:P}){let J=await _({clientId:L,clientSecret:q,robotCode:z,downloadCode:j,signal:P,kind:"file"});if(J.protocol!=="https:")throw new gt("invalid-file-download","\u9489\u9489\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u6587\u4EF6\u4E0B\u8F7D\u5730\u5740\u3002");try{let U=await n(J,{method:"GET",redirect:"follow",signal:P});if(!U?.ok)throw await U?.body?.cancel?.().catch?.(()=>{}),new gt("file-content-download-failed",`\u9489\u9489\u6587\u4EF6\u5185\u5BB9\u4E0B\u8F7D\u5931\u8D25\uFF08HTTP ${U?.status??"unknown"}\uFF09\u3002`,{status:U?.status});return Buffer.from(await U.arrayBuffer())}catch(U){throw P?.aborted?jn(P):U instanceof gt?U:new gt("file-content-download-failed","\u9489\u9489\u6587\u4EF6\u5185\u5BB9\u4E0B\u8F7D\u5931\u8D25\u3002",{cause:U})}},async createAiCard({clientId:L,clientSecret:q,target:z,initialText:j,signal:P}){let J=ZA(L),U=ZA(q),N=ZA(j);if(!J||!U)throw new TypeError("clientId and clientSecret are required");if(!N)throw new TypeError("initialText is required");let k=Yle(z),V=await y({clientId:J,clientSecret:U,signal:P}),Ae=`dsh_${DE()}`,ie={"x-acs-dingtalk-access-token":V},De=!1;try{await R("v1.0/card/instances",{body:{cardTemplateId:Nle,outTrackId:Ae,cardData:{cardParamMap:{config:JSON.stringify({autoLayout:!0})}},callbackType:"STREAM",cardAtUserIds:k.atUserIds?Object.keys(k.atUserIds):void 0,imGroupOpenSpaceModel:{supportForward:!0},imRobotOpenSpaceModel:{supportForward:!0}},headers:ie,signal:P,action:"AI Card \u521B\u5EFA"}),await R("v1.0/card/instances/deliver",{body:jle(Ae,k,J),headers:ie,signal:P,action:"AI Card \u6295\u653E"}),De=!0,await R("v1.0/card/instances",{method:"PUT",body:{outTrackId:Ae,cardData:RM(N,"2",k)},headers:ie,signal:P,action:"AI Card \u542F\u52A8"}),await R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:Ae,guid:DE(),key:"msgContent",content:bE(N,k).replace(/\n+$/,""),isFull:!0,isFinalize:!1,isError:!1},headers:ie,signal:P,action:"AI Card \u542F\u52A8"})}catch(fe){if(De){let _e=AbortSignal.timeout(5e3);await F({clientId:J,clientSecret:U,cardInstanceId:Ae,text:w("\u5361\u7247\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u67E5\u770B\u540E\u7EED\u6D88\u606F\u3002"),target:k,signal:_e}).catch(()=>{})}throw fe}return{cardInstanceId:Ae}},async updateAiCard({clientId:L,clientSecret:q,cardInstanceId:z,text:j,target:P,signal:J}){let U=ZA(z),N=ZA(j);if(!U)throw new TypeError("cardInstanceId is required");if(!N)throw new TypeError("text is required");let k=await y({clientId:L,clientSecret:q,signal:J});return await R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:U,guid:DE(),key:"msgContent",content:bE(N,P).replace(/\n+$/,""),isFull:!0,isFinalize:!1,isError:!1},headers:{"x-acs-dingtalk-access-token":k},signal:J,action:"AI Card \u66F4\u65B0"}),!0},async finishAiCard({clientId:L,clientSecret:q,cardInstanceId:z,text:j,target:P,signal:J}){let U=ZA(z),N=ZA(j);if(!U)throw new TypeError("cardInstanceId is required");if(!N)throw new TypeError("text is required");let V={"x-acs-dingtalk-access-token":await y({clientId:L,clientSecret:q,signal:J})},Ae=bE(N,P);await R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:U,guid:DE(),key:"msgContent",content:Ae,isFull:!0,isFinalize:!0,isError:!1},headers:V,signal:J,action:"AI Card \u5B8C\u6210"});let ie=!0,De={method:"PUT",body:{outTrackId:U,cardData:RM(N,"3",P),cardUpdateOptions:{updateCardDataByKey:!0}},headers:V,signal:J,action:"AI Card \u6536\u53E3"};try{await R("v1.0/card/instances",De)}catch{try{await R("v1.0/card/instances",De)}catch{ie=!1}}return{delivered:!0,completed:ie}},failAiCard:F,async sendText({clientId:L,clientSecret:q,sessionWebhook:z,text:j,at:P,signal:J}){let U=ZA(j);if(!U)throw new TypeError("text is required");let N=tc(z),k=await y({clientId:L,clientSecret:q,signal:J}),V=P&&typeof P=="object"&&(Array.isArray(P.atUserIds)&&P.atUserIds.length>0||Array.isArray(P.atMobiles)&&P.atMobiles.length>0||P.isAtAll===!0)?{at:P}:{},Ae=await cn(n,N,{body:{msgtype:"text",text:{content:U},...V},headers:{"x-acs-dingtalk-access-token":k},signal:J,action:"\u6D88\u606F\u56DE\u590D"});if(Ae?.errcode!==void 0&&Ae.errcode!==0||Ae?.code!==void 0&&Ae.code!==0)throw new gt("send-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002");return!0},async sendRobotText({clientId:L,clientSecret:q,target:z,text:j,signal:P}){if(typeof j!="string"||!j.trim())throw new TypeError("text is required");let J=j,U=gx(z),N=await y({clientId:L,clientSecret:q,signal:P}),k={robotCode:U.robotCode,msgKey:"sampleText",msgParam:JSON.stringify({content:J}),...U.type==="group"?{openConversationId:U.openConversationId}:{userIds:[U.userId]}},V=U.type==="group"?"v1.0/robot/groupMessages/send":"v1.0/robot/oToMessages/batchSend",Ae=await cn(n,Q(s,V),{body:k,headers:{"x-acs-dingtalk-access-token":N},signal:P,action:"\u4E3B\u52A8\u6587\u5B57\u6D88\u606F\u53D1\u9001"}),ie=nQ(Ae);if(ie)throw new gt("send-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u4E3B\u52A8\u6587\u5B57\u6D88\u606F\u3002",{providerCode:ie});return Ae},async sendFile(L){return K(L,{uploadType:"file",messageKey:"sampleFile",createMessageParams:(q,z)=>({mediaId:q,fileName:z.fileName,fileType:xle(z.fileName)})})},async sendImage(L){return K(L,{uploadType:"image",messageKey:"sampleImageMsg",createMessageParams:q=>({photoURL:q})})},clearAccessToken(L){let q=ZA(L);q&&c.delete(q)}})}var qle=500,zle="\u5361\u7247\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u67E5\u770B\u540E\u7EED\u6D88\u606F\u3002";function GM(n,t){if(typeof n!="string")throw new TypeError(`${t} must be a string`);return n}function hx(n,t){if(typeof n!="string"||!n.trim())throw new TypeError(`${t} is required`);return n.trim()}function Ex({api:n,clientId:t,clientSecret:o,target:i,signal:e,logger:a=console,updateIntervalMs:A=qle,clock:r=()=>Date.now(),timer:s={setTimeout:(g,c)=>globalThis.setTimeout(g,c),clearTimeout:g=>globalThis.clearTimeout(g)}}={}){if(!n||typeof n.createAiCard!="function"||typeof n.updateAiCard!="function"||typeof n.finishAiCard!="function")throw new TypeError("DingTalk AI Card API is required");let g=hx(t,"clientId"),c=hx(o,"clientSecret");if(i==null)throw new TypeError("target is required");if(!Number.isFinite(A)||A<0)throw new TypeError("updateIntervalMs must be a non-negative number");if(typeof r!="function")throw new TypeError("clock must be a function");if(typeof s?.setTimeout!="function"||typeof s?.clearTimeout!="function")throw new TypeError("timer must provide setTimeout and clearTimeout");let I=()=>{let N=r();if(!Number.isFinite(N))throw new TypeError("clock must return a finite timestamp");return N};I();let d=e?.aborted?"aborted":"idle",B=null,f=null,Q=null,y=null,m=null,_=null,T=0,R=()=>{Q!==null&&(s.clearTimeout(Q),Q=null)},F=()=>e?.removeEventListener("abort",z),K=N=>{d=N,f=null,R(),F()},L=()=>!B||typeof n.failAiCard!="function"?Promise.resolve(!1):(_||(_=n.failAiCard({...B,text:w(zle),signal:AbortSignal.timeout(5e3)}).then(()=>!0,()=>!1)),_),q=N=>{d==="failed"||d==="finished"||d==="aborted"||(L(),K("failed"),a?.error?.(`[dsh-dingtalk] AI Card ${N} failed`))};function z(){d==="finished"||d==="failed"||d==="aborted"||(L(),K("aborted"))}d!=="aborted"&&e?.addEventListener("abort",z,{once:!0});let j=()=>{if(d!=="active"||y||f===null)return;let N=Math.max(0,T+A-I());if(N>0){Q=s.setTimeout(()=>{Q=null,j()},N);return}let k=f;f=null,y=(async()=>{try{await n.updateAiCard({...B,text:k,finished:!1}),T=I()}catch{if(e?.aborted||d==="aborted")return;q("update")}})().finally(()=>{y=null,d==="active"&&f!==null&&j()})};return Object.freeze({start:async N=>{if(GM(N,"initialText"),d!=="idle")return!1;d="starting";try{let k=await n.createAiCard({clientId:g,clientSecret:c,target:i,initialText:N,signal:e}),V=typeof k?.cardInstanceId=="string"?k.cardInstanceId.trim():"";if(!V)throw new TypeError("DingTalk did not return a card instance id");return B=Object.freeze({clientId:g,clientSecret:c,target:i,cardInstanceId:V,signal:e}),d!=="starting"?(L(),!1):(T=I(),d="active",!0)}catch{return e?.aborted||d==="aborted"?(K("aborted"),!1):(q("creation"),!1)}},push:N=>{GM(N,"progressText"),d==="active"&&(f=N,!Q&&!y&&j())},finish:N=>{if(GM(N,"finalText"),d==="finished")return Promise.resolve(!0);if(d==="finishing")return m;if(d!=="active")return Promise.resolve(!1);d="finishing",f=null,R();let k=y;return m=(async()=>{if(k&&await k,d!=="finishing")return!1;try{return await n.finishAiCard({...B,text:N}),d!=="finishing"?!1:(K("finished"),!0)}catch{return e?.aborted||d==="aborted"?(K("aborted"),!1):(q("finish"),!1)}})(),m}})}function sQ(n){return typeof n=="string"&&n.trim()?n.trim():null}function di(n){return n&&typeof n.id=="string"&&typeof n.question=="string"&&(n.header===void 0||typeof n.header=="string")&&(n.detail===void 0||typeof n.detail=="string")&&(n.multiSelect===void 0||typeof n.multiSelect=="boolean")&&(n.options===void 0||Array.isArray(n.options)&&n.options.every(t=>t&&typeof t.label=="string"&&(t.description===void 0||typeof t.description=="string")))}function hi(n,t,o,{requiresMention:i=!1}={}){let e=[],a=o>1?`\uFF08${t+1}/${o}\uFF09`:"";e.push(w("DeepSeek Harness \u9700\u8981\u4F60\u8865\u5145\u4FE1\u606F{progress}\uFF1A",{progress:a})),sQ(n.header)&&e.push("",n.header.trim()),e.push("",sQ(n.question)??w("\u8BF7\u8F93\u5165\u4F60\u7684\u56DE\u7B54\u3002")),sQ(n.detail)&&e.push("",n.detail.trim());let A=Array.isArray(n.options)?n.options:[];return A.length>0?(e.push(""),A.forEach((r,s)=>{let g=typeof r?.label=="string"?r.label:"",c=sQ(r?.description);e.push(`${s+1}. ${g}${c?` \u2014 ${c}`:""}`)}),e.push("",n.multiSelect===!0?w("\u8BF7\u56DE\u590D\u9009\u9879\u5E8F\u53F7\u6216\u6587\u5B57\uFF1B\u591A\u9009\u7528\u9017\u53F7\u5206\u9694\uFF0C\u4E5F\u53EF\u8865\u5145\u5176\u4ED6\u5185\u5BB9\u3002"):w("\u8BF7\u56DE\u590D\u4E00\u4E2A\u9009\u9879\u5E8F\u53F7\u6216\u6587\u5B57\uFF0C\u4E5F\u53EF\u76F4\u63A5\u8F93\u5165\u5176\u4ED6\u7B54\u6848\u3002"))):e.push("",w("\u8BF7\u76F4\u63A5\u56DE\u590D\u4F60\u7684\u7B54\u6848\u3002")),i&&e.push("",w("\u7FA4\u804A\u4E2D\u8BF7 @\u673A\u5668\u4EBA \u540E\u53D1\u9001\u7B54\u6848\u3002")),e.join(` +`:`${e}
`}).join("")}function kM(n,t){if(!n||typeof n!="object"||n.errcode!==0)throw new gt("registration-rejected",`\u9489\u9489\u626B\u7801${t}\u5931\u8D25\u3002`);return n}function vM(n,t){let o=Number(n);return Number.isFinite(o)&&o>0?o:t}function dx({fetchImpl:n=fetch,registrationBaseUrl:t=process.env.DINGTALK_REGISTRATION_BASE_URL||nx,registrationSource:o=process.env.DINGTALK_REGISTRATION_SOURCE||Tle,now:i=()=>Date.now(),cardMinIntervalMs:e=50,cardBackoffMs:a=1e3,delay:A=Hle}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");if(typeof i!="function")throw new TypeError("now must be a function");if(!Number.isFinite(e)||e<0)throw new TypeError("cardMinIntervalMs must be a non-negative number");if(!Number.isFinite(a)||a<0)throw new TypeError("cardBackoffMs must be a non-negative number");if(typeof A!="function")throw new TypeError("delay must be a function");let r=PM(t,{label:"\u9489\u9489\u6CE8\u518C\u670D\u52A1",requireSubdomain:!1}),s=new URL(_le),g=ZA(o);if(!g)throw new TypeError("registrationSource is required");let c=new Map,I=new Map,d=new Map,B=Promise.resolve(),f=0,Q=(F,q)=>new URL(q.replace(/^\//,""),F);async function y({clientId:F,clientSecret:q,signal:z,requestKind:j="normal"}){let P=ZA(F),J=ZA(q);if(!P||!J)throw new TypeError("clientId and clientSecret are required");let H=c.get(P);if(H&&H.expiresAt>i())return H.token;let N=j==="reaction"?d:I;if(N.has(P))return N.get(P);let V=(async()=>{let Ae=await cn(n,Q(s,"v1.0/oauth2/accessToken"),{body:{appKey:P,appSecret:J},signal:z,action:"\u9274\u6743"}),ie=ZA(Ae?.accessToken);if(!ie)throw new gt("invalid-access-token","\u9489\u9489\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u8BBF\u95EE\u4EE4\u724C\u3002");let De=vM(Ae?.expireIn??Ae?.expiresIn,7200),fe=Math.max(1e3,(De-60)*1e3);return c.set(P,{token:ie,expiresAt:i()+fe}),ie})().finally(()=>N.delete(P));return N.set(P,V),V}async function m({clientId:F,clientSecret:q,robotCode:z,messageId:j,conversationId:P,reactionName:J=yI,signal:H},N){let k=ZA(F),V=ZA(q),Ae=ZA(z)??k,ie=ZA(j),De=ZA(P),fe=ZA(J);if(!k||!V)throw new TypeError("clientId and clientSecret are required");if(!Ae)throw new TypeError("robotCode is required");if(!ie||!De)throw new TypeError("messageId and conversationId are required");if(!fe)throw new TypeError("reactionName is required");let _e=await y({clientId:k,clientSecret:V,signal:H,requestKind:"reaction"}),Ee=await cn(n,Q(s,`v1.0/robot/emotion/${N}`),{body:{robotCode:Ae,openMsgId:ie,openConversationId:De,emotionType:2,emotionName:fe,textEmotion:{emotionId:vle,emotionName:fe,text:fe,backgroundId:Ple}},headers:{"x-acs-dingtalk-access-token":_e},signal:H,timeoutMs:kle,action:N==="reply"?"\u6D88\u606F\u72B6\u6001\u6DFB\u52A0":"\u6D88\u606F\u72B6\u6001\u64A4\u56DE"}),Qe=Ee?.success===!1?ME(Ee?.code??Ee?.errcode)??"rejected":nQ(Ee);if(Qe)throw new gt("reaction-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u6D88\u606F\u72B6\u6001\u8BF7\u6C42\u3002",{providerCode:Qe});return!0}async function _({clientId:F,clientSecret:q,robotCode:z,downloadCode:j,signal:P,kind:J}){let H=ZA(z),N=ZA(j);if(!H||!N)throw new TypeError("robotCode and downloadCode are required");let k=await y({clientId:F,clientSecret:q,signal:P}),V;try{V=await cn(n,Q(s,"v1.0/robot/messageFiles/download"),{body:{downloadCode:N,robotCode:H},headers:{"x-acs-dingtalk-access-token":k},signal:P,action:`${J==="image"?"\u56FE\u7247":"\u6587\u4EF6"}\u4E0B\u8F7D\u5730\u5740`})}catch(ie){throw P?.aborted?ie:new gt(`${J}-download-address-failed`,`\u9489\u9489${J==="image"?"\u56FE\u7247":"\u6587\u4EF6"}\u4E0B\u8F7D\u5730\u5740\u83B7\u53D6\u5931\u8D25\u3002`,{cause:ie,status:ie?.status,providerCode:ie?.providerCode})}let Ae=ZA(V?.downloadUrl??V?.download_url);if(!Ae)throw new gt(`invalid-${J}-download`,`\u9489\u9489\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE${J==="image"?"\u56FE\u7247":"\u6587\u4EF6"}\u4E0B\u8F7D\u5730\u5740\u3002`);return Ule(Ae)}function T(F){let q=async()=>{let j=Math.max(0,f-i());j>0&&await A(j,F),f=Math.max(f,i())+e},z=B.then(q,q);return B=z.catch(()=>{}),z}async function R(F,q){await T(q.signal);try{return await cn(n,Q(s,F),q)}catch(z){if(!(z instanceof gt)||z.status!==403)throw z;return await A(a,q.signal),await T(q.signal),cn(n,Q(s,F),q)}}async function L({clientId:F,clientSecret:q,cardInstanceId:z,text:j,target:P,signal:J}){let H=ZA(z),N=ZA(j);if(!H)throw new TypeError("cardInstanceId is required");if(!N)throw new TypeError("text is required");let V={"x-acs-dingtalk-access-token":await y({clientId:F,clientSecret:q,signal:J})},Ae=[R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:H,guid:DE(),key:"msgContent",content:bE(N,P),isFull:!0,isFinalize:!1,isError:!0},headers:V,signal:J,action:"AI Card \u5931\u8D25\u6536\u53E3"}),R("v1.0/card/instances",{method:"PUT",body:{outTrackId:H,cardData:RM(N,"5",P),cardUpdateOptions:{updateCardDataByKey:!0}},headers:V,signal:J,action:"AI Card \u5931\u8D25\u72B6\u6001"})],ie=await Promise.allSettled(Ae);if(ie.every(({status:De})=>De==="rejected"))throw ie[0].reason;return!0}async function U({clientId:F,clientSecret:q,target:z,file:j,signal:P},{uploadType:J,messageKey:H,createMessageParams:N}){if(!j||typeof j!="object"||typeof j.fileName!="string"||!j.fileName||!Buffer.isBuffer(j.bytes))throw new TypeError("A DingTalk file is required");let k=gx(z),V;try{V=await y({clientId:F,clientSecret:q,signal:P})}catch(aA){if(P?.aborted)throw jn(P);let He=Number(aA?.status),ce=aA?.code==="http-error"&&He>=400&&He<500?"artifact-provider-rejected":"artifact-provider-failed";throw OE(aA,{fallback:ce})}let Ae=new URL("media/upload",nx);Ae.searchParams.set("access_token",V),Ae.searchParams.set("type",J);let ie=new FormData;ie.append("media",new Blob([j.bytes],{type:j.mediaType??"application/octet-stream"}),j.fileName);let De;try{De=await Kle(n,Ae,{body:ie,signal:P})}catch(aA){if(P?.aborted)throw jn(P);let He=Number(aA?.status),ce=aA?.code==="http-error"&&He>=400&&He<500?"artifact-provider-rejected":"artifact-provider-failed";throw OE(aA,{fallback:ce})}let fe=nQ(De),_e=ZA(De?.media_id);if(fe||!_e)throw OE(new gt("upload-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u4E0A\u4F20\u3002",{providerCode:fe??"missing-media-id"}));P?.throwIfAborted();let Ee={robotCode:k.robotCode,msgKey:H,msgParam:JSON.stringify(N(_e,j)),...k.type==="group"?{openConversationId:k.openConversationId}:{userIds:[k.userId]}},Qe=k.type==="group"?"v1.0/robot/groupMessages/send":"v1.0/robot/oToMessages/batchSend",Le;try{Le=await cn(n,Q(s,Qe),{body:Ee,headers:{"x-acs-dingtalk-access-token":V},signal:P,action:"\u6587\u4EF6\u6D88\u606F\u53D1\u9001"})}catch(aA){throw Lle(aA,P)}let AA=nQ(Le);if(AA)throw OE(new gt("send-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u6D88\u606F\u3002",{providerCode:AA}));return Le}return Object.freeze({async beginRegistration({signal:F}={}){let q=kM(await cn(n,Q(r,"app/registration/init"),{body:{source:g},signal:F,action:"\u521D\u59CB\u5316"}),"\u521D\u59CB\u5316"),z=ZA(q.nonce);if(!z)throw new gt("invalid-registration","\u9489\u9489\u626B\u7801\u521D\u59CB\u5316\u7F3A\u5C11 nonce\u3002");let j=kM(await cn(n,Q(r,"app/registration/begin"),{body:{nonce:z},signal:F,action:"\u521B\u5EFA"}),"\u521B\u5EFA"),P=ZA(j.device_code),J=ZA(j.verification_uri_complete);if(!P||!J)throw new gt("invalid-registration","\u9489\u9489\u626B\u7801\u670D\u52A1\u8FD4\u56DE\u7684\u4FE1\u606F\u4E0D\u5B8C\u6574\u3002");let H=PM(J,{label:"\u9489\u9489\u626B\u7801",requireSubdomain:!1}).toString();return{deviceCode:P,userCode:ZA(j.user_code)??void 0,verificationUri:ZA(j.verification_uri)??void 0,verificationUriComplete:H,expiresInSeconds:vM(j.expires_in,7200),intervalSeconds:vM(j.interval,5)}},async pollRegistration({deviceCode:F,signal:q}={}){let z=ZA(F);if(!z)throw new TypeError("deviceCode is required");let j=kM(await cn(n,Q(r,"app/registration/poll"),{body:{device_code:z},signal:q,action:"\u72B6\u6001\u67E5\u8BE2"}),"\u72B6\u6001\u67E5\u8BE2"),P=ZA(j.status)?.toUpperCase();if(!P||!Gle.has(P))throw new gt("invalid-registration-status","\u9489\u9489\u626B\u7801\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u72B6\u6001\u3002");let J={status:P,failReason:ZA(j.fail_reason)??void 0};if(P==="SUCCESS"&&(J.clientId=ZA(j.client_id)??void 0,J.clientSecret=ZA(j.client_secret)??void 0,!J.clientId||!J.clientSecret))throw new gt("missing-credentials","\u9489\u9489\u626B\u7801\u5DF2\u786E\u8BA4\uFF0C\u4F46\u6CA1\u6709\u8FD4\u56DE\u673A\u5668\u4EBA\u51ED\u636E\u3002");return J},accessToken:y,async addReaction(F){return m(F,"reply")},async recallReaction(F){return m(F,"recall")},async addThinkingReaction(F){return m({...F,reactionName:yI},"reply")},async recallThinkingReaction(F){return m({...F,reactionName:yI},"recall")},async downloadImage({clientId:F,clientSecret:q,robotCode:z,downloadCode:j,signal:P,maxBytes:J}){let H=await _({clientId:F,clientSecret:q,robotCode:z,downloadCode:j,signal:P,kind:"image"});try{return await uo(H,{fetchImpl:n,signal:P,maxBytes:J})}catch(N){throw P?.aborted||N instanceof Bt?N:new gt("image-content-download-failed","\u9489\u9489\u56FE\u7247\u5185\u5BB9\u4E0B\u8F7D\u5931\u8D25\u3002",{cause:N})}},async downloadFile({clientId:F,clientSecret:q,robotCode:z,downloadCode:j,signal:P}){let J=await _({clientId:F,clientSecret:q,robotCode:z,downloadCode:j,signal:P,kind:"file"});if(J.protocol!=="https:")throw new gt("invalid-file-download","\u9489\u9489\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u6587\u4EF6\u4E0B\u8F7D\u5730\u5740\u3002");try{let H=await n(J,{method:"GET",redirect:"follow",signal:P});if(!H?.ok)throw await H?.body?.cancel?.().catch?.(()=>{}),new gt("file-content-download-failed",`\u9489\u9489\u6587\u4EF6\u5185\u5BB9\u4E0B\u8F7D\u5931\u8D25\uFF08HTTP ${H?.status??"unknown"}\uFF09\u3002`,{status:H?.status});return Buffer.from(await H.arrayBuffer())}catch(H){throw P?.aborted?jn(P):H instanceof gt?H:new gt("file-content-download-failed","\u9489\u9489\u6587\u4EF6\u5185\u5BB9\u4E0B\u8F7D\u5931\u8D25\u3002",{cause:H})}},async createAiCard({clientId:F,clientSecret:q,target:z,initialText:j,signal:P}){let J=ZA(F),H=ZA(q),N=ZA(j);if(!J||!H)throw new TypeError("clientId and clientSecret are required");if(!N)throw new TypeError("initialText is required");let k=Yle(z),V=await y({clientId:J,clientSecret:H,signal:P}),Ae=`dsh_${DE()}`,ie={"x-acs-dingtalk-access-token":V},De=!1;try{await R("v1.0/card/instances",{body:{cardTemplateId:Nle,outTrackId:Ae,cardData:{cardParamMap:{config:JSON.stringify({autoLayout:!0})}},callbackType:"STREAM",cardAtUserIds:k.atUserIds?Object.keys(k.atUserIds):void 0,imGroupOpenSpaceModel:{supportForward:!0},imRobotOpenSpaceModel:{supportForward:!0}},headers:ie,signal:P,action:"AI Card \u521B\u5EFA"}),await R("v1.0/card/instances/deliver",{body:jle(Ae,k,J),headers:ie,signal:P,action:"AI Card \u6295\u653E"}),De=!0,await R("v1.0/card/instances",{method:"PUT",body:{outTrackId:Ae,cardData:RM(N,"2",k)},headers:ie,signal:P,action:"AI Card \u542F\u52A8"}),await R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:Ae,guid:DE(),key:"msgContent",content:bE(N,k).replace(/\n+$/,""),isFull:!0,isFinalize:!1,isError:!1},headers:ie,signal:P,action:"AI Card \u542F\u52A8"})}catch(fe){if(De){let _e=AbortSignal.timeout(5e3);await L({clientId:J,clientSecret:H,cardInstanceId:Ae,text:w("\u5361\u7247\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u67E5\u770B\u540E\u7EED\u6D88\u606F\u3002"),target:k,signal:_e}).catch(()=>{})}throw fe}return{cardInstanceId:Ae}},async updateAiCard({clientId:F,clientSecret:q,cardInstanceId:z,text:j,target:P,signal:J}){let H=ZA(z),N=ZA(j);if(!H)throw new TypeError("cardInstanceId is required");if(!N)throw new TypeError("text is required");let k=await y({clientId:F,clientSecret:q,signal:J});return await R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:H,guid:DE(),key:"msgContent",content:bE(N,P).replace(/\n+$/,""),isFull:!0,isFinalize:!1,isError:!1},headers:{"x-acs-dingtalk-access-token":k},signal:J,action:"AI Card \u66F4\u65B0"}),!0},async finishAiCard({clientId:F,clientSecret:q,cardInstanceId:z,text:j,target:P,signal:J}){let H=ZA(z),N=ZA(j);if(!H)throw new TypeError("cardInstanceId is required");if(!N)throw new TypeError("text is required");let V={"x-acs-dingtalk-access-token":await y({clientId:F,clientSecret:q,signal:J})},Ae=bE(N,P);await R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:H,guid:DE(),key:"msgContent",content:Ae,isFull:!0,isFinalize:!0,isError:!1},headers:V,signal:J,action:"AI Card \u5B8C\u6210"});let ie=!0,De={method:"PUT",body:{outTrackId:H,cardData:RM(N,"3",P),cardUpdateOptions:{updateCardDataByKey:!0}},headers:V,signal:J,action:"AI Card \u6536\u53E3"};try{await R("v1.0/card/instances",De)}catch{try{await R("v1.0/card/instances",De)}catch{ie=!1}}return{delivered:!0,completed:ie}},failAiCard:L,async sendText({clientId:F,clientSecret:q,sessionWebhook:z,text:j,at:P,signal:J}){let H=ZA(j);if(!H)throw new TypeError("text is required");let N=tc(z),k=await y({clientId:F,clientSecret:q,signal:J}),V=P&&typeof P=="object"&&(Array.isArray(P.atUserIds)&&P.atUserIds.length>0||Array.isArray(P.atMobiles)&&P.atMobiles.length>0||P.isAtAll===!0)?{at:P}:{},Ae=await cn(n,N,{body:{msgtype:"text",text:{content:H},...V},headers:{"x-acs-dingtalk-access-token":k},signal:J,action:"\u6D88\u606F\u56DE\u590D"});if(Ae?.errcode!==void 0&&Ae.errcode!==0||Ae?.code!==void 0&&Ae.code!==0)throw new gt("send-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002");return!0},async sendRobotText({clientId:F,clientSecret:q,target:z,text:j,signal:P}){if(typeof j!="string"||!j.trim())throw new TypeError("text is required");let J=j,H=gx(z),N=await y({clientId:F,clientSecret:q,signal:P}),k={robotCode:H.robotCode,msgKey:"sampleText",msgParam:JSON.stringify({content:J}),...H.type==="group"?{openConversationId:H.openConversationId}:{userIds:[H.userId]}},V=H.type==="group"?"v1.0/robot/groupMessages/send":"v1.0/robot/oToMessages/batchSend",Ae=await cn(n,Q(s,V),{body:k,headers:{"x-acs-dingtalk-access-token":N},signal:P,action:"\u4E3B\u52A8\u6587\u5B57\u6D88\u606F\u53D1\u9001"}),ie=nQ(Ae);if(ie)throw new gt("send-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u4E3B\u52A8\u6587\u5B57\u6D88\u606F\u3002",{providerCode:ie});return Ae},async sendFile(F){return U(F,{uploadType:"file",messageKey:"sampleFile",createMessageParams:(q,z)=>({mediaId:q,fileName:z.fileName,fileType:xle(z.fileName)})})},async sendImage(F){return U(F,{uploadType:"image",messageKey:"sampleImageMsg",createMessageParams:q=>({photoURL:q})})},clearAccessToken(F){let q=ZA(F);q&&c.delete(q)}})}var qle=500,zle="\u5361\u7247\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u67E5\u770B\u540E\u7EED\u6D88\u606F\u3002";function GM(n,t){if(typeof n!="string")throw new TypeError(`${t} must be a string`);return n}function hx(n,t){if(typeof n!="string"||!n.trim())throw new TypeError(`${t} is required`);return n.trim()}function Ex({api:n,clientId:t,clientSecret:o,target:i,signal:e,logger:a=console,updateIntervalMs:A=qle,clock:r=()=>Date.now(),timer:s={setTimeout:(g,c)=>globalThis.setTimeout(g,c),clearTimeout:g=>globalThis.clearTimeout(g)}}={}){if(!n||typeof n.createAiCard!="function"||typeof n.updateAiCard!="function"||typeof n.finishAiCard!="function")throw new TypeError("DingTalk AI Card API is required");let g=hx(t,"clientId"),c=hx(o,"clientSecret");if(i==null)throw new TypeError("target is required");if(!Number.isFinite(A)||A<0)throw new TypeError("updateIntervalMs must be a non-negative number");if(typeof r!="function")throw new TypeError("clock must be a function");if(typeof s?.setTimeout!="function"||typeof s?.clearTimeout!="function")throw new TypeError("timer must provide setTimeout and clearTimeout");let I=()=>{let N=r();if(!Number.isFinite(N))throw new TypeError("clock must return a finite timestamp");return N};I();let d=e?.aborted?"aborted":"idle",B=null,f=null,Q=null,y=null,m=null,_=null,T=0,R=()=>{Q!==null&&(s.clearTimeout(Q),Q=null)},L=()=>e?.removeEventListener("abort",z),U=N=>{d=N,f=null,R(),L()},F=()=>!B||typeof n.failAiCard!="function"?Promise.resolve(!1):(_||(_=n.failAiCard({...B,text:w(zle),signal:AbortSignal.timeout(5e3)}).then(()=>!0,()=>!1)),_),q=N=>{d==="failed"||d==="finished"||d==="aborted"||(F(),U("failed"),a?.error?.(`[dsh-dingtalk] AI Card ${N} failed`))};function z(){d==="finished"||d==="failed"||d==="aborted"||(F(),U("aborted"))}d!=="aborted"&&e?.addEventListener("abort",z,{once:!0});let j=()=>{if(d!=="active"||y||f===null)return;let N=Math.max(0,T+A-I());if(N>0){Q=s.setTimeout(()=>{Q=null,j()},N);return}let k=f;f=null,y=(async()=>{try{await n.updateAiCard({...B,text:k,finished:!1}),T=I()}catch{if(e?.aborted||d==="aborted")return;q("update")}})().finally(()=>{y=null,d==="active"&&f!==null&&j()})};return Object.freeze({start:async N=>{if(GM(N,"initialText"),d!=="idle")return!1;d="starting";try{let k=await n.createAiCard({clientId:g,clientSecret:c,target:i,initialText:N,signal:e}),V=typeof k?.cardInstanceId=="string"?k.cardInstanceId.trim():"";if(!V)throw new TypeError("DingTalk did not return a card instance id");return B=Object.freeze({clientId:g,clientSecret:c,target:i,cardInstanceId:V,signal:e}),d!=="starting"?(F(),!1):(T=I(),d="active",!0)}catch{return e?.aborted||d==="aborted"?(U("aborted"),!1):(q("creation"),!1)}},push:N=>{GM(N,"progressText"),d==="active"&&(f=N,!Q&&!y&&j())},finish:N=>{if(GM(N,"finalText"),d==="finished")return Promise.resolve(!0);if(d==="finishing")return m;if(d!=="active")return Promise.resolve(!1);d="finishing",f=null,R();let k=y;return m=(async()=>{if(k&&await k,d!=="finishing")return!1;try{return await n.finishAiCard({...B,text:N}),d!=="finishing"?!1:(U("finished"),!0)}catch{return e?.aborted||d==="aborted"?(U("aborted"),!1):(q("finish"),!1)}})(),m}})}function sQ(n){return typeof n=="string"&&n.trim()?n.trim():null}function di(n){return n&&typeof n.id=="string"&&typeof n.question=="string"&&(n.header===void 0||typeof n.header=="string")&&(n.detail===void 0||typeof n.detail=="string")&&(n.multiSelect===void 0||typeof n.multiSelect=="boolean")&&(n.options===void 0||Array.isArray(n.options)&&n.options.every(t=>t&&typeof t.label=="string"&&(t.description===void 0||typeof t.description=="string")))}function hi(n,t,o,{requiresMention:i=!1}={}){let e=[],a=o>1?`\uFF08${t+1}/${o}\uFF09`:"";e.push(w("DeepSeek Harness \u9700\u8981\u4F60\u8865\u5145\u4FE1\u606F{progress}\uFF1A",{progress:a})),sQ(n.header)&&e.push("",n.header.trim()),e.push("",sQ(n.question)??w("\u8BF7\u8F93\u5165\u4F60\u7684\u56DE\u7B54\u3002")),sQ(n.detail)&&e.push("",n.detail.trim());let A=Array.isArray(n.options)?n.options:[];return A.length>0?(e.push(""),A.forEach((r,s)=>{let g=typeof r?.label=="string"?r.label:"",c=sQ(r?.description);e.push(`${s+1}. ${g}${c?` \u2014 ${c}`:""}`)}),e.push("",n.multiSelect===!0?w("\u8BF7\u56DE\u590D\u9009\u9879\u5E8F\u53F7\u6216\u6587\u5B57\uFF1B\u591A\u9009\u7528\u9017\u53F7\u5206\u9694\uFF0C\u4E5F\u53EF\u8865\u5145\u5176\u4ED6\u5185\u5BB9\u3002"):w("\u8BF7\u56DE\u590D\u4E00\u4E2A\u9009\u9879\u5E8F\u53F7\u6216\u6587\u5B57\uFF0C\u4E5F\u53EF\u76F4\u63A5\u8F93\u5165\u5176\u4ED6\u7B54\u6848\u3002"))):e.push("",w("\u8BF7\u76F4\u63A5\u56DE\u590D\u4F60\u7684\u7B54\u6848\u3002")),i&&e.push("",w("\u7FA4\u804A\u4E2D\u8BF7 @\u673A\u5668\u4EBA \u540E\u53D1\u9001\u7B54\u6848\u3002")),e.join(` `)}function Cx(n,t){let o=n.trim();if(!o)return null;if(/^\d+$/.test(o)){let e=t[Number(o)-1];return typeof e?.label=="string"?e.label:null}let i=t.find(e=>e?.label===o);return typeof i?.label=="string"?i.label:null}function Ei(n,t){let o=Array.isArray(n.options)?n.options:[];if(o.length===0)return{id:n.id,selected:[],custom:t};let i=Cx(t,o);if(n.multiSelect!==!0)return i?{id:n.id,selected:[i]}:{id:n.id,selected:[],custom:t};if(i)return{id:n.id,selected:[i]};let e=[],a=[];for(let A of t.split(/[,,、;;\n]+/)){let r=A.trim();if(!r)continue;let s=Cx(r,o);s?e.includes(s)||e.push(s):a.push(r)}return{id:n.id,selected:e,...a.length>0?{custom:a.join("\u3001")}:{}}}var Vle=new Map([["\u6279\u51C6","allowed-once"],["\u540C\u610F","allowed-once"],["yes","allowed-once"],["\u62D2\u7EDD","rejected"],["\u4E0D\u540C\u610F","rejected"],["no","rejected"]]),FM="\u8BF7\u7CBE\u51C6\u56DE\u590D\u300C\u6279\u51C6\u300D\u6216\u300C\u62D2\u7EDD\u300D\uFF08\u4E5F\u652F\u6301\uFF1A\u540C\u610F / \u4E0D\u540C\u610F / yes / no\uFF09\u3002",Wle="\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u95EE\u9898\uFF0C\u518D\u7CBE\u51C6\u56DE\u590D\u300C\u6279\u51C6\u300D\u6216\u300C\u62D2\u7EDD\u300D\u3002",Cp="\u8BE5\u5BA1\u6279\u5DF2\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u590D\u3002",Zle=5*6e4,Xle=2048;function Ta(n){return typeof n=="string"?n.trim():""}function LM(n){return Ta(n).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"")}function $le(n){return Vle.get(Ta(n).toLowerCase())??null}function Bx(n){return n?.type==="approval/requested"&&!!Ta(n.sessionId)&&!!Ta(n.approvalId)&&!!Ta(n.toolName)&&(n.callId===void 0||!!Ta(n.callId))&&(n.reason===void 0||typeof n.reason=="string")}function epe(n){let t=n?.arguments;if(t!==null&&typeof t=="object")try{return JSON.stringify(t,null,2)}catch{return null}if(typeof t!="string")return null;let o=LM(t);if(!o)return t===""?"{}":null;try{return JSON.stringify(JSON.parse(o),null,2)}catch{return o}}function UM(n,{toolCall:t,requiresMention:o=!1,maxArgumentsLength:i=6e3}={}){if(!Bx(n))return null;let e=Ta(n.callId);if(!e||Ta(t?.callId)!==e||Ta(t?.name)!==Ta(n.toolName))return null;let a=epe(t);if(!a||a.length>i)return null;let A=[w("DeepSeek Harness \u9700\u8981\u4F60\u7684\u5BA1\u6279\uFF1A"),"",w("\u5DE5\u5177\uFF1A{tool}",{tool:LM(n.toolName)}),w("\u64CD\u4F5C\u53C2\u6570\uFF1A"),a],r=LM(n.reason);return r&&A.push(w("\u539F\u56E0\uFF1A{reason}",{reason:r})),A.push("",w(FM)),o&&A.push("",w("\u7FA4\u804A\u4E2D\u8BF7 @\u673A\u5668\u4EBA \u540E\u53D1\u9001\u5BA1\u6279\u51B3\u5B9A\u3002")),A.join(` `)}function ux(n,t){return{ok:!0,value:{sessionId:n.sessionId,approvalId:n.approvalId,outcome:t}}}function gQ(n){return n==="allowed-once"?w("\u5DF2\u6279\u51C6\uFF0C\u4EC5\u5BF9\u672C\u6B21\u64CD\u4F5C\u6709\u6548\u3002"):n==="rejected"?w("\u5DF2\u62D2\u7EDD\u6B64\u6B21\u64CD\u4F5C\u3002"):w(Cp)}var Ci=class{#e;#A;#t=new Map;#r=new Map;#g=new Map;constructor({label:t="IM",logger:o=console}={}){this.#e=t,this.#A=o}hasPending(t){return this.#r.get(t)?.items.some(o=>!o.inactive)===!0}claimReply({key:t,actor:o,text:i,addressed:e=!0,hasPendingQuestion:a=!1,questionCompletion:A,isQuestionPending:r,send:s}){let c=this.#r.get(t)?.items[0],I=$le(i),d=(f,Q=!1)=>({...Q?{resolved:!0}:{},process:async y=>{typeof y=="function"&&await y()===!1||await s(f)}}),B=a&&c&&A&&typeof A.then=="function";return a&&!B?null:!c||c.inactive?(this.#g.get(t)??0)<=Date.now()?(this.#g.delete(t),null):I?d(w(Cp),!0):null:c.actor!==o||c.requiresMention&&e!==!0?I?d(w("\u53EA\u6709\u53D1\u8D77\u5F53\u524D\u4EFB\u52A1\u7684\u7528\u6237\u53EF\u4EE5\u5904\u7406\u8FD9\u6761\u5BA1\u6279\u3002")):null:{process:async f=>{let Q=c.presented,m=(c.replyTail??Promise.resolve()).catch(()=>{}).then(async()=>{if(!(typeof f=="function"&&await f()===!1)){if(B){if(await A.catch(()=>{}),c.inactive||c.resolving)return;if(typeof r=="function"&&r()){await s(w(Wle));return}}if(await c.activationTask?.catch(()=>{}),await c.presentationTask?.catch(()=>{}),c.inactive||c.resolving){await s(w(Cp));return}if(c.send=s,!Q||!c.presented){if(c.presented||await this.#a(c),c.inactive||c.resolving)return;await s(w(FM));return}if(c.submitting){await s(w("\u5BA1\u6279\u51B3\u5B9A\u6B63\u5728\u63D0\u4EA4\uFF0C\u8BF7\u7A0D\u5019\u3002"));return}if(!I){await s(w(FM));return}await this.#n(c,I)}});c.replyTail=m;try{await m}finally{c.replyTail===m&&(c.replyTail=null)}}}}async handleRequested(t,o){if(t?.kind!=="approval")return!1;let i=t.payload,e=Ta(i?.approvalId);if(!Ta(t.rpcId)||!Ta(t.sessionId)||!e||!Bx(i)||i.sessionId!==t.sessionId||typeof t.respond!="function")return this.#A.warn?.(`[dsh-im:${this.#e}] ignored an invalid Harness approval`),!0;if(t.recovered===!0)return await this.#s(t,i),!0;let a=this.#t.get(e);if(a)return a.interaction=t,a.toolCall=t.toolCall,a.presented||await this.#a(a),!0;let A=o?.send,r=Ta(o?.key),s=Ta(o?.actor);if(!r||!s||typeof A!="function")return this.#A.warn?.(`[dsh-im:${this.#e}] ignored an approval without a reply route`),await this.#s(t,i),!0;let g=UM(i,{toolCall:t.toolCall,requiresMention:o.requiresMention===!0});if(!g){let d=await this.#s(t,i);return await A(d?w("\u65E0\u6CD5\u5B8C\u6574\u5C55\u793A\u8FD9\u6B21\u64CD\u4F5C\uFF0C\u5DF2\u5B89\u5168\u62D2\u7EDD\u6B64\u6B21\u5BA1\u6279\u3002"):w(Cp)),!0}let c={approvalId:e,sessionId:t.sessionId,interaction:t,toolCall:t.toolCall,key:r,actor:s,requiresMention:o.requiresMention===!0,send:A,text:g,presented:!1,presentationTask:null,deliveryCompleted:!1,replyTail:null,submitting:!1,inactive:!1,resolving:!1,closedOutcome:null,resolutionNotified:!1,activationTask:null};this.#t.set(e,c);let I=this.#r.get(r)??{items:[]};return I.items.push(c),this.#r.set(r,I),I.items[0]===c&&await this.#a(c),!0}async handleResolved(t){if(t?.kind!=="approval")return!1;let o=this.#t.get(Ta(t.interactionId));if(!o||(o.resolving=!0,o.activationTask&&await o.activationTask.catch(()=>{}),o.inactive||this.#t.get(o.approvalId)!==o))return!0;let i=o.presentationTask,e=o.presented||i,a=o.send,A=this.#l(o);return await this.#i(A,async()=>{let r=o.presented;i&&(r=await i.then(()=>!0,()=>!1)),e&&r&&(o.resolutionNotified=!0,await a(gQ(t.outcome)).catch(()=>{}))}),!0}async closeRoute(t){let o=this.#r.get(t);if(!o)return;let i=[...o.items];for(let e of i)this.#l(e);await Promise.all(i.map(async e=>{try{await e.interaction.respond(ux(e,"rejected"),{signal:AbortSignal.timeout(5e3)}),e.closedOutcome="rejected",(e.presented||e.deliveryCompleted)&&!e.resolutionNotified&&(e.resolutionNotified=!0,await e.send(gQ("rejected")).catch(()=>{}))}catch(a){a?.code==="interaction-not-pending"?(e.closedOutcome="resolved",(e.presented||e.deliveryCompleted)&&!e.resolutionNotified&&(e.resolutionNotified=!0,await e.send(w(Cp)).catch(()=>{}))):this.#A.warn?.(`[dsh-im:${this.#e}] failed to reject a closing approval:`,a)}}))}async#a(t){if(this.#r.get(t.key)?.items[0]!==t||t.inactive||t.resolving||t.presented||(await t.activationTask?.catch(()=>{}),this.#r.get(t.key)?.items[0]!==t||t.inactive||t.resolving||t.presented))return;if(t.presentationTask)return t.presentationTask;let o=Promise.resolve().then(()=>t.send(t.text));t.presentationTask=o;try{await o,t.deliveryCompleted=!0,t.inactive?t.closedOutcome&&!t.resolutionNotified&&(t.resolutionNotified=!0,await t.send(gQ(t.closedOutcome)).catch(()=>{})):t.presented=!0}finally{t.presentationTask===o&&(t.presentationTask=null)}}async#n(t,o){t.submitting=!0;try{await t.interaction.respond(ux(t,o))}catch(a){if(a?.code==="interaction-not-pending"){let A=t.send,r=this.#l(t);await this.#i(r,async()=>{t.resolutionNotified||await A(w(Cp)).catch(()=>{})});return}if(t.inactive)return;t.submitting=!1,this.#A.error?.(`[dsh-im:${this.#e}] failed to submit an approval:`,a),await t.send(w("\u5BA1\u6279\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u56DE\u590D\u300C\u6279\u51C6\u300D\u6216\u300C\u62D2\u7EDD\u300D\u3002")).catch(()=>{});return}let i=t.send,e=this.#l(t);await this.#i(e,async()=>{t.resolutionNotified||await i(gQ(o)).catch(()=>{})})}async#i(t,o){let i,e=new Promise(a=>{i=a});t&&(t.activationTask=e);try{await o()}finally{i(),t?.activationTask===e&&(t.activationTask=null)}await this.#I(t)}async#I(t){if(t)try{await this.#a(t)}catch(o){this.#A.error?.(`[dsh-im:${this.#e}] failed to present the next approval:`,o);try{t.interaction.reconnect?.()}catch{}}}#l(t){if(t.inactive)return null;t.inactive=!0,this.#o(t.key),this.#t.delete(t.approvalId);let o=this.#r.get(t.key);if(!o)return null;let i=o.items[0]===t,e=o.items.indexOf(t);return e!==-1&&o.items.splice(e,1),o.items.length===0?(this.#r.delete(t.key),null):i?o.items[0]:null}#o(t){let o=Date.now();for(let[i,e]of this.#g)e<=o&&this.#g.delete(i);for(this.#g.delete(t),this.#g.set(t,o+Zle);this.#g.size>Xle;)this.#g.delete(this.#g.keys().next().value)}async#s(t,o){try{return await t.respond({ok:!0,value:{sessionId:t.sessionId,approvalId:o.approvalId,outcome:"rejected"}},{signal:AbortSignal.timeout(5e3)}),!0}catch(i){if(i?.code==="interaction-not-pending")return!1;throw i}}};var HM=new WeakMap;function Ape(n){let t=HM.get(n);return t||(t=new Map,HM.set(n,t)),t}async function Zs(n,t,o){let i=typeof n;if(i!=="object"&&i!=="function"||n===null)throw new TypeError("state is required");if(typeof t!="string"||!t)throw new TypeError("conversation key is required");if(typeof o!="function")throw new TypeError("operation is required");let e=Ape(n),a=e.get(t)??Promise.resolve(),A,r=new Promise(s=>{A=s});e.set(t,r),await a;try{return await o()}finally{A(),e.get(t)===r&&(e.delete(t),e.size===0&&HM.delete(n))}}var Na="workspace-session-stale";function fx(n,t){return typeof n.workspaceSession=="function"?n.workspaceSession(t):Object.freeze({sessionId:t,sessionExists:(...o)=>n.sessionExists(t,...o),models:(...o)=>n.getSessionModels(t,...o),selectModel:(...o)=>n.selectSessionModel(t,...o),isRunning:(...o)=>n.isSessionRunning(t,...o),hasActiveTurn:(...o)=>n.hasActiveTurn(t,...o),stopActiveTurn:(...o)=>n.stopActiveTurn(t,...o),steerActiveTurn:(...o)=>n.steerActiveTurn(t,...o),ask:(...o)=>n.ask(t,...o)})}async function tpe(n,t){return t===void 0?n.sessionExists():n.sessionExists(t)}async function rpe(n,t){return t===void 0?n.createSession():n.createSession(t)}async function ui({harness:n,state:t,key:o,text:i,content:e,createOptions:a,existsOptions:A,askOptions:r}){for(;;)try{let s=await Zs(t,o,async()=>{let B=t.sessionFor(o),f=B?fx(n,B):null;if(!f||!await tpe(f,A)){if(B=await rpe(n,a),await t.setSession(o,B)===!1)return null;f=fx(n,B)}return{sessionId:B,session:f}});if(!s)continue;let g=[],c=typeof r=="object"&&typeof r?.onArtifact=="function"?r.onArtifact:null,I=typeof r=="number"?{timeoutMs:r}:{...r};I.onArtifact=async B=>{g.push(B),await c?.(B)};let d=await s.session.ask(e??i,I);return{sessionId:s.sessionId,answer:d,...g.length>0?{artifacts:g}:{}}}catch(s){if(s?.code!==Na)throw s}}var ape=/^\/compact(?=$|\s)([\s\S]*)$/i,ipe="\u7528\u6CD5\uFF1A/compact\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",Qx=new Map([["No compactable history yet.","\u6682\u65E0\u53EF\u538B\u7F29\u7684\u5386\u53F2\u8BB0\u5F55\u3002"],["Compaction is unavailable because this process has an active compaction, or the agent is not idle.","\u5F53\u524D\u4F1A\u8BDD\u6B63\u5728\u751F\u6210\u56DE\u590D\u6216\u6267\u884C\u538B\u7F29\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"],["Compaction cancelled.","\u4E0A\u4E0B\u6587\u538B\u7F29\u5DF2\u53D6\u6D88\u3002"],["The history selected for compaction changed before it could be replaced. The conversation is unchanged; the attempt is recorded in the session log.","\u538B\u7F29\u671F\u95F4\u4F1A\u8BDD\u5386\u53F2\u53D1\u751F\u53D8\u5316\uFF0C\u672C\u6B21\u672A\u4FEE\u6539\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u8BD5\u3002"],["Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log.","\u672A\u80FD\u751F\u6210\u6709\u6548\u7684\u538B\u7F29\u6458\u8981\uFF0C\u672C\u6B21\u672A\u4FEE\u6539\u4F1A\u8BDD\u3002"],["Compaction did not finish cleanly; some session history may have changed. Inspect the current session state before retrying.","\u4E0A\u4E0B\u6587\u538B\u7F29\u672A\u6B63\u5E38\u5B8C\u6210\uFF0C\u90E8\u5206\u4F1A\u8BDD\u5386\u53F2\u53EF\u80FD\u5DF2\u53D8\u5316\uFF0C\u8BF7\u68C0\u67E5\u4F1A\u8BDD\u540E\u518D\u91CD\u8BD5\u3002"],["Compaction finished, but the session could not be saved.","\u4E0A\u4E0B\u6587\u5DF2\u538B\u7F29\uFF0C\u4F46\u4F1A\u8BDD\u4FDD\u5B58\u5931\u8D25\u3002"]]);function mI(n){return{handled:!0,message:n,messages:[n]}}function ope(n){if(!n||typeof n!="object"||!["success","error"].includes(n.kind)||n.text!==void 0&&typeof n.text!="string")throw new TypeError("Harness returned an invalid /compact result");let t=n.text?.trim()??"",o=/^Compacted (\d+) history items \(~(\d+) tokens\)\.$/u.exec(t);return o?w("\u5DF2\u538B\u7F29 {count} \u6761\u5386\u53F2\u8BB0\u5F55\uFF08\u7EA6 {tokens} \u4E2A token\uFF09\u3002",{count:o[1],tokens:o[2]}):Qx.has(t)?w(Qx.get(t)):t||(n.kind==="success"?w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210\u3002"):w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\u3002"))}function npe(n){let t=n?.code??n?.failure?.code;return t==="session-not-found"?w("\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u7684\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u53D1\u9001\u65B0\u6D88\u606F\u5F00\u542F\u4F1A\u8BDD\u3002"):t==="agent-busy"?w("\u5F53\u524D\u4F1A\u8BDD\u6B63\u5728\u751F\u6210\u56DE\u590D\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):t==="cancelled"||n?.name==="AbortError"?w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5DF2\u53D6\u6D88\u3002"):t===Na||t==="workspace-bot-not-found"?w("\u5DE5\u4F5C\u533A\u6216\u673A\u5668\u4EBA\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5\u3002"):t==="commands-unavailable"?w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u4ECE\u673A\u5668\u4EBA\u6267\u884C\u4E0A\u4E0B\u6587\u538B\u7F29\u3002"):w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}async function Bi(n,t,o,i,e={}){if(typeof n!="string")return null;let a=ape.exec(n.trim());if(!a)return null;if(a[1].trim())return mI(w(ipe));if(typeof o?.sessionFor!="function")return mI(w("\u5F53\u524D\u673A\u5668\u4EBA\u6CA1\u6709\u53EF\u7528\u7684\u4F1A\u8BDD\u72B6\u6001\u3002"));let A=o.sessionFor(i);if(typeof A!="string"||!A)return mI(w("\u5F53\u524D\u804A\u5929\u8FD8\u6CA1\u6709\u53EF\u538B\u7F29\u7684\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u4E00\u6761\u6D88\u606F\u3002"));if(typeof t?.executeCommand!="function")return mI(w("\u5F53\u524D\u673A\u5668\u4EBA\u6682\u4E0D\u652F\u6301\u4E0A\u4E0B\u6587\u538B\u7F29\u3002"));try{let r=await t.executeCommand(A,"/compact",e);return mI(r===void 0?w("\u5F53\u524D Harness \u672A\u6CE8\u518C /compact \u547D\u4EE4\uFF0C\u8BF7\u786E\u8BA4\u4E0A\u4E0B\u6587\u538B\u7F29\u7EC4\u4EF6\u5DF2\u542F\u7528\u3002"):ope(r?.result))}catch(r){return mI(npe(r))}}import{isDeepStrictEqual as Spe}from"node:util";import{realpath as Sx,stat as wx}from"node:fs/promises";import{isAbsolute as Dx,resolve as spe}from"node:path";var gpe=/^\/workspace(?:\s+([\s\S]+))?$/i,cpe=/^\/workspacelist(?:\s+([\s\S]+))?$/i,Ipe=/^\/(?:sessionlist|sessions)(?:\s+([\s\S]+))?$/i,lpe=/^\/session(?=$|\s)/i,ppe=/^\/session[ \t]+([^\s]+)$/i,dpe=4096,hpe=1800,Epe=256,Ox=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u,Cpe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu,bx="\u7528\u6CD5\uFF1A/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7\uFF08/session N\uFF09",up=["\u7528\u6CD5\uFF1A","/sessionlist \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u4F1A\u8BDD","/sessionlist \u5DE5\u4F5C\u533A\u5E8F\u53F7 \u6309 /workspacelist \u5E8F\u53F7\u5217\u51FA\u4F1A\u8BDD","/sessionlist \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5217\u51FA\u6307\u5B9A\u5DE5\u4F5C\u533A\u4F1A\u8BDD"].join(` `);function Ft(n,t=[n]){return{handled:!0,message:n,messages:t}}function Bp(n){return typeof n!="string"||n.length>dpe||!Dx(n)||Ox.test(n)?null:spe(n)}function cQ(n){return typeof n!="string"?"":n.replace(Cpe," ").replace(/\s+/gu," ").trim()}function yx(n){return typeof n=="string"&&n.length>0&&n.length<=Epe&&!new RegExp("\\p{White_Space}","u").test(n)&&!Ox.test(n)}async function KM(n){let t=await Promise.all(n.map(async o=>{let i=Bp(o);if(!i)return null;try{return(await wx(i)).isDirectory()?Bp(await Sx(i)):null}catch{return null}}));return[...new Set(t.filter(Boolean))]}async function xM(n){if(typeof n!="string"||!Dx(n.trim()))return{error:w(`\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002 @@ -245,7 +245,7 @@ ${n}`:n)}function RM(n,t,o){return{cardParamMap:{flowStatus:t,msgContent:bE(n,o) ${_pe(I.text,s)}`);g=rc([a,...c,A.join(` `)].join(` -`)),s=Math.floor(s/2)}while(s>0&&(g.message.length>3e3||g.messages.length>3));return g}function Npe(n){let t=n?.code??n?.failure?.code;return t==="session-not-found"?w("\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u7684\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u91CD\u65B0\u7ED1\u5B9A\u4F1A\u8BDD\u3002"):t===Na||t==="workspace-bot-not-found"||t==="session-binding-changed"?w("\u4F1A\u8BDD\u3001\u5DE5\u4F5C\u533A\u6216\u673A\u5668\u4EBA\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C /history\u3002"):t==="harness-api-not-found"?w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"):n?.name==="AbortError"?w("\u5386\u53F2\u8BFB\u53D6\u5DF2\u53D6\u6D88\u3002"):n?.name==="TimeoutError"||t==="harness-timeout"?w("\u8BFB\u53D6\u5386\u53F2\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):w("\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}function fi(n){return typeof n=="string"&&_x.test(n.trim())}async function qi(n,t,o,i,{signal:e,isDirect:a=!1,hasImages:A=!1,hasFiles:r=!1}={}){if(!fi(n))return null;let s=_x.exec(n.trim())[1].trim();if(s&&(!/^\d+$/u.test(s)||/^0+$/u.test(s)))return rc(w(wpe));let g=s?Math.min(Number(s),Dpe):3;if(!a)return rc(w("\u8BF7\u5728\u4E0E\u673A\u5668\u4EBA\u7684\u79C1\u804A\u4E2D\u4F7F\u7528 /history\u3002"));if(A||r)return rc(w("/history \u4EC5\u652F\u6301\u6587\u5B57\u547D\u4EE4\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u6216\u6587\u4EF6\u540E\u91CD\u8BD5\u3002"));let c=o?.sessionFor?.(i);if(typeof c!="string"||!c)return rc(w("\u5F53\u524D\u804A\u5929\u5C1A\u672A\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u6D88\u606F\u6216\u4F7F\u7528 /session \u7ED1\u5B9A\u4F1A\u8BDD\u3002"));try{let I=t?.workspaceSession?.(c);if(typeof I?.readHistory!="function")return rc(w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"));let d=AbortSignal.timeout(Mx),B=e?AbortSignal.any([e,d]):d,f=Date.now()+Mx,Q=new Map,y,m,_=[],T=!1;for(let R=0;R=f)throw new DOMException("History read timed out","TimeoutError");let F=await I.readHistory({maxMessages:Ope,...y===void 0?{}:{beforeSeq:y},timeoutMs:Math.max(1,f-Date.now()),signal:B});if(B.throwIfAborted(),Date.now()>=f)throw new DOMException("History read timed out","TimeoutError");if(o.sessionFor(i)!==c){let q=new Error("Session binding changed during history read");throw q.code="session-binding-changed",q}if(!F||!Array.isArray(F.events)||typeof F.hasMore!="boolean")throw new TypeError("Invalid history page");let K=y??1/0;for(let q of F.events){let z=q?.event;if(!z||!Number.isSafeInteger(z.seq)||z.seq<0||typeof z.type!="string"||!z.type)throw new TypeError("Invalid history event");if(m!==void 0&&z.seq>m)continue;let j=Q.get(z.seq);if(j){if(!Spe(j,z))throw new TypeError("Conflicting history events")}else{if(y!==void 0&&z.seq>=y)throw new TypeError("Invalid history cursor");Q.set(z.seq,z)}K=Math.min(K,z.seq)}let L=[...Q.values()].sort((q,z)=>q.seq-z.seq);if(m??=L.at(-1)?.seq,T=F.hasMore,T&&(!Number.isFinite(K)||K===y))throw new TypeError("History cursor did not advance");if(_=Mpe(L).slice(-g),_.length>=g||!T)break;y=K}return _.length===0?rc(T?w("\u672C\u6B21\u6709\u9650\u8BFB\u53D6\u4E2D\u672A\u627E\u5230\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002"):w("\u5F53\u524D\u4F1A\u8BDD\u6682\u65E0\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002")):Tpe(c,_,g,T)}catch(I){return rc(Npe(I))}}var IQ={name:"@xmanrui/dsh-im",version:"4.2.1",description:"\u628A\u4E5D\u79CD IM \u673A\u5668\u4EBA\u548C\u516C\u7F51 AI Office \u63A5\u5165\u672C\u673A DeepSeek Harness\u3002 Connect nine IM channels and a public AI Office to a local DeepSeek Harness.",keywords:["deepseek-harness","dsh","dsh-plugin","ai-agent","im","instant-messaging","chatbot","feishu","lark","wechat","wecom","dingtalk","qq","slack","telegram","discord","whatsapp","ai-office"],author:{name:"xmanrui",url:"https://github.com/xmanrui"},contributors:[{name:"C3H3-AI",url:"https://github.com/C3H3-AI"},{name:"divingleee",url:"https://github.com/divingleee"}],license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/xmanrui/dsh-im.git"},homepage:"https://github.com/xmanrui/dsh-im#readme",bugs:"https://github.com/xmanrui/dsh-im/issues",publishConfig:{access:"public"},bin:{"dsh-im":"bin/dsh-im.mjs"},main:"./lib/index.js",exports:{".":"./lib/index.js","./client":"./lib/client.js","./package.json":"./package.json"},files:["assets","bin","cordis.patch.yml","lib","plugin-src","scripts","src","PROACTIVE_DELIVERY.md","PROACTIVE_DELIVERY.en.md","LICENSE","README.md","README.en.md","THIRD_PARTY_NOTICES.md"],dsh:{bundle:{patch:"./cordis.patch.yml"},client:{inject:["@deepseek-ai/dsh-client-connection","@deepseek-ai/dsh-client-runtime","@deepseek-ai/dsh-client-ui-settings","@deepseek-ai/dsh-client-ui-slots","@deepseek-ai/dsh-client-locale"],platform:"web"}},scripts:{build:"node plugin-src/client/build.mjs && node plugin-src/host/build.mjs",test:"node --test test/*.test.mjs test/channels/*/*.test.mjs",check:"npm run build && npm test && node scripts/verify-package.mjs"},engines:{node:">=22.19"},dependencies:{"@tencent-connect/qqbot-connector":"1.2.0","@tencent-connect/qqbot-nodejs":"1.0.4","@wecom/aibot-node-sdk":"1.0.7","dingtalk-stream":"2.1.4",qrcode:"1.5.4",undici:"7.29.0"},devDependencies:{"@deepseek-ai/cordis":"4.0.1","@larksuiteoapi/node-sdk":"1.73.0","@whiskeysockets/baileys":"7.0.0-rc14",esbuild:"0.25.9","https-proxy-agent":"5.0.1",react:"18.3.1","react-dom":"18.3.1","react-test-renderer":"18.3.1",semver:"7.8.5"}};var kpe=/^\/(?:stop|steer|version)(?=$|\s)/iu,vpe=/^\/stop(?=$|\s)/iu,Ppe=/^\/version(?=$|\s)/iu,Gpe="\u7528\u6CD5\uFF1A/stop\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",Fpe="\u7528\u6CD5\uFF1A/version\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",Lpe="\u7528\u6CD5\uFF1A/steer <\u8865\u5145\u6307\u4EE4>",Upe="\u63A7\u5236\u547D\u4EE4\u4EC5\u652F\u6301\u7EAF\u6587\u5B57\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u540E\u91CD\u8BD5\u3002";function yo(n,t={}){return{message:n,...t}}function Nx(n){return n?{signal:n}:{}}function Rx(n,t,o){if(typeof t?.sessionFor!="function")return null;let i=t.sessionFor(o);if(typeof i!="string"||!i)return null;if(typeof n?.workspaceSession!="function")throw new TypeError("Harness does not support workspace sessions");let e=n.workspaceSession(i);if(!e||typeof e!="object")throw new TypeError("Harness returned an invalid workspace session");return e}function zi(n){return typeof n=="string"&&kpe.test(n.trim())}async function Qi(n,t,o,i,{signal:e,hasImages:a=!1,pendingInteraction:A=!1,control:r}={}){if(!zi(n))return null;let s=n.trim(),g=vpe.test(s),c=Ppe.test(s);if(a)return yo(w(Upe));if(c)return/^\/version$/iu.test(s)?yo(`dsh-im v${IQ.version}`):yo(w(Fpe));if(g){if(!/^\/stop$/iu.test(s))return yo(w(Gpe));let Q=Rx(t,o,i);if(!Q)return yo(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"));if(typeof Q.stopActiveTurn!="function")throw new TypeError("Harness session does not support stopping active turns");return await Q.stopActiveTurn(r,Nx(e))?yo(w("\u5DF2\u8BF7\u6C42\u505C\u6B62\u5F53\u524D\u4EFB\u52A1\u3002"),{stopped:!0}):yo(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"))}let d=/^\/steer(?:\s+([\s\S]*))?$/iu.exec(s)?.[1]?.trim()??"";if(!d)return yo(w(Lpe));if(A)return yo([w("\u5F53\u524D\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u4F60\u7684\u56DE\u7B54\u6216\u5BA1\u6279\u3002"),"",w("\u8BF7\u5148\u5904\u7406\u5F53\u524D\u8BF7\u6C42\uFF0C\u6216\u8005\u53D1\u9001 /stop \u505C\u6B62\u4EFB\u52A1\u3002")].join(` +`)),s=Math.floor(s/2)}while(s>0&&(g.message.length>3e3||g.messages.length>3));return g}function Npe(n){let t=n?.code??n?.failure?.code;return t==="session-not-found"?w("\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u7684\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u91CD\u65B0\u7ED1\u5B9A\u4F1A\u8BDD\u3002"):t===Na||t==="workspace-bot-not-found"||t==="session-binding-changed"?w("\u4F1A\u8BDD\u3001\u5DE5\u4F5C\u533A\u6216\u673A\u5668\u4EBA\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C /history\u3002"):t==="harness-api-not-found"?w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"):n?.name==="AbortError"?w("\u5386\u53F2\u8BFB\u53D6\u5DF2\u53D6\u6D88\u3002"):n?.name==="TimeoutError"||t==="harness-timeout"?w("\u8BFB\u53D6\u5386\u53F2\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):w("\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}function fi(n){return typeof n=="string"&&_x.test(n.trim())}async function qi(n,t,o,i,{signal:e,isDirect:a=!1,hasImages:A=!1,hasFiles:r=!1}={}){if(!fi(n))return null;let s=_x.exec(n.trim())[1].trim();if(s&&(!/^\d+$/u.test(s)||/^0+$/u.test(s)))return rc(w(wpe));let g=s?Math.min(Number(s),Dpe):3;if(!a)return rc(w("\u8BF7\u5728\u4E0E\u673A\u5668\u4EBA\u7684\u79C1\u804A\u4E2D\u4F7F\u7528 /history\u3002"));if(A||r)return rc(w("/history \u4EC5\u652F\u6301\u6587\u5B57\u547D\u4EE4\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u6216\u6587\u4EF6\u540E\u91CD\u8BD5\u3002"));let c=o?.sessionFor?.(i);if(typeof c!="string"||!c)return rc(w("\u5F53\u524D\u804A\u5929\u5C1A\u672A\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u6D88\u606F\u6216\u4F7F\u7528 /session \u7ED1\u5B9A\u4F1A\u8BDD\u3002"));try{let I=t?.workspaceSession?.(c);if(typeof I?.readHistory!="function")return rc(w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"));let d=AbortSignal.timeout(Mx),B=e?AbortSignal.any([e,d]):d,f=Date.now()+Mx,Q=new Map,y,m,_=[],T=!1;for(let R=0;R=f)throw new DOMException("History read timed out","TimeoutError");let L=await I.readHistory({maxMessages:Ope,...y===void 0?{}:{beforeSeq:y},timeoutMs:Math.max(1,f-Date.now()),signal:B});if(B.throwIfAborted(),Date.now()>=f)throw new DOMException("History read timed out","TimeoutError");if(o.sessionFor(i)!==c){let q=new Error("Session binding changed during history read");throw q.code="session-binding-changed",q}if(!L||!Array.isArray(L.events)||typeof L.hasMore!="boolean")throw new TypeError("Invalid history page");let U=y??1/0;for(let q of L.events){let z=q?.event;if(!z||!Number.isSafeInteger(z.seq)||z.seq<0||typeof z.type!="string"||!z.type)throw new TypeError("Invalid history event");if(m!==void 0&&z.seq>m)continue;let j=Q.get(z.seq);if(j){if(!Spe(j,z))throw new TypeError("Conflicting history events")}else{if(y!==void 0&&z.seq>=y)throw new TypeError("Invalid history cursor");Q.set(z.seq,z)}U=Math.min(U,z.seq)}let F=[...Q.values()].sort((q,z)=>q.seq-z.seq);if(m??=F.at(-1)?.seq,T=L.hasMore,T&&(!Number.isFinite(U)||U===y))throw new TypeError("History cursor did not advance");if(_=Mpe(F).slice(-g),_.length>=g||!T)break;y=U}return _.length===0?rc(T?w("\u672C\u6B21\u6709\u9650\u8BFB\u53D6\u4E2D\u672A\u627E\u5230\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002"):w("\u5F53\u524D\u4F1A\u8BDD\u6682\u65E0\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002")):Tpe(c,_,g,T)}catch(I){return rc(Npe(I))}}var IQ={name:"@xmanrui/dsh-im",version:"4.2.1",description:"\u628A\u4E5D\u79CD IM \u673A\u5668\u4EBA\u548C\u516C\u7F51 AI Office \u63A5\u5165\u672C\u673A DeepSeek Harness\u3002 Connect nine IM channels and a public AI Office to a local DeepSeek Harness.",keywords:["deepseek-harness","dsh","dsh-plugin","ai-agent","im","instant-messaging","chatbot","feishu","lark","wechat","wecom","dingtalk","qq","slack","telegram","discord","whatsapp","ai-office"],author:{name:"xmanrui",url:"https://github.com/xmanrui"},contributors:[{name:"C3H3-AI",url:"https://github.com/C3H3-AI"},{name:"divingleee",url:"https://github.com/divingleee"}],license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/xmanrui/dsh-im.git"},homepage:"https://github.com/xmanrui/dsh-im#readme",bugs:"https://github.com/xmanrui/dsh-im/issues",publishConfig:{access:"public"},bin:{"dsh-im":"bin/dsh-im.mjs"},main:"./lib/index.js",exports:{".":"./lib/index.js","./client":"./lib/client.js","./package.json":"./package.json"},files:["assets","bin","cordis.patch.yml","lib","plugin-src","scripts","src","PROACTIVE_DELIVERY.md","PROACTIVE_DELIVERY.en.md","LICENSE","README.md","README.en.md","THIRD_PARTY_NOTICES.md"],dsh:{bundle:{patch:"./cordis.patch.yml"},client:{inject:["@deepseek-ai/dsh-client-connection","@deepseek-ai/dsh-client-runtime","@deepseek-ai/dsh-client-ui-settings","@deepseek-ai/dsh-client-ui-slots","@deepseek-ai/dsh-client-locale"],platform:"web"}},scripts:{build:"node plugin-src/client/build.mjs && node plugin-src/host/build.mjs",test:"node --test test/*.test.mjs test/channels/*/*.test.mjs",check:"npm run build && npm test && node scripts/verify-package.mjs"},engines:{node:">=22.19"},dependencies:{"@tencent-connect/qqbot-connector":"1.2.0","@tencent-connect/qqbot-nodejs":"1.0.4","@wecom/aibot-node-sdk":"1.0.7","dingtalk-stream":"2.1.4",qrcode:"1.5.4",undici:"7.29.0"},devDependencies:{"@deepseek-ai/cordis":"4.0.1","@larksuiteoapi/node-sdk":"1.73.0","@whiskeysockets/baileys":"7.0.0-rc14",esbuild:"0.25.9","https-proxy-agent":"5.0.1",react:"18.3.1","react-dom":"18.3.1","react-test-renderer":"18.3.1",semver:"7.8.5"}};var kpe=/^\/(?:stop|steer|version)(?=$|\s)/iu,vpe=/^\/stop(?=$|\s)/iu,Ppe=/^\/version(?=$|\s)/iu,Gpe="\u7528\u6CD5\uFF1A/stop\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",Fpe="\u7528\u6CD5\uFF1A/version\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",Lpe="\u7528\u6CD5\uFF1A/steer <\u8865\u5145\u6307\u4EE4>",Upe="\u63A7\u5236\u547D\u4EE4\u4EC5\u652F\u6301\u7EAF\u6587\u5B57\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u540E\u91CD\u8BD5\u3002";function yo(n,t={}){return{message:n,...t}}function Nx(n){return n?{signal:n}:{}}function Rx(n,t,o){if(typeof t?.sessionFor!="function")return null;let i=t.sessionFor(o);if(typeof i!="string"||!i)return null;if(typeof n?.workspaceSession!="function")throw new TypeError("Harness does not support workspace sessions");let e=n.workspaceSession(i);if(!e||typeof e!="object")throw new TypeError("Harness returned an invalid workspace session");return e}function zi(n){return typeof n=="string"&&kpe.test(n.trim())}async function Qi(n,t,o,i,{signal:e,hasImages:a=!1,pendingInteraction:A=!1,control:r}={}){if(!zi(n))return null;let s=n.trim(),g=vpe.test(s),c=Ppe.test(s);if(a)return yo(w(Upe));if(c)return/^\/version$/iu.test(s)?yo(`dsh-im v${IQ.version}`):yo(w(Fpe));if(g){if(!/^\/stop$/iu.test(s))return yo(w(Gpe));let Q=Rx(t,o,i);if(!Q)return yo(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"));if(typeof Q.stopActiveTurn!="function")throw new TypeError("Harness session does not support stopping active turns");return await Q.stopActiveTurn(r,Nx(e))?yo(w("\u5DF2\u8BF7\u6C42\u505C\u6B62\u5F53\u524D\u4EFB\u52A1\u3002"),{stopped:!0}):yo(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"))}let d=/^\/steer(?:\s+([\s\S]*))?$/iu.exec(s)?.[1]?.trim()??"";if(!d)return yo(w(Lpe));if(A)return yo([w("\u5F53\u524D\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u4F60\u7684\u56DE\u7B54\u6216\u5BA1\u6279\u3002"),"",w("\u8BF7\u5148\u5904\u7406\u5F53\u524D\u8BF7\u6C42\uFF0C\u6216\u8005\u53D1\u9001 /stop \u505C\u6B62\u4EFB\u52A1\u3002")].join(` `));let B=Rx(t,o,i);if(!B)return yo(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u65E0\u6CD5\u8865\u5145\u6307\u4EE4\u3002\u8BF7\u5148\u7ED1\u5B9A\u4F1A\u8BDD\u3002"));if(typeof B.steerActiveTurn!="function")throw new TypeError("Harness session does not support steering active turns");let f=await B.steerActiveTurn(d,r,Nx(e));return yo(f?w("\u5DF2\u63D0\u4EA4\u8865\u5145\u6307\u4EE4\uFF0CAgent \u4F1A\u5728\u4E0B\u4E00\u6B65\u8BFB\u53D6\u3002"):w("\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\uFF0C\u65E0\u6CD5\u8865\u5145\u6307\u4EE4\u3002\u8BF7\u76F4\u63A5\u53D1\u9001\u6D88\u606F\u5F00\u59CB\u65B0\u4EFB\u52A1\u3002"))}var Hpe=/^\/model(?=$|\s)/i,Kx=/^\/models(?=$|\s)/i,xx=/^\/reasoning(?=$|\s)/i,Yx=/^\/reasonings(?=$|\s)/i,jx=/^\/reasoninglist(?=$|\s)/i,kx="\u7528\u6CD5\uFF1A/model <\u5E8F\u53F7\u6216 provider/model> [\u63A8\u7406\u7B49\u7EA7ID]",Kpe="\u7528\u6CD5\uFF1A/models\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",xpe="\u7528\u6CD5\uFF1A/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default]",Ype="\u7528\u6CD5\uFF1A/reasoninglist \u6216 /reasonings\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",Jx="session-binding-changed",qx="model-selection-mismatch",jpe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu;function ht(n){return{handled:!0,message:n,messages:Xs(n)}}function Zr(n){return typeof n!="string"?"":n.replace(jpe," ").replace(/\s+/gu," ").trim()}function Jpe(n){return n?{signal:n}:{}}function qpe(n){if(n===void 0)return;if(!n||typeof n!="object"||!Array.isArray(n.efforts)||n.efforts.length===0)throw new TypeError("Harness returned invalid model reasoning metadata");let t=n.efforts.map(o=>{if(!o||typeof o!="object"||typeof o.id!="string"||!o.id||typeof o.name!="string"||!o.name||o.description!==void 0&&typeof o.description!="string")throw new TypeError("Harness returned an invalid reasoning effort");return{id:o.id,name:o.name,...o.description===void 0?{}:{description:o.description}}});if(n.defaultEffort!==void 0&&(typeof n.defaultEffort!="string"||!n.defaultEffort))throw new TypeError("Harness returned an invalid default reasoning effort");return{efforts:t,...n.defaultEffort===void 0?{}:{defaultEffort:n.defaultEffort}}}function zx(n,{requireCurrent:t=!1}={}){if(!n||typeof n!="object"||!Array.isArray(n.groups)||!Array.isArray(n.failures))throw new TypeError("Harness returned an invalid model catalog");let o=n.groups.map(a=>{if(!a||typeof a!="object"||typeof a.id!="string"||!a.id||typeof a.name!="string"||!a.name||!Array.isArray(a.models))throw new TypeError("Harness returned an invalid model provider group");return{id:a.id,name:a.name,models:a.models.map(A=>{if(!A||typeof A!="object"||typeof A.id!="string"||!A.id||typeof A.name!="string"||!A.name||A.description!==void 0&&typeof A.description!="string")throw new TypeError("Harness returned an invalid model");return{id:A.id,name:A.name,...A.description===void 0?{}:{description:A.description},...A.reasoning===void 0?{}:{reasoning:qpe(A.reasoning)}}})}}),i=n.failures.map(a=>{if(!a||typeof a!="object"||typeof a.id!="string"||!a.id||typeof a.name!="string"||!a.name)throw new TypeError("Harness returned an invalid model provider failure");return{id:a.id,name:a.name}}),e=null;if(n.current!==void 0){if(!n.current||typeof n.current!="object"||typeof n.current.provider!="string"||!n.current.provider||typeof n.current.model!="string"||!n.current.model||n.current.reasoningEffort!==void 0&&(typeof n.current.reasoningEffort!="string"||!n.current.reasoningEffort))throw new TypeError("Harness returned an invalid current model");e={provider:n.current.provider,model:n.current.model,...n.current.reasoningEffort===void 0?{}:{reasoningEffort:n.current.reasoningEffort}}}else if(t)throw new TypeError("Harness returned no current model");return{groups:o,failures:i,current:e}}function $s(n,t){return`${n}/${t}`}function Vx(n,t){return n?.provider===t?.provider&&n?.model===t?.model}function zpe(n,t){return Vx(n,t)&&n?.reasoningEffort===t?.reasoningEffort}function Vpe(n,t){return Vx(n,t)&&(t.reasoningEffort===void 0||n?.reasoningEffort===t.reasoningEffort)}function zM(n){if(!n?.provider||!n?.model)return"";let t=$s(n.provider,n.model);return n.reasoningEffort===void 0?t:`${t} \xB7 reasoningEffort=${Zr(n.reasoningEffort)}`}function vx(n,t,o){let i=new Error(`Harness ${o} did not confirm the selected model`);return i.code=qx,i.expected=n,i.actual=t,i.source=o,i}function Wx(){let n=new Error("Conversation binding changed during model selection");return n.code=Jx,n}function Px(n,t,o){if((typeof n?.sessionFor=="function"?n.sessionFor(t):null)!==o)throw Wx()}function Wpe(n,t){for(let o of n.groups)for(let i of o.models)if($s(o.id,i.id)===t)return{provider:o.id,model:i.id};return null}function Zpe(n,t){let o=0;for(let i of n.groups)for(let e of i.models)if(o+=1,o===t)return{provider:i.id,model:e.id};return null}function Gx(n){if(!/^\d+$/u.test(n))return null;let t=Number(n);return{index:Number.isSafeInteger(t)&&t>0?t:null}}function lQ(n,t){return t?n.groups.find(({id:i})=>i===t.provider)?.models.find(({id:i})=>i===t.model)??null:null}function Xpe(n,t){return n?.reasoning?.efforts?.[t-1]??null}function VM(n,t){return n?.reasoning?.efforts?.find(({id:o})=>o===t)??null}function pQ(n,t){return n?.reasoningEffort??t?.reasoning?.defaultEffort}function TE(n,t){if(t===void 0)return w("Default\uFF08\u7531\u6A21\u578B\u6216 Provider \u51B3\u5B9A\uFF09");let o=VM(n,t);if(!o)return Zr(t);let i=Zr(o.name),e=Zr(o.id);return i===e?e:`${i} (${e})`}function Zx(n){let t=lQ(n,n.current);return TE(t,pQ(n.current,t))}function $pe(n,t,o){return n===t&&n===o?w("\uFF08\u5F53\u524D\u3001\u9ED8\u8BA4\uFF09"):n===t?w("\uFF08\u5F53\u524D\uFF09"):n===o?w("\uFF08\u9ED8\u8BA4\uFF09"):""}function Fx(n){return[w("\u6A21\u578B\u5E8F\u53F7\u65E0\u6548\uFF1A{input}",{input:Zr(n)}),"",w("\u8BF7\u53D1\u9001 /models \u67E5\u770B\u5E76\u8F93\u5165\u6709\u6548\u7684\u6B63\u6574\u6570\u5E8F\u53F7\u3002")].join(` `)}function Lx(n){return[w("\u63A8\u7406\u7B49\u7EA7\u5E8F\u53F7\u65E0\u6548\uFF1A{input}",{input:Zr(n)}),"",w("\u8BF7\u53D1\u9001 /reasoninglist \u67E5\u770B\u5E76\u8F93\u5165\u6709\u6548\u7684\u6B63\u6574\u6570\u5E8F\u53F7\u3002")].join(` `)}function jM(n,t,o){let i=[w("\u6A21\u578B\u4E0D\u652F\u6301\u63A8\u7406\u7B49\u7EA7\uFF1A{effort}",{effort:Zr(t)}),"",Zr(zM(n))],e=o?.reasoning?.efforts?.map(({id:a})=>Zr(a))??[];return e.length>0?i.push(w("\u53EF\u7528\u63A8\u7406\u7B49\u7EA7\uFF1A{efforts}",{efforts:e.join(", ")})):i.push(w("\u8BE5\u6A21\u578B\u4E0D\u63D0\u4F9B\u53EF\u5207\u6362\u7684\u63A8\u7406\u7B49\u7EA7\u3002")),i.join(` @@ -295,25 +295,25 @@ ${o}`);return[w("\u4EE5\u4E0B\u662F\u7528\u6237\u901A\u8FC7\u6279\u91CF\u8F93\u5 \u8BF7\u518D\u6B21\u53D1\u9001 /send \u91CD\u8BD5\u6216 /cancel \u53D6\u6D88\u3002`,{count:e})})}};import{createWriteStream as Gde}from"node:fs";import{mkdir as Fde,mkdtemp as Lde,rm as nY,writeFile as Ude}from"node:fs/promises";import{isAbsolute as sY,join as t_,relative as Hde,resolve as gY}from"node:path";import{pipeline as Kde}from"node:stream/promises";var xde=t_(".dsh-im","inbound"),Do=class extends Error{constructor(t,o,i=w("\u6587\u4EF6\u63A5\u6536\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002"),e={}){super(o,e),this.name="InboundFileError",this.code=t,this.userMessage=i}};function r_(n){return Array.isArray(n?.files)?n.files.filter(Boolean):[]}function cY(n,t){return typeof n!="string"?t:n.replaceAll("\\","/").split("/").at(-1)?.replace(/[\u0000-\u001f\u007f]/g,"").trim()||t}function Yde(n,t){let o=cY(n,"file").replace(/[^\p{L}\p{N}._ -]/gu,"_").replace(/^\.+/,"").slice(0,160)||"file";return`${String(t+1).padStart(2,"0")}-${o}`}function jde(n){if(Buffer.isBuffer(n)||n instanceof Uint8Array)return{data:Buffer.from(n)};let t=n?.data??n?.buffer;if(Buffer.isBuffer(t)||t instanceof Uint8Array)return{data:Buffer.from(t),name:n?.name??n?.filename,mediaType:n?.mediaType??n?.mimetype};let o=n?.stream??n;return o&&typeof o[Symbol.asyncIterator]=="function"?{stream:o,name:n?.name??n?.filename,mediaType:n?.mediaType??n?.mimetype}:null}function Lt(n){return r_(n).length>0}function wp(n,{signal:t}={}){let o=r_(n);return o.length===0?n:{...n,files:o.map(i=>{if(i?.data!==void 0||typeof i?.load!="function")return i;let e;try{e=Promise.resolve(i.load({signal:t}))}catch(a){e=Promise.reject(a)}return e.catch(()=>{}),{...i,async load({signal:a}={}){a?.throwIfAborted();let A=await e;return a?.throwIfAborted(),A}}})}}async function IY(n,{workspace:t,signal:o}={}){let i=r_(n);if(i.length===0)return null;if(typeof t!="string"||!sY(t))throw new Do("inbound-file-workspace-unavailable","The Harness Session workspace is unavailable for inbound files.");o?.throwIfAborted();let e=gY(t,xde);await Fde(e,{recursive:!0,mode:448});let a=await Lde(t_(e,"turn-")),A=[];try{for(let[r,s]of i.entries()){o?.throwIfAborted();let g;try{g=s?.data===void 0?await s?.load?.({signal:o}):s.data}catch(f){throw o?.aborted?f:new Do("inbound-file-download-failed",`Unable to download inbound file ${r+1}: ${f?.message??String(f)}`,w("\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002"),{cause:f})}let c=jde(g);if(!c)throw new Do("inbound-file-data-invalid",`Inbound file ${r+1} returned no readable data.`);let I=cY(c.name??s?.name,`file-${r+1}`),d=t_(a,Yde(I,r));if(c.data)await Ude(d,c.data,{mode:384,signal:o});else try{await Kde(c.stream,Gde(d,{flags:"wx",mode:384}),{signal:o})}catch(f){throw o?.aborted?f:new Do("inbound-file-download-failed",`Unable to stream inbound file ${r+1}: ${f?.message??String(f)}`,w("\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002"),{cause:f})}let B=Hde(gY(t),d);if(!B||B.startsWith("..")||sY(B))throw new Do("inbound-file-path-invalid","The staged inbound file escaped the Harness Session workspace.");A.push(Object.freeze({name:I,path:B,...typeof(c.mediaType??s?.mediaType)=="string"&&(c.mediaType??s.mediaType).trim()?{mediaType:(c.mediaType??s.mediaType).trim()}:{}}))}return Object.freeze({files:Object.freeze(A),async cleanup(){await nY(a,{recursive:!0,force:!0})}})}catch(r){throw await nY(a,{recursive:!0,force:!0}).catch(()=>{}),r}}function lY(n,t){if(!t?.files?.length)return n;let o=["",JSON.stringify({description:"Files uploaded with this user message. Paths are relative to the current Harness workspace.",files:t.files}),""].join(` `);if(Array.isArray(n))return[...n,{type:"text",text:o}];let i=typeof n=="string"?n.trim():"";return i?`${i} -${o}`:o}function Oo(n){return n instanceof Do?n.userMessage:null}import{createHash as uY,randomUUID as BY}from"node:crypto";import{constants as NE}from"node:fs";import{copyFile as Jde,lstat as pY,mkdtemp as qde,open as fY,realpath as zde,unlink as QY}from"node:fs/promises";import{tmpdir as Vde}from"node:os";import{basename as Wde,extname as Zde,isAbsolute as Xde,join as yY,resolve as $de}from"node:path";var uQ="dsh_im_return_file",CQ="dsh-im-outbound-artifact",a_=64*1024,ehe=new Map([[".csv","text/csv"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".gif","image/gif"],[".html","text/html"],[".jpeg","image/jpeg"],[".jpg","image/jpeg"],[".json","application/json"],[".md","text/markdown"],[".pdf","application/pdf"],[".png","image/png"],[".rar","application/vnd.rar"],[".txt","text/plain"],[".webp","image/webp"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".xml","application/xml"],[".zip","application/zip"]]),rg=new WeakMap,mY=new WeakMap,RE=new WeakMap,dY;function Ahe(){return dY??=qde(yY(Vde(),"dsh-im-outbound-")),dY}function tg(n,t){let o=new Error(t);return o.code=n,o}function hY(n){let t=n?.session?.events;if(!Array.isArray(t))return null;let o=null;for(let i of t)i?.type==="turn/start"?o=Number.isInteger(i.data?.turn)?i.data.turn:null:i?.type==="turn/end"&&i.data?.turn===o&&(o=null);return Number.isInteger(o)&&o>=0?o:null}function EY(n){let t=n?.id??n?.header?.id;return typeof t=="string"&&t?t:null}function Ag(n,t){return`${n}\0${t}`}function CY(n,t){return`${n}\0${t}`}function the(n){let t=String(n??"").replace(/[\u0000-\u001f\u007f]/g," ").replace(new RegExp("\\p{Cf}","gu"),"").replace(/\s+/g," ").trim();return t?[...t].slice(0,255).join(""):"result.bin"}function rhe(n){return ehe.get(Zde(n).toLowerCase())??"application/octet-stream"}function ahe(n){return uY("sha256").update(n).digest("hex")}function ihe(n,t){return typeof n?.dev=="bigint"&&typeof n?.ino=="bigint"&&typeof n?.size=="bigint"&&typeof n?.mtimeNs=="bigint"&&typeof n?.ctimeNs=="bigint"&&n.dev===t?.dev&&n.ino===t?.ino&&n.size===t?.size&&n.mtimeNs===t?.mtimeNs&&n.ctimeNs===t?.ctimeNs}async function ohe(n,t){let o;try{o=await fY(n,NE.O_RDONLY);let i=uY("sha256"),e=o.createReadStream({autoClose:!1,highWaterMark:a_,...t?{signal:t}:{}});for await(let a of e)t?.throwIfAborted(),i.update(a);return i.digest("hex")}finally{await o?.close().catch(()=>{})}}async function nhe(n,t,{signal:o,errorCode:i="artifact-changed",errorMessage:e="The result file changed while it was being read."}={}){let a=()=>tg(i,e);if(!Number.isSafeInteger(t)||t<0)throw a();o?.throwIfAborted();let A;try{A=Buffer.allocUnsafe(t)}catch{throw a()}if(typeof n?.createReadStream=="function"){let g=n.createReadStream({autoClose:!1,start:0,end:t,highWaterMark:a_,...o?{signal:o}:{}}),c=0;for await(let I of g){o?.throwIfAborted();let d=Buffer.isBuffer(I)?I:Buffer.from(I);if(c+d.length>t)throw a();d.copy(A,c),c+=d.length}if(c!==t)throw a();return A}let r=0;for(;rg)throw a();r+=I}o?.throwIfAborted();let s=Buffer.allocUnsafe(1);if((await n.read(s,0,1,t))?.bytesRead!==0)throw a();return A}async function she(n,t,o){o?.throwIfAborted();let i;try{let e=Xde(t)?t:$de(n,t),a=await zde(e);if(!(await pY(a,{bigint:!0})).isFile())throw tg("artifact-not-file","The requested path is not a file.");let r=await Ahe();i=yY(r,`${BY()}.artifact`),await Jde(a,i,NE.COPYFILE_EXCL),o?.throwIfAborted();let s=await pY(i,{bigint:!0}),g=Number(s.size);if(!s.isFile()||!Number.isSafeInteger(g)||g<0)throw tg("artifact-unavailable","The file could not be prepared for delivery.");let c=the(Wde(e));return Object.freeze({fileName:c,mediaType:rhe(c),size:g,digest:await ohe(i,o),storagePath:i})}catch(e){throw i&&await QY(i).catch(()=>{}),e?.code?.startsWith?.("artifact-")?e:o?.aborted?o.reason??e:tg("artifact-unavailable","The requested file is unavailable.")}}function SY(n){return Object.freeze({artifactId:n.artifactId,fileName:n.fileName,size:n.size})}function EQ(n){return n.artifactId}function zn(n){let t=rg.get(n);if(!t)return;if(t.releaseRequested=!0,t.materializing>0){t.cleanupRequested=!0;return}let o=[...RE.get(n)??[]];if(o.length>0){t.cleanupDeferred||(t.cleanupDeferred=!0,Promise.allSettled(o).finally(()=>{t.cleanupDeferred=!1,zn(n)}));return}rg.delete(n),RE.delete(n),t.onCleanup?.(),QY(t.path).catch(()=>{})}var i_=class{#e=new Map;#A=new Map;#t=new Map;#r=new Map;#g=new Map;#a=new Map;#n=new Map;#i=new Map;#I;constructor({uuid:t=BY}={}){if(typeof t!="function")throw new TypeError("uuid must be a function");this.#I=t}openConsumer(t,o){if(typeof t!="string"||!t||typeof o!="string"||!o)throw new TypeError("sessionId and promptRpcId are required");let i=CY(t,o),e={sessionId:t,promptRpcId:o,turn:null,released:!1};return this.#a.set(i,e),()=>{if(!e.released&&(e.released=!0,this.#a.get(i)===e&&this.#a.delete(i),e.turn!==null)){let a=Ag(t,e.turn);this.#n.get(a)===e&&this.#n.delete(a),this.discard(t,e.turn)}}}observeSessionEvent(t,o){let i=EY(t);if(!i||!o||typeof o!="object")return;if(o.type==="turn/start"){let A=o.data?.turn;Number.isInteger(A)&&A>=0&&this.#i.set(i,A);return}if(o.type==="user/message"){let A=o.data?.source?.rpcId,r=this.#i.get(i)??hY({session:t});if(typeof A!="string"||!A||!Number.isInteger(r))return;this.#i.set(i,r);let s=this.#a.get(CY(i,A));if(!s||s.released)return;s.turn=r,this.#n.set(Ag(i,r),s);return}if(o.type!=="turn/end")return;let e=o.data?.turn;if(!Number.isInteger(e)||e<0)return;this.#i.get(i)===e&&this.#i.delete(i);let a=this.#n.get(Ag(i,e));(!a||a.released)&&this.discard(i,e)}disposeSession(t){let o=EY(t);if(!o)return;let i=`${o}\0`,e=new Set;for(let a of[this.#e,this.#A])for(let[A,r]of a)if(A.startsWith(i)){for(let s of r.values())e.add(s);a.delete(A)}for(let[a,A]of this.#a)a.startsWith(i)&&(A.released=!0,this.#a.delete(a));for(let a of this.#n.keys())a.startsWith(i)&&this.#n.delete(a);this.#i.delete(o);for(let a of e)zn(a)}async stage(t,o){let i=t?.path;if(typeof i!="string"||!i.trim())throw new TypeError("A file path is required.");let e=o?.agent,a=e?.session?.header?.id,A=e?.session?.header?.cwd,r=hY(e);if(typeof a!="string"||!a||typeof A!="string"||!A||r===null)throw tg("artifact-context-required","A live Harness Session is required to return a file.");let s=await she(A,i,o?.signal),{storagePath:g,...c}=s,I=Object.freeze({kind:CQ,schemaVersion:1,artifactId:this.#I(),deliveryKey:this.#I(),...c,source:"managed-temp",registeredBy:Object.freeze({kind:"tool-result",eventId:typeof o?.callId=="string"?o.callId:"unknown",toolName:uQ}),origin:Object.freeze({sessionId:a,turn:r,callId:typeof o?.callId=="string"?o.callId:null}),createdAt:Date.now()});rg.set(I,{path:g,materializing:0,materialized:!1,releaseRequested:!1,cleanupRequested:!1,cleanupDeferred:!1,onCleanup:()=>this.#s(I)});let d=Ag(a,r),B=this.#A.get(d);return B||(B=new Map,this.#A.set(d,B)),B.set(EQ(I),I),I}commit(t){if(t?.kind!==CQ||!rg.has(t))return null;let o=Ag(t.origin.sessionId,t.origin.turn),i=EQ(t),e=this.#A.get(o);if(e?.get(i)!==t)return null;e.delete(i),e.size===0&&this.#A.delete(o);let a=this.#e.get(o);return a||(a=new Map,this.#e.set(o,a)),a.set(i,t),SY(t)}release(t){if(t?.kind!==CQ)return;let o=Ag(t.origin.sessionId,t.origin.turn),i=EQ(t),e=this.#A.get(o);e?.get(i)===t&&e.delete(i),e?.size===0&&this.#A.delete(o),zn(t)}take(t,o,{signal:i}={}){let e=Ag(t,o),a=this.#e.get(e);if(this.#e.delete(e),!a)return[];if(i?.aborted){for(let s of a.values())zn(s);return[]}let A=this.#t.get(e)??new Map;this.#t.set(e,A);let r=[];for(let[s,g]of a)rg.has(g)&&(A.set(s,g),r.push(g));if(A.size===0)this.#t.delete(e);else if(!this.#l(e,i))return[];return r}discard(t,o){if(typeof t!="string"||!Number.isInteger(o))return;let i=Ag(t,o),e=new Set([...this.#e.get(i)?.values()??[],...this.#A.get(i)?.values()??[]]);this.#e.delete(i),this.#A.delete(i);for(let a of e)zn(a)}clear(){let t=new Set;for(let o of this.#e.values())for(let i of o.values())t.add(i);for(let o of this.#A.values())for(let i of o.values())t.add(i);for(let o of this.#t.values())for(let i of o.values())t.add(i);for(let o of t)zn(o);this.#e.clear(),this.#A.clear(),this.#t.clear();for(let o of this.#r.keys())this.#o(o);for(let o of this.#a.values())o.released=!0;this.#a.clear(),this.#n.clear(),this.#i.clear()}#l(t,o){if(!o)return!0;this.#o(t);let i=this.#g.get(o);return i||(i={turnKeys:new Set,onAbort:null},i.onAbort=()=>{for(let e of[...i.turnKeys])for(let a of this.#t.get(e)?.values()??[])zn(a)},this.#g.set(o,i),o.addEventListener("abort",i.onAbort,{once:!0})),i.turnKeys.add(t),this.#r.set(t,o),o.aborted?(i.onAbort(),!1):!0}#o(t){let o=this.#r.get(t);if(!o)return;this.#r.delete(t);let i=this.#g.get(o);i?.turnKeys.delete(t),i?.turnKeys.size===0&&(o.removeEventListener("abort",i.onAbort),this.#g.delete(o))}#s(t){let o=Ag(t.origin.sessionId,t.origin.turn),i=EQ(t),e=this.#e.get(o);e?.get(i)===t&&e.delete(i),e?.size===0&&this.#e.delete(o);let a=this.#A.get(o);a?.get(i)===t&&a.delete(i),a?.size===0&&this.#A.delete(o);let A=this.#t.get(o);A?.get(i)===t&&A.delete(i),A?.size===0&&(this.#t.delete(o),this.#o(o))}},wI=new i_;function ghe({registry:n=wI}={}){let t=new WeakMap,o=new Map,i=(A,r)=>{let s=o.get(A);s||(s={artifacts:[]},o.set(A,s)),s.artifacts.push(r)},e=Object.freeze({name:uQ,description:"Send a readable file or generated image to the user through the current conversation. Existing and newly created files are both valid.",parameters:{type:"object",additionalProperties:!1,properties:{path:{type:"string",description:"Absolute path, or a path relative to the current workspace."}},required:["path"]},output:{schema:{type:"object",additionalProperties:!1,properties:{artifactId:{type:"string"},fileName:{type:"string"},size:{type:"number"}},required:["artifactId","fileName","size"]},render:(A,r)=>[{type:"text",text:`Registered ${r.fileName} (${r.size} bytes) for IM delivery.`}]},async execute(A,r){let s=await n.stage(A,r);return t.set(r,s),SY(s)}});return Object.freeze({definition:e,onResult:(A,r)=>{if(A?.name===uQ){let g=t.get(A);if(!g)return;if(t.delete(A),r?.isError){n.release(g);return}A.parent===void 0?n.commit(g):i(A.parent,g);return}let s=o.get(A?.token);if(s){if(o.delete(A.token),r?.isError){for(let g of s.artifacts)n.release(g);return}if(A.parent!==void 0){for(let g of s.artifacts)i(A.parent,g);return}for(let g of s.artifacts)n.commit(g)}}})}function o_(n,{registry:t=wI}={}){if(typeof n?.tools?.register!="function"||typeof n?.systemPrompt?.section!="function"||typeof n?.on!="function")return!1;let o=ghe({registry:t});return n.tools.register(o.definition),n.on("tools/result",o.onResult),n.on("session/event",(i,e)=>t.observeSessionEvent(i,e)),n.on("session/disposed",i=>t.disposeSession(i)),n.systemPrompt.section({name:"dsh-im:return-file",order:115,text:`When the user asks to receive a file or generated image, call ${uQ} with its path. Existing files can be sent directly; do not recreate or rename a file solely for delivery.`}),!0}async function wY(n,{signal:t}={}){if(t?.aborted&&(zn(n),t.throwIfAborted()),n?.kind!==CQ||n.schemaVersion!==1||!rg.has(n)||typeof n.digest!="string"||!Number.isSafeInteger(n.size)||n.size<0)throw tg("artifact-invalid","The file registration is invalid.");let o=rg.get(n);o.materializing+=1;let i,e=!1;try{let a=Number.isInteger(NE.O_NOFOLLOW)?NE.O_NOFOLLOW:0;i=await fY(o.path,NE.O_RDONLY|a);let A=await i.stat({bigint:!0});if(!A.isFile()||A.size!==BigInt(n.size))throw tg("artifact-invalid","The file registration is invalid.");let r=await nhe(i,n.size,{signal:t,errorCode:"artifact-invalid",errorMessage:"The file registration is invalid."}),s=await i.stat({bigint:!0});if(!ihe(A,s)||r.byteLength!==n.size||ahe(r)!==n.digest)throw tg("artifact-invalid","The file registration is invalid.");t?.throwIfAborted(),e=!0;let g=Object.freeze({artifactId:n.artifactId,deliveryKey:n.deliveryKey,fileName:n.fileName,mediaType:n.mediaType,size:n.size,bytes:r});return mY.set(g,n),o.materialized=!0,g}catch(a){throw a?.code?.startsWith?.("artifact-")?a:t?.aborted?t.reason??a:tg("artifact-invalid","The file registration is invalid.")}finally{await i?.close().catch(()=>{}),o.materializing-=1,(!e||o.cleanupRequested)&&zn(n)}}function ln(n,t){let o=mY.get(n);if(!o||!rg.has(o)||!t||typeof t.then!="function")return t;let i=RE.get(o)??new Set,e=Promise.resolve(t).then(()=>{},()=>{});return i.add(e),RE.set(o,i),e.finally(()=>{i.delete(e),i.size===0&&RE.delete(o)}),t}function n_(n){let t=rg.get(n);t&&(t.releaseRequested=!0),zn(n)}var che=new Set(["sent","rejected","failed","unknown"]),Ihe=new Set(["sent","failed","unknown"]),lhe=new Set(["plain","markdown"]),phe=new Set(["artifact-changed","artifact-context-required","artifact-empty","artifact-invalid","artifact-not-file","artifact-permission-required","artifact-provider-rejected","artifact-too-large","artifact-unavailable"]);function ka(n){if(!n||typeof n!="object")return[];let t=Array.isArray(n.providerMessageIds)?n.providerMessageIds.filter(e=>typeof e=="string"&&e.trim()||Number.isSafeInteger(e)).map(String):[],i=[n.message_id,n.messageId,n.id,n.ts,n.message?.message_id,n.message?.messageId,n.message?.id,n.message?.ts,n.key?.id,n.data?.message_id,n.body?.msgid,n.body?.message_id].find(e=>typeof e=="string"&&e.trim()||Number.isSafeInteger(e));return i!==void 0&&t.push(String(i)),[...new Set(t)]}function Dp(n,t){if(typeof n!="string"||!n.trim())throw new TypeError(`${t} must be a non-empty string`);return n}function Vn(n,t="plain"){let o=typeof n=="string"?{kind:"text",text:n,format:t}:n;if(!o||typeof o!="object"||Array.isArray(o)||o.kind!=="text"||typeof o.text!="string"||!o.text.trim())throw new TypeError("text delivery block must contain non-empty text");if(!lhe.has(o.format))throw new TypeError("text delivery format must be plain or markdown");return Object.freeze({kind:"text",text:o.text,format:o.format})}function dhe(n){if(!Array.isArray(n))throw new TypeError("providerMessageIds must be an array");let t=[],o=new Set;for(let i of n){let e=Dp(i,"providerMessageId");o.has(e)||(o.add(e),t.push(e))}return Object.freeze(t)}function hhe(n){if(!Array.isArray(n))throw new TypeError("artifacts must be an array");return Object.freeze(n.map(t=>{if(!t||typeof t!="object")throw new TypeError("artifact result must be an object");let o=Dp(t.artifactId,"artifactId");if(!che.has(t.outcome))throw new TypeError("artifact outcome must be sent, rejected, failed, or unknown");let i=t.reason===void 0?void 0:Dp(t.reason,"artifact reason");return Object.freeze({artifactId:o,outcome:t.outcome,...i===void 0?{}:{reason:i}})}))}function Ehe(n){let t=typeof n=="string"?n:n?.code;return t==="artifact-delivery-uncertain"?"unknown":phe.has(t)?"rejected":"failed"}function Zt({deliveryId:n,presentation:t,providerMessageIds:o=[],artifacts:i=[],deliveryOutcome:e,reason:a}){if(e!==void 0&&!Ihe.has(e))throw new TypeError("deliveryOutcome must be sent, failed, or unknown");let A=a===void 0?void 0:Dp(a,"delivery reason");return Object.freeze({schemaVersion:1,deliveryId:Dp(n,"deliveryId"),presentation:Dp(t,"presentation"),providerMessageIds:dhe(o),...e===void 0?{}:{deliveryOutcome:e},...A===void 0?{}:{reason:A},artifacts:hhe(i)})}function DY({artifactId:n,deliveryId:t,error:o,presentation:i="text-fallback",providerMessageIds:e=[]}){let a=typeof o=="string"?o:o?.code,A=typeof a=="string"&&a?a:"artifact-provider-failed";return Zt({deliveryId:t,presentation:i,providerMessageIds:e,artifacts:[{artifactId:n,outcome:Ehe(o),reason:A}]})}function OY({deliveryId:n,presentation:t,receipts:o}){if(!Array.isArray(o)||o.length===0)throw new TypeError("receipts must contain at least one delivery receipt");let i=[],e=new Map,a,A;for(let r of o){if(!r||r.schemaVersion!==1)throw new TypeError("receipt must use DeliveryReceipt schema version 1");i.push(...r.providerMessageIds??[]),a===void 0&&r.deliveryOutcome!==void 0&&(a=r.deliveryOutcome,A=r.reason);for(let s of r.artifacts??[])e.set(s.artifactId,s)}return Zt({deliveryId:n,presentation:t,providerMessageIds:i,deliveryOutcome:a,reason:A,artifacts:[...e.values()]})}function Che(){let n=new Error("Native file delivery is unavailable");return n.code="artifact-provider-unavailable",n}function s_(n,t){return t?.aborted||n?.name==="AbortError"||n?.code==="ABORT_ERR"}function bY(n){return Array.isArray(n)?[...new Set(n.filter(t=>typeof t=="string"&&t.trim()||Number.isSafeInteger(t)).map(String))]:ka(n)}async function uhe(n,{sendFile:t,sendImage:o,signal:i}){if(n.mediaType?.startsWith("image/")&&typeof o=="function")try{return{presentation:"image",result:await o(n)}}catch(e){if(s_(e,i)||e?.code==="artifact-delivery-uncertain")throw e}if(i?.throwIfAborted(),typeof t!="function")throw Che();return{presentation:"file",result:await t(n)}}async function bo({artifacts:n=[],baseReceipt:t=null,deliveryId:o,aggregatePresentation:i,alwaysMerge:e=!1,channelKey:a,signal:A,sendFile:r,sendImage:s,sendFailureNotice:g,onFailure:c,logger:I}){let d=t?[t]:[],B=!!t&&t.deliveryOutcome!=="failed",f=!1,Q=0,y=0,m=0;try{for(;m0&&(_=OY({deliveryId:o??t?.deliveryId??n[0]?.deliveryKey,presentation:i??`${a}-${t?"text-and-files":"files"}`,receipts:d})),{receipt:_,userVisible:B,failureNoticeVisible:f,artifactsSent:Q,artifactSendErrors:y}}var Bhe="\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026",g_="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",fhe=["\u9489\u9489\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002","","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B","/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7","/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]","/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset","/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset","\u7EAF\u6570\u5B57 ID\uFF1A/preset id:","/preset --default \u8DDF\u968F Host \u9ED8\u8BA4","/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1","/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1","/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09","/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21","/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C","/help \u663E\u793A\u672C\u5E2E\u52A9"];function Qhe(){return fhe.map(n=>w(n)).join(` +${o}`:o}function Oo(n){return n instanceof Do?n.userMessage:null}import{createHash as uY,randomUUID as BY}from"node:crypto";import{constants as NE}from"node:fs";import{copyFile as Jde,lstat as pY,mkdtemp as qde,open as fY,realpath as zde,unlink as QY}from"node:fs/promises";import{tmpdir as Vde}from"node:os";import{basename as Wde,extname as Zde,isAbsolute as Xde,join as yY,resolve as $de}from"node:path";var uQ="dsh_im_return_file",CQ="dsh-im-outbound-artifact",a_=64*1024,ehe=new Map([[".csv","text/csv"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".gif","image/gif"],[".html","text/html"],[".jpeg","image/jpeg"],[".jpg","image/jpeg"],[".json","application/json"],[".md","text/markdown"],[".pdf","application/pdf"],[".png","image/png"],[".rar","application/vnd.rar"],[".txt","text/plain"],[".webp","image/webp"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".xml","application/xml"],[".zip","application/zip"]]),rg=new WeakMap,mY=new WeakMap,RE=new WeakMap,dY;function Ahe(){return dY??=qde(yY(Vde(),"dsh-im-outbound-")),dY}function tg(n,t){let o=new Error(t);return o.code=n,o}function hY(n){let t=n?.session?.events;if(!Array.isArray(t))return null;let o=null;for(let i of t)i?.type==="turn/start"?o=Number.isInteger(i.data?.turn)?i.data.turn:null:i?.type==="turn/end"&&i.data?.turn===o&&(o=null);return Number.isInteger(o)&&o>=0?o:null}function EY(n){let t=n?.id??n?.header?.id;return typeof t=="string"&&t?t:null}function Ag(n,t){return`${n}\0${t}`}function CY(n,t){return`${n}\0${t}`}function the(n){let t=String(n??"").replace(/[\u0000-\u001f\u007f]/g," ").replace(new RegExp("\\p{Cf}","gu"),"").replace(/\s+/g," ").trim();return t?[...t].slice(0,255).join(""):"result.bin"}function rhe(n){return ehe.get(Zde(n).toLowerCase())??"application/octet-stream"}function ahe(n){return uY("sha256").update(n).digest("hex")}function ihe(n,t){return typeof n?.dev=="bigint"&&typeof n?.ino=="bigint"&&typeof n?.size=="bigint"&&typeof n?.mtimeNs=="bigint"&&typeof n?.ctimeNs=="bigint"&&n.dev===t?.dev&&n.ino===t?.ino&&n.size===t?.size&&n.mtimeNs===t?.mtimeNs&&n.ctimeNs===t?.ctimeNs}async function ohe(n,t){let o;try{o=await fY(n,NE.O_RDONLY);let i=uY("sha256"),e=o.createReadStream({autoClose:!1,highWaterMark:a_,...t?{signal:t}:{}});for await(let a of e)t?.throwIfAborted(),i.update(a);return i.digest("hex")}finally{await o?.close().catch(()=>{})}}async function nhe(n,t,{signal:o,errorCode:i="artifact-changed",errorMessage:e="The result file changed while it was being read."}={}){let a=()=>tg(i,e);if(!Number.isSafeInteger(t)||t<0)throw a();o?.throwIfAborted();let A;try{A=Buffer.allocUnsafe(t)}catch{throw a()}if(typeof n?.createReadStream=="function"){let g=n.createReadStream({autoClose:!1,start:0,end:t,highWaterMark:a_,...o?{signal:o}:{}}),c=0;for await(let I of g){o?.throwIfAborted();let d=Buffer.isBuffer(I)?I:Buffer.from(I);if(c+d.length>t)throw a();d.copy(A,c),c+=d.length}if(c!==t)throw a();return A}let r=0;for(;rg)throw a();r+=I}o?.throwIfAborted();let s=Buffer.allocUnsafe(1);if((await n.read(s,0,1,t))?.bytesRead!==0)throw a();return A}async function she(n,t,o){o?.throwIfAborted();let i;try{let e=Xde(t)?t:$de(n,t),a=await zde(e);if(!(await pY(a,{bigint:!0})).isFile())throw tg("artifact-not-file","The requested path is not a file.");let r=await Ahe();i=yY(r,`${BY()}.artifact`),await Jde(a,i,NE.COPYFILE_EXCL),o?.throwIfAborted();let s=await pY(i,{bigint:!0}),g=Number(s.size);if(!s.isFile()||!Number.isSafeInteger(g)||g<0)throw tg("artifact-unavailable","The file could not be prepared for delivery.");let c=the(Wde(e));return Object.freeze({fileName:c,mediaType:rhe(c),size:g,digest:await ohe(i,o),storagePath:i})}catch(e){throw i&&await QY(i).catch(()=>{}),e?.code?.startsWith?.("artifact-")?e:o?.aborted?o.reason??e:tg("artifact-unavailable","The requested file is unavailable.")}}function SY(n){return Object.freeze({artifactId:n.artifactId,fileName:n.fileName,size:n.size})}function EQ(n){return n.artifactId}function zn(n){let t=rg.get(n);if(!t)return;if(t.releaseRequested=!0,t.materializing>0){t.cleanupRequested=!0;return}let o=[...RE.get(n)??[]];if(o.length>0){t.cleanupDeferred||(t.cleanupDeferred=!0,Promise.allSettled(o).finally(()=>{t.cleanupDeferred=!1,zn(n)}));return}rg.delete(n),RE.delete(n),t.onCleanup?.(),QY(t.path).catch(()=>{})}var i_=class{#e=new Map;#A=new Map;#t=new Map;#r=new Map;#g=new Map;#a=new Map;#n=new Map;#i=new Map;#I;constructor({uuid:t=BY}={}){if(typeof t!="function")throw new TypeError("uuid must be a function");this.#I=t}openConsumer(t,o){if(typeof t!="string"||!t||typeof o!="string"||!o)throw new TypeError("sessionId and promptRpcId are required");let i=CY(t,o),e={sessionId:t,promptRpcId:o,turn:null,released:!1};return this.#a.set(i,e),()=>{if(!e.released&&(e.released=!0,this.#a.get(i)===e&&this.#a.delete(i),e.turn!==null)){let a=Ag(t,e.turn);this.#n.get(a)===e&&this.#n.delete(a),this.discard(t,e.turn)}}}observeSessionEvent(t,o){let i=EY(t);if(!i||!o||typeof o!="object")return;if(o.type==="turn/start"){let A=o.data?.turn;Number.isInteger(A)&&A>=0&&this.#i.set(i,A);return}if(o.type==="user/message"){let A=o.data?.source?.rpcId,r=this.#i.get(i)??hY({session:t});if(typeof A!="string"||!A||!Number.isInteger(r))return;this.#i.set(i,r);let s=this.#a.get(CY(i,A));if(!s||s.released)return;s.turn=r,this.#n.set(Ag(i,r),s);return}if(o.type!=="turn/end")return;let e=o.data?.turn;if(!Number.isInteger(e)||e<0)return;this.#i.get(i)===e&&this.#i.delete(i);let a=this.#n.get(Ag(i,e));(!a||a.released)&&this.discard(i,e)}disposeSession(t){let o=EY(t);if(!o)return;let i=`${o}\0`,e=new Set;for(let a of[this.#e,this.#A])for(let[A,r]of a)if(A.startsWith(i)){for(let s of r.values())e.add(s);a.delete(A)}for(let[a,A]of this.#a)a.startsWith(i)&&(A.released=!0,this.#a.delete(a));for(let a of this.#n.keys())a.startsWith(i)&&this.#n.delete(a);this.#i.delete(o);for(let a of e)zn(a)}async stage(t,o){let i=t?.path;if(typeof i!="string"||!i.trim())throw new TypeError("A file path is required.");let e=o?.agent,a=e?.session?.header?.id,A=e?.session?.header?.cwd,r=hY(e);if(typeof a!="string"||!a||typeof A!="string"||!A||r===null)throw tg("artifact-context-required","A live Harness Session is required to return a file.");let s=await she(A,i,o?.signal),{storagePath:g,...c}=s,I=Object.freeze({kind:CQ,schemaVersion:1,artifactId:this.#I(),deliveryKey:this.#I(),...c,source:"managed-temp",registeredBy:Object.freeze({kind:"tool-result",eventId:typeof o?.callId=="string"?o.callId:"unknown",toolName:uQ}),origin:Object.freeze({sessionId:a,turn:r,callId:typeof o?.callId=="string"?o.callId:null}),createdAt:Date.now()});rg.set(I,{path:g,materializing:0,materialized:!1,releaseRequested:!1,cleanupRequested:!1,cleanupDeferred:!1,onCleanup:()=>this.#s(I)});let d=Ag(a,r),B=this.#A.get(d);return B||(B=new Map,this.#A.set(d,B)),B.set(EQ(I),I),I}commit(t){if(t?.kind!==CQ||!rg.has(t))return null;let o=Ag(t.origin.sessionId,t.origin.turn),i=EQ(t),e=this.#A.get(o);if(e?.get(i)!==t)return null;e.delete(i),e.size===0&&this.#A.delete(o);let a=this.#e.get(o);return a||(a=new Map,this.#e.set(o,a)),a.set(i,t),SY(t)}release(t){if(t?.kind!==CQ)return;let o=Ag(t.origin.sessionId,t.origin.turn),i=EQ(t),e=this.#A.get(o);e?.get(i)===t&&e.delete(i),e?.size===0&&this.#A.delete(o),zn(t)}take(t,o,{signal:i}={}){let e=Ag(t,o),a=this.#e.get(e);if(this.#e.delete(e),!a)return[];if(i?.aborted){for(let s of a.values())zn(s);return[]}let A=this.#t.get(e)??new Map;this.#t.set(e,A);let r=[];for(let[s,g]of a)rg.has(g)&&(A.set(s,g),r.push(g));if(A.size===0)this.#t.delete(e);else if(!this.#l(e,i))return[];return r}discard(t,o){if(typeof t!="string"||!Number.isInteger(o))return;let i=Ag(t,o),e=new Set([...this.#e.get(i)?.values()??[],...this.#A.get(i)?.values()??[]]);this.#e.delete(i),this.#A.delete(i);for(let a of e)zn(a)}clear(){let t=new Set;for(let o of this.#e.values())for(let i of o.values())t.add(i);for(let o of this.#A.values())for(let i of o.values())t.add(i);for(let o of this.#t.values())for(let i of o.values())t.add(i);for(let o of t)zn(o);this.#e.clear(),this.#A.clear(),this.#t.clear();for(let o of this.#r.keys())this.#o(o);for(let o of this.#a.values())o.released=!0;this.#a.clear(),this.#n.clear(),this.#i.clear()}#l(t,o){if(!o)return!0;this.#o(t);let i=this.#g.get(o);return i||(i={turnKeys:new Set,onAbort:null},i.onAbort=()=>{for(let e of[...i.turnKeys])for(let a of this.#t.get(e)?.values()??[])zn(a)},this.#g.set(o,i),o.addEventListener("abort",i.onAbort,{once:!0})),i.turnKeys.add(t),this.#r.set(t,o),o.aborted?(i.onAbort(),!1):!0}#o(t){let o=this.#r.get(t);if(!o)return;this.#r.delete(t);let i=this.#g.get(o);i?.turnKeys.delete(t),i?.turnKeys.size===0&&(o.removeEventListener("abort",i.onAbort),this.#g.delete(o))}#s(t){let o=Ag(t.origin.sessionId,t.origin.turn),i=EQ(t),e=this.#e.get(o);e?.get(i)===t&&e.delete(i),e?.size===0&&this.#e.delete(o);let a=this.#A.get(o);a?.get(i)===t&&a.delete(i),a?.size===0&&this.#A.delete(o);let A=this.#t.get(o);A?.get(i)===t&&A.delete(i),A?.size===0&&(this.#t.delete(o),this.#o(o))}},wI=new i_;function ghe({registry:n=wI}={}){let t=new WeakMap,o=new Map,i=(A,r)=>{let s=o.get(A);s||(s={artifacts:[]},o.set(A,s)),s.artifacts.push(r)},e=Object.freeze({name:uQ,description:"Send a readable file or generated image to the user through the current conversation. Existing and newly created files are both valid.",parameters:{type:"object",additionalProperties:!1,properties:{path:{type:"string",description:"Absolute path, or a path relative to the current workspace."}},required:["path"]},output:{schema:{type:"object",additionalProperties:!1,properties:{artifactId:{type:"string"},fileName:{type:"string"},size:{type:"number"}},required:["artifactId","fileName","size"]},render:(A,r)=>[{type:"text",text:`Registered ${r.fileName} (${r.size} bytes) for IM delivery.`}]},async execute(A,r){let s=await n.stage(A,r);return t.set(r,s),SY(s)}});return Object.freeze({definition:e,onResult:(A,r)=>{if(A?.name===uQ){let g=t.get(A);if(!g)return;if(t.delete(A),r?.isError){n.release(g);return}A.parent===void 0?n.commit(g):i(A.parent,g);return}let s=o.get(A?.token);if(s){if(o.delete(A.token),r?.isError){for(let g of s.artifacts)n.release(g);return}if(A.parent!==void 0){for(let g of s.artifacts)i(A.parent,g);return}for(let g of s.artifacts)n.commit(g)}}})}function o_(n,{registry:t=wI}={}){if(typeof n?.tools?.register!="function"||typeof n?.systemPrompt?.section!="function"||typeof n?.on!="function")return!1;let o=ghe({registry:t});return n.tools.register(o.definition),n.on("tools/result",o.onResult),n.on("session/event",(i,e)=>t.observeSessionEvent(i,e)),n.on("session/disposed",i=>t.disposeSession(i)),n.systemPrompt.section({name:"dsh-im:return-file",order:115,text:`When the user asks to receive a file or generated image, call ${uQ} with its path. Existing files can be sent directly; do not recreate or rename a file solely for delivery.`}),!0}async function wY(n,{signal:t}={}){if(t?.aborted&&(zn(n),t.throwIfAborted()),n?.kind!==CQ||n.schemaVersion!==1||!rg.has(n)||typeof n.digest!="string"||!Number.isSafeInteger(n.size)||n.size<0)throw tg("artifact-invalid","The file registration is invalid.");let o=rg.get(n);o.materializing+=1;let i,e=!1;try{let a=Number.isInteger(NE.O_NOFOLLOW)?NE.O_NOFOLLOW:0;i=await fY(o.path,NE.O_RDONLY|a);let A=await i.stat({bigint:!0});if(!A.isFile()||A.size!==BigInt(n.size))throw tg("artifact-invalid","The file registration is invalid.");let r=await nhe(i,n.size,{signal:t,errorCode:"artifact-invalid",errorMessage:"The file registration is invalid."}),s=await i.stat({bigint:!0});if(!ihe(A,s)||r.byteLength!==n.size||ahe(r)!==n.digest)throw tg("artifact-invalid","The file registration is invalid.");t?.throwIfAborted(),e=!0;let g=Object.freeze({artifactId:n.artifactId,deliveryKey:n.deliveryKey,fileName:n.fileName,mediaType:n.mediaType,size:n.size,bytes:r});return mY.set(g,n),o.materialized=!0,g}catch(a){throw a?.code?.startsWith?.("artifact-")?a:t?.aborted?t.reason??a:tg("artifact-invalid","The file registration is invalid.")}finally{await i?.close().catch(()=>{}),o.materializing-=1,(!e||o.cleanupRequested)&&zn(n)}}function ln(n,t){let o=mY.get(n);if(!o||!rg.has(o)||!t||typeof t.then!="function")return t;let i=RE.get(o)??new Set,e=Promise.resolve(t).then(()=>{},()=>{});return i.add(e),RE.set(o,i),e.finally(()=>{i.delete(e),i.size===0&&RE.delete(o)}),t}function n_(n){let t=rg.get(n);t&&(t.releaseRequested=!0),zn(n)}var che=new Set(["sent","rejected","failed","unknown"]),Ihe=new Set(["sent","failed","unknown"]),lhe=new Set(["plain","markdown"]),phe=new Set(["artifact-changed","artifact-context-required","artifact-empty","artifact-invalid","artifact-not-file","artifact-permission-required","artifact-provider-rejected","artifact-too-large","artifact-unavailable"]);function ka(n){if(!n||typeof n!="object")return[];let t=Array.isArray(n.providerMessageIds)?n.providerMessageIds.filter(e=>typeof e=="string"&&e.trim()||Number.isSafeInteger(e)).map(String):[],i=[n.message_id,n.messageId,n.id,n.ts,n.message?.message_id,n.message?.messageId,n.message?.id,n.message?.ts,n.key?.id,n.data?.message_id,n.body?.msgid,n.body?.message_id].find(e=>typeof e=="string"&&e.trim()||Number.isSafeInteger(e));return i!==void 0&&t.push(String(i)),[...new Set(t)]}function Dp(n,t){if(typeof n!="string"||!n.trim())throw new TypeError(`${t} must be a non-empty string`);return n}function Vn(n,t="plain"){let o=typeof n=="string"?{kind:"text",text:n,format:t}:n;if(!o||typeof o!="object"||Array.isArray(o)||o.kind!=="text"||typeof o.text!="string"||!o.text.trim())throw new TypeError("text delivery block must contain non-empty text");if(!lhe.has(o.format))throw new TypeError("text delivery format must be plain or markdown");return Object.freeze({kind:"text",text:o.text,format:o.format})}function dhe(n){if(!Array.isArray(n))throw new TypeError("providerMessageIds must be an array");let t=[],o=new Set;for(let i of n){let e=Dp(i,"providerMessageId");o.has(e)||(o.add(e),t.push(e))}return Object.freeze(t)}function hhe(n){if(!Array.isArray(n))throw new TypeError("artifacts must be an array");return Object.freeze(n.map(t=>{if(!t||typeof t!="object")throw new TypeError("artifact result must be an object");let o=Dp(t.artifactId,"artifactId");if(!che.has(t.outcome))throw new TypeError("artifact outcome must be sent, rejected, failed, or unknown");let i=t.reason===void 0?void 0:Dp(t.reason,"artifact reason");return Object.freeze({artifactId:o,outcome:t.outcome,...i===void 0?{}:{reason:i}})}))}function Ehe(n){let t=typeof n=="string"?n:n?.code;return t==="artifact-delivery-uncertain"?"unknown":phe.has(t)?"rejected":"failed"}function Zt({deliveryId:n,presentation:t,providerMessageIds:o=[],artifacts:i=[],deliveryOutcome:e,reason:a}){if(e!==void 0&&!Ihe.has(e))throw new TypeError("deliveryOutcome must be sent, failed, or unknown");let A=a===void 0?void 0:Dp(a,"delivery reason");return Object.freeze({schemaVersion:1,deliveryId:Dp(n,"deliveryId"),presentation:Dp(t,"presentation"),providerMessageIds:dhe(o),...e===void 0?{}:{deliveryOutcome:e},...A===void 0?{}:{reason:A},artifacts:hhe(i)})}function DY({artifactId:n,deliveryId:t,error:o,presentation:i="text-fallback",providerMessageIds:e=[]}){let a=typeof o=="string"?o:o?.code,A=typeof a=="string"&&a?a:"artifact-provider-failed";return Zt({deliveryId:t,presentation:i,providerMessageIds:e,artifacts:[{artifactId:n,outcome:Ehe(o),reason:A}]})}function OY({deliveryId:n,presentation:t,receipts:o}){if(!Array.isArray(o)||o.length===0)throw new TypeError("receipts must contain at least one delivery receipt");let i=[],e=new Map,a,A;for(let r of o){if(!r||r.schemaVersion!==1)throw new TypeError("receipt must use DeliveryReceipt schema version 1");i.push(...r.providerMessageIds??[]),a===void 0&&r.deliveryOutcome!==void 0&&(a=r.deliveryOutcome,A=r.reason);for(let s of r.artifacts??[])e.set(s.artifactId,s)}return Zt({deliveryId:n,presentation:t,providerMessageIds:i,deliveryOutcome:a,reason:A,artifacts:[...e.values()]})}function Che(){let n=new Error("Native file delivery is unavailable");return n.code="artifact-provider-unavailable",n}function s_(n,t){return t?.aborted||n?.name==="AbortError"||n?.code==="ABORT_ERR"}function bY(n){return Array.isArray(n)?[...new Set(n.filter(t=>typeof t=="string"&&t.trim()||Number.isSafeInteger(t)).map(String))]:ka(n)}async function uhe(n,{sendFile:t,sendImage:o,signal:i}){if(n.mediaType?.startsWith("image/")&&typeof o=="function")try{return{presentation:"image",result:await o(n)}}catch(e){if(s_(e,i)||e?.code==="artifact-delivery-uncertain")throw e}if(i?.throwIfAborted(),typeof t!="function")throw Che();return{presentation:"file",result:await t(n)}}async function bo({artifacts:n=[],baseReceipt:t=null,deliveryId:o,aggregatePresentation:i,alwaysMerge:e=!1,channelKey:a,signal:A,sendFile:r,sendImage:s,sendFailureNotice:g,onFailure:c,logger:I}){let d=t?[t]:[],B=!!t&&t.deliveryOutcome!=="failed",f=!1,Q=0,y=0,m=0;try{for(;m0&&(_=OY({deliveryId:o??t?.deliveryId??n[0]?.deliveryKey,presentation:i??`${a}-${t?"text-and-files":"files"}`,receipts:d})),{receipt:_,userVisible:B,failureNoticeVisible:f,artifactsSent:Q,artifactSendErrors:y}}var Bhe="\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026",g_="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",fhe=["\u9489\u9489\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002","","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B","/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7","/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]","/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset","/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset","\u7EAF\u6570\u5B57 ID\uFF1A/preset id:","/preset --default \u8DDF\u968F Host \u9ED8\u8BA4","/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1","/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1","/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09","/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21","/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C","/help \u663E\u793A\u672C\u5E2E\u52A9"];function Qhe(){return fhe.map(n=>w(n)).join(` `)}function mt(n){return typeof n=="string"&&n.trim()?n.trim():null}function yhe(n){let t=ka(n),o=mt(n?.processQueryKey);return o&&!t.includes(o)&&t.push(o),t}function BQ(n){let t=[],o=new Set,i=n;for(;i&&typeof i=="object"&&t.length<3&&!o.has(i);){o.add(i);let e=mt(i.name)?.slice(0,80),a=mt(i.code)?.slice(0,80),A=mt(i.providerCode)?.slice(0,160),r=Number.isInteger(i.status)?i.status:void 0;t.push({...e?{name:e}:{},...a?{code:a}:{},...A?{providerCode:A}:{},...r?{status:r}:{}}),i=i.cause}return t}function mhe(n){let t=n,o=new Set;for(;t&&typeof t=="object"&&!o.has(t);){if(o.add(t),t.code==="image-download-address-failed")return w("\u9489\u9489\u672A\u80FD\u6362\u53D6\u56FE\u7247\u4E0B\u8F7D\u5730\u5740\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\uFF1B\u82E5\u6301\u7EED\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u673A\u5668\u4EBA\u7684\u201C\u4F01\u4E1A\u5185\u673A\u5668\u4EBA\u53D1\u9001\u6D88\u606F\u6743\u9650\u201D\u3002");if(t.code==="invalid-image-download")return w("\u9489\u9489\u6CA1\u6709\u8FD4\u56DE\u56FE\u7247\u4E0B\u8F7D\u5730\u5740\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002");if(t.code==="image-content-download-failed")return w("\u9489\u9489\u8FD4\u56DE\u7684\u56FE\u7247\u4E34\u65F6\u5730\u5740\u65E0\u6CD5\u8BFB\u53D6\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002");t=t.cause}return fo(n)}function MY(n){return mt(n?.senderStaffId)??mt(n?.senderId)}function She(n){if(n?.content&&typeof n.content=="object")return n.content;if(typeof n?.content!="string")return null;try{let t=JSON.parse(n.content);return t&&typeof t=="object"?t:null}catch{return null}}function whe(n){let t=n?.richText??n?.rich_text;return Array.isArray(t)?t:[]}function Dhe(n){return typeof n?.text=="string"?mt(n.text):typeof n?.text?.content=="string"?mt(n.text.content):String(n?.type).toLowerCase()==="text"&&typeof n?.content=="string"?mt(n.content):null}function c_(n){return mt(n?.downloadCode)??mt(n?.pictureDownloadCode)}function I_(n,{api:t,clientId:o,clientSecret:i}={}){let e=String(n?.msgtype??"").toLowerCase(),a=She(n),A=e==="richtext"?whe(a):[],r=e==="text"?mt(n?.text?.content)??"":A.map(Dhe).filter(Boolean).join(` -`),s=[];if(e==="picture"){let c=c_(a);c&&s.push(c)}else if(e==="richtext")for(let c of A){if(String(c?.type??"").toLowerCase()!=="picture")continue;let I=c_(c);I&&s.push(I)}let g=e==="file"?c_(a):null;return{content:r,images:s.map((c,I)=>({name:I===0?"image":`image-${I+1}`,load:({signal:d,maxBytes:B})=>{if(typeof t?.downloadImage!="function")throw new Error("DingTalk API does not support image downloads");return t.downloadImage({clientId:o,clientSecret:i,robotCode:n?.robotCode,downloadCode:c,signal:d,maxBytes:B})}})),files:g?[{name:mt(a?.fileName??a?.file_name)??"file",load:({signal:c}={})=>{if(typeof t?.downloadFile!="function")throw new Error("DingTalk API does not support file downloads");return t.downloadFile({clientId:o,clientSecret:i,robotCode:n?.robotCode,downloadCode:g,signal:c})}}]:[]}}function Ohe(n,t){if(String(n?.conversationType)==="2"){let o=mt(n?.conversationId);if(!o)throw new Error("DingTalk group message has no conversation id");return`group:${o}`}return`p2p:${t}`}function bhe(n,t){return String(n?.conversationType)==="2"?{type:"group",openConversationId:mt(n?.conversationId),atUserIds:{[t]:mt(n?.senderNick)??t}}:{type:"user",userId:t}}function Mhe(n,t,o){let i=mt(n?.robotCode)??o;return String(n?.conversationType)==="2"?{type:"group",openConversationId:mt(n?.conversationId),robotCode:i}:{type:"user",userId:t,robotCode:i}}function _he(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u9489\u9489\u5E94\u7528\u6216\u673A\u5668\u4EBA\u7F3A\u5C11\u6587\u4EF6\u6D88\u606F\u6743\u9650\u3002\u8BF7\u5F00\u901A\u5E94\u7528 qyapi_base \u6743\u9650\uFF0C\u5E76\u786E\u8BA4\u673A\u5668\u4EBA\u5177\u5907\u6587\u4EF6\u6D88\u606F\u53D1\u9001\u80FD\u529B\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u9489\u9489\u673A\u5668\u4EBA\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u9489\u9489\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u9489\u9489\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6D88\u606F\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u7C7B\u578B\u548C\u673A\u5668\u4EBA\u6587\u4EF6\u6D88\u606F\u914D\u7F6E\u3002",{name:o});case"artifact-invalid":case"artifact-changed":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7\u9489\u9489\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function The(n){return n?.type==="text"&&mt(n.text)?n.text:n?.type==="tool"?n.name==="web_search"?w("_\u6B63\u5728\u641C\u7D22\u7F51\u7EDC\u5E76\u6574\u7406\u4FE1\u606F\u2026_"):w("_\u6B63\u5728\u4F7F\u7528 {name}\u2026_",{name:mt(n.name)??w("\u5DE5\u5177")}):w("_{text}_",{text:mt(n?.text)??w("\u6B63\u5728\u5904\u7406\u2026")})}function Nhe(n,t,o){if(t.needsPresentation||!t.questions[t.index]||t.actor!==o||String(n?.conversationType)==="2"&&n?.isInAtList!==!0||n?.msgtype!=="text"||!mt(n?.text?.content))return!1;try{return tc(n.sessionWebhook),!0}catch{return!1}}function Rhe(n){n.stats??={};for(let t of["messagesReceived","messagesReplied","messagesRejected","messagesIgnored","reactionsAdded","reactionsRemoved","reactionErrors"])n[t]??=0,n.stats[t]=n[t];n.pendingSenders??=[]}function va(n,t){n[t]=(n[t]??0)+1,n.stats??={},n.stats[t]=n[t]}function l_({pendingSenders:n=[]}={}){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,messagesIgnored:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null,pendingSenders:structuredClone(n),stats:{messagesReceived:0,messagesReplied:0,messagesRejected:0,messagesIgnored:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0}}}var fQ=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c=new Map;#p=new Map;#d=new Map;#h=new Set;#E=new Set;#C=new Map;#f;#B=new mi;constructor({api:t,clientId:o,clientSecret:i,harness:e,state:a,contextEnhancement:A,status:r=l_(),logger:s=console,replyTimeoutMs:g=6e5,reactionTimeoutMs:c=5e3,maxMessageChars:I=4e3,signal:d}){if(!t||typeof t.sendText!="function")throw new TypeError("DingTalk API is required");if(!mt(o)||!mt(i))throw new TypeError("DingTalk app credentials are required");if(!e||!a)throw new TypeError("Harness client and state store are required");this.#e=t,this.#A=o.trim(),this.#t=i.trim(),this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#f=new Ci({label:"DingTalk",logger:s}),this.#I=g,this.#l=Number.isFinite(c)&&c>0?Math.floor(c):5e3,this.#o=I,this.#s=d,Rhe(this.#n),this.#v()}get status(){return this.#v(),structuredClone(this.#n)}accept(t,{contextSnapshot:o}={}){if(this.#s?.aborted)return Promise.resolve();let i=mt(t?.msgId),e=MY(t);if(!i||!e||this.#g.hasSeen(i)||this.#C.has(i))return Promise.resolve();this.#C.set(i,o===void 0?Xr(this.#a,t.conversationType==="1"||t.conversationType===1?"direct":t.conversationType==="2"||t.conversationType===2?"group":null):o);let a;try{a=Ohe(t,e)}catch{return this.#C.delete(i),va(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),Promise.resolve()}let A=null;try{A=tc(t.sessionWebhook)}catch{}A&&String(t.conversationType)!=="2"&&Eo(this.#g,{sessionWebhook:A});let r=this.#p.get(a),s=I_(t,{api:this.#e,clientId:this.#A,clientSecret:this.#t}),g=mt(s.content)??"",c=String(t.conversationType)!=="2"||t?.isInAtList===!0,I=String(t.conversationType)!=="2",d=A&&c?this.#S(t):null,B=_=>Promise.resolve(_).then(T=>(this.#Q(d,this.#s?.aborted?"clear":"success"),T),T=>{throw this.#Q(d,this.#s?.aborted||T?.name==="AbortError"||T?.code==="turn-stopped"?"clear":"error"),T}),f=String(t?.msgtype).toLowerCase()==="text"&&So(g),Q=this.#B.status(a);if(f&&!I&&A&&c)return B(this.#b(i,A,{message:qn()},d));if(I&&A&&(f||Q.phase==="collecting")){let T=/^\/batch$/iu.test(g)&&Q.phase==="idle"&&(this.#c.has(a)||r||this.#f.hasPending(a))?{handled:!0,kind:"busy",message:wo()}:this.#B.handle(a,g,{plainText:!!g&&String(t?.msgtype).toLowerCase()==="text"&&!Lt(s)&&!Wt(s)});if(T.handled)return T.kind==="submit"?B(this.#m({...t,msgtype:"text",text:{content:T.prompt}},i,e,a,{batchSubmission:T,statusReaction:d})):B(this.#b(i,A,T,d))}let y=fi(g)?qi:Lt(s)?null:zi(g)?Qi:Vi(g)?Wi:Zi(g)?yi:null;if(y&&A&&c){let _;return _=this.#u(t,i,a,A,s,y).catch(T=>{if(T?.code==="turn-stopped"||this.#s?.aborted){this.#Q(d,"clear");return}this.#Q(d,"error"),this.#n.lastError=T?.message??String(T);let R=tt(this.#n,T);return this.#i.error?.(`[dsh-dingtalk] failed to process a command [${R.referenceId}]`,BQ(T)),this.#N(A,dt(R),this.#P(t)).catch(()=>{})}).finally(()=>{this.#C.delete(i),this.#E.delete(_)}),this.#E.add(_),B(_)}let m=this.#f.claimReply({key:a,actor:e,messageId:i,text:A&&t?.msgtype==="text"?mt(t?.text?.content)??"":"",addressed:String(t?.conversationType)!=="2"||t?.isInAtList===!0,hasPendingQuestion:!!r,questionCompletion:r?.submitting||r?.claimedReplyMessageId?r.queue:null,isQuestionPending:()=>this.#p.has(a),send:A?_=>this.#N(A,_,this.#P(t)):async()=>{}});if(m){let _;return _=m.process(async()=>this.#g.hasSeen(i)?!1:(await this.#g.markSeen(i),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString(),A||(va(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),this.#n.lastError=w("\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002")),!0)).catch(T=>{if(this.#s?.aborted){this.#Q(d,"clear");return}this.#Q(d,"error"),this.#n.lastError=w("\u9489\u9489\u5BA1\u6279\u5904\u7406\u5931\u8D25\u3002"),this.#i.error?.("[dsh-dingtalk] failed to process an approval reply",T)}).finally(()=>{this.#C.delete(i),this.#h.delete(_)}),this.#h.add(_),B(_)}if(r&&r.actor!==e)return B(this.#m(t,i,e,a,{statusReaction:d}));if(r?.submitting||r?.claimedReplyMessageId)return B(this.#m(t,i,e,a,{statusReaction:d}));if(r){Nhe(t,r,e)&&(r.claimedReplyMessageId=i);let T=(r.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#D(t,i,e,a,r,d)).finally(()=>{this.#C.delete(i),r.claimedReplyMessageId===i&&(r.claimedReplyMessageId=null),r.queue===T&&(r.queue=null)});return r.queue=T,B(T)}return B(this.#m(t,i,e,a,{statusReaction:d}))}#y(t,o,i,e){let a=new AbortController,A=Promise.resolve().then(()=>this.#e[t]({clientId:this.#A,clientSecret:this.#t,...o,reactionName:i,signal:a.signal})),r,s=new Promise((g,c)=>{r=setTimeout(()=>{let I=new DOMException("DingTalk reaction timed out","TimeoutError");a.abort(I),c(I)},this.#l),r.unref?.()});return Promise.race([A,s]).then(()=>(va(this.#n,e==="add"?"reactionsAdded":"reactionsRemoved"),!0)).catch(g=>(va(this.#n,"reactionErrors"),this.#i.debug?.(`[dsh-dingtalk] ${t} failed`,BQ(g)),!1)).finally(()=>clearTimeout(r))}#S(t){if(typeof this.#e.addReaction!="function"||typeof this.#e.recallReaction!="function")return null;let o=mt(t?.msgId),i=mt(t?.conversationId);if(!o||!i)return null;let e={messageId:o,conversationId:i,robotCode:mt(t?.robotCode)??this.#A};return{target:e,attached:this.#y("addReaction",e,yI,"add"),terminal:!1}}#Q(t,o){if(!t||t.terminal)return;t.terminal=!0;let i=o==="success"?cx:o==="error"?Ix:null;t.attached.then(async e=>{let a=await this.#y("recallReaction",t.target,yI,"remove");(!e||!a)&&(await new Promise(A=>{setTimeout(A,Math.min(1e3,this.#l)).unref?.()}),a=await this.#y("recallReaction",t.target,yI,"remove")||a),!(!a||!i||this.#s?.aborted)&&await this.#y("addReaction",t.target,i,"add")}).catch(()=>{})}#m(t,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1,batchSubmission:r=null,statusReaction:s=null}={}){let g=!1;try{tc(t.sessionWebhook),g=!0}catch{}let c=String(t.conversationType)!=="2"||t.isInAtList===!0,I=g&&c?wp(I_(t,{api:this.#e,clientId:this.#A,clientSecret:this.#t}),{signal:this.#s}):void 0,B=(this.#c.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#R(t,o,i,e,{alreadyRecorded:A,preparedMessage:I,batchSubmission:r,statusReaction:s})).finally(()=>{a&&this.#C.delete(o),this.#c.get(e)===B&&this.#c.delete(e)});return this.#c.set(e,B),B}async waitForIdle(){await Promise.allSettled([...this.#c.values(),...[...this.#p.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#h,...this.#E])}async#u(t,o,i,e,a,A){if(this.#s?.throwIfAborted(),this.#g.hasSeen(o))return;await this.#g.markSeen(o),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString();let r=await A(mt(a.content)??"",this.#r,this.#g,i,{signal:this.#s,isDirect:String(t.conversationType)==="1",hasImages:Wt(a),hasFiles:Lt(a),pendingInteraction:this.#p.has(i)||this.#f.hasPending(i),control:{owner:this,key:i}});r?.stopped&&await Promise.allSettled([this.#U(i),this.#f.closeRoute(i)]);for(let s of r?.messages??[r?.message])s&&await this.#N(e,s,this.#P(t));this.#n.lastError=null}#b(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#g.hasSeen(t)||(await this.#g.markSeen(t),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString(),i.message&&await this.#N(o,i.message),this.#n.lastError=null)}).catch(async A=>{if(this.#s?.aborted){this.#Q(e,"clear");return}this.#Q(e,"error"),this.#n.lastError=A?.message??String(A);let r=tt(this.#n,A);this.#i.error?.(`[dsh-dingtalk] failed to process a batch input message [${r.referenceId}]`,BQ(A)),await this.#N(o,dt(r)).catch(()=>{})}).finally(()=>{this.#C.delete(t),this.#E.delete(a)}),this.#E.add(a),a}async#R(t,o,i,e,{alreadyRecorded:a=!1,preparedMessage:A,batchSubmission:r=null,statusReaction:s=null}={}){if(this.#s?.throwIfAborted(),!a){if(this.#g.hasSeen(o))return;await this.#g.markSeen(o),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString()}if(String(t.conversationType)==="2"&&t.isInAtList!==!0){va(this.#n,"messagesIgnored");return}let g;try{g=tc(t.sessionWebhook)}catch{va(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),this.#n.lastError=w("\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002");return}let c=A??I_(t,{api:this.#e,clientId:this.#A,clientSecret:this.#t}),I=c.content,d=Wt(c),B=Lt(c),f=String(t?.msgtype).toLowerCase()==="text",Q=null,y=!1,m=r===null;try{if(!I&&!d&&!B){await this.#N(g,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002"),this.#P(t));return}let _=I.toLowerCase();if(f&&!d&&!B&&_==="/help"){await this.#N(g,Qhe(),this.#P(t));return}if(f&&!d&&!B&&_==="/status"){await this.#r.ensureRunning({signal:this.#s}),await this.#N(g,w("\u9489\u9489\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),this.#P(t));return}if(f&&!d&&!B&&_==="/new"){await this.#g.clearSession(e),await this.#N(g,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),this.#P(t));return}let T=f&&!d&&!B?await Qo(I,this.#r,e):null;if(T){for(let N of T.messages??[T.message])await this.#N(g,N,this.#P(t));return}let R=f&&!d&&!B?await Bi(I,this.#r,this.#g,e,{signal:this.#s}):null;if(R){await this.#N(g,R.message,this.#P(t));return}let F=d?await Bo(c,{signal:this.#s}):void 0,K=this.#C.get(o);K&&(F=mo(F??I,K,()=>({channel:"dingtalk",senderId:i,senderName:t.senderNick}))),typeof this.#e.createAiCard=="function"&&typeof this.#e.updateAiCard=="function"&&typeof this.#e.finishAiCard=="function"&&(Q=Ex({api:this.#e,clientId:this.#A,clientSecret:this.#t,target:bhe(t,i),signal:this.#s,logger:this.#i}),y=await Q.start(w(Bhe)));let{answer:L,artifacts:q=[]}=await ui({harness:this.#r,state:this.#g,key:e,...F!==void 0?{content:F}:{text:I},createOptions:{signal:this.#s},existsOptions:{signal:this.#s},askOptions:{timeoutMs:this.#I,signal:this.#s,control:{owner:this,key:e},onUpdate:y?N=>Q.push(The(N)):void 0,onInteraction:N=>this.#w(N,{key:e,actor:i,sessionWebhook:g,requiresMention:String(t.conversationType)==="2"}),onInteractionResolved:N=>this.#T(N),files:c.files}});r&&(this.#B.complete(e,r.token),m=!0);let z=typeof L=="string"&&L.trim()?L:q.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):L,j=null,P=null,J=!1;try{J=y&&await Q.finish(z),J?P=Zt({deliveryId:o,presentation:"dingtalk-card"}):P=Zt({deliveryId:o,presentation:"dingtalk-text",providerMessageIds:await this.#N(g,z,this.#P(t))})}catch(N){j=Ma(N)}let U=await this.#Y(Mhe(t,i,this.#A),g,o,q,P);if(j&&!U.userVisible)throw j;return j&&U.artifactSendErrors===0&&tt(this.#n,j),va(this.#n,"messagesReplied"),this.#n.lastReplyAt=new Date().toISOString(),this.#n.lastError=null,!j&&U.artifactSendErrors===0&&Co(this.#n),U.receipt}catch(_){let T=null;if(!m&&r&&(_?.code==="turn-stopped"?this.#B.complete(e,r.token):T=this.#B.fail(e,r.token).message??null,m=!0),_?.code==="turn-stopped"){this.#Q(s,"clear"),y&&await Q.finish(w("\u5DF2\u505C\u6B62\u3002")).catch(()=>{});return}if(this.#s?.aborted){this.#Q(s,"clear");return}this.#Q(s,"error"),this.#n.lastError=_?.message??String(_);let R=Oo(_)??mhe(_),F=tt(this.#n,_,{userMessage:R,reason:Ji(_)?.reason});this.#i.error?.(`[dsh-dingtalk] failed to process an inbound message [${F.referenceId}]`,BQ(_));try{let K=dt(F),L=T?`${K} +`),s=[];if(e==="picture"){let c=c_(a);c&&s.push(c)}else if(e==="richtext")for(let c of A){if(String(c?.type??"").toLowerCase()!=="picture")continue;let I=c_(c);I&&s.push(I)}let g=e==="file"?c_(a):null;return{content:r,images:s.map((c,I)=>({name:I===0?"image":`image-${I+1}`,load:({signal:d,maxBytes:B})=>{if(typeof t?.downloadImage!="function")throw new Error("DingTalk API does not support image downloads");return t.downloadImage({clientId:o,clientSecret:i,robotCode:n?.robotCode,downloadCode:c,signal:d,maxBytes:B})}})),files:g?[{name:mt(a?.fileName??a?.file_name)??"file",load:({signal:c}={})=>{if(typeof t?.downloadFile!="function")throw new Error("DingTalk API does not support file downloads");return t.downloadFile({clientId:o,clientSecret:i,robotCode:n?.robotCode,downloadCode:g,signal:c})}}]:[]}}function Ohe(n,t){if(String(n?.conversationType)==="2"){let o=mt(n?.conversationId);if(!o)throw new Error("DingTalk group message has no conversation id");return`group:${o}`}return`p2p:${t}`}function bhe(n,t){return String(n?.conversationType)==="2"?{type:"group",openConversationId:mt(n?.conversationId),atUserIds:{[t]:mt(n?.senderNick)??t}}:{type:"user",userId:t}}function Mhe(n,t,o){let i=mt(n?.robotCode)??o;return String(n?.conversationType)==="2"?{type:"group",openConversationId:mt(n?.conversationId),robotCode:i}:{type:"user",userId:t,robotCode:i}}function _he(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u9489\u9489\u5E94\u7528\u6216\u673A\u5668\u4EBA\u7F3A\u5C11\u6587\u4EF6\u6D88\u606F\u6743\u9650\u3002\u8BF7\u5F00\u901A\u5E94\u7528 qyapi_base \u6743\u9650\uFF0C\u5E76\u786E\u8BA4\u673A\u5668\u4EBA\u5177\u5907\u6587\u4EF6\u6D88\u606F\u53D1\u9001\u80FD\u529B\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u9489\u9489\u673A\u5668\u4EBA\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u9489\u9489\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u9489\u9489\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6D88\u606F\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u7C7B\u578B\u548C\u673A\u5668\u4EBA\u6587\u4EF6\u6D88\u606F\u914D\u7F6E\u3002",{name:o});case"artifact-invalid":case"artifact-changed":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7\u9489\u9489\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function The(n){return n?.type==="text"&&mt(n.text)?n.text:n?.type==="tool"?n.name==="web_search"?w("_\u6B63\u5728\u641C\u7D22\u7F51\u7EDC\u5E76\u6574\u7406\u4FE1\u606F\u2026_"):w("_\u6B63\u5728\u4F7F\u7528 {name}\u2026_",{name:mt(n.name)??w("\u5DE5\u5177")}):w("_{text}_",{text:mt(n?.text)??w("\u6B63\u5728\u5904\u7406\u2026")})}function Nhe(n,t,o){if(t.needsPresentation||!t.questions[t.index]||t.actor!==o||String(n?.conversationType)==="2"&&n?.isInAtList!==!0||n?.msgtype!=="text"||!mt(n?.text?.content))return!1;try{return tc(n.sessionWebhook),!0}catch{return!1}}function Rhe(n){n.stats??={};for(let t of["messagesReceived","messagesReplied","messagesRejected","messagesIgnored","reactionsAdded","reactionsRemoved","reactionErrors"])n[t]??=0,n.stats[t]=n[t];n.pendingSenders??=[]}function va(n,t){n[t]=(n[t]??0)+1,n.stats??={},n.stats[t]=n[t]}function l_({pendingSenders:n=[]}={}){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,messagesIgnored:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null,pendingSenders:structuredClone(n),stats:{messagesReceived:0,messagesReplied:0,messagesRejected:0,messagesIgnored:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0}}}var fQ=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c=new Map;#p=new Map;#d=new Map;#h=new Set;#E=new Set;#C=new Map;#f;#B=new mi;constructor({api:t,clientId:o,clientSecret:i,harness:e,state:a,contextEnhancement:A,status:r=l_(),logger:s=console,replyTimeoutMs:g=6e5,reactionTimeoutMs:c=5e3,maxMessageChars:I=4e3,signal:d}){if(!t||typeof t.sendText!="function")throw new TypeError("DingTalk API is required");if(!mt(o)||!mt(i))throw new TypeError("DingTalk app credentials are required");if(!e||!a)throw new TypeError("Harness client and state store are required");this.#e=t,this.#A=o.trim(),this.#t=i.trim(),this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#f=new Ci({label:"DingTalk",logger:s}),this.#I=g,this.#l=Number.isFinite(c)&&c>0?Math.floor(c):5e3,this.#o=I,this.#s=d,Rhe(this.#n),this.#v()}get status(){return this.#v(),structuredClone(this.#n)}accept(t,{contextSnapshot:o}={}){if(this.#s?.aborted)return Promise.resolve();let i=mt(t?.msgId),e=MY(t);if(!i||!e||this.#g.hasSeen(i)||this.#C.has(i))return Promise.resolve();this.#C.set(i,o===void 0?Xr(this.#a,t.conversationType==="1"||t.conversationType===1?"direct":t.conversationType==="2"||t.conversationType===2?"group":null):o);let a;try{a=Ohe(t,e)}catch{return this.#C.delete(i),va(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),Promise.resolve()}let A=null;try{A=tc(t.sessionWebhook)}catch{}A&&String(t.conversationType)!=="2"&&Eo(this.#g,{sessionWebhook:A});let r=this.#p.get(a),s=I_(t,{api:this.#e,clientId:this.#A,clientSecret:this.#t}),g=mt(s.content)??"",c=String(t.conversationType)!=="2"||t?.isInAtList===!0,I=String(t.conversationType)!=="2",d=A&&c?this.#S(t):null,B=_=>Promise.resolve(_).then(T=>(this.#Q(d,this.#s?.aborted?"clear":"success"),T),T=>{throw this.#Q(d,this.#s?.aborted||T?.name==="AbortError"||T?.code==="turn-stopped"?"clear":"error"),T}),f=String(t?.msgtype).toLowerCase()==="text"&&So(g),Q=this.#B.status(a);if(f&&!I&&A&&c)return B(this.#b(i,A,{message:qn()},d));if(I&&A&&(f||Q.phase==="collecting")){let T=/^\/batch$/iu.test(g)&&Q.phase==="idle"&&(this.#c.has(a)||r||this.#f.hasPending(a))?{handled:!0,kind:"busy",message:wo()}:this.#B.handle(a,g,{plainText:!!g&&String(t?.msgtype).toLowerCase()==="text"&&!Lt(s)&&!Wt(s)});if(T.handled)return T.kind==="submit"?B(this.#m({...t,msgtype:"text",text:{content:T.prompt}},i,e,a,{batchSubmission:T,statusReaction:d})):B(this.#b(i,A,T,d))}let y=fi(g)?qi:Lt(s)?null:zi(g)?Qi:Vi(g)?Wi:Zi(g)?yi:null;if(y&&A&&c){let _;return _=this.#u(t,i,a,A,s,y).catch(T=>{if(T?.code==="turn-stopped"||this.#s?.aborted){this.#Q(d,"clear");return}this.#Q(d,"error"),this.#n.lastError=T?.message??String(T);let R=tt(this.#n,T);return this.#i.error?.(`[dsh-dingtalk] failed to process a command [${R.referenceId}]`,BQ(T)),this.#N(A,dt(R),this.#P(t)).catch(()=>{})}).finally(()=>{this.#C.delete(i),this.#E.delete(_)}),this.#E.add(_),B(_)}let m=this.#f.claimReply({key:a,actor:e,messageId:i,text:A&&t?.msgtype==="text"?mt(t?.text?.content)??"":"",addressed:String(t?.conversationType)!=="2"||t?.isInAtList===!0,hasPendingQuestion:!!r,questionCompletion:r?.submitting||r?.claimedReplyMessageId?r.queue:null,isQuestionPending:()=>this.#p.has(a),send:A?_=>this.#N(A,_,this.#P(t)):async()=>{}});if(m){let _;return _=m.process(async()=>this.#g.hasSeen(i)?!1:(await this.#g.markSeen(i),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString(),A||(va(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),this.#n.lastError=w("\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002")),!0)).catch(T=>{if(this.#s?.aborted){this.#Q(d,"clear");return}this.#Q(d,"error"),this.#n.lastError=w("\u9489\u9489\u5BA1\u6279\u5904\u7406\u5931\u8D25\u3002"),this.#i.error?.("[dsh-dingtalk] failed to process an approval reply",T)}).finally(()=>{this.#C.delete(i),this.#h.delete(_)}),this.#h.add(_),B(_)}if(r&&r.actor!==e)return B(this.#m(t,i,e,a,{statusReaction:d}));if(r?.submitting||r?.claimedReplyMessageId)return B(this.#m(t,i,e,a,{statusReaction:d}));if(r){Nhe(t,r,e)&&(r.claimedReplyMessageId=i);let T=(r.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#D(t,i,e,a,r,d)).finally(()=>{this.#C.delete(i),r.claimedReplyMessageId===i&&(r.claimedReplyMessageId=null),r.queue===T&&(r.queue=null)});return r.queue=T,B(T)}return B(this.#m(t,i,e,a,{statusReaction:d}))}#y(t,o,i,e){let a=new AbortController,A=Promise.resolve().then(()=>this.#e[t]({clientId:this.#A,clientSecret:this.#t,...o,reactionName:i,signal:a.signal})),r,s=new Promise((g,c)=>{r=setTimeout(()=>{let I=new DOMException("DingTalk reaction timed out","TimeoutError");a.abort(I),c(I)},this.#l),r.unref?.()});return Promise.race([A,s]).then(()=>(va(this.#n,e==="add"?"reactionsAdded":"reactionsRemoved"),!0)).catch(g=>(va(this.#n,"reactionErrors"),this.#i.debug?.(`[dsh-dingtalk] ${t} failed`,BQ(g)),!1)).finally(()=>clearTimeout(r))}#S(t){if(typeof this.#e.addReaction!="function"||typeof this.#e.recallReaction!="function")return null;let o=mt(t?.msgId),i=mt(t?.conversationId);if(!o||!i)return null;let e={messageId:o,conversationId:i,robotCode:mt(t?.robotCode)??this.#A};return{target:e,attached:this.#y("addReaction",e,yI,"add"),terminal:!1}}#Q(t,o){if(!t||t.terminal)return;t.terminal=!0;let i=o==="success"?cx:o==="error"?Ix:null;t.attached.then(async e=>{let a=await this.#y("recallReaction",t.target,yI,"remove");(!e||!a)&&(await new Promise(A=>{setTimeout(A,Math.min(1e3,this.#l)).unref?.()}),a=await this.#y("recallReaction",t.target,yI,"remove")||a),!(!a||!i||this.#s?.aborted)&&await this.#y("addReaction",t.target,i,"add")}).catch(()=>{})}#m(t,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1,batchSubmission:r=null,statusReaction:s=null}={}){let g=!1;try{tc(t.sessionWebhook),g=!0}catch{}let c=String(t.conversationType)!=="2"||t.isInAtList===!0,I=g&&c?wp(I_(t,{api:this.#e,clientId:this.#A,clientSecret:this.#t}),{signal:this.#s}):void 0,B=(this.#c.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#R(t,o,i,e,{alreadyRecorded:A,preparedMessage:I,batchSubmission:r,statusReaction:s})).finally(()=>{a&&this.#C.delete(o),this.#c.get(e)===B&&this.#c.delete(e)});return this.#c.set(e,B),B}async waitForIdle(){await Promise.allSettled([...this.#c.values(),...[...this.#p.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#h,...this.#E])}async#u(t,o,i,e,a,A){if(this.#s?.throwIfAborted(),this.#g.hasSeen(o))return;await this.#g.markSeen(o),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString();let r=await A(mt(a.content)??"",this.#r,this.#g,i,{signal:this.#s,isDirect:String(t.conversationType)==="1",hasImages:Wt(a),hasFiles:Lt(a),pendingInteraction:this.#p.has(i)||this.#f.hasPending(i),control:{owner:this,key:i}});r?.stopped&&await Promise.allSettled([this.#U(i),this.#f.closeRoute(i)]);for(let s of r?.messages??[r?.message])s&&await this.#N(e,s,this.#P(t));this.#n.lastError=null}#b(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#g.hasSeen(t)||(await this.#g.markSeen(t),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString(),i.message&&await this.#N(o,i.message),this.#n.lastError=null)}).catch(async A=>{if(this.#s?.aborted){this.#Q(e,"clear");return}this.#Q(e,"error"),this.#n.lastError=A?.message??String(A);let r=tt(this.#n,A);this.#i.error?.(`[dsh-dingtalk] failed to process a batch input message [${r.referenceId}]`,BQ(A)),await this.#N(o,dt(r)).catch(()=>{})}).finally(()=>{this.#C.delete(t),this.#E.delete(a)}),this.#E.add(a),a}async#R(t,o,i,e,{alreadyRecorded:a=!1,preparedMessage:A,batchSubmission:r=null,statusReaction:s=null}={}){if(this.#s?.throwIfAborted(),!a){if(this.#g.hasSeen(o))return;await this.#g.markSeen(o),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString()}if(String(t.conversationType)==="2"&&t.isInAtList!==!0){va(this.#n,"messagesIgnored");return}let g;try{g=tc(t.sessionWebhook)}catch{va(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),this.#n.lastError=w("\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002");return}let c=A??I_(t,{api:this.#e,clientId:this.#A,clientSecret:this.#t}),I=c.content,d=Wt(c),B=Lt(c),f=String(t?.msgtype).toLowerCase()==="text",Q=null,y=!1,m=r===null;try{if(!I&&!d&&!B){await this.#N(g,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002"),this.#P(t));return}let _=I.toLowerCase();if(f&&!d&&!B&&_==="/help"){await this.#N(g,Qhe(),this.#P(t));return}if(f&&!d&&!B&&_==="/status"){await this.#r.ensureRunning({signal:this.#s}),await this.#N(g,w("\u9489\u9489\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),this.#P(t));return}if(f&&!d&&!B&&_==="/new"){await this.#g.clearSession(e),await this.#N(g,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),this.#P(t));return}let T=f&&!d&&!B?await Qo(I,this.#r,e):null;if(T){for(let N of T.messages??[T.message])await this.#N(g,N,this.#P(t));return}let R=f&&!d&&!B?await Bi(I,this.#r,this.#g,e,{signal:this.#s}):null;if(R){await this.#N(g,R.message,this.#P(t));return}let L=d?await Bo(c,{signal:this.#s}):void 0,U=this.#C.get(o);U&&(L=mo(L??I,U,()=>({channel:"dingtalk",senderId:i,senderName:t.senderNick}))),typeof this.#e.createAiCard=="function"&&typeof this.#e.updateAiCard=="function"&&typeof this.#e.finishAiCard=="function"&&(Q=Ex({api:this.#e,clientId:this.#A,clientSecret:this.#t,target:bhe(t,i),signal:this.#s,logger:this.#i}),y=await Q.start(w(Bhe)));let{answer:F,artifacts:q=[]}=await ui({harness:this.#r,state:this.#g,key:e,...L!==void 0?{content:L}:{text:I},createOptions:{signal:this.#s},existsOptions:{signal:this.#s},askOptions:{timeoutMs:this.#I,signal:this.#s,control:{owner:this,key:e},onUpdate:y?N=>Q.push(The(N)):void 0,onInteraction:N=>this.#w(N,{key:e,actor:i,sessionWebhook:g,requiresMention:String(t.conversationType)==="2"}),onInteractionResolved:N=>this.#T(N),files:c.files}});r&&(this.#B.complete(e,r.token),m=!0);let z=typeof F=="string"&&F.trim()?F:q.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):F,j=null,P=null,J=!1;try{J=y&&await Q.finish(z),J?P=Zt({deliveryId:o,presentation:"dingtalk-card"}):P=Zt({deliveryId:o,presentation:"dingtalk-text",providerMessageIds:await this.#N(g,z,this.#P(t))})}catch(N){j=Ma(N)}let H=await this.#Y(Mhe(t,i,this.#A),g,o,q,P);if(j&&!H.userVisible)throw j;return j&&H.artifactSendErrors===0&&tt(this.#n,j),va(this.#n,"messagesReplied"),this.#n.lastReplyAt=new Date().toISOString(),this.#n.lastError=null,!j&&H.artifactSendErrors===0&&Co(this.#n),H.receipt}catch(_){let T=null;if(!m&&r&&(_?.code==="turn-stopped"?this.#B.complete(e,r.token):T=this.#B.fail(e,r.token).message??null,m=!0),_?.code==="turn-stopped"){this.#Q(s,"clear"),y&&await Q.finish(w("\u5DF2\u505C\u6B62\u3002")).catch(()=>{});return}if(this.#s?.aborted){this.#Q(s,"clear");return}this.#Q(s,"error"),this.#n.lastError=_?.message??String(_);let R=Oo(_)??mhe(_),L=tt(this.#n,_,{userMessage:R,reason:Ji(_)?.reason});this.#i.error?.(`[dsh-dingtalk] failed to process an inbound message [${L.referenceId}]`,BQ(_));try{let U=dt(L),F=T?`${U} -${T}`:K;y&&await Q.finish(L)||await this.#N(g,L,this.#P(t))}catch{this.#i.error?.("[dsh-dingtalk] failed to send the safe error reply")}}finally{await this.#U(e),await this.#f.closeRoute(e)}}async#D(t,o,i,e,a,A){this.#s?.throwIfAborted();let r=this.#p.get(e),s=a.claimedReplyMessageId===o;if(!r||r!==a||r.submitting)return s&&(!r||r!==a)?this.#M(t,o):this.#m(t,o,i,e,{releaseMessageId:!1,statusReaction:A});if(this.#g.hasSeen(o))return;if(await this.#g.markSeen(o),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString(),String(t.conversationType)==="2"&&t.isInAtList!==!0){va(this.#n,"messagesIgnored");return}let g;try{g=tc(t.sessionWebhook)}catch{va(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),this.#n.lastError=w("\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002");return}let c=t?.msgtype==="text"?mt(t?.text?.content):null;if(!c){try{await this.#N(g,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002"),this.#P(t))}catch{this.#i.error?.("[dsh-dingtalk] failed to reject a non-text interaction reply")}return}let I=this.#p.get(e);if(!I||I!==a||I.submitting){if(s&&(!I||I!==a)){try{await this.#N(g,w(g_),this.#P(t))}catch{this.#i.error?.("[dsh-dingtalk] failed to send an expired interaction notice")}return}return this.#m(t,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0,statusReaction:A})}if(I.sessionWebhook=g,I.needsPresentation){try{await this.#k(I)}catch{this.#Q(A,"error"),this.#n.lastError=w("\u9489\u9489\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002"),this.#i.error?.("[dsh-dingtalk] failed to retry an interaction question"),I.interaction.reconnect?.()}return}let d=I.questions[I.index];if(d){if(I.answers.push(Ei(d,c)),I.index+=1,I.indexthis.#N(e,c)})||t?.kind!=="question")return;let A=t?.payload?.questions,r=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t.rpcId!="string"||typeof r!="string"||typeof t.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!di(c))){this.#i.warn?.("[dsh-dingtalk] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"DingTalk safely cancelled an interaction left by an earlier client.",details:{}}});try{await this.#N(e,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002"))}catch{this.#i.error?.("[dsh-dingtalk] failed to send an interaction recovery notice")}return}let s=this.#p.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#k(s);return}if(this.#d.has(r))return;if(s){this.#i.warn?.("[dsh-dingtalk] cancelled a second pending Harness question"),await t.respond({ok:!1,error:{code:"cancelled",message:"DingTalk is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,requiresMention:a,questions:A,answers:[],index:0,sessionWebhook:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0};this.#p.set(o,g),this.#d.set(g.interactionId,o),await this.#k(g)}async#T(t){if(await this.#f.handleResolved(t))return;let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#d.get(o);i&&this.#_(i,o)}async#k(t){let o=t.questions[t.index];o&&(await this.#N(t.sessionWebhook,hi(o,t.index,t.questions.length,{requiresMention:t.requiresMention})),t.needsPresentation=!1)}async#M(t,o){if(this.#g.hasSeen(o))return;await this.#g.markSeen(o),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString();let i;try{i=tc(t.sessionWebhook)}catch{va(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString();return}try{await this.#N(i,w(g_),this.#P(t))}catch{this.#i.error?.("[dsh-dingtalk] failed to send an expired interaction notice")}}#L(t,o){let i=this.#p.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#p.delete(t),this.#d.delete(i.interactionId),i)}#_(t,o){return this.#L(t,o)!==null}async#U(t){let o=this.#L(t);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The DingTalk interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#i.warn?.("[dsh-dingtalk] failed to cancel a pending Harness interaction")}}#v(){typeof this.#g.pendingSenders=="function"&&(this.#n.pendingSenders=this.#g.pendingSenders())}#P(t){let o=MY(t);return String(t?.conversationType)==="2"&&o?{atUserIds:[o]}:void 0}async#N(t,o,i){let e=[];for(let a of px(o,this.#o)){this.#s?.throwIfAborted();let A=await this.#e.sendText({clientId:this.#A,clientSecret:this.#t,sessionWebhook:t,text:a,at:i,signal:this.#s});e.push(...ka(A))}return e}async#Y(t,o,i,e,a){let A=async(s,g)=>yhe(await this.#e[s]({clientId:this.#A,clientSecret:this.#t,target:t,file:g,signal:this.#s})),r=await bo({artifacts:e,baseReceipt:a,deliveryId:i,aggregatePresentation:a?"dingtalk-text-and-files":"dingtalk-files",channelKey:"dingtalk",signal:this.#s,sendImage:typeof this.#e.sendImage=="function"?s=>A("sendImage",s):void 0,sendFile:typeof this.#e.sendFile=="function"?s=>A("sendFile",s):void 0,onFailure:(s,g)=>tt(this.#n,g,{userMessage:_he(s?.fileName,g),reason:g?.code}),sendFailureNotice:(s,g,c)=>this.#N(o,dt(c)),logger:this.#i});return this.#n.artifactsSent=(this.#n.artifactsSent??0)+r.artifactsSent,this.#n.artifactSendErrors=(this.#n.artifactSendErrors??0)+r.artifactSendErrors,{receipt:r.receipt,userVisible:r.userVisible,artifactSendErrors:r.artifactSendErrors}}};function QQ(n){return typeof n=="string"&&n.trim()?n.trim():null}function _Y(n){let t=Array.isArray(n?.approvedSenders)?n.approvedSenders:n?.approvedSenders instanceof Set?[...n.approvedSenders]:[];return new Set(t.map(o=>QQ(typeof o=="string"?o:o?.staffId)).filter(Boolean))}function khe(n){return _Y(n).size}function TY(n){return n?.connected===!0||n?.socket?.readyState===1}function vhe(n,t){return new Promise((o,i)=>{if(t.aborted){i(t.reason);return}let e=()=>i(t.reason);t.addEventListener("abort",e,{once:!0}),Promise.resolve(n).then(a=>{t.removeEventListener("abort",e),o(a)},a=>{t.removeEventListener("abort",e),i(a)})})}async function Phe(n,t,o){for(;;){if(o?.throwIfAborted(),TY(n))return;await new Promise((i,e)=>{let a=setTimeout(()=>{o?.removeEventListener("abort",A),i()},t),A=()=>{clearTimeout(a),e(o.reason??new DOMException("Aborted","AbortError"))};o?.addEventListener("abort",A,{once:!0})})}}async function Ghe(n,t,o,i){let e=AbortSignal.timeout(t),a=AbortSignal.any([i,e]),A=!1,r=Promise.resolve().then(()=>n.connect()).finally(()=>{A=!0});try{await vhe(r,a),await Phe(n,o,a)}catch(s){throw a.aborted?(A||r.then(()=>n.disconnect()).catch(()=>{}),i.aborted?i.reason:new Error(`DingTalk Stream handshake timed out after ${t}ms`)):s}}async function Fhe({clientId:n,clientSecret:t}){let{DWClient:o,TOPIC_ROBOT:i}=await import("dingtalk-stream");return{client:new o({clientId:n,clientSecret:t,endpoint:"https://api.dingtalk.com",autoReconnect:!1,keepAlive:!0,debug:!1}),topic:i}}function Lhe({pendingSenders:n=[],approvedSenders:t=0}={}){return{startedAt:null,ready:!1,dingtalkStreamState:"idle",harnessReachable:!1,lastConnectedAt:null,lastCheckedAt:null,lastCallbackAt:null,authorizationMode:"sender-staff-id-approval",approvedSenderCount:t,...l_({pendingSenders:n})}}var kE=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c;#p=null;#d=null;#h=null;#E=null;#C=null;#f=null;#B=new Set;constructor({config:t,clientSecret:o,harness:i,state:e,contextEnhancement:a,logger:A=console,replyTimeoutMs:r=6e5,maxMessageChars:s=4e3,connectTimeoutMs:g=15e3,connectPollIntervalMs:c=25,api:I=dx(),streamFactory:d=Fhe}){if(!t||!QQ(t.clientId)||!QQ(o))throw new TypeError("DingtalkRuntime requires app credentials");if(!i||!e)throw new TypeError("DingtalkRuntime requires Harness and state");if(typeof d!="function")throw new TypeError("streamFactory must be a function");this.#e=t,this.#A=o.trim(),this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c,this.#o=I,this.#s=d,this.#c=Lhe({pendingSenders:this.#S(),approvedSenders:khe(t)})}get status(){if(this.#d){let t=this.#d.status;Object.assign(this.#c,t)}else this.#c.pendingSenders=this.#S();return structuredClone(this.#c)}pendingSender(t){return typeof this.#r.pendingSender=="function"?this.#r.pendingSender(t):null}pendingSenders(){return this.#S()}async start(){return this.#p&&this.#c.ready?this.status:this.#E?this.#E:(this.#E=this.#y().finally(()=>{this.#E=null}),this.#E)}async#y(){await this.stop();let t=new AbortController;this.#f=t;let{signal:o}=t;this.#c.startedAt=new Date().toISOString(),this.#c.dingtalkStreamState="connecting",this.#c.lastError=null;try{if(await this.#t.ensureRunning({signal:o}),this.#c.harnessReachable=!0,typeof this.#r.removePendingSenderByStaffId=="function"){for(let A of _Y(this.#e))await this.#r.removePendingSenderByStaffId(A);this.#c.pendingSenders=this.#S()}this.#d=new fQ({api:this.#o,clientId:this.#e.clientId,clientSecret:this.#A,approvedSenders:this.#e.approvedSenders,harness:this.#t,state:this.#r,contextEnhancement:this.#g,status:this.#c,logger:this.#a,replyTimeoutMs:this.#n,maxMessageChars:this.#i,signal:o});let i=await this.#s({clientId:this.#e.clientId,clientSecret:this.#A});if(o.throwIfAborted(),this.#p=i?.client??i,this.#h=i?.topic??i?.TOPIC_ROBOT??"/v1.0/im/bot/messages/get",!this.#p||typeof this.#p.registerCallbackListener!="function"||typeof this.#p.connect!="function"||typeof this.#p.disconnect!="function"||typeof this.#p.socketCallBackResponse!="function")throw new TypeError("streamFactory returned an invalid DingTalk Stream client");let e=this.#p,a=this.#d;return e.registerCallbackListener(this.#h,A=>{if(this.#p!==e||this.#d!==a)return;let r=QQ(A?.headers?.messageId);if(r)try{e.socketCallBackResponse(r,{success:!0})}catch{this.#a.warn?.("[dsh-dingtalk] unable to acknowledge an inbound callback")}let s=this.#g,g;try{g=s?.getSettings?.()}catch{}let c=Promise.resolve().then(async()=>{if(this.#d!==a)return;let I;try{I=typeof A?.data=="string"?JSON.parse(A.data):A?.data}catch{this.#c.lastError=w("\u9489\u9489\u6D88\u606F\u683C\u5F0F\u65E0\u6548\u3002"),this.#a.warn?.("[dsh-dingtalk] ignored an invalid callback payload");return}if(!I||typeof I!="object")return;this.#c.lastCallbackAt=Date.now();let d=Xr({getSettings:()=>g,get botId(){return s?.botId}},I.conversationType==="1"||I.conversationType===1?"direct":I.conversationType==="2"||I.conversationType===2?"group":null);await a.accept(I,{contextSnapshot:d})}).catch(()=>{o.aborted||this.#d!==a||(this.#c.lastError=w("\u9489\u9489\u6D88\u606F\u5904\u7406\u5931\u8D25\u3002"),this.#a.error?.("[dsh-dingtalk] callback processing failed"))}).finally(()=>this.#B.delete(c));this.#B.add(c)}),await Ghe(e,this.#I,this.#l,o),this.#c.ready=!0,this.#c.dingtalkStreamState="connected",this.#c.lastConnectedAt=Date.now(),this.#c.lastCheckedAt=Date.now(),this.#c.lastError=null,this.#C=setInterval(()=>{let A=TY(e);this.#c.ready=A,this.#c.dingtalkStreamState=A?"connected":"reconnecting",this.#c.lastCheckedAt=Date.now(),A&&(this.#c.lastError=null)},1e3),this.#C.unref?.(),this.status}catch(i){let e=o.aborted;throw this.#c.ready=!1,this.#c.dingtalkStreamState=e?"idle":"failed",this.#c.lastError=e?null:i?.message??String(i),await this.stop({preserveError:!e}),i}}async stop({preserveError:t=!1}={}){let o=t?this.#c.lastError:null,i=this.#f;this.#f=null,i?.abort(new DOMException("DingTalk runtime stopped","AbortError")),this.#C&&clearInterval(this.#C),this.#C=null,this.#c.ready=!1;let e=this.#p;if(this.#p=null,this.#h=null,e)try{await e.disconnect()}catch{this.#a.warn?.("[dsh-dingtalk] DingTalk Stream disconnect failed")}return await Promise.allSettled([...this.#B]),this.#B.clear(),this.#d&&await this.#d.waitForIdle(),this.#d=null,this.#c.dingtalkStreamState=t?"failed":"idle",this.#c.lastError=o,this.status}async sendConnectionTest(t){return ec({state:this.#r,text:t,channelLabel:w("\u9489\u9489\u673A\u5668\u4EBA"),send:async({sessionWebhook:o},i)=>{if(!this.#c.ready||!this.#f)throw new Error("DingTalk runtime is not connected");await this.#o.sendText({clientId:this.#e.clientId,clientSecret:this.#A,sessionWebhook:o,text:i,signal:this.#f.signal})}})}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.userId=="string"?t.route.userId.trim():"",a=typeof t?.route?.openConversationId=="string"?t.route.openConversationId.trim():"";if(t?.kind==="user"&&(!e||a)||t?.kind==="group"&&(!a||e)||t?.kind!=="user"&&t?.kind!=="group"){let A=new TypeError("Invalid DingTalk proactive delivery target");throw A.code="invalid-target",A}if(!this.#c.ready||!this.#f){let A=new Error("DingTalk runtime is not connected");throw A.code="bot-not-connected",A}i?.throwIfAborted();try{await this.#o.sendRobotText({clientId:this.#e.clientId,clientSecret:this.#A,target:{type:t.kind,robotCode:this.#e.clientId,...t.kind==="user"?{userId:e}:{openConversationId:a}},text:o,signal:i??this.#f.signal})}catch(A){if(A?.code!=="send-rejected")throw A;let r=new Error("DingTalk rejected the proactive delivery target",{cause:A});throw r.code="target-rejected",r}return{sent:!0}}#S(){return typeof this.#r.pendingSenders=="function"?this.#r.pendingSenders():[]}};import{spawn as Vhe}from"node:child_process";import{randomUUID as p_}from"node:crypto";import{isAbsolute as Whe}from"node:path";import{isAbsolute as Uhe}from"node:path";var Hhe=256,Khe=/[\p{White_Space}\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u,xhe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;function vE(n,t){let o=new Error(t);return o.code=n,o}function Yhe(n){if(typeof n!="string"||!n||n.length>Hhe||Khe.test(n))throw vE("session-id-invalid","A non-empty, safe session id is required");return n}function jhe(n,t){if(!Array.isArray(t?.items)||!Array.isArray(t?.archivedSessionIds)||t.archivedSessionIds.some(i=>typeof i!="string"||!i))throw new Error("Harness returned an invalid response for workspace.list");let o=[];for(let i of t.items){if(typeof i?.workspaceId!="string"||!i.workspaceId||typeof i.path!="string"||!Uhe(i.path)||!Array.isArray(i.sessionIds)||i.sessionIds.some(e=>typeof e!="string"||!e))throw new Error("Harness returned an invalid response for workspace.list");for(let e of i.sessionIds)e===n&&o.push(i)}if(o.length===0)throw vE("session-not-registered","The session is not registered to a Harness workspace");if(o.length!==1)throw vE("session-workspace-ambiguous","The session is registered to more than one Harness workspace");if(xhe.test(o[0].path))throw new Error("Harness returned an unsafe workspace path for the session");return{workspace:o[0],archived:t.archivedSessionIds.includes(n)}}function Jhe(n,t){if(!Array.isArray(t?.items)||t.items.some(a=>typeof a?.sessionId!="string"||!a.sessionId))throw new Error("Harness returned an invalid response for session.list");let o=t.items.filter(a=>a.sessionId===n);if(o.length===0)throw vE("session-summary-unavailable","The session is no longer available from Harness");if(o.length!==1)throw new Error("Harness returned duplicate session summaries for session.list");let[i]=o;if(i.origin==="subagent")throw vE("session-subagent-unsupported","Subagent sessions cannot be adopted as a bot conversation");if(i.origin!==void 0)throw new Error("Harness returned an invalid session origin for session.list");let e=i.projections?.values?.title;if(e!=null&&typeof e!="string")throw new Error("Harness returned an invalid session title for session.list");return{title:typeof e=="string"?e:null}}async function NY(n,t,o={},i=3e4){let e=Yhe(t);await n.ensureRunning(o);let a=await n.rpc("workspace.list",{},i,o),{workspace:A,archived:r}=jhe(e,a),s=Jhe(e,await n.rpc("session.list",{},i,o)),g=await n.rpc("session.create",{workspaceId:A.workspaceId,sessionId:e},i,o);if(!g||g.sessionId!==e)throw new Error("Harness returned an invalid response for session.create");return{sessionId:e,workspace:A.path,title:s.title,archived:r}}function PE(n,t,o){try{let i=n?.(t);i&&typeof i.then=="function"&&Promise.resolve(i).catch(o)}catch(i){o(i)}}async function qhe({apiProxy:n,rpcId:t,signal:o,onOpen:i,onEnvelope:e}){let a=new AbortController,A=()=>a.abort(o.reason),r,s,g,c=I=>{a.signal.aborted||(g=I,A())};o.addEventListener("abort",A,{once:!0});try{for(r=n.events.mux({rpcId:t,payload:{}},a.signal)[Symbol.asyncIterator](),s=Promise.resolve(r.next()),a.signal.aborted||PE(i,A,c);!a.signal.aborted;){let{value:I,done:d}=await s;if(d||a.signal.aborted)break;PE(e,{type:"server-request",rpcId:I?.rpcId,method:I?.payload?.type,payload:I?.payload},c),a.signal.aborted||(s=Promise.resolve(r.next()))}}catch(I){c(I)}finally{let I=a.signal.aborted;o.removeEventListener("abort",A),A(),await s?.catch(()=>{});try{await r?.return?.()}catch(d){I||(g??=d)}}if(g)throw g}function zhe({baseUrl:n,createWebSocket:t,signal:o,onOpen:i,onEnvelope:e,onMalformed:a}){let A=new URL("/api/events.mux",n);return A.protocol=A.protocol==="https:"?"wss:":"ws:",new Promise((r,s)=>{let g=t(A.toString()),c=!1,I=!1,d=T=>{if(!I){I=!0,g.removeEventListener("open",f),g.removeEventListener("message",Q),g.removeEventListener("close",y),g.removeEventListener("error",m),o.removeEventListener("abort",_);try{(g.readyState===0||g.readyState===1)&&g.close()}catch{}T&&!o.aborted?s(T):r()}},B=()=>d(),f=()=>{I||c||(c=!0,PE(i,B,d))},Q=T=>{if(I)return;let R;try{if(typeof T.data!="string")throw new Error("binary WebSocket frame");R=JSON.parse(T.data)}catch(F){PE(a,F,()=>{});return}PE(e,R,d)},y=()=>d(c?void 0:new Error("Harness event mux WebSocket closed before opening")),m=()=>d(new Error(c?"Harness event mux WebSocket failed":"Harness event mux WebSocket failed before opening")),_=()=>d();g.addEventListener("open",f),g.addEventListener("message",Q),g.addEventListener("close",y,{once:!0}),g.addEventListener("error",m,{once:!0}),o.addEventListener("abort",_,{once:!0}),o.aborted&&_()})}async function RY(n){if(!n.signal.aborted)return n.baseUrl!==void 0&&n.baseUrl!==null?zhe(n):qhe(n)}var Zhe=new Map,Xhe=new WeakMap,$he=64;async function eEe(n){let t=n?.body;if(!t||typeof t.getReader!="function")return null;let o=t.getReader(),i=[],e=0;try{for(;;){let{done:r,value:s}=await o.read();if(r)break;if(!(s instanceof Uint8Array)||e+s.byteLength>$he)return null;i.push(s),e+=s.byteLength}}catch{return null}finally{try{await o.cancel()}catch{}}let a=new Uint8Array(e),A=0;for(let r of i)a.set(r,A),A+=r.byteLength;return new TextDecoder().decode(a)}function AEe(n){if(n==="localhost"||n==="[::1]")return!0;let t=n.split(".");return t.length===4&&t[0]==="127"&&t.every(o=>/^\d{1,3}$/.test(o)&&Number(o)<=255)}async function tEe(n,t){return n.status===401?"harness-auth-required":n.status===407?"harness-proxy-auth-required":n.status===403?(await eEe(n))?.trim()!=="forbidden"?"harness-request-forbidden":AEe(t)?"harness-loopback-forbidden":"harness-host-untrusted":n.status===404?"harness-api-not-found":"harness-http-failed"}function LY(n){let t=typeof n=="string"?Zhe:Xhe,o=t.get(n);return o||(o={ownerships:new Map,claims:new Map,controls:new WeakMap,nextOrder:0},t.set(n,o)),o}function kY(n,t){return new Promise((o,i)=>{let e=()=>t.removeEventListener("abort",a),a=()=>{e(),i(t.reason)};if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),Promise.resolve().then(()=>(t.throwIfAborted(),n())).then(A=>{e(),o(A)},A=>{e(),i(A)})})}function vY(n){let t=typeof n?.owner;return t!=="object"&&t!=="function"||n.owner===null||typeof n.key!="string"||!n.key?null:{owner:n.owner,key:n.key}}function d_(n){return n!==null&&typeof n=="object"&&typeof n.provider=="string"&&!!n.provider&&typeof n.model=="string"&&!!n.model&&(n.reasoningEffort===void 0||typeof n.reasoningEffort=="string"&&!!n.reasoningEffort)}function rEe(n){return n!==null&&typeof n=="object"&&Array.isArray(n.efforts)&&n.efforts.length>0&&n.efforts.every(t=>t!==null&&typeof t=="object"&&typeof t.id=="string"&&!!t.id&&typeof t.name=="string"&&!!t.name&&(t.description===void 0||typeof t.description=="string"))&&(n.defaultEffort===void 0||typeof n.defaultEffort=="string"&&!!n.defaultEffort)}function PY(n,t,{session:o=!1}={}){if(!n||typeof n!="object"||!Array.isArray(n.groups)||!Array.isArray(n.failures))throw new Error(`Harness returned an invalid response for ${t}`);for(let i of n.groups){if(!i||typeof i!="object"||typeof i.id!="string"||!i.id||typeof i.name!="string"||!i.name||!Array.isArray(i.models))throw new Error(`Harness returned an invalid response for ${t}`);for(let e of i.models)if(!e||typeof e!="object"||typeof e.id!="string"||!e.id||typeof e.name!="string"||!e.name||e.description!==void 0&&typeof e.description!="string"||e.reasoning!==void 0&&!rEe(e.reasoning))throw new Error(`Harness returned an invalid response for ${t}`)}for(let i of n.failures)if(!i||typeof i!="object"||typeof i.id!="string"||!i.id||typeof i.name!="string"||!i.name||i.message!==void 0&&typeof i.message!="string")throw new Error(`Harness returned an invalid response for ${t}`);if(o&&(!d_(n.current)||typeof n.routable!="boolean"))throw new Error(`Harness returned an invalid response for ${t}`);return n}function GY(){let n=new Error("Harness turn was stopped before producing a text reply");return n.code="turn-stopped",n}function aEe(n){return Array.isArray(n?.items)?n.items.flatMap(t=>typeof t?.path=="string"&&Whe(t.path)?[t.path]:[]):[]}function iEe(n,t){if(!Array.isArray(t?.items)||!Array.isArray(t?.archivedSessionIds))throw new Error("Harness returned an invalid response for workspace.list");let o=t.items.find(i=>i?.path===n);if(!o)return null;if(!Array.isArray(o.sessionIds)||o.sessionIds.some(i=>typeof i!="string"))throw new Error("Harness returned invalid session IDs for workspace.list");return o}function oEe(n){if(typeof n=="number"&&Number.isFinite(n))return n<1e12?n*1e3:n;if(typeof n=="string"&&n){let t=Date.parse(n);if(!Number.isNaN(t))return t}return null}function nEe(n){if(!n||typeof n!="object")return null;let t=[n?.header?.lastActivityAt,n?.header?.updatedAt,n?.header?.createdAt,n?.projections?.values?.lastActivityAt,n?.projections?.values?.updatedAt,n?.projections?.values?.createdAt,n?.lastActivityAt,n?.updatedAt,n?.createdAt];for(let o of t){let i=oEe(o);if(i!==null)return i}return null}function sEe(n,t,o){if(!Array.isArray(o?.items))throw new Error("Harness returned an invalid response for session.list");let i=new Set(t),e=new Map(o.items.flatMap(a=>typeof a?.sessionId=="string"?[[a.sessionId,a]]:[]));return{workspace:n.path,sessions:n.sessionIds.map(a=>{let A=e.get(a),r=A?.projections?.values?.title,s={sessionId:a,title:typeof r=="string"?r:null,archived:i.has(a),blank:A?.blank===!0,origin:A?.origin==="subagent"?"subagent":null,summaryAvailable:A!==void 0},g=A?.projections?.asOfSeq;Number.isSafeInteger(g)&&g>=-1&&(s.lastSeq=g);let c=nEe(A);return c!==null&&(s.time=c),s})}}function GE(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(()=>{t?.removeEventListener("abort",a),o()},n),a=()=>{clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))};t?.addEventListener("abort",a,{once:!0})})}function gEe(n){return(n?.data?.message?.content??[]).filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(` +${T}`:U;y&&await Q.finish(F)||await this.#N(g,F,this.#P(t))}catch{this.#i.error?.("[dsh-dingtalk] failed to send the safe error reply")}}finally{await this.#U(e),await this.#f.closeRoute(e)}}async#D(t,o,i,e,a,A){this.#s?.throwIfAborted();let r=this.#p.get(e),s=a.claimedReplyMessageId===o;if(!r||r!==a||r.submitting)return s&&(!r||r!==a)?this.#M(t,o):this.#m(t,o,i,e,{releaseMessageId:!1,statusReaction:A});if(this.#g.hasSeen(o))return;if(await this.#g.markSeen(o),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString(),String(t.conversationType)==="2"&&t.isInAtList!==!0){va(this.#n,"messagesIgnored");return}let g;try{g=tc(t.sessionWebhook)}catch{va(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString(),this.#n.lastError=w("\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002");return}let c=t?.msgtype==="text"?mt(t?.text?.content):null;if(!c){try{await this.#N(g,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002"),this.#P(t))}catch{this.#i.error?.("[dsh-dingtalk] failed to reject a non-text interaction reply")}return}let I=this.#p.get(e);if(!I||I!==a||I.submitting){if(s&&(!I||I!==a)){try{await this.#N(g,w(g_),this.#P(t))}catch{this.#i.error?.("[dsh-dingtalk] failed to send an expired interaction notice")}return}return this.#m(t,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0,statusReaction:A})}if(I.sessionWebhook=g,I.needsPresentation){try{await this.#k(I)}catch{this.#Q(A,"error"),this.#n.lastError=w("\u9489\u9489\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002"),this.#i.error?.("[dsh-dingtalk] failed to retry an interaction question"),I.interaction.reconnect?.()}return}let d=I.questions[I.index];if(d){if(I.answers.push(Ei(d,c)),I.index+=1,I.indexthis.#N(e,c)})||t?.kind!=="question")return;let A=t?.payload?.questions,r=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t.rpcId!="string"||typeof r!="string"||typeof t.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!di(c))){this.#i.warn?.("[dsh-dingtalk] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"DingTalk safely cancelled an interaction left by an earlier client.",details:{}}});try{await this.#N(e,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002"))}catch{this.#i.error?.("[dsh-dingtalk] failed to send an interaction recovery notice")}return}let s=this.#p.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#k(s);return}if(this.#d.has(r))return;if(s){this.#i.warn?.("[dsh-dingtalk] cancelled a second pending Harness question"),await t.respond({ok:!1,error:{code:"cancelled",message:"DingTalk is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,requiresMention:a,questions:A,answers:[],index:0,sessionWebhook:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0};this.#p.set(o,g),this.#d.set(g.interactionId,o),await this.#k(g)}async#T(t){if(await this.#f.handleResolved(t))return;let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#d.get(o);i&&this.#_(i,o)}async#k(t){let o=t.questions[t.index];o&&(await this.#N(t.sessionWebhook,hi(o,t.index,t.questions.length,{requiresMention:t.requiresMention})),t.needsPresentation=!1)}async#M(t,o){if(this.#g.hasSeen(o))return;await this.#g.markSeen(o),va(this.#n,"messagesReceived"),this.#n.lastMessageAt=new Date().toISOString();let i;try{i=tc(t.sessionWebhook)}catch{va(this.#n,"messagesRejected"),this.#n.lastRejectedAt=new Date().toISOString();return}try{await this.#N(i,w(g_),this.#P(t))}catch{this.#i.error?.("[dsh-dingtalk] failed to send an expired interaction notice")}}#L(t,o){let i=this.#p.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#p.delete(t),this.#d.delete(i.interactionId),i)}#_(t,o){return this.#L(t,o)!==null}async#U(t){let o=this.#L(t);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The DingTalk interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#i.warn?.("[dsh-dingtalk] failed to cancel a pending Harness interaction")}}#v(){typeof this.#g.pendingSenders=="function"&&(this.#n.pendingSenders=this.#g.pendingSenders())}#P(t){let o=MY(t);return String(t?.conversationType)==="2"&&o?{atUserIds:[o]}:void 0}async#N(t,o,i){let e=[];for(let a of px(o,this.#o)){this.#s?.throwIfAborted();let A=await this.#e.sendText({clientId:this.#A,clientSecret:this.#t,sessionWebhook:t,text:a,at:i,signal:this.#s});e.push(...ka(A))}return e}async#Y(t,o,i,e,a){let A=async(s,g)=>yhe(await this.#e[s]({clientId:this.#A,clientSecret:this.#t,target:t,file:g,signal:this.#s})),r=await bo({artifacts:e,baseReceipt:a,deliveryId:i,aggregatePresentation:a?"dingtalk-text-and-files":"dingtalk-files",channelKey:"dingtalk",signal:this.#s,sendImage:typeof this.#e.sendImage=="function"?s=>A("sendImage",s):void 0,sendFile:typeof this.#e.sendFile=="function"?s=>A("sendFile",s):void 0,onFailure:(s,g)=>tt(this.#n,g,{userMessage:_he(s?.fileName,g),reason:g?.code}),sendFailureNotice:(s,g,c)=>this.#N(o,dt(c)),logger:this.#i});return this.#n.artifactsSent=(this.#n.artifactsSent??0)+r.artifactsSent,this.#n.artifactSendErrors=(this.#n.artifactSendErrors??0)+r.artifactSendErrors,{receipt:r.receipt,userVisible:r.userVisible,artifactSendErrors:r.artifactSendErrors}}};function QQ(n){return typeof n=="string"&&n.trim()?n.trim():null}function _Y(n){let t=Array.isArray(n?.approvedSenders)?n.approvedSenders:n?.approvedSenders instanceof Set?[...n.approvedSenders]:[];return new Set(t.map(o=>QQ(typeof o=="string"?o:o?.staffId)).filter(Boolean))}function khe(n){return _Y(n).size}function TY(n){return n?.connected===!0||n?.socket?.readyState===1}function vhe(n,t){return new Promise((o,i)=>{if(t.aborted){i(t.reason);return}let e=()=>i(t.reason);t.addEventListener("abort",e,{once:!0}),Promise.resolve(n).then(a=>{t.removeEventListener("abort",e),o(a)},a=>{t.removeEventListener("abort",e),i(a)})})}async function Phe(n,t,o){for(;;){if(o?.throwIfAborted(),TY(n))return;await new Promise((i,e)=>{let a=setTimeout(()=>{o?.removeEventListener("abort",A),i()},t),A=()=>{clearTimeout(a),e(o.reason??new DOMException("Aborted","AbortError"))};o?.addEventListener("abort",A,{once:!0})})}}async function Ghe(n,t,o,i){let e=AbortSignal.timeout(t),a=AbortSignal.any([i,e]),A=!1,r=Promise.resolve().then(()=>n.connect()).finally(()=>{A=!0});try{await vhe(r,a),await Phe(n,o,a)}catch(s){throw a.aborted?(A||r.then(()=>n.disconnect()).catch(()=>{}),i.aborted?i.reason:new Error(`DingTalk Stream handshake timed out after ${t}ms`)):s}}async function Fhe({clientId:n,clientSecret:t}){let{DWClient:o,TOPIC_ROBOT:i}=await import("dingtalk-stream");return{client:new o({clientId:n,clientSecret:t,endpoint:"https://api.dingtalk.com",autoReconnect:!1,keepAlive:!0,debug:!1}),topic:i}}function Lhe({pendingSenders:n=[],approvedSenders:t=0}={}){return{startedAt:null,ready:!1,dingtalkStreamState:"idle",harnessReachable:!1,lastConnectedAt:null,lastCheckedAt:null,lastCallbackAt:null,authorizationMode:"sender-staff-id-approval",approvedSenderCount:t,...l_({pendingSenders:n})}}var kE=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c;#p=null;#d=null;#h=null;#E=null;#C=null;#f=null;#B=new Set;constructor({config:t,clientSecret:o,harness:i,state:e,contextEnhancement:a,logger:A=console,replyTimeoutMs:r=6e5,maxMessageChars:s=4e3,connectTimeoutMs:g=15e3,connectPollIntervalMs:c=25,api:I=dx(),streamFactory:d=Fhe}){if(!t||!QQ(t.clientId)||!QQ(o))throw new TypeError("DingtalkRuntime requires app credentials");if(!i||!e)throw new TypeError("DingtalkRuntime requires Harness and state");if(typeof d!="function")throw new TypeError("streamFactory must be a function");this.#e=t,this.#A=o.trim(),this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c,this.#o=I,this.#s=d,this.#c=Lhe({pendingSenders:this.#S(),approvedSenders:khe(t)})}get status(){if(this.#d){let t=this.#d.status;Object.assign(this.#c,t)}else this.#c.pendingSenders=this.#S();return structuredClone(this.#c)}pendingSender(t){return typeof this.#r.pendingSender=="function"?this.#r.pendingSender(t):null}pendingSenders(){return this.#S()}async start(){return this.#p&&this.#c.ready?this.status:this.#E?this.#E:(this.#E=this.#y().finally(()=>{this.#E=null}),this.#E)}async#y(){await this.stop();let t=new AbortController;this.#f=t;let{signal:o}=t;this.#c.startedAt=new Date().toISOString(),this.#c.dingtalkStreamState="connecting",this.#c.lastError=null;try{if(await this.#t.ensureRunning({signal:o}),this.#c.harnessReachable=!0,typeof this.#r.removePendingSenderByStaffId=="function"){for(let A of _Y(this.#e))await this.#r.removePendingSenderByStaffId(A);this.#c.pendingSenders=this.#S()}this.#d=new fQ({api:this.#o,clientId:this.#e.clientId,clientSecret:this.#A,approvedSenders:this.#e.approvedSenders,harness:this.#t,state:this.#r,contextEnhancement:this.#g,status:this.#c,logger:this.#a,replyTimeoutMs:this.#n,maxMessageChars:this.#i,signal:o});let i=await this.#s({clientId:this.#e.clientId,clientSecret:this.#A});if(o.throwIfAborted(),this.#p=i?.client??i,this.#h=i?.topic??i?.TOPIC_ROBOT??"/v1.0/im/bot/messages/get",!this.#p||typeof this.#p.registerCallbackListener!="function"||typeof this.#p.connect!="function"||typeof this.#p.disconnect!="function"||typeof this.#p.socketCallBackResponse!="function")throw new TypeError("streamFactory returned an invalid DingTalk Stream client");let e=this.#p,a=this.#d;return e.registerCallbackListener(this.#h,A=>{if(this.#p!==e||this.#d!==a)return;let r=QQ(A?.headers?.messageId);if(r)try{e.socketCallBackResponse(r,{success:!0})}catch{this.#a.warn?.("[dsh-dingtalk] unable to acknowledge an inbound callback")}let s=this.#g,g;try{g=s?.getSettings?.()}catch{}let c=Promise.resolve().then(async()=>{if(this.#d!==a)return;let I;try{I=typeof A?.data=="string"?JSON.parse(A.data):A?.data}catch{this.#c.lastError=w("\u9489\u9489\u6D88\u606F\u683C\u5F0F\u65E0\u6548\u3002"),this.#a.warn?.("[dsh-dingtalk] ignored an invalid callback payload");return}if(!I||typeof I!="object")return;this.#c.lastCallbackAt=Date.now();let d=Xr({getSettings:()=>g,get botId(){return s?.botId}},I.conversationType==="1"||I.conversationType===1?"direct":I.conversationType==="2"||I.conversationType===2?"group":null);await a.accept(I,{contextSnapshot:d})}).catch(()=>{o.aborted||this.#d!==a||(this.#c.lastError=w("\u9489\u9489\u6D88\u606F\u5904\u7406\u5931\u8D25\u3002"),this.#a.error?.("[dsh-dingtalk] callback processing failed"))}).finally(()=>this.#B.delete(c));this.#B.add(c)}),await Ghe(e,this.#I,this.#l,o),this.#c.ready=!0,this.#c.dingtalkStreamState="connected",this.#c.lastConnectedAt=Date.now(),this.#c.lastCheckedAt=Date.now(),this.#c.lastError=null,this.#C=setInterval(()=>{let A=TY(e);this.#c.ready=A,this.#c.dingtalkStreamState=A?"connected":"reconnecting",this.#c.lastCheckedAt=Date.now(),A&&(this.#c.lastError=null)},1e3),this.#C.unref?.(),this.status}catch(i){let e=o.aborted;throw this.#c.ready=!1,this.#c.dingtalkStreamState=e?"idle":"failed",this.#c.lastError=e?null:i?.message??String(i),await this.stop({preserveError:!e}),i}}async stop({preserveError:t=!1}={}){let o=t?this.#c.lastError:null,i=this.#f;this.#f=null,i?.abort(new DOMException("DingTalk runtime stopped","AbortError")),this.#C&&clearInterval(this.#C),this.#C=null,this.#c.ready=!1;let e=this.#p;if(this.#p=null,this.#h=null,e)try{await e.disconnect()}catch{this.#a.warn?.("[dsh-dingtalk] DingTalk Stream disconnect failed")}return await Promise.allSettled([...this.#B]),this.#B.clear(),this.#d&&await this.#d.waitForIdle(),this.#d=null,this.#c.dingtalkStreamState=t?"failed":"idle",this.#c.lastError=o,this.status}async sendConnectionTest(t){return ec({state:this.#r,text:t,channelLabel:w("\u9489\u9489\u673A\u5668\u4EBA"),send:async({sessionWebhook:o},i)=>{if(!this.#c.ready||!this.#f)throw new Error("DingTalk runtime is not connected");await this.#o.sendText({clientId:this.#e.clientId,clientSecret:this.#A,sessionWebhook:o,text:i,signal:this.#f.signal})}})}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.userId=="string"?t.route.userId.trim():"",a=typeof t?.route?.openConversationId=="string"?t.route.openConversationId.trim():"";if(t?.kind==="user"&&(!e||a)||t?.kind==="group"&&(!a||e)||t?.kind!=="user"&&t?.kind!=="group"){let A=new TypeError("Invalid DingTalk proactive delivery target");throw A.code="invalid-target",A}if(!this.#c.ready||!this.#f){let A=new Error("DingTalk runtime is not connected");throw A.code="bot-not-connected",A}i?.throwIfAborted();try{await this.#o.sendRobotText({clientId:this.#e.clientId,clientSecret:this.#A,target:{type:t.kind,robotCode:this.#e.clientId,...t.kind==="user"?{userId:e}:{openConversationId:a}},text:o,signal:i??this.#f.signal})}catch(A){if(A?.code!=="send-rejected")throw A;let r=new Error("DingTalk rejected the proactive delivery target",{cause:A});throw r.code="target-rejected",r}return{sent:!0}}#S(){return typeof this.#r.pendingSenders=="function"?this.#r.pendingSenders():[]}};import{spawn as Vhe}from"node:child_process";import{randomUUID as p_}from"node:crypto";import{isAbsolute as Whe}from"node:path";import{isAbsolute as Uhe}from"node:path";var Hhe=256,Khe=/[\p{White_Space}\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u,xhe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;function vE(n,t){let o=new Error(t);return o.code=n,o}function Yhe(n){if(typeof n!="string"||!n||n.length>Hhe||Khe.test(n))throw vE("session-id-invalid","A non-empty, safe session id is required");return n}function jhe(n,t){if(!Array.isArray(t?.items)||!Array.isArray(t?.archivedSessionIds)||t.archivedSessionIds.some(i=>typeof i!="string"||!i))throw new Error("Harness returned an invalid response for workspace.list");let o=[];for(let i of t.items){if(typeof i?.workspaceId!="string"||!i.workspaceId||typeof i.path!="string"||!Uhe(i.path)||!Array.isArray(i.sessionIds)||i.sessionIds.some(e=>typeof e!="string"||!e))throw new Error("Harness returned an invalid response for workspace.list");for(let e of i.sessionIds)e===n&&o.push(i)}if(o.length===0)throw vE("session-not-registered","The session is not registered to a Harness workspace");if(o.length!==1)throw vE("session-workspace-ambiguous","The session is registered to more than one Harness workspace");if(xhe.test(o[0].path))throw new Error("Harness returned an unsafe workspace path for the session");return{workspace:o[0],archived:t.archivedSessionIds.includes(n)}}function Jhe(n,t){if(!Array.isArray(t?.items)||t.items.some(a=>typeof a?.sessionId!="string"||!a.sessionId))throw new Error("Harness returned an invalid response for session.list");let o=t.items.filter(a=>a.sessionId===n);if(o.length===0)throw vE("session-summary-unavailable","The session is no longer available from Harness");if(o.length!==1)throw new Error("Harness returned duplicate session summaries for session.list");let[i]=o;if(i.origin==="subagent")throw vE("session-subagent-unsupported","Subagent sessions cannot be adopted as a bot conversation");if(i.origin!==void 0)throw new Error("Harness returned an invalid session origin for session.list");let e=i.projections?.values?.title;if(e!=null&&typeof e!="string")throw new Error("Harness returned an invalid session title for session.list");return{title:typeof e=="string"?e:null}}async function NY(n,t,o={},i=3e4){let e=Yhe(t);await n.ensureRunning(o);let a=await n.rpc("workspace.list",{},i,o),{workspace:A,archived:r}=jhe(e,a),s=Jhe(e,await n.rpc("session.list",{},i,o)),g=await n.rpc("session.create",{workspaceId:A.workspaceId,sessionId:e},i,o);if(!g||g.sessionId!==e)throw new Error("Harness returned an invalid response for session.create");return{sessionId:e,workspace:A.path,title:s.title,archived:r}}function PE(n,t,o){try{let i=n?.(t);i&&typeof i.then=="function"&&Promise.resolve(i).catch(o)}catch(i){o(i)}}async function qhe({apiProxy:n,rpcId:t,signal:o,onOpen:i,onEnvelope:e}){let a=new AbortController,A=()=>a.abort(o.reason),r,s,g,c=I=>{a.signal.aborted||(g=I,A())};o.addEventListener("abort",A,{once:!0});try{for(r=n.events.mux({rpcId:t,payload:{}},a.signal)[Symbol.asyncIterator](),s=Promise.resolve(r.next()),a.signal.aborted||PE(i,A,c);!a.signal.aborted;){let{value:I,done:d}=await s;if(d||a.signal.aborted)break;PE(e,{type:"server-request",rpcId:I?.rpcId,method:I?.payload?.type,payload:I?.payload},c),a.signal.aborted||(s=Promise.resolve(r.next()))}}catch(I){c(I)}finally{let I=a.signal.aborted;o.removeEventListener("abort",A),A(),await s?.catch(()=>{});try{await r?.return?.()}catch(d){I||(g??=d)}}if(g)throw g}function zhe({baseUrl:n,createWebSocket:t,signal:o,onOpen:i,onEnvelope:e,onMalformed:a}){let A=new URL("/api/events.mux",n);return A.protocol=A.protocol==="https:"?"wss:":"ws:",new Promise((r,s)=>{let g=t(A.toString()),c=!1,I=!1,d=T=>{if(!I){I=!0,g.removeEventListener("open",f),g.removeEventListener("message",Q),g.removeEventListener("close",y),g.removeEventListener("error",m),o.removeEventListener("abort",_);try{(g.readyState===0||g.readyState===1)&&g.close()}catch{}T&&!o.aborted?s(T):r()}},B=()=>d(),f=()=>{I||c||(c=!0,PE(i,B,d))},Q=T=>{if(I)return;let R;try{if(typeof T.data!="string")throw new Error("binary WebSocket frame");R=JSON.parse(T.data)}catch(L){PE(a,L,()=>{});return}PE(e,R,d)},y=()=>d(c?void 0:new Error("Harness event mux WebSocket closed before opening")),m=()=>d(new Error(c?"Harness event mux WebSocket failed":"Harness event mux WebSocket failed before opening")),_=()=>d();g.addEventListener("open",f),g.addEventListener("message",Q),g.addEventListener("close",y,{once:!0}),g.addEventListener("error",m,{once:!0}),o.addEventListener("abort",_,{once:!0}),o.aborted&&_()})}async function RY(n){if(!n.signal.aborted)return n.baseUrl!==void 0&&n.baseUrl!==null?zhe(n):qhe(n)}var Zhe=new Map,Xhe=new WeakMap,$he=64;async function eEe(n){let t=n?.body;if(!t||typeof t.getReader!="function")return null;let o=t.getReader(),i=[],e=0;try{for(;;){let{done:r,value:s}=await o.read();if(r)break;if(!(s instanceof Uint8Array)||e+s.byteLength>$he)return null;i.push(s),e+=s.byteLength}}catch{return null}finally{try{await o.cancel()}catch{}}let a=new Uint8Array(e),A=0;for(let r of i)a.set(r,A),A+=r.byteLength;return new TextDecoder().decode(a)}function AEe(n){if(n==="localhost"||n==="[::1]")return!0;let t=n.split(".");return t.length===4&&t[0]==="127"&&t.every(o=>/^\d{1,3}$/.test(o)&&Number(o)<=255)}async function tEe(n,t){return n.status===401?"harness-auth-required":n.status===407?"harness-proxy-auth-required":n.status===403?(await eEe(n))?.trim()!=="forbidden"?"harness-request-forbidden":AEe(t)?"harness-loopback-forbidden":"harness-host-untrusted":n.status===404?"harness-api-not-found":"harness-http-failed"}function LY(n){let t=typeof n=="string"?Zhe:Xhe,o=t.get(n);return o||(o={ownerships:new Map,claims:new Map,controls:new WeakMap,nextOrder:0},t.set(n,o)),o}function kY(n,t){return new Promise((o,i)=>{let e=()=>t.removeEventListener("abort",a),a=()=>{e(),i(t.reason)};if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),Promise.resolve().then(()=>(t.throwIfAborted(),n())).then(A=>{e(),o(A)},A=>{e(),i(A)})})}function vY(n){let t=typeof n?.owner;return t!=="object"&&t!=="function"||n.owner===null||typeof n.key!="string"||!n.key?null:{owner:n.owner,key:n.key}}function d_(n){return n!==null&&typeof n=="object"&&typeof n.provider=="string"&&!!n.provider&&typeof n.model=="string"&&!!n.model&&(n.reasoningEffort===void 0||typeof n.reasoningEffort=="string"&&!!n.reasoningEffort)}function rEe(n){return n!==null&&typeof n=="object"&&Array.isArray(n.efforts)&&n.efforts.length>0&&n.efforts.every(t=>t!==null&&typeof t=="object"&&typeof t.id=="string"&&!!t.id&&typeof t.name=="string"&&!!t.name&&(t.description===void 0||typeof t.description=="string"))&&(n.defaultEffort===void 0||typeof n.defaultEffort=="string"&&!!n.defaultEffort)}function PY(n,t,{session:o=!1}={}){if(!n||typeof n!="object"||!Array.isArray(n.groups)||!Array.isArray(n.failures))throw new Error(`Harness returned an invalid response for ${t}`);for(let i of n.groups){if(!i||typeof i!="object"||typeof i.id!="string"||!i.id||typeof i.name!="string"||!i.name||!Array.isArray(i.models))throw new Error(`Harness returned an invalid response for ${t}`);for(let e of i.models)if(!e||typeof e!="object"||typeof e.id!="string"||!e.id||typeof e.name!="string"||!e.name||e.description!==void 0&&typeof e.description!="string"||e.reasoning!==void 0&&!rEe(e.reasoning))throw new Error(`Harness returned an invalid response for ${t}`)}for(let i of n.failures)if(!i||typeof i!="object"||typeof i.id!="string"||!i.id||typeof i.name!="string"||!i.name||i.message!==void 0&&typeof i.message!="string")throw new Error(`Harness returned an invalid response for ${t}`);if(o&&(!d_(n.current)||typeof n.routable!="boolean"))throw new Error(`Harness returned an invalid response for ${t}`);return n}function GY(){let n=new Error("Harness turn was stopped before producing a text reply");return n.code="turn-stopped",n}function aEe(n){return Array.isArray(n?.items)?n.items.flatMap(t=>typeof t?.path=="string"&&Whe(t.path)?[t.path]:[]):[]}function iEe(n,t){if(!Array.isArray(t?.items)||!Array.isArray(t?.archivedSessionIds))throw new Error("Harness returned an invalid response for workspace.list");let o=t.items.find(i=>i?.path===n);if(!o)return null;if(!Array.isArray(o.sessionIds)||o.sessionIds.some(i=>typeof i!="string"))throw new Error("Harness returned invalid session IDs for workspace.list");return o}function oEe(n){if(typeof n=="number"&&Number.isFinite(n))return n<1e12?n*1e3:n;if(typeof n=="string"&&n){let t=Date.parse(n);if(!Number.isNaN(t))return t}return null}function nEe(n){if(!n||typeof n!="object")return null;let t=[n?.header?.lastActivityAt,n?.header?.updatedAt,n?.header?.createdAt,n?.projections?.values?.lastActivityAt,n?.projections?.values?.updatedAt,n?.projections?.values?.createdAt,n?.lastActivityAt,n?.updatedAt,n?.createdAt];for(let o of t){let i=oEe(o);if(i!==null)return i}return null}function sEe(n,t,o){if(!Array.isArray(o?.items))throw new Error("Harness returned an invalid response for session.list");let i=new Set(t),e=new Map(o.items.flatMap(a=>typeof a?.sessionId=="string"?[[a.sessionId,a]]:[]));return{workspace:n.path,sessions:n.sessionIds.map(a=>{let A=e.get(a),r=A?.projections?.values?.title,s={sessionId:a,title:typeof r=="string"?r:null,archived:i.has(a),blank:A?.blank===!0,origin:A?.origin==="subagent"?"subagent":null,summaryAvailable:A!==void 0},g=A?.projections?.asOfSeq;Number.isSafeInteger(g)&&g>=-1&&(s.lastSeq=g);let c=nEe(A);return c!==null&&(s.time=c),s})}}function GE(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(()=>{t?.removeEventListener("abort",a),o()},n),a=()=>{clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))};t?.addEventListener("abort",a,{once:!0})})}function gEe(n){return(n?.data?.message?.content??[]).filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(` `).trim()}function Si(n){return typeof n=="string"&&n.trim()?n.trim():null}function cEe(n){if(!n||typeof n!="object")return null;let t=Si(n.message);if(t)return t;let o=Si(n.name),i=Si(n.code);return o||i?[o??"Error",i].filter(Boolean).join(": "):null}function UY(n,t){let o=[...t].map(i=>i?.event??i).filter(Boolean).sort((i,e)=>(i.seq??-1)-(e.seq??-1));for(let i of o){let e=i.seq??-1;if(e<=n.lastSeq)continue;if(n.lastSeq=e,i.type==="turn/start"){let A=i.data?.turn??null;n.active&&A!==n.turn&&(n.active=!1),n.turn!==null&&A!==n.turn&&(n.completed=!0),n.openTurn=A;continue}if(i.type==="user/message"&&i.data?.source?.rpcId===n.promptRpcId){n.active=!0,n.started=!0,n.completed=!1,n.turn=i.data?.turn??n.openTurn;continue}if(i.type==="turn/end"&&i.data?.turn===n.turn){n.active=!1,n.completed=!0;continue}let a=null;if(i.type==="tool/call"&&n.active&&i.data?.turn===n.turn&&typeof i.data?.callId=="string"&&i.data.callId)a={callId:i.data.callId,name:i.data?.name,arguments:i.data?.arguments};else if(i.type==="tool/code-dispatch-start"&&n.active&&typeof i.data?.subCallId=="string"&&i.data.subCallId){let A;try{A=JSON.stringify(i.data?.arguments)}catch{A=void 0}a={callId:i.data.subCallId,name:i.data?.name,arguments:A}}a&&n.toolCalls.set(a.callId,Object.freeze(a))}}function HY(n,t,o=[]){if(!n||!["object","function","string"].includes(typeof n)||typeof t!="string"||!t)return!1;let i=LY(n).ownerships.get(t);if(!i||i.size===0)return!1;for(let e of i)UY(e,o);return[...i].some(e=>e.active&&!e.completed&&typeof e.reconnect=="function")}var Op=class{#e;#A;#t=null;#r=null;#g=new Map;#a="";#n=!1;#i=null;#I=new Map;#l=null;constructor({promptRpcId:t,afterSeq:o=-1}){this.#e=t,this.#A=o}get finished(){return this.#n}get answer(){return this.#a.trim()}get reason(){return this.#i}get tracking(){return this.#r!==null&&!this.#n}get turn(){return this.#r}consumeAll(t){let o=[],i=a=>{if(a.type==="text"&&o.length>0&&o[o.length-1].type==="text"){o[o.length-1]=a;return}o.push(a)},e=[...t].map(a=>a?.event??a).filter(Boolean).sort((a,A)=>(a.seq??-1)-(A.seq??-1));for(let a of e){let A=a.seq??-1;if(!(A<=this.#A)){if(this.#A=A,a.type==="turn/start"&&(this.#t=a.data?.turn??null),a.type==="user/message"&&a.data?.source?.rpcId===this.#e){this.#r=this.#t;continue}if(this.#r!==null){if(a.type==="turn/end"){if(a.data?.turn!==this.#r)continue;this.#n=!0,this.#i=a.data?.reason??null,this.#t=null;continue}if(a.data?.turn===this.#r){if(a.type==="assistant/chunk"&&a.data?.chunk?.type==="text-delta"){let r=a.data?.step??0,s=a.data.chunk.index??0,g=`${r}:${s}`;this.#g.set(g,(this.#g.get(g)??"")+a.data.chunk.text);let c=`${r}:`,I=[...this.#g.entries()].filter(([d])=>d.startsWith(c)).sort(([d],[B])=>Number(d.split(":")[1])-Number(B.split(":")[1])).map(([,d])=>d).join(` -`).trim();I&&I!==this.#a&&(this.#a=I,i({type:"text",text:I}));continue}if(a.type==="assistant/message"){let r=gEe(a);r&&r!==this.#a&&(this.#a=r,i({type:"text",text:r}));continue}if(a.type==="tool/call"){let r=Si(a.data?.name)??w("\u5DE5\u5177"),s=Si(a.data?.callId)??Si(a.data?.subCallId);s&&this.#I.set(s,r),this.#l=r,i({type:"tool",name:r,...s?{callId:s}:{}})}else if(a.type==="tool/result"){let r=Si(a.data?.message?.source?.callId)??Si(a.data?.callId)??Si(a.data?.subCallId),s=(r?this.#I.get(r):null)??this.#l,g=cEe(a.data?.error);i({type:"status",text:w("\u6B63\u5728\u6574\u7406\u7ED3\u679C\u2026"),...s?{toolName:s}:{},...g?{error:g}:{}})}}}}}return o}consume(t){return this.consumeAll(t).at(-1)??null}},pn=class extends Error{constructor(t,o){super(`${t}: ${o?.message??"unknown Harness RPC error"}`),this.name="HarnessRpcError",this.method=t,this.code=o?.code??"internal",this.details=o?.details??{}}},Wn=class extends Error{constructor(t,o,{cause:i,status:e}={}){let a=Number.isInteger(e)?`, HTTP ${e}`:"";super(`Harness ${o} transport failed (${t}${a})`,{cause:i}),this.name="HarnessTransportError",this.code=t,this.method=o,Number.isInteger(e)&&(this.status=e)}},h_=class extends Error{constructor(t){super("Harness health RPC was rejected",{cause:t}),this.name="HarnessHealthError",this.code="harness-rpc-rejected",this.method="host.describe"}},bp=class extends Error{constructor(t,o){super(o),this.name="HarnessInteractionError",this.code=t}},Zn=class extends Error{constructor(t,{reason:o,providerCode:i}={}){super(`Harness turn failed (${t})`),this.name="HarnessTurnError",this.code=t,this.promptAccepted=!0,o&&typeof o=="object"&&(this.reason=o),typeof i=="string"&&i&&(this.providerCode=i)}};function FY(n){let t=Si(n?.kind)??Si(n);if(t==="error"){let o=n?.error??n?.failure;return new Zn("harness-turn-failed",{reason:n,providerCode:Si(o?.code)??void 0})}return t==="max-tokens"?new Zn("model-max-tokens",{reason:n}):t==="blocked"?new Zn("turn-blocked",{reason:n}):["interrupted","stopped","cancelled","canceled"].includes(t)?new Zn("turn-interrupted",{reason:n}):t==="aborted"?new Zn("turn-aborted",{reason:n}):t==="completed"?new Zn("model-empty-response",{reason:n}):new Zn("harness-turn-failed",{reason:n})}function IEe(n){return n==null?!0:(Si(n?.kind)??Si(n))==="completed"}var lr=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c;#p;#d;#h=null;#E;#C;#f;#B;constructor({baseUrl:t,apiProxy:o,interactionScope:i=o,workspace:e,agentPreset:a,autostart:A=!1,dshBin:r="dsh",fetchImpl:s=fetch,createWebSocket:g=m=>new WebSocket(m),interactionReconnectDelayMs:c=500,rpcIdPrefix:I="im",logPrefix:d="dsh-im",commandExecutor:B,controlExecutor:f,sessionMaintenanceExecutor:Q,fileIngressExecutor:y}){if(typeof g!="function")throw new TypeError("createWebSocket must be a function");if(!Number.isFinite(c)||c<0)throw new TypeError("interactionReconnectDelayMs must be a non-negative number");if(typeof I!="string"||!I.trim())throw new TypeError("rpcIdPrefix must be a non-empty string");if(typeof d!="string"||!d.trim())throw new TypeError("logPrefix must be a non-empty string");if(B!==void 0&&typeof B!="function")throw new TypeError("commandExecutor must be a function");if(f!==void 0&&typeof f!="function")throw new TypeError("controlExecutor must be a function");if(Q!==void 0&&typeof Q!="function")throw new TypeError("sessionMaintenanceExecutor must be a function");if(y!==void 0&&typeof y!="function")throw new TypeError("fileIngressExecutor must be a function");if(this.#e=t===void 0?null:new URL(t),this.#A=this.#e?null:o,!this.#e&&(!this.#A||typeof this.#A!="object"))throw new TypeError("HarnessClient requires the current Host apiProxy or an explicit baseUrl");if(this.#A&&(!i||!["object","function"].includes(typeof i)))throw new TypeError("interactionScope must identify the current Host");this.#t=e,this.#r=a??void 0,this.#g=!!(this.#e&&A),this.#a=r,this.#n=s,this.#i=g,this.#I=c,this.#l=I.trim(),this.#o=d.trim(),this.#s=B,this.#c=f,this.#p=Q,this.#d=y,this.#E=LY(this.#e?.origin??i),this.#C=this.#E.ownerships,this.#f=this.#E.claims,this.#B=this.#E.controls}async rpc(t,o={},i=3e4,e={}){let a=e.rpcId??`${this.#l}-${p_()}`,A=AbortSignal.timeout(i),r=e.signal?AbortSignal.any([e.signal,A]):A,s;try{if(this.#A){let[g,c,I]=t.split("."),d={host:"host",workspace:"workspace",session:"sessions",llm:"llm"}[g],B=d&&this.#A[d];if(I!==void 0||!Object.hasOwn(B??{},c)||typeof B[c]!="function")throw new Wn("harness-api-not-found",t);s={type:"server-response",...await kY(()=>B[c]({rpcId:a,payload:o},r),r)}}else{let g=await this.#n(new URL(`/api/${t}`,this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:a,method:t,payload:o}),signal:r});if(!g.ok){let c=await tEe(g,this.#e.hostname);throw new Wn(c,t,{status:g.status})}try{s=await g.json()}catch(c){throw new Wn("harness-response-invalid",t,{cause:c})}}}catch(g){throw e.signal?.aborted||g instanceof Wn?g:new Wn(A.aborted?"harness-timeout":"harness-connect-failed",t,{cause:g})}if(s?.type!=="server-response"||s?.rpcId!==a)throw new Wn("harness-response-invalid",t,{cause:new Error(`Harness returned an invalid response for ${t}`)});if(!s.result||typeof s.result!="object"||typeof s.result.ok!="boolean")throw new Wn("harness-response-invalid",t,{cause:new Error(`Harness returned an invalid result for ${t}`)});if(!s.result?.ok)throw new pn(t,s.result?.error);return s.result.value}async health(t={}){try{return await this.rpc("host.describe",{},5e3,t),!0}catch(o){throw o instanceof pn?new h_(o):o}}async ensureRunning(t={}){try{return await this.health(t)}catch(e){if(!this.#g)throw e}if(!this.#h||this.#h.exitCode!==null){let e=this.#e.port||(this.#e.protocol==="https:"?"443":"80");this.#h=Vhe(this.#a,["web","--host",this.#e.hostname,"--port",e],{cwd:this.#t,env:process.env,stdio:["ignore","inherit","inherit"]}),this.#h.on("error",a=>{console.error(`[${this.#o}] failed to start Harness:`,a.message)})}let o=Date.now()+6e4,i;for(;Date.now(){let r=A&&i.signal?AbortSignal.any([A,i.signal]):A??i.signal;return this.rpc("session.selectModel",{sessionId:t,provider:o.provider,model:o.model,...o.reasoningEffort===void 0?{}:{reasoningEffort:o.reasoningEffort}},3e4,r?{...i,signal:r}:i)},a=this.#p?await this.#p({sessionId:t,operation:e}):await e();if(!a||typeof a!="object"||!d_(a.selected))throw new Error("Harness returned an invalid response for session.selectModel");return a}async isSessionRunning(t,o={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");await this.ensureRunning(o);let i=await this.rpc("session.list",{},3e4,o);if(!i||typeof i!="object"||!Array.isArray(i.items))throw new Error("Harness returned an invalid response for session.list");for(let e of i.items)if(!e||typeof e!="object"||typeof e.sessionId!="string"||!e.sessionId||typeof e.running!="boolean")throw new Error("Harness returned an invalid response for session.list");return i.items.find(e=>e.sessionId===t)?.running??!1}async adoptWorkspaceSession(t,o={}){return NY(this,t,o)}async workspaceId(t={}){let{workspace:o=this.#t,...i}=t,{items:e}=await this.rpc("workspace.list",{},3e4,i),a=e.find(r=>r.path===o);return a?a.workspaceId:(await this.rpc("workspace.create",{path:o},3e4,i)).workspace.workspaceId}async createSession(t={}){let{agentPreset:o,...i}=t;await this.ensureRunning(i);let a={workspaceId:await this.workspaceId(i)},A=o!==void 0?o:this.#r;return A!=null&&(a.agentPreset=A),(await this.rpc("session.create",a,3e4,i)).sessionId}async executeCommand(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(typeof o!="string"||!o)throw new TypeError("command line is required");if(!this.#s){let e=new Error("Harness command execution is unavailable");throw e.code="commands-unavailable",e}try{return await this.#s(t,o,i)}catch(e){throw e?.failure&&typeof e.failure=="object"?new pn("commands.execute",e.failure):e}}async readSessionHistory(t,{maxMessages:o=50,beforeSeq:i,timeoutMs:e=1e4,...a}={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(!Number.isSafeInteger(o)||o<1||i!==void 0&&(!Number.isSafeInteger(i)||i<0))throw new TypeError("Invalid history pagination");return this.rpc("session.history",{sessionId:t,maxMessages:o,...i===void 0?{}:{beforeSeq:i}},e,a)}async sessionExists(t,o={}){try{return await this.rpc("session.history",{sessionId:t,maxMessages:1},3e4,o),!0}catch(i){if(i instanceof pn&&i.code==="session-not-found")return!1;throw i}}async respondInteraction(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("rpcId is required");if(!o||typeof o!="object"||typeof o.ok!="boolean")throw new TypeError("A Harness RPC result is required");let e=AbortSignal.timeout(i.timeoutMs??3e4),a=i.signal?AbortSignal.any([i.signal,e]):e,A={type:"client-response",rpcId:t,result:o},r;if(this.#A)r=await kY(()=>this.#A.respond(A),a);else{let g=await this.#n(new URL("/api/respond",this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(A),signal:a});if(!g.ok)throw new Error(`Harness transport respond failed: HTTP ${g.status}`);r=await g.json()}if(r?.accepted===!0)return r;if(r?.accepted!==!1||r.reason!=="bad-response"&&r.reason!=="not-pending")throw new Error("Harness returned an invalid interaction response receipt");let s=r.reason;throw new bp(`interaction-${s}`,`Harness interaction response was rejected (${s})`)}async watchInteractions(t,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(!o||typeof o.addEventListener!="function")throw new TypeError("watchInteractions requires an AbortSignal");if(i!==void 0&&typeof i!="function")throw new TypeError("onInteraction must be a function");if(e!==void 0&&typeof e!="function")throw new TypeError("onResolved must be a function");if(a!==void 0&&typeof a!="function")throw new TypeError("onOpen must be a function");for(;!o.aborted;){try{await this.#k(t,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A})}catch(r){if(o.aborted)return;console.warn(`[${this.#o}] Harness interaction stream disconnected:`,r.message)}if(o.aborted)return;try{await GE(this.#I,o)}catch{if(o.aborted)return;throw new Error("Harness interaction reconnect wait failed")}}}#y(t,o){let i=this.#C.get(t)??new Set;o.order=this.#E.nextOrder,this.#E.nextOrder+=1,i.add(o),this.#C.set(t,i)}#S(t,o){let i=this.#C.get(t);i?.delete(o),i?.size===0&&this.#C.delete(t);for(let[e,a]of this.#f)a.ownership===o&&this.#f.delete(e)}#Q(t){if(!t.control)return;let o=this.#B.get(t.control.owner);o||(o=new Map,this.#B.set(t.control.owner,o));let i=o.get(t.control.key)??new Set;i.add(t),o.set(t.control.key,i)}#m(t){if(!t.control)return;let o=this.#B.get(t.control.owner),i=o?.get(t.control.key);i?.delete(t),i?.size===0&&o.delete(t.control.key),o?.size===0&&this.#B.delete(t.control.owner)}#u(t,o){let i=vY(o);return i?[...this.#B.get(i.owner)?.get(i.key)??[]].filter(a=>a.sessionId===t).sort((a,A)=>a.order-A.order):[]}#b(t,o){return this.#u(t,o).find(i=>i.started&&i.active&&!i.completed&&i.turn!==null)??null}async#R(t,o,i){let e=this.#u(t,o);if(e.length===0)return null;try{let a=await this.rpc("session.history",{sessionId:t,maxMessages:50},3e4,i);this.#D(t,a.events??[])}catch(a){if(!(a instanceof pn)||a.code!=="session-not-found")throw a;for(let A of e)A.active=!1,A.completed=!0;return null}return this.#b(t,o)}async hasActiveTurn(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");return!!await this.#R(t,o,i)}async stopActiveTurn(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");let e=await this.#R(t,o,i);if(!e)return!1;if(e.stopRequested)return!0;if(this.#b(t,o)!==e)return!1;e.stopRequested=!0;try{if(this.#c){let a=this.#c({sessionId:t,expectedTurn:e.turn,promptRpcId:e.promptRpcId,action:"stop"});if(a&&typeof a.then=="function")throw new TypeError("controlExecutor must return synchronously");if(a!==void 0){if(typeof a!="boolean")throw new TypeError("controlExecutor must return a boolean or undefined");return a||(e.stopRequested=!1),a}}return await this.rpc("session.cancel",{sessionId:t,keepInbox:!0},3e4,i),!0}catch(a){if(this.#b(t,o)===e&&(e.stopRequested=!1),a instanceof pn&&a.code==="session-not-found")return!1;throw a}}async steerActiveTurn(t,o,i,e={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(typeof o!="string"||!o.trim())throw new TypeError("Steering text is required");let a=await this.#R(t,i,e);if(!a||a.stopRequested||this.#b(t,i)!==a)return!1;if(this.#c){let A=this.#c({sessionId:t,expectedTurn:a.turn,promptRpcId:a.promptRpcId,action:"steer",text:o});if(A&&typeof A.then=="function")throw new TypeError("controlExecutor must return synchronously");if(A!==void 0){if(typeof A!="boolean")throw new TypeError("controlExecutor must return a boolean or undefined");return A}}return await this.rpc("session.prompt",{sessionId:t,mode:"steer",content:[{type:"text",text:o}],clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,e),!0}#D(t,o){for(let i of this.#C.get(t)??[])UY(i,o)}async#w(t,o){let i=await this.rpc("session.history",{sessionId:t,maxMessages:50},3e4,{signal:o});this.#D(t,i.events??[])}#T(t,o,i){let e=this.#f.get(o);if(e&&this.#C.get(t)?.has(e.ownership))return e;let a=[...this.#C.get(t)??[]],A=a.filter(s=>s.active).sort((s,g)=>s.order-g.order);if(A.length>0)return{ownership:A[0],recovered:!1};let r=a.filter(s=>!s.started&&!s.completed).sort((s,g)=>s.order-g.order)[0]??null;return r?{ownership:r,recovered:!0}:null}async ask(t,o,i={}){typeof i=="number"&&(i={timeoutMs:i});let e=i.timeoutMs??6e5,a=i.signal,A=typeof i.onUpdate=="function"?i.onUpdate:null,r=i.progressMode==="all"?"all":"latest",s=typeof i.onArtifact=="function"?i.onArtifact:null,g=typeof i.onInteraction=="function"?i.onInteraction:void 0,c=typeof i.onInteractionResolved=="function"?i.onInteractionResolved:void 0,I=vY(i.control),d=Array.isArray(i.files)?i.files.filter(Boolean):[];await this.ensureRunning({signal:a});let B=await this.rpc("session.history",{sessionId:t,maxMessages:1},3e4,{signal:a}),f=Math.max(-1,...(B.events??[]).map(({event:J})=>J.seq??-1)),Q=`${this.#l}-${p_()}`,y=new Op({promptRpcId:Q,afterSeq:f}),m=g||c?new AbortController:null,_=m?a?AbortSignal.any([a,m.signal]):m.signal:null,T=m||I?{sessionId:t,promptRpcId:Q,active:!1,started:!1,completed:!1,stopRequested:!1,turn:null,openTurn:null,lastSeq:f,reconnect:null,order:-1,toolCalls:new Map,control:I}:null,R=null,F=!1,K=0,L=null,q=!1,z=!1,j=async()=>{if(!s||F||y.turn===null)return K;F=!0;let J=wI.take(t,y.turn,{signal:a});for(let U of J)try{await s(U),K+=1}catch(N){wI.release(U),console.warn(`[${this.#o}] ignored an artifact handoff failure:`,N.message)}return K};T&&(this.#y(t,T),this.#Q(T));let P=wI.openConsumer(t,Q);try{if(d.length>0){if(!this.#d)throw new Do("inbound-file-ingress-unavailable","Harness file ingress is unavailable in this Host process.");let N=(await this.rpc("session.list",{},3e4,{signal:a}))?.items?.find(k=>k?.sessionId===t)?.cwd;L=await this.#d({sessionId:t,workspace:N,files:d,signal:a}),o=lY(o,L)}if(_){let U,N=new Promise(k=>{U=k});R=this.watchInteractions(t,{signal:_,onInteraction:g,onResolved:c,onOpen:U,ownership:T}),R.catch(()=>{}),await Promise.race([N,GE(3e4,_).then(()=>{throw new Error("Harness interaction stream did not open within 30 seconds")})])}let J=typeof o=="string"?[{type:"text",text:o}]:o;if(!Array.isArray(J)||J.length===0)throw new TypeError("Harness prompt content is required");await this.rpc("session.prompt",{sessionId:t,mode:"queue",content:J,clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,{rpcId:Q,signal:a}),q=!0;try{let U=Date.now()+e;for(;Date.now()0)return"";throw T?.stopRequested?GY():FY(y.reason)}throw new Zn("harness-reply-timeout")}catch(U){if(!T?.stopRequested)throw U;if(y.answer)return y.answer;throw U?.code==="turn-stopped"?U:GY()}}finally{L&&(!q||z)&&await L.cleanup().catch(J=>{console.warn(`[${this.#o}] unable to clean inbound files:`,J.message)}),P(),T&&(this.#m(T),this.#S(t,T)),y.turn!==null&&wI.discard(t,y.turn),m?.abort(new DOMException("Harness turn finished","AbortError")),R&&await R.catch(()=>{})}}async#k(t,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}){let r=!1,s=null,g=Promise.resolve(),c=A==null,I=[],d=()=>{},B=m=>{d=m,A&&(A.reconnect=d);try{a?.()}catch(_){console.warn(`[${this.#o}] ignored an interaction open callback failure:`,_.message)}A&&this.#w(t,o).then(()=>{if(!r){c=!0;for(let _ of I.splice(0))Q(_)}}).catch(_=>{s??=_,d()})},f=(m,_)=>{m&&(g=g.then(()=>m(_)).catch(T=>{s??=T,d()}))},Q=m=>{let _=m.payload;if(A&&_.type==="session/event"){this.#D(t,[_.event]);return}if(_.type==="question/requested"||_.type==="approval/requested"){let T=_.type==="question/requested"?"question":"approval",R=T==="question"?m.rpcId:_.approvalId,F=`${T}:${R}`;if(A){let L=this.#T(t,F,T);if(L?.ownership!==A)return;this.#f.set(F,L)}let K=T==="approval"&&A&&typeof _.callId=="string"?this.#f.get(F)?.ownership.toolCalls.get(_.callId):void 0;f(i,Object.freeze({kind:T,interactionId:R,rpcId:m.rpcId,sessionId:t,payload:_,recovered:A?this.#f.get(F)?.recovered===!0:!1,...K?{toolCall:K}:{},reconnect:d,respond:(L,q={})=>this.respondInteraction(m.rpcId,L,{...q,signal:q.signal??o})}));return}if(_.type==="question/resolved"||_.type==="approval/resolved"){let T=_.type==="question/resolved"?"question":"approval",R=T==="question"?_.questionRpcId:_.approvalId,F=`${T}:${R}`;if(A){if(this.#f.get(F)?.ownership!==A)return;this.#f.delete(F)}f(e,Object.freeze({kind:T,interactionId:R,sessionId:t,outcome:_.outcome,payload:_}))}},y=m=>{try{let _=m?.payload;if(m?.type!=="server-request"||typeof m.rpcId!="string"||!_||typeof _!="object"||m.method!==_.type)throw new Error("invalid server-request envelope");if(_.sessionId!==t)return;c?Q(m):I.push(m)}catch(_){console.warn(`[${this.#o}] ignored a malformed Harness interaction frame:`,_.message)}};try{await this.#M({signal:o,onOpen:B,onEnvelope:y})}finally{r=!0,A?.reconnect===d&&(A.reconnect=null),o.aborted||await g}if(!o.aborted&&s)throw s}async watchHarnessEvents({signal:t,onSessionEvent:o,onReconnect:i}={}){if(typeof o!="function")throw new TypeError("watchHarnessEvents requires onSessionEvent");if(!t||typeof t.addEventListener!="function")throw new TypeError("watchHarnessEvents requires an AbortSignal");if(i!==void 0&&typeof i!="function")throw new TypeError("onReconnect must be a function");for(;!t.aborted;){try{await this.#M({signal:t,onOpen:()=>{try{i?.()}catch(e){console.warn(`[${this.#o}] mux reconnect hook failed:`,e.message)}},onEnvelope:e=>{try{let a=e?.payload;if(e?.type!=="server-request"||!a||typeof a!="object"||e.method!==a.type||a.type!=="session/event"||typeof a.sessionId!="string"||!a.event||typeof a.event!="object")return;o({sessionId:a.sessionId,event:a.event})}catch(a){console.warn(`[${this.#o}] ignored a malformed global mux frame:`,a.message)}}})}catch(e){if(t.aborted)return;console.warn(`[${this.#o}] Harness event mux disconnected:`,e.message)}if(t.aborted)return;try{await GE(this.#I,t)}catch{if(t.aborted)return;throw new Error("Harness event mux reconnect wait failed")}}}#M(t){return RY({apiProxy:this.#A,baseUrl:this.#e,createWebSocket:this.#i,rpcId:`${this.#l}-${p_()}`,...t,onMalformed:o=>{console.warn(`[${this.#o}] ignored a malformed Harness mux frame:`,o.message)}})}stopManagedProcess(){this.#h?.exitCode===null&&this.#h.kill("SIGTERM")}};var yQ=class extends lr{constructor(t){super({...t,rpcIdPrefix:"dingtalk",logPrefix:"dsh-dingtalk"})}};import{randomUUID as lEe}from"node:crypto";import{mkdir as pEe,readFile as dEe,rename as hEe,unlink as EEe,writeFile as CEe}from"node:fs/promises";import{dirname as uEe}from"node:path";var mQ=Object.freeze({version:1,sessions:{},seenMessageIds:[],pendingSenders:{}});function pr(n){return typeof n=="string"&&n.trim()?n.trim():null}function KY(n){return(pr(n)??w("\u9489\u9489\u7528\u6237")).slice(0,100)}function BEe(n,t){if(!n||typeof n!="object")return null;let o=pr(n.requestId)??pr(t),i=pr(n.staffId),e=pr(n.requestedAt)??pr(n.lastSeenAt),a=pr(n.lastSeenAt)??e;return!o||!i||!e||!a?null:{requestId:o,staffId:i,displayName:KY(n.displayName??n.nick),requestedAt:e,lastSeenAt:a}}function fEe(n){if(!n||typeof n!="object")return structuredClone(mQ);let t={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[e,a]of Object.entries(n.sessions)){let A=pr(e),r=pr(a);A&&r&&(t[A]=r)}let o={},i=Array.isArray(n.pendingSenders)?n.pendingSenders.map(e=>[e?.requestId,e]):Object.entries(n.pendingSenders&&typeof n.pendingSenders=="object"?n.pendingSenders:{});for(let[e,a]of i){let A=BEe(a,e);if(!A)continue;let r=Object.values(o).find(s=>s.staffId===A.staffId);(!r||r.lastSeenAtnew Date().toISOString()}={}){if(!pr(t))throw new TypeError("state path is required");if(typeof o!="function"||typeof i!="function")throw new TypeError("idFactory and now must be functions");this.#e=t,this.#r=o,this.#g=i}async load(){try{this.#A=fEe(JSON.parse(await dEe(this.#e,"utf8")))}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=structuredClone(mQ),await this.#a()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){let i=pr(t),e=pr(o);if(!i||!e)throw new TypeError("key and sessionId are required");this.#A.sessions[i]=e,await this.#a()}async clearSession(t){let o=pr(t);!o||!(o in this.#A.sessions)||(delete this.#A.sessions[o],await this.#a())}async clearSessions(){this.#A.sessions={},await this.#a()}hasSeen(t){let o=pr(t);return!!(o&&this.#A.seenMessageIds.includes(o))}async markSeen(t){let o=pr(t);if(!o)throw new TypeError("messageId is required");this.hasSeen(o)||(this.#A.seenMessageIds.push(o),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#a())}pendingSenders(){return Object.values(this.#A.pendingSenders).sort((t,o)=>t.requestedAt.localeCompare(o.requestedAt)).map(t=>structuredClone(t))}pendingSender(t){let o=pr(t),i=o?this.#A.pendingSenders[o]:null;return i?structuredClone(i):null}async recordPendingSender(t,o,i){let e=t&&typeof t=="object"?t:{staffId:t,displayName:o,lastSeenAt:i},a=pr(e.staffId);if(!a)throw new TypeError("staffId is required");let A=pr(e.lastSeenAt)??pr(e.requestedAt)??this.#g(),r=Object.values(this.#A.pendingSenders).find(g=>g.staffId===a),s={requestId:r?.requestId??`ding_sender_${this.#r()}`,staffId:a,displayName:KY(e.displayName??e.nick??o),requestedAt:r?.requestedAt??A,lastSeenAt:A};return this.#A.pendingSenders[s.requestId]=s,await this.#a(),structuredClone(s)}async removePendingSender(t){let o=pr(t);return!o||!this.#A.pendingSenders[o]?!1:(delete this.#A.pendingSenders[o],await this.#a(),!0)}async removePendingSenderByStaffId(t){let o=pr(t),i=o?Object.values(this.#A.pendingSenders).find(e=>e.staffId===o):null;return i?this.removePendingSender(i.requestId):!1}snapshot(){return structuredClone(this.#A)}async remove(){await this.#t;try{await EEe(this.#e)}catch(t){if(t?.code!=="ENOENT")throw t}this.#A=structuredClone(mQ)}async#a(){let t=`${JSON.stringify(this.#A,null,2)} +`).trim();I&&I!==this.#a&&(this.#a=I,i({type:"text",text:I}));continue}if(a.type==="assistant/message"){let r=gEe(a);r&&r!==this.#a&&(this.#a=r,i({type:"text",text:r}));continue}if(a.type==="tool/call"){let r=Si(a.data?.name)??w("\u5DE5\u5177"),s=Si(a.data?.callId)??Si(a.data?.subCallId);s&&this.#I.set(s,r),this.#l=r,i({type:"tool",name:r,...s?{callId:s}:{}})}else if(a.type==="tool/result"){let r=Si(a.data?.message?.source?.callId)??Si(a.data?.callId)??Si(a.data?.subCallId),s=(r?this.#I.get(r):null)??this.#l,g=cEe(a.data?.error);i({type:"status",text:w("\u6B63\u5728\u6574\u7406\u7ED3\u679C\u2026"),...s?{toolName:s}:{},...g?{error:g}:{}})}}}}}return o}consume(t){return this.consumeAll(t).at(-1)??null}},pn=class extends Error{constructor(t,o){super(`${t}: ${o?.message??"unknown Harness RPC error"}`),this.name="HarnessRpcError",this.method=t,this.code=o?.code??"internal",this.details=o?.details??{}}},Wn=class extends Error{constructor(t,o,{cause:i,status:e}={}){let a=Number.isInteger(e)?`, HTTP ${e}`:"";super(`Harness ${o} transport failed (${t}${a})`,{cause:i}),this.name="HarnessTransportError",this.code=t,this.method=o,Number.isInteger(e)&&(this.status=e)}},h_=class extends Error{constructor(t){super("Harness health RPC was rejected",{cause:t}),this.name="HarnessHealthError",this.code="harness-rpc-rejected",this.method="host.describe"}},bp=class extends Error{constructor(t,o){super(o),this.name="HarnessInteractionError",this.code=t}},Zn=class extends Error{constructor(t,{reason:o,providerCode:i}={}){super(`Harness turn failed (${t})`),this.name="HarnessTurnError",this.code=t,this.promptAccepted=!0,o&&typeof o=="object"&&(this.reason=o),typeof i=="string"&&i&&(this.providerCode=i)}};function FY(n){let t=Si(n?.kind)??Si(n);if(t==="error"){let o=n?.error??n?.failure;return new Zn("harness-turn-failed",{reason:n,providerCode:Si(o?.code)??void 0})}return t==="max-tokens"?new Zn("model-max-tokens",{reason:n}):t==="blocked"?new Zn("turn-blocked",{reason:n}):["interrupted","stopped","cancelled","canceled"].includes(t)?new Zn("turn-interrupted",{reason:n}):t==="aborted"?new Zn("turn-aborted",{reason:n}):t==="completed"?new Zn("model-empty-response",{reason:n}):new Zn("harness-turn-failed",{reason:n})}function IEe(n){return n==null?!0:(Si(n?.kind)??Si(n))==="completed"}var lr=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c;#p;#d;#h=null;#E;#C;#f;#B;constructor({baseUrl:t,apiProxy:o,interactionScope:i=o,workspace:e,agentPreset:a,autostart:A=!1,dshBin:r="dsh",fetchImpl:s=fetch,createWebSocket:g=m=>new WebSocket(m),interactionReconnectDelayMs:c=500,rpcIdPrefix:I="im",logPrefix:d="dsh-im",commandExecutor:B,controlExecutor:f,sessionMaintenanceExecutor:Q,fileIngressExecutor:y}){if(typeof g!="function")throw new TypeError("createWebSocket must be a function");if(!Number.isFinite(c)||c<0)throw new TypeError("interactionReconnectDelayMs must be a non-negative number");if(typeof I!="string"||!I.trim())throw new TypeError("rpcIdPrefix must be a non-empty string");if(typeof d!="string"||!d.trim())throw new TypeError("logPrefix must be a non-empty string");if(B!==void 0&&typeof B!="function")throw new TypeError("commandExecutor must be a function");if(f!==void 0&&typeof f!="function")throw new TypeError("controlExecutor must be a function");if(Q!==void 0&&typeof Q!="function")throw new TypeError("sessionMaintenanceExecutor must be a function");if(y!==void 0&&typeof y!="function")throw new TypeError("fileIngressExecutor must be a function");if(this.#e=t===void 0?null:new URL(t),this.#A=this.#e?null:o,!this.#e&&(!this.#A||typeof this.#A!="object"))throw new TypeError("HarnessClient requires the current Host apiProxy or an explicit baseUrl");if(this.#A&&(!i||!["object","function"].includes(typeof i)))throw new TypeError("interactionScope must identify the current Host");this.#t=e,this.#r=a??void 0,this.#g=!!(this.#e&&A),this.#a=r,this.#n=s,this.#i=g,this.#I=c,this.#l=I.trim(),this.#o=d.trim(),this.#s=B,this.#c=f,this.#p=Q,this.#d=y,this.#E=LY(this.#e?.origin??i),this.#C=this.#E.ownerships,this.#f=this.#E.claims,this.#B=this.#E.controls}async rpc(t,o={},i=3e4,e={}){let a=e.rpcId??`${this.#l}-${p_()}`,A=AbortSignal.timeout(i),r=e.signal?AbortSignal.any([e.signal,A]):A,s;try{if(this.#A){let[g,c,I]=t.split("."),d={host:"host",workspace:"workspace",session:"sessions",llm:"llm"}[g],B=d&&this.#A[d];if(I!==void 0||!Object.hasOwn(B??{},c)||typeof B[c]!="function")throw new Wn("harness-api-not-found",t);s={type:"server-response",...await kY(()=>B[c]({rpcId:a,payload:o},r),r)}}else{let g=await this.#n(new URL(`/api/${t}`,this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:a,method:t,payload:o}),signal:r});if(!g.ok){let c=await tEe(g,this.#e.hostname);throw new Wn(c,t,{status:g.status})}try{s=await g.json()}catch(c){throw new Wn("harness-response-invalid",t,{cause:c})}}}catch(g){throw e.signal?.aborted||g instanceof Wn?g:new Wn(A.aborted?"harness-timeout":"harness-connect-failed",t,{cause:g})}if(s?.type!=="server-response"||s?.rpcId!==a)throw new Wn("harness-response-invalid",t,{cause:new Error(`Harness returned an invalid response for ${t}`)});if(!s.result||typeof s.result!="object"||typeof s.result.ok!="boolean")throw new Wn("harness-response-invalid",t,{cause:new Error(`Harness returned an invalid result for ${t}`)});if(!s.result?.ok)throw new pn(t,s.result?.error);return s.result.value}async health(t={}){try{return await this.rpc("host.describe",{},5e3,t),!0}catch(o){throw o instanceof pn?new h_(o):o}}async ensureRunning(t={}){try{return await this.health(t)}catch(e){if(!this.#g)throw e}if(!this.#h||this.#h.exitCode!==null){let e=this.#e.port||(this.#e.protocol==="https:"?"443":"80");this.#h=Vhe(this.#a,["web","--host",this.#e.hostname,"--port",e],{cwd:this.#t,env:process.env,stdio:["ignore","inherit","inherit"]}),this.#h.on("error",a=>{console.error(`[${this.#o}] failed to start Harness:`,a.message)})}let o=Date.now()+6e4,i;for(;Date.now(){let r=A&&i.signal?AbortSignal.any([A,i.signal]):A??i.signal;return this.rpc("session.selectModel",{sessionId:t,provider:o.provider,model:o.model,...o.reasoningEffort===void 0?{}:{reasoningEffort:o.reasoningEffort}},3e4,r?{...i,signal:r}:i)},a=this.#p?await this.#p({sessionId:t,operation:e}):await e();if(!a||typeof a!="object"||!d_(a.selected))throw new Error("Harness returned an invalid response for session.selectModel");return a}async isSessionRunning(t,o={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");await this.ensureRunning(o);let i=await this.rpc("session.list",{},3e4,o);if(!i||typeof i!="object"||!Array.isArray(i.items))throw new Error("Harness returned an invalid response for session.list");for(let e of i.items)if(!e||typeof e!="object"||typeof e.sessionId!="string"||!e.sessionId||typeof e.running!="boolean")throw new Error("Harness returned an invalid response for session.list");return i.items.find(e=>e.sessionId===t)?.running??!1}async adoptWorkspaceSession(t,o={}){return NY(this,t,o)}async workspaceId(t={}){let{workspace:o=this.#t,...i}=t,{items:e}=await this.rpc("workspace.list",{},3e4,i),a=e.find(r=>r.path===o);return a?a.workspaceId:(await this.rpc("workspace.create",{path:o},3e4,i)).workspace.workspaceId}async createSession(t={}){let{agentPreset:o,...i}=t;await this.ensureRunning(i);let a={workspaceId:await this.workspaceId(i)},A=o!==void 0?o:this.#r;return A!=null&&(a.agentPreset=A),(await this.rpc("session.create",a,3e4,i)).sessionId}async executeCommand(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(typeof o!="string"||!o)throw new TypeError("command line is required");if(!this.#s){let e=new Error("Harness command execution is unavailable");throw e.code="commands-unavailable",e}try{return await this.#s(t,o,i)}catch(e){throw e?.failure&&typeof e.failure=="object"?new pn("commands.execute",e.failure):e}}async readSessionHistory(t,{maxMessages:o=50,beforeSeq:i,timeoutMs:e=1e4,...a}={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(!Number.isSafeInteger(o)||o<1||i!==void 0&&(!Number.isSafeInteger(i)||i<0))throw new TypeError("Invalid history pagination");return this.rpc("session.history",{sessionId:t,maxMessages:o,...i===void 0?{}:{beforeSeq:i}},e,a)}async sessionExists(t,o={}){try{return await this.rpc("session.history",{sessionId:t,maxMessages:1},3e4,o),!0}catch(i){if(i instanceof pn&&i.code==="session-not-found")return!1;throw i}}async respondInteraction(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("rpcId is required");if(!o||typeof o!="object"||typeof o.ok!="boolean")throw new TypeError("A Harness RPC result is required");let e=AbortSignal.timeout(i.timeoutMs??3e4),a=i.signal?AbortSignal.any([i.signal,e]):e,A={type:"client-response",rpcId:t,result:o},r;if(this.#A)r=await kY(()=>this.#A.respond(A),a);else{let g=await this.#n(new URL("/api/respond",this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(A),signal:a});if(!g.ok)throw new Error(`Harness transport respond failed: HTTP ${g.status}`);r=await g.json()}if(r?.accepted===!0)return r;if(r?.accepted!==!1||r.reason!=="bad-response"&&r.reason!=="not-pending")throw new Error("Harness returned an invalid interaction response receipt");let s=r.reason;throw new bp(`interaction-${s}`,`Harness interaction response was rejected (${s})`)}async watchInteractions(t,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(!o||typeof o.addEventListener!="function")throw new TypeError("watchInteractions requires an AbortSignal");if(i!==void 0&&typeof i!="function")throw new TypeError("onInteraction must be a function");if(e!==void 0&&typeof e!="function")throw new TypeError("onResolved must be a function");if(a!==void 0&&typeof a!="function")throw new TypeError("onOpen must be a function");for(;!o.aborted;){try{await this.#k(t,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A})}catch(r){if(o.aborted)return;console.warn(`[${this.#o}] Harness interaction stream disconnected:`,r.message)}if(o.aborted)return;try{await GE(this.#I,o)}catch{if(o.aborted)return;throw new Error("Harness interaction reconnect wait failed")}}}#y(t,o){let i=this.#C.get(t)??new Set;o.order=this.#E.nextOrder,this.#E.nextOrder+=1,i.add(o),this.#C.set(t,i)}#S(t,o){let i=this.#C.get(t);i?.delete(o),i?.size===0&&this.#C.delete(t);for(let[e,a]of this.#f)a.ownership===o&&this.#f.delete(e)}#Q(t){if(!t.control)return;let o=this.#B.get(t.control.owner);o||(o=new Map,this.#B.set(t.control.owner,o));let i=o.get(t.control.key)??new Set;i.add(t),o.set(t.control.key,i)}#m(t){if(!t.control)return;let o=this.#B.get(t.control.owner),i=o?.get(t.control.key);i?.delete(t),i?.size===0&&o.delete(t.control.key),o?.size===0&&this.#B.delete(t.control.owner)}#u(t,o){let i=vY(o);return i?[...this.#B.get(i.owner)?.get(i.key)??[]].filter(a=>a.sessionId===t).sort((a,A)=>a.order-A.order):[]}#b(t,o){return this.#u(t,o).find(i=>i.started&&i.active&&!i.completed&&i.turn!==null)??null}async#R(t,o,i){let e=this.#u(t,o);if(e.length===0)return null;try{let a=await this.rpc("session.history",{sessionId:t,maxMessages:50},3e4,i);this.#D(t,a.events??[])}catch(a){if(!(a instanceof pn)||a.code!=="session-not-found")throw a;for(let A of e)A.active=!1,A.completed=!0;return null}return this.#b(t,o)}async hasActiveTurn(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");return!!await this.#R(t,o,i)}async stopActiveTurn(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");let e=await this.#R(t,o,i);if(!e)return!1;if(e.stopRequested)return!0;if(this.#b(t,o)!==e)return!1;e.stopRequested=!0;try{if(this.#c){let a=this.#c({sessionId:t,expectedTurn:e.turn,promptRpcId:e.promptRpcId,action:"stop"});if(a&&typeof a.then=="function")throw new TypeError("controlExecutor must return synchronously");if(a!==void 0){if(typeof a!="boolean")throw new TypeError("controlExecutor must return a boolean or undefined");return a||(e.stopRequested=!1),a}}return await this.rpc("session.cancel",{sessionId:t,keepInbox:!0},3e4,i),!0}catch(a){if(this.#b(t,o)===e&&(e.stopRequested=!1),a instanceof pn&&a.code==="session-not-found")return!1;throw a}}async steerActiveTurn(t,o,i,e={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(typeof o!="string"||!o.trim())throw new TypeError("Steering text is required");let a=await this.#R(t,i,e);if(!a||a.stopRequested||this.#b(t,i)!==a)return!1;if(this.#c){let A=this.#c({sessionId:t,expectedTurn:a.turn,promptRpcId:a.promptRpcId,action:"steer",text:o});if(A&&typeof A.then=="function")throw new TypeError("controlExecutor must return synchronously");if(A!==void 0){if(typeof A!="boolean")throw new TypeError("controlExecutor must return a boolean or undefined");return A}}return await this.rpc("session.prompt",{sessionId:t,mode:"steer",content:[{type:"text",text:o}],clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,e),!0}#D(t,o){for(let i of this.#C.get(t)??[])UY(i,o)}async#w(t,o){let i=await this.rpc("session.history",{sessionId:t,maxMessages:50},3e4,{signal:o});this.#D(t,i.events??[])}#T(t,o,i){let e=this.#f.get(o);if(e&&this.#C.get(t)?.has(e.ownership))return e;let a=[...this.#C.get(t)??[]],A=a.filter(s=>s.active).sort((s,g)=>s.order-g.order);if(A.length>0)return{ownership:A[0],recovered:!1};let r=a.filter(s=>!s.started&&!s.completed).sort((s,g)=>s.order-g.order)[0]??null;return r?{ownership:r,recovered:!0}:null}async ask(t,o,i={}){typeof i=="number"&&(i={timeoutMs:i});let e=i.timeoutMs??6e5,a=i.signal,A=typeof i.onUpdate=="function"?i.onUpdate:null,r=i.progressMode==="all"?"all":"latest",s=typeof i.onArtifact=="function"?i.onArtifact:null,g=typeof i.onInteraction=="function"?i.onInteraction:void 0,c=typeof i.onInteractionResolved=="function"?i.onInteractionResolved:void 0,I=vY(i.control),d=Array.isArray(i.files)?i.files.filter(Boolean):[];await this.ensureRunning({signal:a});let B=await this.rpc("session.history",{sessionId:t,maxMessages:1},3e4,{signal:a}),f=Math.max(-1,...(B.events??[]).map(({event:J})=>J.seq??-1)),Q=`${this.#l}-${p_()}`,y=new Op({promptRpcId:Q,afterSeq:f}),m=g||c?new AbortController:null,_=m?a?AbortSignal.any([a,m.signal]):m.signal:null,T=m||I?{sessionId:t,promptRpcId:Q,active:!1,started:!1,completed:!1,stopRequested:!1,turn:null,openTurn:null,lastSeq:f,reconnect:null,order:-1,toolCalls:new Map,control:I}:null,R=null,L=!1,U=0,F=null,q=!1,z=!1,j=async()=>{if(!s||L||y.turn===null)return U;L=!0;let J=wI.take(t,y.turn,{signal:a});for(let H of J)try{await s(H),U+=1}catch(N){wI.release(H),console.warn(`[${this.#o}] ignored an artifact handoff failure:`,N.message)}return U};T&&(this.#y(t,T),this.#Q(T));let P=wI.openConsumer(t,Q);try{if(d.length>0){if(!this.#d)throw new Do("inbound-file-ingress-unavailable","Harness file ingress is unavailable in this Host process.");let N=(await this.rpc("session.list",{},3e4,{signal:a}))?.items?.find(k=>k?.sessionId===t)?.cwd;F=await this.#d({sessionId:t,workspace:N,files:d,signal:a}),o=lY(o,F)}if(_){let H,N=new Promise(k=>{H=k});R=this.watchInteractions(t,{signal:_,onInteraction:g,onResolved:c,onOpen:H,ownership:T}),R.catch(()=>{}),await Promise.race([N,GE(3e4,_).then(()=>{throw new Error("Harness interaction stream did not open within 30 seconds")})])}let J=typeof o=="string"?[{type:"text",text:o}]:o;if(!Array.isArray(J)||J.length===0)throw new TypeError("Harness prompt content is required");await this.rpc("session.prompt",{sessionId:t,mode:"queue",content:J,clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,{rpcId:Q,signal:a}),q=!0;try{let H=Date.now()+e;for(;Date.now()0)return"";throw T?.stopRequested?GY():FY(y.reason)}throw new Zn("harness-reply-timeout")}catch(H){if(!T?.stopRequested)throw H;if(y.answer)return y.answer;throw H?.code==="turn-stopped"?H:GY()}}finally{F&&(!q||z)&&await F.cleanup().catch(J=>{console.warn(`[${this.#o}] unable to clean inbound files:`,J.message)}),P(),T&&(this.#m(T),this.#S(t,T)),y.turn!==null&&wI.discard(t,y.turn),m?.abort(new DOMException("Harness turn finished","AbortError")),R&&await R.catch(()=>{})}}async#k(t,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}){let r=!1,s=null,g=Promise.resolve(),c=A==null,I=[],d=()=>{},B=m=>{d=m,A&&(A.reconnect=d);try{a?.()}catch(_){console.warn(`[${this.#o}] ignored an interaction open callback failure:`,_.message)}A&&this.#w(t,o).then(()=>{if(!r){c=!0;for(let _ of I.splice(0))Q(_)}}).catch(_=>{s??=_,d()})},f=(m,_)=>{m&&(g=g.then(()=>m(_)).catch(T=>{s??=T,d()}))},Q=m=>{let _=m.payload;if(A&&_.type==="session/event"){this.#D(t,[_.event]);return}if(_.type==="question/requested"||_.type==="approval/requested"){let T=_.type==="question/requested"?"question":"approval",R=T==="question"?m.rpcId:_.approvalId,L=`${T}:${R}`;if(A){let F=this.#T(t,L,T);if(F?.ownership!==A)return;this.#f.set(L,F)}let U=T==="approval"&&A&&typeof _.callId=="string"?this.#f.get(L)?.ownership.toolCalls.get(_.callId):void 0;f(i,Object.freeze({kind:T,interactionId:R,rpcId:m.rpcId,sessionId:t,payload:_,recovered:A?this.#f.get(L)?.recovered===!0:!1,...U?{toolCall:U}:{},reconnect:d,respond:(F,q={})=>this.respondInteraction(m.rpcId,F,{...q,signal:q.signal??o})}));return}if(_.type==="question/resolved"||_.type==="approval/resolved"){let T=_.type==="question/resolved"?"question":"approval",R=T==="question"?_.questionRpcId:_.approvalId,L=`${T}:${R}`;if(A){if(this.#f.get(L)?.ownership!==A)return;this.#f.delete(L)}f(e,Object.freeze({kind:T,interactionId:R,sessionId:t,outcome:_.outcome,payload:_}))}},y=m=>{try{let _=m?.payload;if(m?.type!=="server-request"||typeof m.rpcId!="string"||!_||typeof _!="object"||m.method!==_.type)throw new Error("invalid server-request envelope");if(_.sessionId!==t)return;c?Q(m):I.push(m)}catch(_){console.warn(`[${this.#o}] ignored a malformed Harness interaction frame:`,_.message)}};try{await this.#M({signal:o,onOpen:B,onEnvelope:y})}finally{r=!0,A?.reconnect===d&&(A.reconnect=null),o.aborted||await g}if(!o.aborted&&s)throw s}async watchHarnessEvents({signal:t,onSessionEvent:o,onReconnect:i}={}){if(typeof o!="function")throw new TypeError("watchHarnessEvents requires onSessionEvent");if(!t||typeof t.addEventListener!="function")throw new TypeError("watchHarnessEvents requires an AbortSignal");if(i!==void 0&&typeof i!="function")throw new TypeError("onReconnect must be a function");for(;!t.aborted;){try{await this.#M({signal:t,onOpen:()=>{try{i?.()}catch(e){console.warn(`[${this.#o}] mux reconnect hook failed:`,e.message)}},onEnvelope:e=>{try{let a=e?.payload;if(e?.type!=="server-request"||!a||typeof a!="object"||e.method!==a.type||a.type!=="session/event"||typeof a.sessionId!="string"||!a.event||typeof a.event!="object")return;o({sessionId:a.sessionId,event:a.event})}catch(a){console.warn(`[${this.#o}] ignored a malformed global mux frame:`,a.message)}}})}catch(e){if(t.aborted)return;console.warn(`[${this.#o}] Harness event mux disconnected:`,e.message)}if(t.aborted)return;try{await GE(this.#I,t)}catch{if(t.aborted)return;throw new Error("Harness event mux reconnect wait failed")}}}#M(t){return RY({apiProxy:this.#A,baseUrl:this.#e,createWebSocket:this.#i,rpcId:`${this.#l}-${p_()}`,...t,onMalformed:o=>{console.warn(`[${this.#o}] ignored a malformed Harness mux frame:`,o.message)}})}stopManagedProcess(){this.#h?.exitCode===null&&this.#h.kill("SIGTERM")}};var yQ=class extends lr{constructor(t){super({...t,rpcIdPrefix:"dingtalk",logPrefix:"dsh-dingtalk"})}};import{randomUUID as lEe}from"node:crypto";import{mkdir as pEe,readFile as dEe,rename as hEe,unlink as EEe,writeFile as CEe}from"node:fs/promises";import{dirname as uEe}from"node:path";var mQ=Object.freeze({version:1,sessions:{},seenMessageIds:[],pendingSenders:{}});function pr(n){return typeof n=="string"&&n.trim()?n.trim():null}function KY(n){return(pr(n)??w("\u9489\u9489\u7528\u6237")).slice(0,100)}function BEe(n,t){if(!n||typeof n!="object")return null;let o=pr(n.requestId)??pr(t),i=pr(n.staffId),e=pr(n.requestedAt)??pr(n.lastSeenAt),a=pr(n.lastSeenAt)??e;return!o||!i||!e||!a?null:{requestId:o,staffId:i,displayName:KY(n.displayName??n.nick),requestedAt:e,lastSeenAt:a}}function fEe(n){if(!n||typeof n!="object")return structuredClone(mQ);let t={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[e,a]of Object.entries(n.sessions)){let A=pr(e),r=pr(a);A&&r&&(t[A]=r)}let o={},i=Array.isArray(n.pendingSenders)?n.pendingSenders.map(e=>[e?.requestId,e]):Object.entries(n.pendingSenders&&typeof n.pendingSenders=="object"?n.pendingSenders:{});for(let[e,a]of i){let A=BEe(a,e);if(!A)continue;let r=Object.values(o).find(s=>s.staffId===A.staffId);(!r||r.lastSeenAtnew Date().toISOString()}={}){if(!pr(t))throw new TypeError("state path is required");if(typeof o!="function"||typeof i!="function")throw new TypeError("idFactory and now must be functions");this.#e=t,this.#r=o,this.#g=i}async load(){try{this.#A=fEe(JSON.parse(await dEe(this.#e,"utf8")))}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=structuredClone(mQ),await this.#a()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){let i=pr(t),e=pr(o);if(!i||!e)throw new TypeError("key and sessionId are required");this.#A.sessions[i]=e,await this.#a()}async clearSession(t){let o=pr(t);!o||!(o in this.#A.sessions)||(delete this.#A.sessions[o],await this.#a())}async clearSessions(){this.#A.sessions={},await this.#a()}hasSeen(t){let o=pr(t);return!!(o&&this.#A.seenMessageIds.includes(o))}async markSeen(t){let o=pr(t);if(!o)throw new TypeError("messageId is required");this.hasSeen(o)||(this.#A.seenMessageIds.push(o),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#a())}pendingSenders(){return Object.values(this.#A.pendingSenders).sort((t,o)=>t.requestedAt.localeCompare(o.requestedAt)).map(t=>structuredClone(t))}pendingSender(t){let o=pr(t),i=o?this.#A.pendingSenders[o]:null;return i?structuredClone(i):null}async recordPendingSender(t,o,i){let e=t&&typeof t=="object"?t:{staffId:t,displayName:o,lastSeenAt:i},a=pr(e.staffId);if(!a)throw new TypeError("staffId is required");let A=pr(e.lastSeenAt)??pr(e.requestedAt)??this.#g(),r=Object.values(this.#A.pendingSenders).find(g=>g.staffId===a),s={requestId:r?.requestId??`ding_sender_${this.#r()}`,staffId:a,displayName:KY(e.displayName??e.nick??o),requestedAt:r?.requestedAt??A,lastSeenAt:A};return this.#A.pendingSenders[s.requestId]=s,await this.#a(),structuredClone(s)}async removePendingSender(t){let o=pr(t);return!o||!this.#A.pendingSenders[o]?!1:(delete this.#A.pendingSenders[o],await this.#a(),!0)}async removePendingSenderByStaffId(t){let o=pr(t),i=o?Object.values(this.#A.pendingSenders).find(e=>e.staffId===o):null;return i?this.removePendingSender(i.requestId):!1}snapshot(){return structuredClone(this.#A)}async remove(){await this.#t;try{await EEe(this.#e)}catch(t){if(t?.code!=="ENOENT")throw t}this.#A=structuredClone(mQ)}async#a(){let t=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await pEe(uEe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await CEe(i,t,{encoding:"utf8",mode:384}),await hEe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{mkdir as QEe,readFile as yEe,realpath as mEe,rename as SEe,stat as wEe,unlink as DEe,writeFile as OEe}from"node:fs/promises";import{dirname as bEe,isAbsolute as jY,resolve as FE}from"node:path";var M$e=Object.freeze({version:1,workspaces:Object.freeze({})});function DI(n){let t=new Error(n);return t.code=Na,t}async function E_(n){return FE(await mEe(n))}async function MEe(n,t){if(n===t)return!0;try{return await E_(n)===await E_(t)}catch{return!1}}function dr(n){if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n))throw new TypeError("Invalid bot id");return n}function ei(n,t,o){let i=new Error(t,o);return i.code=n,i}function wQ(n){if(typeof n!="string"||!/^[A-Za-z0-9._:@-]{1,128}$/.test(n))throw ei("invalid-target","Invalid target id");return n}function _Ee(n){if(!n||typeof n!="object"||Array.isArray(n))throw ei("invalid-target","Invalid target route");try{let t=JSON.stringify(n);if(t===void 0)throw new TypeError("route is not JSON");let o=JSON.parse(t);if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError("route is not an object");return o}catch(t){throw ei("invalid-target","Invalid target route",{cause:t})}}function OI(n,{targetId:t}={}){if(!n||typeof n!="object"||Array.isArray(n))throw ei("invalid-target","Invalid delivery target");let o=t===void 0?new Set(["targetId","name","kind","route"]):new Set(["name","kind","route"]);if(Object.keys(n).some(a=>!o.has(a)))throw ei("invalid-target","Invalid delivery target");let i=wQ(t??n.targetId);if(typeof n.kind!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n.kind))throw ei("invalid-target","Invalid target kind");let e;if(n.name!==void 0){if(typeof n.name!="string"||!n.name.trim()||n.name.trim().length>80)throw ei("invalid-target","Invalid target name");e=n.name.trim()}return{targetId:i,...e===void 0?{}:{name:e},kind:n.kind,route:_Ee(n.route)}}function TEe(n){let t=Object.create(null);if(n===void 0)return t;if(!n||typeof n!="object"||Array.isArray(n))return null;try{for(let[o,i]of Object.entries(n)){if(dr(o),!i||typeof i!="object"||Array.isArray(i))return null;let e=Object.create(null);for(let[a,A]of Object.entries(i)){let r=OI(A,{targetId:a}),{targetId:s,...g}=r;e[a]=g}t[o]=e}}catch{return null}return t}function NEe(n){if(!n||![1,2].includes(n.version)||!n.workspaces||typeof n.workspaces!="object"||Array.isArray(n.workspaces))return null;let t={};for(let[a,A]of Object.entries(n.workspaces)){if(!/^[A-Za-z0-9_-]{1,128}$/.test(a)||typeof A!="string"||!jY(A))return null;t[a]=FE(A)}let o={};if(n.agentPresets!==void 0){if(!n.agentPresets||typeof n.agentPresets!="object"||Array.isArray(n.agentPresets))return null;for(let[a,A]of Object.entries(n.agentPresets)){if(!/^[A-Za-z0-9_-]{1,128}$/.test(a))return null;try{let r=yp(A);if(!r)return null;o[a]=r}catch{return null}}}let i=Object.create(null);if(n.contextEnhancement&&typeof n.contextEnhancement=="object"&&!Array.isArray(n.contextEnhancement))for(let[a,A]of Object.entries(n.contextEnhancement))/^[A-Za-z0-9_-]{1,128}$/.test(a)&&(i[a]=Sp(A));if(n.version===1&&n.deliveryTargets!==void 0)return null;let e=TEe(n.deliveryTargets);return e?{version:n.version,workspaces:t,agentPresets:o,contextEnhancement:i,deliveryTargets:e}:null}async function xY(n){if(typeof n!="string"||!n.trim()||!jY(n.trim())){let i=new Error("\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");throw i.code="workspace-not-absolute",i}let t=FE(n.trim()),o;try{o=await wEe(t)}catch(i){let e=new Error("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002",{cause:i});throw e.code="workspace-not-found",e}if(!o.isDirectory()){let i=new Error("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002");throw i.code="workspace-not-directory",i}return t}var ea=class{#e;#A;#t=1;#r={};#g={};#a={};#n=Object.create(null);#i=new Map;#I=1;#l=new Map;#o=1;#s=new Map;#c=new WeakMap;#p=new Set;#d=Promise.resolve();#h=new Map;constructor(t,{defaultWorkspace:o=process.cwd()}={}){if(typeof t!="string"||!t)throw new TypeError("workspace store path is required");this.#e=t,this.#A=FE(o)}async load(){try{let t=NEe(JSON.parse(await yEe(this.#e,"utf8")));if(!t)throw new Error("dsh-im workspace config is invalid");this.#t=t.version,this.#r=t.workspaces,this.#g=t.agentPresets,this.#a=t.contextEnhancement,this.#n=t.deliveryTargets}catch(t){if(t?.code!=="ENOENT")throw t;this.#t=1,this.#r={},this.#g={},this.#a={},this.#n=Object.create(null)}this.#i.clear(),this.#I=1,this.#l.clear(),this.#o=1,this.#s.clear(),this.#p.clear();for(let t of Object.keys(this.#r))this.#i.set(t,this.#E()),this.#l.set(t,this.#C());return this}has(t){let o=dr(t);return Object.hasOwn(this.#r,o)&&!this.#s.has(o)}incarnationFor(t){return this.#l.get(dr(t))??null}workspaceFor(t){return this.#r[dr(t)]??this.#A}agentPresetFor(t){return this.#g[dr(t)]??null}contextEnhancementFor(t){let o=dr(t);return this.has(o)&&Object.hasOwn(this.#a,o)?this.#a[o]:A_}listDeliveryTargets(t){let o=dr(t);if(!this.has(o))throw ei("unknown-bot","Unknown bot");return Object.entries(this.#n[o]??{}).map(([i,e])=>OI(e,{targetId:i})).sort((i,e)=>i.targetId.localeCompare(e.targetId))}deliveryTargetFor(t,o){let i=dr(t),e=wQ(o);if(!this.has(i))throw ei("unknown-bot","Unknown bot");let a=this.#n[i]?.[e];return a?OI(a,{targetId:e}):null}async createDeliveryTarget(t,o){let i=dr(t),e=OI(o);return this.#y(i,async()=>{if(!this.has(i))throw ei("unknown-bot","Unknown bot");if(Object.hasOwn(this.#n[i]??{},e.targetId))throw ei("target-conflict","Target already exists");let{targetId:a,...A}=e,r={...this.#n,[i]:{...this.#n[i]??{},[a]:A}};return await this.#S(this.#a,r,2),this.#n=r,this.#t=2,OI(A,{targetId:a})})}async updateDeliveryTarget(t,o,i){let e=dr(t),a=wQ(o),A=OI(i,{targetId:a});return this.#y(e,async()=>{if(!this.has(e))throw ei("unknown-bot","Unknown bot");if(!Object.hasOwn(this.#n[e]??{},a))throw ei("unknown-target","Unknown target");let{targetId:r,...s}=A,g={...this.#n,[e]:{...this.#n[e],[a]:s}};return await this.#S(this.#a,g,2),this.#n=g,this.#t=2,OI(s,{targetId:a})})}async deleteDeliveryTarget(t,o){let i=dr(t),e=wQ(o);return this.#y(i,async()=>{if(!this.has(i))throw ei("unknown-bot","Unknown bot");if(!Object.hasOwn(this.#n[i]??{},e))throw ei("unknown-target","Unknown target");let a={...this.#n[i]};delete a[e];let A={...this.#n};return Object.keys(a).length>0?A[i]=a:delete A[i],await this.#S(this.#a,A,2),this.#n=A,this.#t=2,!0})}generationFor(t){return this.#i.get(dr(t))??null}async whenIdle(){await this.#d}async whenBotIdle(t){let o=dr(t);for(;;){let i=this.#h.get(o);if(!i||(await i,this.#h.get(o)===i))return}}async ensure(t,{workspace:o=this.#A,defaultAgentPreset:i}={}){let e=dr(t),a=FE(o);return this.#y(e,async()=>{if(this.#r[e])this.#i.has(e)||this.#i.set(e,this.#E());else{let A=yp(i),r=Object.hasOwn(this.#g,e),s=this.#g[e];this.#r[e]=a,A&&(this.#g[e]=A),this.#i.set(e,this.#E()),this.#l.set(e,this.#C());try{await this.#S()}catch(g){throw delete this.#r[e],r?this.#g[e]=s:delete this.#g[e],this.#i.delete(e),this.#l.delete(e),g}}return this.#r[e]})}async setWorkspace(t,o,{clearSessions:i,incarnation:e}={}){let a=dr(t);if(!this.has(a)||e!==void 0&&e!==this.incarnationFor(a)){let r=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw r.code="workspace-bot-not-found",r}let A=await xY(o);return this.#y(a,async()=>{if(!this.has(a)||e!==void 0&&e!==this.incarnationFor(a)){let s=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw s.code="workspace-bot-not-found",s}if(A===this.workspaceFor(a))return A;let r=this.#r[a];this.#i.set(a,this.#E()),await i?.(),this.#r[a]=A;try{await this.#S()}catch(s){throw this.#r[a]=r,s}return A})}async setAgentPreset(t,o,{incarnation:i}={}){let e=dr(t);if(!this.has(e)||i!==void 0&&i!==this.incarnationFor(e)){let A=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw A.code="workspace-bot-not-found",A}let a=yp(o);return this.#y(e,async()=>{if(!this.has(e)||i!==void 0&&i!==this.incarnationFor(e)){let r=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw r.code="workspace-bot-not-found",r}let A=this.#g[e]??null;if(A===a)return a;a?this.#g[e]=a:delete this.#g[e];try{await this.#S()}catch(r){throw A?this.#g[e]=A:delete this.#g[e],r}return a})}async setContextEnhancement(t,o,{incarnation:i}={}){let e=dr(t),a=i===void 0?this.incarnationFor(e):i,A=mp(o);return this.#y(e,async()=>{if(!this.has(e)||a!==this.incarnationFor(e)){let s=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw s.code="workspace-bot-not-found",s}let r={...this.#a,[e]:A};return await this.#S(r),this.#a=r,A})}async bindWorkspaceSession(t,o,{conversationKey:i,sessionId:e,clearSessions:a,setSession:A,incarnation:r,expectedGeneration:s}={}){let g=dr(t);if(typeof i!="string"||!i||typeof e!="string"||!e)throw new TypeError("conversationKey and sessionId are required");if(typeof a!="function"||typeof A!="function")throw new TypeError("session state callbacks are required");if(!this.has(g)||r!==void 0&&r!==this.incarnationFor(g)){let I=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw I.code="workspace-bot-not-found",I}let c=await E_(await xY(o));return this.#y(g,async()=>{if(!this.has(g)||r!==void 0&&r!==this.incarnationFor(g)){let I=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw I.code="workspace-bot-not-found",I}if(s!==void 0&&s!==this.generationFor(g))throw DI("The bot workspace changed before the session binding could be committed.");if(!await MEe(c,this.workspaceFor(g))){let I=this.#r[g];this.#i.set(g,this.#E()),await a(),this.#r[g]=c;try{await this.#S()}catch(d){throw this.#r[g]=I,d}}return await A(i,e),{workspace:c,sessionId:e,generation:this.#i.get(g)}})}async invalidateSessions(t,{clearSessions:o}={}){let i=dr(t);return this.#y(i,async()=>{this.#i.set(i,this.#E()),await o?.()})}async beginRemoval(t,{clearSessions:o}={}){let i=dr(t);return this.#y(i,async()=>{let e=this.#s.get(i);if(e)return e;let a=Object.freeze({});this.#s.set(i,a),this.#c.set(a,{botId:i,incarnation:this.incarnationFor(i)}),this.#i.set(i,this.#E());try{await o?.()}catch(A){throw this.#s.get(i)===a&&this.#s.delete(i),A}return a})}async abortRemoval(t){let{botId:o}=this.#f(t);return this.#y(o,async()=>this.#s.get(o)!==t?!1:(this.#s.delete(o),Object.hasOwn(this.#r,o)&&(this.#i.set(o,this.#E()),this.#l.has(o)||this.#l.set(o,this.#C())),!0))}async finishRemoval(t){let{botId:o,incarnation:i}=this.#f(t);return this.#y(o,async()=>this.#s.get(o)!==t?{removed:!1,persisted:!0,error:null,stale:!0}:this.incarnationFor(o)!==i?(this.#s.delete(o),{removed:!1,persisted:!0,error:null,stale:!0}):(this.#s.delete(o),this.#B(o)))}async retireAfterConfigCommit(t){let o=dr(t);return this.#y(o,async()=>(this.#s.delete(o),this.#B(o)))}flushPendingRemoval(t){if(this.#p.has(t))return this.#y(t,async()=>{this.#p.has(t)&&await this.#Q()})}async remove(t){let o=await this.retireAfterConfigCommit(t);if(o.error)throw o.error;return o.removed}async reconcile(t){let o=new Set([...t].map(dr)),i=new Set([...Object.keys(this.#r),...Object.keys(this.#g),...Object.keys(this.#a),...Object.keys(this.#n),...this.#p]);for(let e of i)o.has(e)||await this.remove(e)}decorateStatus(t){return!t||typeof t!="object"||!Array.isArray(t.bots)?t:{...t,bots:t.bots.map(o=>o?.botId?{...o,workspace:this.workspaceFor(o.botId),agentPreset:this.agentPresetFor(o.botId),contextEnhancement:this.contextEnhancementFor(o.botId)}:o)}}#E(){let t=this.#I;return this.#I+=1,t}#C(){let t=this.#o;return this.#o+=1,t}#f(t){if(!t||typeof t!="object")throw new TypeError("Invalid workspace removal transaction");let o=this.#c.get(t);if(!o)throw new TypeError("Invalid workspace removal transaction");return o}async#B(t){let o=Object.hasOwn(this.#r,t),i=Object.hasOwn(this.#g,t),e=Object.hasOwn(this.#a,t),a=Object.hasOwn(this.#n,t),A=o||i||e||a||this.#p.has(t);if(delete this.#r[t],delete this.#g[t],delete this.#a[t],delete this.#n[t],this.#i.delete(t),this.#l.delete(t),!A)return{removed:!1,persisted:!0,error:null,stale:!1};try{return await this.#Q(),{removed:o,persisted:!0,error:null,stale:!1}}catch(r){return this.#p.add(t),{removed:o,persisted:!1,error:r,stale:!1}}}async#y(t,o){let i=this.#d.then(o,o),e=i.then(()=>{},()=>{});return this.#d=e,this.#h.set(t,e),e.finally(()=>{this.#h.get(t)===e&&this.#h.delete(t)}),i}async#S(t=this.#a,o=this.#n,i=this.#t){let e={version:i,workspaces:this.#r};Object.keys(this.#g).length>0&&(e.agentPresets=this.#g),Object.keys(t).length>0&&(e.contextEnhancement=t),i>=2&&Object.keys(o).length>0&&(e.deliveryTargets=o),await QEe(bEe(this.#e),{recursive:!0,mode:448});let a=`${this.#e}.tmp`;await OEe(a,`${JSON.stringify(e,null,2)} -`,{encoding:"utf8",mode:384}),await SEe(a,this.#e),this.#p.clear()}async#Q(){if(Object.keys(this.#r).length>0||Object.keys(this.#g).length>0||Object.keys(this.#a).length>0||Object.keys(this.#n).length>0){await this.#S();return}try{await DEe(this.#e),this.#p.clear()}catch(t){if(t?.code!=="ENOENT")throw t;this.#p.clear()}}};function DQ(n){if(!n)return null;let t=typeof n=="function"?n():n;return t&&typeof t.then=="function"?t.then(Jn):Jn(t)}function JY(){let n=new Error("Agent Preset \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\u3002");return n.code="agent-preset-unavailable",n}function Mp(n){if(n())return;let t=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw t.code="workspace-bot-not-found",t}function YY(n,t,o){let i=e=>{let a=n.decorateStatus(e);if(!o||!a||typeof a!="object")return a;let A=s=>s?{...a,agentPresetCatalog:s}:a,r=DQ(o);return r&&typeof r.then=="function"?r.then(A):A(r)};return t&&typeof t.then=="function"?t.then(i):i(t)}function REe(n){return Promise.resolve(n.status())}function Pa(n,{workspaces:t,method:o="remove",botIdFromRemoved:i=A=>A?.botId,saveMethod:e="save",botIdFromSave:a=A=>A?.botId}){if(!n||!t||typeof n[o]!="function")throw new TypeError("configStore removal observer dependencies are required");return new Proxy(n,{get(A,r){let s=Reflect.get(A,r,A);return r===o?async(...g)=>{let c=await s.apply(A,g),I=c?i(c,g):null;return I&&await t.retireAfterConfigCommit(I),c}:r===e&&typeof s=="function"?(...g)=>{let c=t.flushPendingRemoval(a(g[0],g));return c?c.then(()=>s.apply(A,g)):s.apply(A,g)}:typeof s=="function"?s.bind(A):s}})}function Ga(n,{botId:t,workspaces:o,state:i,agentPresetCatalog:e}={}){if(!n||!o||!i)throw new TypeError("harness, workspaces, and state are required");let a=o.incarnationFor(t),A=()=>o.has(t)&&o.incarnationFor(t)===a,r=async(I=e)=>{let d;try{d=await DQ(I)??Jn(null)}catch(B){throw Mp(A),B}return Mp(A),{agentPreset:o.agentPresetFor(t),agentPresetCatalog:d}},s=new Map,g=new Proxy(n,{get(I,d){if(d==="agentPresetSettings")return async(f={})=>{f?.signal?.throwIfAborted(),Mp(A);let Q=await r();return f?.signal?.throwIfAborted(),Q};if(d==="updateAgentPreset")return async(f,Q={})=>{Q?.signal?.throwIfAborted(),Mp(A);let y=f==="--default"?null:yp(f),m=null;if(y&&({agentPresetCatalog:m}=await r(),Q?.signal?.throwIfAborted(),!m.items.some(_=>_.id===y)))throw JY();if(await o.setAgentPreset(t,y,{incarnation:a}),Mp(A),m)return{agentPreset:o.agentPresetFor(t),agentPresetCatalog:m};try{return await r()}catch(_){if(_?.code==="workspace-bot-not-found")throw _;return Mp(A),{agentPreset:o.agentPresetFor(t),agentPresetCatalog:Jn(null)}}};if(d==="currentWorkspace")return()=>{if(!A()){let f=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw f.code="workspace-bot-not-found",f}return o.workspaceFor(t)};if(d==="assertWorkspaceScope")return()=>{if(!A()){let f=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw f.code="workspace-bot-not-found",f}};if((d==="listWorkspaces"||d==="listWorkspaceSessions"||d==="listModels")&&typeof I[d]=="function")return async(...f)=>{if(!A()){let y=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw y.code="workspace-bot-not-found",y}let Q=await I[d](...f);if(!A()){let y=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw y.code="workspace-bot-not-found",y}return Q};if(d==="switchWorkspace")return f=>{if(!A()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");return Q.code="workspace-bot-not-found",Promise.reject(Q)}return o.setWorkspace(t,f,{clearSessions:()=>i.clearSessions(),incarnation:a})};if(d==="bindWorkspaceSession")return async(f,Q)=>{if(typeof f!="string"||!f||typeof Q!="string"||!Q)throw new TypeError("conversationKey and sessionId are required");if(!A()){let T=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw T.code="workspace-bot-not-found",T}if(typeof I.adoptWorkspaceSession!="function")throw new TypeError("Harness does not support adopting workspace sessions");let y=o.generationFor(t),m=await I.adoptWorkspaceSession(Q);if(!A()){let T=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw T.code="workspace-bot-not-found",T}if(y!==o.generationFor(t))throw DI("The bot workspace changed while the session was being adopted.");if(!m||typeof m!="object"||m.sessionId!==Q||typeof m.workspace!="string")throw new TypeError("Harness returned an invalid adopted workspace session");let _=await o.bindWorkspaceSession(t,m.workspace,{conversationKey:f,sessionId:Q,clearSessions:()=>i.clearSessions(),setSession:(T,R)=>i.setSession(T,R),incarnation:a,expectedGeneration:y});if(!A()){let T=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw T.code="workspace-bot-not-found",T}if(_.generation!==o.generationFor(t))throw DI("The bot workspace changed before the session binding completed.");return s.set(Q,_.generation),{...m,workspace:_.workspace,sessionId:_.sessionId}};if(d==="createSession")return async(f={})=>{if(await o.whenBotIdle(t),!A()){let _=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw _.code="workspace-bot-not-found",_}let Q=o.generationFor(t),y=o.agentPresetFor(t),m=await I.createSession({...f,workspace:o.workspaceFor(t),...y==null?{}:{agentPreset:y}});return s.set(m,Q),m};if(d==="workspaceSession")return f=>{if(typeof f!="string"||!f)throw new TypeError("sessionId is required");let Q=s.get(f)??o.generationFor(t);s.delete(f);let y=()=>A()&&Q===o.generationFor(t),m=async(T,R,F)=>{if(!y())throw DI(`The bot workspace changed before this ${F} started.`);let K=await I[T](f,...R);if(!y())throw DI(`The bot workspace changed while this ${F} was running.`);return K},_=async(T,R,F)=>{if(!y())throw DI(`The bot workspace changed before this ${F} started.`);return I[T](f,...R)};return Object.freeze({sessionId:f,async sessionExists(...T){if(!y())return!1;let R=await I.sessionExists(f,...T);return y()&&R},models(...T){return m("getSessionModels",T,"model listing")},readHistory(...T){return m("readSessionHistory",T,"history read")},selectModel(...T){return m("selectSessionModel",T,"model selection")},isRunning(...T){return m("isSessionRunning",T,"run-state check")},hasActiveTurn(...T){return m("hasActiveTurn",T,"turn ownership check")},stopActiveTurn(...T){return _("stopActiveTurn",T,"turn stop")},steerActiveTurn(...T){return _("steerActiveTurn",T,"turn steering")},ask(...T){if(!y())throw DI("The bot workspace changed before this prompt started.");return I.ask(f,...T)}})};if(d==="sessionExists")return(f,...Q)=>{if(!A())return!1;let y=s.get(f);return y!==void 0&&y!==o.generationFor(t)?(s.delete(f),!1):I.sessionExists(f,...Q)};if(d==="ask")return(f,...Q)=>{let y=s.get(f);if(s.delete(f),!A()||y!==void 0&&y!==o.generationFor(t)){let m=new Error("The bot workspace changed before this prompt started.");throw m.code=Na,m}return I.ask(f,...Q)};if(d==="executeCommand"&&typeof I.executeCommand=="function")return(f,...Q)=>{let y=s.get(f);if(s.delete(f),!A()||y!==void 0&&y!==o.generationFor(t)){let m=new Error("The bot workspace changed before this command started.");throw m.code=Na,m}return I.executeCommand(f,...Q)};let B=Reflect.get(I,d,I);return typeof B=="function"?B.bind(I):B}}),c=new Proxy(i,{get(I,d){if(d===_M)return I;if(d==="sessionFor")return(f,...Q)=>{if(!A())return null;let y=I.sessionFor(f,...Q);return y&&!s.has(y)&&s.set(y,o.generationFor(t)),y};if(d==="setSession")return(f,Q,...y)=>{let m=s.get(Q);return!A()||m!==void 0&&m!==o.generationFor(t)?(s.delete(Q),!1):I.setSession(f,Q,...y)};let B=Reflect.get(I,d,I);return typeof B=="function"?B.bind(I):B}});return Object.freeze({harness:g,state:c})}function Fa(n,{workspaces:t,stateFor:o,agentPresetCatalog:i}={}){if(!n||!t||typeof o!="function")throw new TypeError("controller, workspaces, and stateFor are required");let e=new Map,a=(I,d)=>{let f=(e.get(I)??Promise.resolve()).catch(()=>{}).then(d);return e.set(I,f),f.finally(()=>{e.get(I)===f&&e.delete(I)})},A=I=>YY(t,I,i),r=(I,d)=>{let B=t.incarnationFor(I);return a(I,async()=>{if(!(await n.status())?.bots?.some(y=>y?.botId===I)){let y=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw y.code="workspace-bot-not-found",y}let Q=await o(I);return await t.setWorkspace(I,d,{clearSessions:()=>Q.clearSessions(),incarnation:B}),A(await n.status())})},s=(I,d)=>{let B=t.incarnationFor(I),f=yp(d);return a(I,async()=>{if(!(await n.status())?.bots?.some(m=>m?.botId===I)){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}let y=f&&i?await DQ(i):null;if(f&&i&&!y?.items.some(m=>m.id===f))throw JY();return await t.setAgentPreset(I,f,{incarnation:B}),YY(t,await n.status(),y??i)})},g=(I,d,B)=>{let f=t.incarnationFor(I),Q=mp(d);return a(I,async()=>{let y=await n.status();if(!y?.bots?.some(F=>F?.botId===I)){let F=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw F.code="workspace-bot-not-found",F}let m=await DQ(i),_=t.decorateStatus(y),T={..._,bots:_.bots.map(F=>F?.botId===I?{...F,contextEnhancement:Q}:F),...m?{agentPresetCatalog:m}:{}},R=B?await B(T):T;return await t.setContextEnhancement(I,Q,{incarnation:f}),R})},c=(I,d)=>a(I,async()=>{let B=await t.beginRemoval(I,{clearSessions:async()=>{try{let f=await o(I);if(!f||typeof f.clearSessions!="function")throw new TypeError("bot state does not support session cleanup");await f.clearSessions()}catch(f){console.warn(`[dsh-im] ignored session cleanup failure while deleting bot ${I}:`,f?.message??f)}}});try{let f=await d();return await t.finishRemoval(B),A(f)}catch(f){let Q=await REe(n).catch(()=>null);throw Array.isArray(Q?.bots)&&!Q.bots.some(m=>m?.botId===I)?await t.finishRemoval(B):await t.abortRemoval(B),f}});return new Proxy(n,{get(I,d){if(d==="updateWorkspace")return r;if(d==="updateAgentPreset")return s;if(d==="updateContextEnhancement")return g;let B=Reflect.get(I,d,I);return typeof B!="function"?B:d==="deleteBot"?(f,...Q)=>c(f,()=>B.call(I,f,...Q)):d==="disconnect"?async(...f)=>{let y=(await I.status())?.bots?.[0]?.botId;return y?c(y,()=>B.apply(I,f)):A(B.apply(I,f))}:(...f)=>A(B.apply(I,f))}})}var qY=new Set(["weixin","feishu","dingtalk","wecom","qq","slack","telegram","discord","whatsapp"]);function kEe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function vEe(n){return typeof n=="string"&&n.length>0&&n.length<=512&&n.trim()===n&&!/[\s:\u0000-\u001f\u007f]/u.test(n)}function C_(n,t){let o=`${t}:`;if(!n.startsWith(o))return null;let i=n.slice(o.length);return vEe(i)?i:null}function LE(n,t){for(let[o,i,e]of t){let a=C_(n,o);if(a)return{kind:i,route:{[e]:a}}}return null}function PEe(n){let t=C_(n,"p2p");return t?.startsWith("ou_")?{kind:"user",route:{openId:t}}:LE(n,[["group","group","chatId"]])}function GEe(n){let t=C_(n,"direct");if(t&&/^[A-Za-z0-9_-]{1,128}$/.test(t))return{kind:"conversation",route:{channelId:t}};let o=/^group:([^:]+):(\d{1,20}(?:\.\d{1,20})?)$/.exec(n);return!o||!/^[A-Za-z0-9_-]{1,128}$/.test(o[1])?null:{kind:"thread",route:{channelId:o[1],threadTs:o[2]}}}function FEe(n){let t=/^(direct|group):(-?\d+)(?::([1-9]\d*))?$/.exec(n);if(!t)return null;let o=Number(t[2]);if(!Number.isSafeInteger(o)||t[1]==="direct"&&t[3]!==void 0)return null;if(t[3]===void 0)return{kind:"chat",route:{chatId:t[2]}};let i=Number(t[3]);return!Number.isSafeInteger(i)||i<=0?null:{kind:"topic",route:{chatId:t[2],messageThreadId:i}}}function LEe(n){let t=/^(?:direct|group):(\d{1,32})$/.exec(n);return t?{kind:"channel",route:{channelId:t[1]}}:null}function UEe(n){let t=/^direct:(\d{5,32}@(s\.whatsapp\.net|lid))$/.exec(n);if(t)return{kind:"user",route:{jid:t[1]}};let o=/^group:(\d{5,32}(?:-\d{1,32})?@g\.us)$/.exec(n);return o?{kind:"group",route:{jid:o[1]}}:null}function HEe(n,t){if(!qY.has(n)||typeof t!="string")return null;switch(n){case"weixin":return LE(t,[["p2p","user","toUserId"]]);case"feishu":return PEe(t);case"dingtalk":return LE(t,[["p2p","user","userId"],["group","group","openConversationId"]]);case"wecom":return LE(t,[["direct","user","chatId"],["group","group","chatId"]]);case"qq":return LE(t,[["c2c","user","userOpenId"],["group","group","groupOpenId"]]);case"slack":return GEe(t);case"telegram":return FEe(t);case"discord":return LEe(t);case"whatsapp":return UEe(t);default:return null}}function zY(n,t){if(!qY.has(n)||!kEe(t))return[];let o=[],i=new Set;for(let e of Object.keys(t)){let a=HEe(n,e);if(!a)continue;let A=JSON.stringify(a);i.has(A)||(i.add(A),o.push(a))}return o}var KEe=new Set(["weixin","feishu","dingtalk","wecom","qq","slack","telegram","discord","whatsapp"]);function bQ(n){return KEe.has(n)}function ic(n){let t=new Error(n);return t.code="invalid-target",t}function xEe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function u_(n,t,o){if(!xEe(n))throw ic(`${o} must be an object`);if(Object.keys(n).find(e=>!t.includes(e))!==void 0)throw ic(`${o} contains an unknown field`)}function OQ(n,t){if(typeof n!="string"||!n||n.trim()!==n)throw ic(`${t} must be a non-empty string without surrounding whitespace`);return n}function YEe(n){if(typeof n!="string"||!n.trim()||n.trim().length>80)throw ic("target.name must contain 1 to 80 characters");return n.trim()}function ac(n,t){u_(n,t,"route");let o={};for(let i of t)o[i]=OQ(n[i],`route.${i}`);return o}function ag(n,t){if(!t.includes(n))throw ic("target kind is not supported by this channel");return n}function jEe(n,t,o){switch(n){case"weixin":return ag(t,["user"]),ac(o,["toUserId"]);case"feishu":return ag(t,["user","group"]),ac(o,t==="user"?["openId"]:["chatId"]);case"dingtalk":return ag(t,["user","group"]),ac(o,t==="user"?["userId"]:["openConversationId"]);case"wecom":return ag(t,["user","group"]),ac(o,["chatId"]);case"qq":return ag(t,["user","group"]),ac(o,t==="user"?["userOpenId"]:["groupOpenId"]);case"slack":return ag(t,["conversation","thread"]),ac(o,t==="conversation"?["channelId"]:["channelId","threadTs"]);case"telegram":{ag(t,["chat","topic"]),u_(o,t==="chat"?["chatId"]:["chatId","messageThreadId"],"route");let i=OQ(o.chatId,"route.chatId");if(!/^-?\d+$/.test(i))throw ic("route.chatId must be a decimal string");if(t==="chat")return{chatId:i};if(!Number.isSafeInteger(o.messageThreadId)||o.messageThreadId<=0)throw ic("route.messageThreadId must be a positive integer");return{chatId:i,messageThreadId:o.messageThreadId}}case"discord":return ag(t,["channel"]),ac(o,["channelId"]);case"whatsapp":{ag(t,["user","group"]);let i=ac(o,["jid"]);if(!(t==="user"?/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(i.jid):/^\d{5,32}(?:-\d{1,32})?@g\.us$/.test(i.jid)))throw ic(`route.jid must be a ${t} WhatsApp JID`);return i}default:throw new TypeError(`Unsupported delivery channel: ${n}`)}}function _p(n,t,{targetIdRequired:o=!0}={}){if(!bQ(n))throw new TypeError(`Unsupported delivery channel: ${n}`);u_(t,o?["targetId","name","kind","route"]:["name","kind","route"],"target");let i={};return o&&(i.targetId=OQ(t.targetId,"target.targetId")),t.name!==void 0&&(i.name=YEe(t.name)),i.kind=OQ(t.kind,"target.kind"),i.route=jEe(n,i.kind,t.route),i}function La({channel:n,workspaces:t,coreController:o,stateFor:i}){if(!bQ(n))throw new TypeError(`Unsupported delivery channel: ${n}`);if(!t||typeof t!="object")throw new TypeError("delivery adapter requires a workspace store");if(!o||typeof o!="object")throw new TypeError("delivery adapter requires a proactive text controller");if(typeof i!="function")throw new TypeError("delivery adapter requires a bot state getter");return Object.freeze({channel:n,ownsBot:e=>t.has(e),listTargets:e=>t.listDeliveryTargets(e),async listSuggestions(e){let a=await i(e);if(!a||typeof a.snapshot!="function")throw new TypeError("delivery suggestion state cannot be inspected");return zY(n,a.snapshot()?.sessions).map(r=>_p(n,r,{targetIdRequired:!1}))},createTarget:(e,a)=>t.createDeliveryTarget(e,_p(n,a)),updateTarget:(e,a,A)=>t.updateDeliveryTarget(e,a,_p(n,A,{targetIdRequired:!1})),deleteTarget:(e,a)=>t.deleteDeliveryTarget(e,a),async sendText(e,a,A,r={}){let s=_p(n,a);if(typeof o.sendProactiveText!="function")throw new TypeError("delivery controller cannot send proactive text");return await o.sendProactiveText(e,s,A,r),{sent:!0}}})}var VY=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function JEe(n){if(!Array.isArray(n)||n.length===0)return[...VY];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...VY]}var MQ=class{#e;#A;#t;#r;#g;#a;#n;#i=null;#I=null;#l=0;#o=!1;#s=!1;#c;#p;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=JEe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#a=A,this.#n=r,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#s||this.#o?this:(this.#s=!0,this.#d(0),this)}async close(){this.#o||(this.#o=!0,this.#i!==null&&this.#n(this.#i),this.#i=null,await this.#I?.catch(()=>{}),this.#p?.(null),this.#p=null)}#d(t){this.#o||(this.#i=this.#a(()=>{this.#i=null,this.#h()},t),this.#i?.unref?.())}async#h(){if(this.#o||this.#I)return;let t=this.#E();this.#I=t;try{await t}finally{this.#I===t&&(this.#I=null)}}async#E(){try{if(await this.#A.ensureRunning(),this.#o)return;let t=await this.#e.initialize();if(this.#o)return;this.#p?.(t),this.#p=null;let{configured:o,connected:i}=t.totals;if(i{let A={namespace:"commands",method:"execute",args:{agentId:i,line:e,images:[]},signal:a.signal};try{return await o.invoke(A)}catch(r){if(r?.name!=="TypertGatewayError"||r.code!=="arguments-invalid"||r.endpoint!=="commands/execute"||r.message!=='typert gateway: commands/execute: args fields do not match the descriptor: unexpected "images"')throw r;return a.signal?.throwIfAborted(),o.invoke({...A,args:{agentId:i,line:e}})}}}}import{randomUUID as f_}from"node:crypto";var _Q=new WeakMap;function qEe(n){let t=n?.failure;return t&&typeof t=="object"&&typeof t.code=="string"&&typeof t.message=="string"?{code:t.code,message:t.message,details:t.details&&typeof t.details=="object"?t.details:{}}:n?.name==="AbortError"||n?.name==="RemoteInvocationCancelled"?{code:"cancelled",message:n instanceof Error?n.message:"Harness request was cancelled",details:{}}:{code:"internal",message:n instanceof Error?n.message:String(n),details:{}}}function dn(n,t){return Promise.resolve().then(t).then(o=>({rpcId:n.rpcId,result:{ok:!0,value:o}}),o=>({rpcId:n.rpcId,result:{ok:!1,error:qEe(o)}}))}function WY(n,t,o,i){return{namespace:n,method:t,args:o,...i===void 0?{}:{signal:i}}}function TQ(n,t){let o=new Error(n);return o.name="UserQuestionError",o.code=t,o}function zEe(n,t){return!n||typeof n!="object"||n.sessionId!==t.sessionId||!n.answer||typeof n.answer!="object"||!Array.isArray(n.answer.answers)||n.answer.answers.length!==t.questions.length?!1:n.answer.answers.every((o,i)=>{let e=t.questions[i];if(!o||typeof o!="object"||o.id!==e.id||!Array.isArray(o.selected)||o.selected.some(r=>typeof r!="string")||new Set(o.selected).size!==o.selected.length||o.custom!==void 0&&typeof o.custom!="string")return!1;let a=o.custom?.trim();if(a!==void 0&&!a||e.multiSelect!==!0&&(a!==void 0&&o.selected.length>0||o.selected.length>1))return!1;let A=new Set(e.options?.map(r=>r.label)??[]);return o.selected.every(r=>A.has(r))})}function VEe(n){if(n?.type==="event"&&n.event&&typeof n.event=="object")return[{event:n.event}];let t=n?.type==="chunks"?n.event:null;if(!t||typeof t!="object")throw new Error("Harness returned an invalid session history record");let{data:o}=t,i=t.type,e=i==="chunkrow/tool-call-chunks"?o?.args:o?.texts;if(!o||!Array.isArray(e)||e.length===0||e.some(A=>typeof A!="string")||!Array.isArray(o.dt)||o.dt.length!==e.length-1)throw new Error("Harness returned an invalid packed session chunk");let a=t.time;return e.map((A,r)=>{r>0&&(a+=o.dt[r-1]);let s;if(i==="chunkrow/text-chunks")s={type:"text-delta",index:o.index,text:A};else if(i==="chunkrow/reasoning-chunks")s={type:"reasoning-delta",index:o.index,text:A};else if(i==="chunkrow/tool-call-chunks")s={type:"tool-call-delta",index:o.index,id:o.id,...Object.hasOwn(o,"name")?{name:o.name}:{},argumentsDelta:A};else throw new Error(`Harness returned an unsupported packed session chunk: ${String(i)}`);return{event:{type:"assistant/chunk",seq:t.seq+r,time:a,data:{turn:o.turn,step:o.step,chunk:s}}}})}function ZY(n){if(!Array.isArray(n))throw new Error("Harness returned invalid session history records");return n.flatMap(VEe)}var Q_=class{#e=[];#A=null;#t=!1;#r;#g;#a;constructor(t,o){this.#r=t,this.#a=o,this.#g=()=>this.close(),t?.addEventListener("abort",this.#g,{once:!0}),t?.aborted&&this.close()}push(t){if(!this.#t)if(this.#A){let o=this.#A;this.#A=null,o({value:t,done:!1})}else this.#e.push(t)}next(){return this.#e.length>0?Promise.resolve({value:this.#e.shift(),done:!1}):this.#t?Promise.resolve({value:void 0,done:!0}):new Promise(t=>{this.#A=t})}return(){return this.close(),Promise.resolve({value:void 0,done:!0})}close(){if(!this.#t&&(this.#t=!0,this.#r?.removeEventListener("abort",this.#g),this.#a?.(),this.#a=null,this.#A)){let t=this.#A;this.#A=null,t({value:void 0,done:!0})}}[Symbol.asyncIterator](){return this}},y_=class{#e;#A;#t=new Set;#r=new Map;#g=new Map;#a=new Map;#n=[];#i=!1;constructor(t,o,i){this.#e=o,this.#A=i,this.host=Object.freeze({describe:e=>dn(e,()=>({ready:!0,transport:"typert"}))}),this.workspace=Object.freeze({list:(e,a)=>dn(e,()=>this.#o(a)),create:(e,a)=>dn(e,()=>this.#I("workspace","create",{request:e.payload},a))}),this.sessions=Object.freeze({list:(e,a)=>dn(e,()=>this.#I("session","list",{_request:e.payload},a)),create:(e,a)=>dn(e,()=>this.#I("session","create",{request:e.payload},a)),history:(e,a)=>dn(e,()=>this.#c(e.payload,a)),prompt:(e,a)=>dn(e,()=>this.#I("session","prompt",{request:{requestId:e.rpcId,...e.payload}},a)),cancel:(e,a)=>dn(e,()=>this.#I("session","cancel",{request:{sessionId:e.payload.sessionId}},a)),models:(e,a)=>dn(e,()=>this.#h(e.payload.sessionId,a)),selectModel:(e,a)=>dn(e,()=>this.#I("session","selectModel",{request:e.payload},a))}),this.llm=Object.freeze({models:(e,a)=>dn(e,async()=>{let A=await this.#d(a);return{groups:A.groups,failures:A.failures}})}),this.events=Object.freeze({mux:(e,a)=>this.#E(a)}),this.respond=e=>Promise.resolve(this.#m(e)),typeof t?.on=="function"&&(this.#n.push(t.on("session/event",(e,a)=>{let A=e?.id;typeof A!="string"||!a||typeof a!="object"||(Number.isSafeInteger(a.seq)&&this.#p(A,a.seq),this.#C({type:"session/event",sessionId:A,event:a}))},{global:!0})),this.#n.push(t.on("approval/request",(e,a)=>this.#Q(e,a),{global:!0,prepend:!0})),this.#n.push(t.on("user-questions/request",(e,a)=>this.#y(e,a),{global:!0,prepend:!0})))}async#I(t,o,i,e){return this.#e.invoke(WY(t,o,i,e))}async#l(t,o,i,e){let a=new AbortController,A=e?AbortSignal.any([e,a.signal]):a.signal,r;try{r=(await this.#e.stream(WY(t,o,i,A)))[Symbol.asyncIterator]();let g=await r.next();if(g.done)throw new Error(`Harness ${t}.${o} stream ended before its baseline`);return g.value}finally{a.abort(new DOMException("Baseline received","AbortError")),await Promise.resolve(r?.return?.()).catch(()=>{})}}async#o(t){let o=await this.#l("workspace","follow",{},t);if(o?.type!=="baseline"||!o.value||typeof o.value!="object")throw new Error("Harness workspace.follow returned no baseline");return o.value}async#s(t,o,i){let e=await this.#l("session","follow",{request:{address:{kind:"session",sessionId:t},maxMessages:o}},i);if(e?.type!=="snapshot"||!Number.isSafeInteger(e.cursor))throw new Error("Harness session.follow returned no snapshot");return this.#p(t,e.cursor),e}async#c(t,o){let{sessionId:i,maxMessages:e=50,beforeSeq:a}=t,A=this.#a.get(i);if(A===void 0){let s=await this.#s(i,e,o);if(A=this.#a.get(i)??s.cursor,a===void 0&&A===s.cursor)return{events:ZY(s.records),hasMore:s.hasMore===!0,...s.projections===void 0?{}:{projections:s.projections}}}let r=await this.#I("session","page",{request:{address:{kind:"session",sessionId:i},throughSeq:A,maxMessages:e,...a===void 0?{}:{beforeSeq:a}}},o);return{events:ZY(r.records),hasMore:r.hasMore===!0}}#p(t,o){let i=this.#a.get(t);(i===void 0||o>i)&&this.#a.set(t,o)}#d(t){return this.#I("session","modelCatalog",{},t)}async#h(t,o){let[i,e]=await Promise.all([this.#d(o),this.#I("session","list",{_request:{}},o)]),a=e?.items?.find(s=>s?.sessionId===t);if(!a){let s=new Error(`session "${t}" not found`);throw s.failure={code:"session-not-found",message:s.message,details:{sessionId:t}},s}let A=a.projections?.values?.modelSelection,r=A?.next??A?.lastUsed??i.default;return{current:r,routable:i.routableProviders.includes(r.provider),groups:i.groups,failures:i.failures}}#E(t){let o;o=new Q_(t,()=>this.#t.delete(o)),this.#t.add(o);for(let i of this.#r.values())o.push(this.#B(i));for(let i of this.#g.values())o.push(this.#S(i));return o}#C(t,o=f_()){let i={rpcId:o,payload:t};for(let e of this.#t)e.push(i)}#f(t){let o=t?.session?.id??t?.id;return typeof o!="string"||!t?.session||!Array.isArray(t.session.events)?null:HY(this.#A,o,t.session.events)?{sessionId:o,session:t.session}:null}#B(t){return{rpcId:t.rpcId,payload:{type:"question/requested",sessionId:t.sessionId,questions:t.questions}}}#y(t,o){let i=this.#f(t?.agent);return i?t.signal?.aborted?Promise.reject(TQ("ask_user_question was aborted before the user answered","ASK_ABORTED")):new Promise((e,a)=>{let A={rpcId:f_(),sessionId:i.sessionId,questions:t.questions,signal:t.signal,settle:(s,g)=>{this.#r.delete(A.rpcId)&&(t.signal?.removeEventListener("abort",r),this.#C({type:"question/resolved",sessionId:A.sessionId,questionRpcId:A.rpcId,outcome:s}),s==="answered"?e(g):a(g))}},r=()=>A.settle("cancelled",TQ("ask_user_question was aborted before the user answered","ASK_ABORTED"));this.#r.set(A.rpcId,A),t.signal?.addEventListener("abort",r,{once:!0}),this.#C(this.#B(A).payload,A.rpcId)}):o()}#S(t){return{rpcId:t.rpcId,payload:{type:"approval/requested",sessionId:t.sessionId,approvalId:t.approvalId,toolName:t.toolName,...t.callId===void 0?{}:{callId:t.callId},...t.reason===void 0?{}:{reason:t.reason}}}}#Q(t,o){let i=this.#f(t?.agent);if(!i)return o();if(t.signal?.aborted)return Promise.resolve("cancelled");let e=new Set([...this.#g.values()].map(r=>r.approvalId)),a=new Set,A;for(let r=i.session.events.length-1;r>=0;r-=1){let s=i.session.events[r];if(s.type==="approval/decided")a.add(s.data?.id);else if(s.type==="approval/asked"){let g=s.data?.id;if(!g||a.has(g)||e.has(g)||(t.callId??null)!==(s.data?.callId??null))continue;A=g;break}}return A===void 0?o():new Promise(r=>{let s={rpcId:f_(),sessionId:i.sessionId,approvalId:A,toolName:t.toolName,callId:t.callId,reason:t.reason,settle:c=>{this.#g.delete(s.rpcId)&&(t.signal?.removeEventListener("abort",g),this.#C({type:"approval/resolved",sessionId:s.sessionId,approvalId:s.approvalId,outcome:c}),r(c))}},g=()=>s.settle("cancelled");this.#g.set(s.rpcId,s),t.signal?.addEventListener("abort",g,{once:!0}),this.#C(this.#S(s).payload,s.rpcId)})}#m(t){let o=this.#g.get(t?.rpcId);if(o){let a=t?.result?.value;return t?.result?.ok!==!0||!a||typeof a!="object"||a.sessionId!==o.sessionId||a.approvalId!==o.approvalId||a.outcome!=="allowed-once"&&a.outcome!=="rejected"?{accepted:!1,reason:"bad-response"}:(o.settle(a.outcome),{accepted:!0})}let i=this.#r.get(t?.rpcId);if(!i)return{accepted:!1,reason:"not-pending"};if(t?.result?.ok!==!0)return t?.result?.error?.code!=="cancelled"?{accepted:!1,reason:"bad-response"}:(i.settle("cancelled",TQ("the user cancelled ask_user_question","ASK_CANCELLED")),{accepted:!0});if(!zEe(t.result.value,i))return{accepted:!1,reason:"bad-response"};let e={answers:t.result.value.answer.answers.map(a=>({id:a.id,selected:[...a.selected],...a.custom===void 0?{}:{custom:a.custom}}))};return i.settle("answered",e),{accepted:!0}}dispose(){if(!this.#i){this.#i=!0;for(let t of[...this.#t])t.close();for(let t of[...this.#g.values()])t.settle("cancelled");for(let t of[...this.#r.values()])t.settle("cancelled",TQ("dsh-im interaction adapter was disposed","ASK_ABORTED"));for(let t of this.#n.splice(0).reverse())t?.()}}};function XY(n){let t=n?.root??n;if(!t||!["object","function"].includes(typeof t))throw new TypeError("dsh-im requires a Cordis Host context");let o=_Q.get(t);if(o)return o;let i=n?.typertGateway;if(!i||typeof i.invoke!="function"||typeof i.stream!="function")throw new TypeError("dsh-im requires the modern Host Typert gateway");let e=new y_(n,i,t);return _Q.set(t,e),typeof n.effect=="function"&&n.effect(()=>()=>{_Q.get(t)===e&&_Q.delete(t),e.dispose()},"dsh-im: modern Harness compatibility API"),e}function WEe(n,t){return n&&Object.hasOwn(n,t)?n[t]:typeof n?.get=="function"?n.get(t):void 0}function Aa(n,t={}){return t.harnessBaseUrl!==void 0?{baseUrl:new URL(t.harnessBaseUrl)}:{apiProxy:WEe(n,"apiProxy")??XY(n),interactionScope:n.root??n}}import{randomUUID as ZEe}from"node:crypto";function XEe(n){if(typeof n?.get!="function")return;let t;try{t=n.get("agents")}catch{return}if(t!=null){if(typeof t.get!="function")throw new TypeError('dsh-im requires a callable AgentRegistry when ctx.get("agents") is present');return t}}function $Ee(n,t,o){if(n?.status!=="running")return!1;let i=n?.session?.events;if(!Array.isArray(i))return!1;let e=null,a=!1;for(let A of i){if(A?.type==="turn/start"){e=A.data?.turn??null,a=!1;continue}if(A?.type==="turn/end"&&A.data?.turn===e){e=null,a=!1;continue}e===t&&A?.type==="user/message"&&A.data?.source?.rpcId===o&&(a=!0)}return e===t&&a}function $Y(n){if(!n||typeof n!="object"||Object.isFrozen(n))return n;for(let t of Object.values(n))$Y(t);return Object.freeze(n)}function eCe(n){return $Y({id:ZEe(),role:"user",content:[{type:"text",text:n}],source:{kind:"user"}})}function ACe(n){let t=new Error("Session is busy with an active turn or maintenance task",{cause:n});return t.code="agent-busy",t}function tCe(n){return({sessionId:t,expectedTurn:o,promptRpcId:i,action:e,text:a})=>{let A=n.get(t);if(A){if(!$Ee(A,o,i))return!1;if(e==="stop")return A.cancel({kind:"user"},{keepInbox:!0}),!0;if(e==="steer")return typeof a!="string"||!a.trim()?!1:(A.inject(eCe(a)),!0);throw new TypeError(`Unsupported Harness control action: ${String(e)}`)}}}function rCe(n){return({sessionId:t,operation:o})=>{if(typeof o!="function")throw new TypeError("maintenance operation is required");let i=n.get(t);if(!i)return o();try{return i.runMaintenance(e=>{if(n.get(t)!==i){let a=new Error("Session agent changed before maintenance started");throw a.code="agent-unavailable",a}return o(e)})}catch(e){throw ACe(e)}}}function aCe(n){return({sessionId:t,workspace:o,files:i,signal:e})=>{let A=n.get(t)?.session?.header?.cwd,r=typeof A=="string"&&A?A:o;if(typeof r!="string"||!r)throw new Do("inbound-file-workspace-unavailable","The Harness Session workspace is unavailable for inbound files.");return IY({files:i},{workspace:r,signal:e})}}function Ha(n,t={}){let{controlExecutor:o,sessionMaintenanceExecutor:i,fileIngressExecutor:e}=t;if(o!==void 0&&typeof o!="function")throw new TypeError("controlExecutor must be a function");if(i!==void 0&&typeof i!="function")throw new TypeError("sessionMaintenanceExecutor must be a function");if(e!==void 0&&typeof e!="function")throw new TypeError("fileIngressExecutor must be a function");let a=o&&i&&e?void 0:XEe(n);return{controlExecutor:o??(a?tCe(a):void 0),sessionMaintenanceExecutor:i??(a?rCe(a):void 0),fileIngressExecutor:e??aCe(a??{get:()=>{}})}}function nCe(n){let t=bI(n.dshHome??process.env.DSH_HOME??UE(oCe(),".dsh")),o=bI(n.dataDir??UE(t,"integrations","dsh-dingtalk"));return{root:o,config:bI(n.configPath??UE(o,"config.json")),bots:bI(n.botsDir??UE(o,"bots")),workspaces:bI(n.workspacesPath??UE(o,"workspaces.json"))}}async function m_(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-dingtalk requires ctx.credentials");let i=Aa(n,t),e=o.ConfigStore??rQ,a=o.DeviceAuth??iQ,A=o.StateStore??SQ,r=o.HarnessClient??yQ,s=o.Controller??wE,g=o.Runtime??kE,c=o.createConnectionSupervisor??B_,I=typeof n.logger=="function"?n.logger("dsh-dingtalk"):n.logger??console,d=()=>Ra(n),B=nCe(t),f=await new e(B.config).load(),Q=bI(t.workspace??process.cwd()),y=o.WorkspaceStore??ea,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=typeof f.list=="function",T=_?f.list():[];_&&await m.reconcile(T.map(Ae=>Ae.botId)),await Promise.all(T.map(Ae=>m.ensure(Ae.botId,{defaultAgentPreset:t.agentPreset})));let R=typeof f.remove=="function"?Pa(f,{workspaces:m}):f,F=o.deviceAuth??new a({baseUrl:t.registrationBaseUrl}),K=new Map,L=Ae=>bI(B.bots,Ae,"state.json"),q=async Ae=>{let ie=K.get(Ae);return ie||(ie=await new A(L(Ae)).load(),K.set(Ae,ie)),ie},z=Ua(n,o.commandExecutor),{controlExecutor:j,sessionMaintenanceExecutor:P,fileIngressExecutor:J}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),U=new r({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...z?{commandExecutor:z}:{},...j?{controlExecutor:j}:{},...P?{sessionMaintenanceExecutor:P}:{},...J?{fileIngressExecutor:J}:{}}),N=new s({deviceAuth:F,credentials:n.credentials,configStore:R,logger:I,createRuntime:async({botId:Ae,config:ie,clientSecret:De})=>{let fe=await q(Ae);await m.ensure(Ae,{defaultAgentPreset:t.agentPreset});let _e=Ga(U,{botId:Ae,workspaces:m,state:fe,agentPresetCatalog:d});return new g({config:ie,clientSecret:De,harness:_e.harness,state:_e.state,contextEnhancement:{botId:Ae,getSettings:()=>m.contextEnhancementFor(Ae)},replyTimeoutMs:t.replyTimeoutMs??6e5,maxMessageChars:t.maxMessageChars??4e3,connectTimeoutMs:t.connectTimeoutMs??15e3,logger:{error:(...Ee)=>I.error?.(`[${Ae}]`,...Ee),warn:(...Ee)=>I.warn?.(`[${Ae}]`,...Ee),info:(...Ee)=>I.info?.(`[${Ae}]`,...Ee),debug:(...Ee)=>I.debug?.(`[${Ae}]`,...Ee)}})},deleteState:async({botId:Ae})=>{let ie=K.get(Ae);if(K.delete(Ae),ie&&typeof ie.remove=="function")await ie.remove();else try{await iCe(L(Ae))}catch(De){if(De?.code!=="ENOENT")throw De}}}),k=Fa(N,{workspaces:m,stateFor:q,agentPresetCatalog:d}),V=c({controller:k,harness:U,logger:I,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:k,deliveryAdapter:La({channel:"dingtalk",workspaces:m,coreController:N,stateFor:q}),ready:V.ready,async close(){await V.close(),await k.close(),U.stopManagedProcess()}}}import ICe from"qrcode";var wi="bot.context-enhancement.set";function Ka(n){try{return!n||typeof n!="object"||Array.isArray(n)||Reflect.ownKeys(n).length!==2||!Object.hasOwn(n,"botId")||!Object.hasOwn(n,"config")||typeof n.botId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)?!1:(mp(n.config),!0)}catch{return!1}}var sCe=new Set(["loopback","trusted-host"]);function hr(n){if(n===void 0)return"loopback";if(sCe.has(n))return n;throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"')}import{isAbsolute as gCe}from"node:path";var Di="bot.workspace.set";function xa(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).every(t=>["botId","workspace"].includes(t))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&typeof n.workspace=="string"&&n.workspace.length<=4096&&gCe(n.workspace.trim())}function Ya(n){return["workspace-not-absolute","workspace-not-found","workspace-not-directory","workspace-bot-not-found","agent-preset-invalid","agent-preset-unavailable","context-enhancement-invalid"].includes(n?.code)?{code:n.code,message:n.message}:null}var Oi="bot.preset.set";function cCe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ja(n){return cCe(n)&&Object.keys(n).every(t=>["botId","agentPreset"].includes(t))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&(n.agentPreset===null||typeof n.agentPreset=="string"&&WM.test(n.agentPreset))}var A1="/dingtalk",Kt=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi,approveSender:"bot.sender.approve",revokeSender:"bot.sender.revoke"}),t1=Object.freeze(Object.values(Kt)),lCe=new Set(["clientSecret","client_secret","deviceCode","device_code","secretRef","staffId","senderStaffId","verificationUrl","verificationUri","userCode"]);function w_(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function oc(n,t){return w_(n)&&Object.keys(n).every(o=>t.includes(o))}function MI(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function e1(n,t){return typeof n=="string"&&n.trim().length>0&&n.length<=t}function pCe(n,t){return w_(t)?n===Kt.status?oc(t,[])?null:"connection.status does not accept fields.":n===Kt.beginProvisioning?oc(t,["locale"])&&(t.locale===void 0||t.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Kt.pollProvisioning,Kt.cancelProvisioning].includes(n)?oc(t,["attemptId"])&&MI(t.attemptId)?null:`${n} requires an attemptId.`:n===Kt.bindCredentials?oc(t,["clientId","clientSecret"])&&e1(t.clientId,256)&&e1(t.clientSecret,1024)?null:"bot.bind-credentials requires Client ID and Client Secret.":n===Kt.reconnectBot?oc(t,["botId","sendTest"])&&MI(t.botId)&&(t.sendTest===void 0||t.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Kt.deleteBot?oc(t,["botId","confirm"])&&MI(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Kt.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Kt.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===Kt.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":n===Kt.approveSender?oc(t,["botId","requestId","confirm"])&&MI(t.botId)&&MI(t.requestId)&&t.confirm===!0?null:"bot.sender.approve requires botId, requestId, and confirm=true.":n===Kt.revokeSender?oc(t,["botId","senderKey","confirm"])&&MI(t.botId)&&MI(t.senderKey)&&t.confirm===!0?null:"bot.sender.revoke requires botId, senderKey, and confirm=true.":"Unknown DingTalk endpoint.":"Payload must be an object."}function NQ(n){return{ok:!1,error:{code:"bad-request",message:n}}}function HE(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function dCe(){return{ok:!1,error:{code:"dingtalk-operation-failed",message:"\u9489\u9489\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}function Tp(n){if(Array.isArray(n))return n.map(Tp);if(!w_(n))return n;let t={};for(let[o,i]of Object.entries(n))lCe.has(o)||(t[o]=Tp(i));return t}async function hCe(n){return ICe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function S_(n,t){return!n||typeof n.verificationUrl!="string"?Tp(n):Tp({...n,qrCodeDataUrl:await t(n.verificationUrl)})}async function ig(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await S_(o.provisioning,t)),Tp(o)}function ECe(n){for(let t of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot","approveSender","revokeSender"])if(typeof n?.[t]!="function")throw new TypeError(`A complete DingTalk controller is required (${t})`)}function r1(n,{encodeQr:t=hCe}={}){ECe(n);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return HE();if(!t1.includes(e))return NQ("Unknown DingTalk endpoint.");let r=pCe(e,a);if(r)return NQ(r);try{let s;if(e===Kt.status)s=await ig(await n.status(),i);else if(e===Kt.beginProvisioning){let g=await n.startProvisioning({signal:A});if(A?.aborted)return await n.cancelProvisioning(g.attemptId),HE();s=await S_(g,i)}else if(e===Kt.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return NQ("The provisioning attempt no longer exists.");s=await S_(g,i)}else if(e===Kt.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return NQ("The provisioning attempt no longer exists.");s=Tp(s)}else if(e===Kt.bindCredentials)s=await ig(await n.bindCredentials(a),i);else if(e===Kt.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return HE();let c;if(a.sendTest===!0)if(!g?.bots?.some(d=>d?.botId===a.botId&&d?.connected===!0)||typeof n.sendConnectionTest!="function")c=ir(Ir("\u9489\u9489\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=ir()}catch(d){c=ir(d)}s=await ig({...g,...c?{testMessage:c}:{}},i)}else if(e===Kt.deleteBot)s=await ig(await n.deleteBot(a.botId),i);else if(e===Kt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await ig(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===Kt.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>ig(g,i))}else if(e===Kt.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await ig(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else e===Kt.approveSender?s=await ig(await n.approveSender(a.botId,a.requestId),i):s=await ig(await n.revokeSender(a.botId,a.senderKey),i);return A?.aborted?HE():{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?HE():g?{ok:!1,error:g}:dCe()}}}function RQ(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(A1,r1(t,o),{authority:hr(i)})}async function a1(n,t={}){if(t?.controller)return RQ(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await m_(n,t,t.internals),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=RQ(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-dingtalk: close bot connections"),e}import{createHash as CCe}from"node:crypto";import{mkdir as uCe,readFile as BCe,rename as fCe,unlink as QCe,writeFile as yCe}from"node:fs/promises";import{dirname as mCe}from"node:path";var D_=Object.freeze({version:1,bots:Object.freeze([])});function og(n){return typeof n=="string"&&n.trim()?n.trim():null}function i1(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function KE(n,{botPrefix:t,tokenRefPrefix:o}){let i=og(n);if(!i)throw new TypeError("platformId is required");let e=CCe("sha256").update(i).digest("hex").slice(0,24);return{botId:`${t}_${e}`,tokenRef:`${o}_${e.toUpperCase()}`}}function kQ(n,t){let o=og(n)??"";return o.length<=10?o?`${o.slice(0,3)}\u2022\u2022\u2022`:t:`${o.slice(0,6)}\u2022\u2022\u2022\u2022${o.slice(-4)}`}var Np=class{#e;#A;#t;#r;#g;#a;#n;#i=D_;#I=Promise.resolve();constructor(t,{channel:o,botPrefix:i,tokenRefPrefix:e,normalizeBotExtension:a=()=>({})}){if(typeof a!="function")throw new TypeError("normalizeBotExtension must be a function");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=new RegExp(`^${i1(i)}_[a-f0-9]{24}$`),this.#n=new RegExp(`^${i1(e)}_[A-F0-9]{24}$`)}async load(){try{let t=this.#o(JSON.parse(await BCe(this.#e,"utf8")));if(!t)throw new Error(`dsh-im ${this.#A} config contains invalid bot data`);this.#i=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#i=D_}return this}list(){return structuredClone(this.#i.bots)}get(t){let o=this.#i.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByPlatformId(t){let o=this.#i.bots.find(i=>i.platformId===t);return o?structuredClone(o):null}async save(t){let o=this.#l(t);if(!o)throw new Error(`Refusing to persist incomplete ${this.#A} bot data`);return this.#s(i=>{let e=i.find(r=>r.platformId===o.platformId&&r.botId!==o.botId),a=i.find(r=>r.tokenRef===o.tokenRef&&r.botId!==o.botId);if(e||a)throw new Error(`Duplicate ${this.#A} bot identity`);let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!this.#a.test(t))throw new TypeError(`Invalid ${this.#A} bot id`);return this.#s(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#I.then(async()=>{try{await QCe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#i=D_});this.#I=t.then(()=>{},()=>{}),await t}#l(t){if(!t||typeof t!="object")return null;let o=og(t.platformId),i=og(t.botId),e=og(t.tokenRef),a=og(t.name);if(!o||!i||!e||!a||!this.#a.test(i)||!this.#n.test(e))return null;let A=KE(o,{botPrefix:this.#t,tokenRefPrefix:this.#r});if(A.botId!==i||A.tokenRef!==e)return null;let r=this.#g(t);return!r||typeof r!="object"||Array.isArray(r)?null:Object.freeze({botId:i,platformId:o,tokenRef:e,name:a,username:og(t.username),createdAt:og(t.createdAt)??new Date().toISOString(),connectedAt:og(t.connectedAt),...r})}#o(t){if(!t||t.version!==1||!Array.isArray(t.bots))return null;let o=t.bots.map(A=>this.#l(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||a.has(A.tokenRef))return null;i.add(A.botId),e.add(A.platformId),a.add(A.tokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#s(t){let o,i=this.#I.then(async()=>{let e=[...this.#i.bots];o=t(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#c(a),this.#i=a});return this.#I=i.then(()=>{},()=>{}),await i,o}async#c(t){await uCe(mCe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await yCe(o,`${JSON.stringify(t,null,2)} +`,{encoding:"utf8",mode:384}),await SEe(a,this.#e),this.#p.clear()}async#Q(){if(Object.keys(this.#r).length>0||Object.keys(this.#g).length>0||Object.keys(this.#a).length>0||Object.keys(this.#n).length>0){await this.#S();return}try{await DEe(this.#e),this.#p.clear()}catch(t){if(t?.code!=="ENOENT")throw t;this.#p.clear()}}};function DQ(n){if(!n)return null;let t=typeof n=="function"?n():n;return t&&typeof t.then=="function"?t.then(Jn):Jn(t)}function JY(){let n=new Error("Agent Preset \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\u3002");return n.code="agent-preset-unavailable",n}function Mp(n){if(n())return;let t=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw t.code="workspace-bot-not-found",t}function YY(n,t,o){let i=e=>{let a=n.decorateStatus(e);if(!o||!a||typeof a!="object")return a;let A=s=>s?{...a,agentPresetCatalog:s}:a,r=DQ(o);return r&&typeof r.then=="function"?r.then(A):A(r)};return t&&typeof t.then=="function"?t.then(i):i(t)}function REe(n){return Promise.resolve(n.status())}function Pa(n,{workspaces:t,method:o="remove",botIdFromRemoved:i=A=>A?.botId,saveMethod:e="save",botIdFromSave:a=A=>A?.botId}){if(!n||!t||typeof n[o]!="function")throw new TypeError("configStore removal observer dependencies are required");return new Proxy(n,{get(A,r){let s=Reflect.get(A,r,A);return r===o?async(...g)=>{let c=await s.apply(A,g),I=c?i(c,g):null;return I&&await t.retireAfterConfigCommit(I),c}:r===e&&typeof s=="function"?(...g)=>{let c=t.flushPendingRemoval(a(g[0],g));return c?c.then(()=>s.apply(A,g)):s.apply(A,g)}:typeof s=="function"?s.bind(A):s}})}function Ga(n,{botId:t,workspaces:o,state:i,agentPresetCatalog:e}={}){if(!n||!o||!i)throw new TypeError("harness, workspaces, and state are required");let a=o.incarnationFor(t),A=()=>o.has(t)&&o.incarnationFor(t)===a,r=async(I=e)=>{let d;try{d=await DQ(I)??Jn(null)}catch(B){throw Mp(A),B}return Mp(A),{agentPreset:o.agentPresetFor(t),agentPresetCatalog:d}},s=new Map,g=new Proxy(n,{get(I,d){if(d==="agentPresetSettings")return async(f={})=>{f?.signal?.throwIfAborted(),Mp(A);let Q=await r();return f?.signal?.throwIfAborted(),Q};if(d==="updateAgentPreset")return async(f,Q={})=>{Q?.signal?.throwIfAborted(),Mp(A);let y=f==="--default"?null:yp(f),m=null;if(y&&({agentPresetCatalog:m}=await r(),Q?.signal?.throwIfAborted(),!m.items.some(_=>_.id===y)))throw JY();if(await o.setAgentPreset(t,y,{incarnation:a}),Mp(A),m)return{agentPreset:o.agentPresetFor(t),agentPresetCatalog:m};try{return await r()}catch(_){if(_?.code==="workspace-bot-not-found")throw _;return Mp(A),{agentPreset:o.agentPresetFor(t),agentPresetCatalog:Jn(null)}}};if(d==="currentWorkspace")return()=>{if(!A()){let f=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw f.code="workspace-bot-not-found",f}return o.workspaceFor(t)};if(d==="assertWorkspaceScope")return()=>{if(!A()){let f=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw f.code="workspace-bot-not-found",f}};if((d==="listWorkspaces"||d==="listWorkspaceSessions"||d==="listModels")&&typeof I[d]=="function")return async(...f)=>{if(!A()){let y=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw y.code="workspace-bot-not-found",y}let Q=await I[d](...f);if(!A()){let y=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw y.code="workspace-bot-not-found",y}return Q};if(d==="switchWorkspace")return f=>{if(!A()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");return Q.code="workspace-bot-not-found",Promise.reject(Q)}return o.setWorkspace(t,f,{clearSessions:()=>i.clearSessions(),incarnation:a})};if(d==="bindWorkspaceSession")return async(f,Q)=>{if(typeof f!="string"||!f||typeof Q!="string"||!Q)throw new TypeError("conversationKey and sessionId are required");if(!A()){let T=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw T.code="workspace-bot-not-found",T}if(typeof I.adoptWorkspaceSession!="function")throw new TypeError("Harness does not support adopting workspace sessions");let y=o.generationFor(t),m=await I.adoptWorkspaceSession(Q);if(!A()){let T=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw T.code="workspace-bot-not-found",T}if(y!==o.generationFor(t))throw DI("The bot workspace changed while the session was being adopted.");if(!m||typeof m!="object"||m.sessionId!==Q||typeof m.workspace!="string")throw new TypeError("Harness returned an invalid adopted workspace session");let _=await o.bindWorkspaceSession(t,m.workspace,{conversationKey:f,sessionId:Q,clearSessions:()=>i.clearSessions(),setSession:(T,R)=>i.setSession(T,R),incarnation:a,expectedGeneration:y});if(!A()){let T=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw T.code="workspace-bot-not-found",T}if(_.generation!==o.generationFor(t))throw DI("The bot workspace changed before the session binding completed.");return s.set(Q,_.generation),{...m,workspace:_.workspace,sessionId:_.sessionId}};if(d==="createSession")return async(f={})=>{if(await o.whenBotIdle(t),!A()){let _=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw _.code="workspace-bot-not-found",_}let Q=o.generationFor(t),y=o.agentPresetFor(t),m=await I.createSession({...f,workspace:o.workspaceFor(t),...y==null?{}:{agentPreset:y}});return s.set(m,Q),m};if(d==="workspaceSession")return f=>{if(typeof f!="string"||!f)throw new TypeError("sessionId is required");let Q=s.get(f)??o.generationFor(t);s.delete(f);let y=()=>A()&&Q===o.generationFor(t),m=async(T,R,L)=>{if(!y())throw DI(`The bot workspace changed before this ${L} started.`);let U=await I[T](f,...R);if(!y())throw DI(`The bot workspace changed while this ${L} was running.`);return U},_=async(T,R,L)=>{if(!y())throw DI(`The bot workspace changed before this ${L} started.`);return I[T](f,...R)};return Object.freeze({sessionId:f,async sessionExists(...T){if(!y())return!1;let R=await I.sessionExists(f,...T);return y()&&R},models(...T){return m("getSessionModels",T,"model listing")},readHistory(...T){return m("readSessionHistory",T,"history read")},selectModel(...T){return m("selectSessionModel",T,"model selection")},isRunning(...T){return m("isSessionRunning",T,"run-state check")},hasActiveTurn(...T){return m("hasActiveTurn",T,"turn ownership check")},stopActiveTurn(...T){return _("stopActiveTurn",T,"turn stop")},steerActiveTurn(...T){return _("steerActiveTurn",T,"turn steering")},ask(...T){if(!y())throw DI("The bot workspace changed before this prompt started.");return I.ask(f,...T)}})};if(d==="sessionExists")return(f,...Q)=>{if(!A())return!1;let y=s.get(f);return y!==void 0&&y!==o.generationFor(t)?(s.delete(f),!1):I.sessionExists(f,...Q)};if(d==="ask")return(f,...Q)=>{let y=s.get(f);if(s.delete(f),!A()||y!==void 0&&y!==o.generationFor(t)){let m=new Error("The bot workspace changed before this prompt started.");throw m.code=Na,m}return I.ask(f,...Q)};if(d==="executeCommand"&&typeof I.executeCommand=="function")return(f,...Q)=>{let y=s.get(f);if(s.delete(f),!A()||y!==void 0&&y!==o.generationFor(t)){let m=new Error("The bot workspace changed before this command started.");throw m.code=Na,m}return I.executeCommand(f,...Q)};let B=Reflect.get(I,d,I);return typeof B=="function"?B.bind(I):B}}),c=new Proxy(i,{get(I,d){if(d===_M)return I;if(d==="sessionFor")return(f,...Q)=>{if(!A())return null;let y=I.sessionFor(f,...Q);return y&&!s.has(y)&&s.set(y,o.generationFor(t)),y};if(d==="setSession")return(f,Q,...y)=>{let m=s.get(Q);return!A()||m!==void 0&&m!==o.generationFor(t)?(s.delete(Q),!1):I.setSession(f,Q,...y)};let B=Reflect.get(I,d,I);return typeof B=="function"?B.bind(I):B}});return Object.freeze({harness:g,state:c})}function Fa(n,{workspaces:t,stateFor:o,agentPresetCatalog:i}={}){if(!n||!t||typeof o!="function")throw new TypeError("controller, workspaces, and stateFor are required");let e=new Map,a=(I,d)=>{let f=(e.get(I)??Promise.resolve()).catch(()=>{}).then(d);return e.set(I,f),f.finally(()=>{e.get(I)===f&&e.delete(I)})},A=I=>YY(t,I,i),r=(I,d)=>{let B=t.incarnationFor(I);return a(I,async()=>{if(!(await n.status())?.bots?.some(y=>y?.botId===I)){let y=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw y.code="workspace-bot-not-found",y}let Q=await o(I);return await t.setWorkspace(I,d,{clearSessions:()=>Q.clearSessions(),incarnation:B}),A(await n.status())})},s=(I,d)=>{let B=t.incarnationFor(I),f=yp(d);return a(I,async()=>{if(!(await n.status())?.bots?.some(m=>m?.botId===I)){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}let y=f&&i?await DQ(i):null;if(f&&i&&!y?.items.some(m=>m.id===f))throw JY();return await t.setAgentPreset(I,f,{incarnation:B}),YY(t,await n.status(),y??i)})},g=(I,d,B)=>{let f=t.incarnationFor(I),Q=mp(d);return a(I,async()=>{let y=await n.status();if(!y?.bots?.some(L=>L?.botId===I)){let L=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw L.code="workspace-bot-not-found",L}let m=await DQ(i),_=t.decorateStatus(y),T={..._,bots:_.bots.map(L=>L?.botId===I?{...L,contextEnhancement:Q}:L),...m?{agentPresetCatalog:m}:{}},R=B?await B(T):T;return await t.setContextEnhancement(I,Q,{incarnation:f}),R})},c=(I,d)=>a(I,async()=>{let B=await t.beginRemoval(I,{clearSessions:async()=>{try{let f=await o(I);if(!f||typeof f.clearSessions!="function")throw new TypeError("bot state does not support session cleanup");await f.clearSessions()}catch(f){console.warn(`[dsh-im] ignored session cleanup failure while deleting bot ${I}:`,f?.message??f)}}});try{let f=await d();return await t.finishRemoval(B),A(f)}catch(f){let Q=await REe(n).catch(()=>null);throw Array.isArray(Q?.bots)&&!Q.bots.some(m=>m?.botId===I)?await t.finishRemoval(B):await t.abortRemoval(B),f}});return new Proxy(n,{get(I,d){if(d==="updateWorkspace")return r;if(d==="updateAgentPreset")return s;if(d==="updateContextEnhancement")return g;let B=Reflect.get(I,d,I);return typeof B!="function"?B:d==="deleteBot"?(f,...Q)=>c(f,()=>B.call(I,f,...Q)):d==="disconnect"?async(...f)=>{let y=(await I.status())?.bots?.[0]?.botId;return y?c(y,()=>B.apply(I,f)):A(B.apply(I,f))}:(...f)=>A(B.apply(I,f))}})}var qY=new Set(["weixin","feishu","dingtalk","wecom","qq","slack","telegram","discord","whatsapp"]);function kEe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function vEe(n){return typeof n=="string"&&n.length>0&&n.length<=512&&n.trim()===n&&!/[\s:\u0000-\u001f\u007f]/u.test(n)}function C_(n,t){let o=`${t}:`;if(!n.startsWith(o))return null;let i=n.slice(o.length);return vEe(i)?i:null}function LE(n,t){for(let[o,i,e]of t){let a=C_(n,o);if(a)return{kind:i,route:{[e]:a}}}return null}function PEe(n){let t=C_(n,"p2p");return t?.startsWith("ou_")?{kind:"user",route:{openId:t}}:LE(n,[["group","group","chatId"]])}function GEe(n){let t=C_(n,"direct");if(t&&/^[A-Za-z0-9_-]{1,128}$/.test(t))return{kind:"conversation",route:{channelId:t}};let o=/^group:([^:]+):(\d{1,20}(?:\.\d{1,20})?)$/.exec(n);return!o||!/^[A-Za-z0-9_-]{1,128}$/.test(o[1])?null:{kind:"thread",route:{channelId:o[1],threadTs:o[2]}}}function FEe(n){let t=/^(direct|group):(-?\d+)(?::([1-9]\d*))?$/.exec(n);if(!t)return null;let o=Number(t[2]);if(!Number.isSafeInteger(o)||t[1]==="direct"&&t[3]!==void 0)return null;if(t[3]===void 0)return{kind:"chat",route:{chatId:t[2]}};let i=Number(t[3]);return!Number.isSafeInteger(i)||i<=0?null:{kind:"topic",route:{chatId:t[2],messageThreadId:i}}}function LEe(n){let t=/^(?:direct|group):(\d{1,32})$/.exec(n);return t?{kind:"channel",route:{channelId:t[1]}}:null}function UEe(n){let t=/^direct:(\d{5,32}@(s\.whatsapp\.net|lid))$/.exec(n);if(t)return{kind:"user",route:{jid:t[1]}};let o=/^group:(\d{5,32}(?:-\d{1,32})?@g\.us)$/.exec(n);return o?{kind:"group",route:{jid:o[1]}}:null}function HEe(n,t){if(!qY.has(n)||typeof t!="string")return null;switch(n){case"weixin":return LE(t,[["p2p","user","toUserId"]]);case"feishu":return PEe(t);case"dingtalk":return LE(t,[["p2p","user","userId"],["group","group","openConversationId"]]);case"wecom":return LE(t,[["direct","user","chatId"],["group","group","chatId"]]);case"qq":return LE(t,[["c2c","user","userOpenId"],["group","group","groupOpenId"]]);case"slack":return GEe(t);case"telegram":return FEe(t);case"discord":return LEe(t);case"whatsapp":return UEe(t);default:return null}}function zY(n,t){if(!qY.has(n)||!kEe(t))return[];let o=[],i=new Set;for(let e of Object.keys(t)){let a=HEe(n,e);if(!a)continue;let A=JSON.stringify(a);i.has(A)||(i.add(A),o.push(a))}return o}var KEe=new Set(["weixin","feishu","dingtalk","wecom","qq","slack","telegram","discord","whatsapp"]);function bQ(n){return KEe.has(n)}function ic(n){let t=new Error(n);return t.code="invalid-target",t}function xEe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function u_(n,t,o){if(!xEe(n))throw ic(`${o} must be an object`);if(Object.keys(n).find(e=>!t.includes(e))!==void 0)throw ic(`${o} contains an unknown field`)}function OQ(n,t){if(typeof n!="string"||!n||n.trim()!==n)throw ic(`${t} must be a non-empty string without surrounding whitespace`);return n}function YEe(n){if(typeof n!="string"||!n.trim()||n.trim().length>80)throw ic("target.name must contain 1 to 80 characters");return n.trim()}function ac(n,t){u_(n,t,"route");let o={};for(let i of t)o[i]=OQ(n[i],`route.${i}`);return o}function ag(n,t){if(!t.includes(n))throw ic("target kind is not supported by this channel");return n}function jEe(n,t,o){switch(n){case"weixin":return ag(t,["user"]),ac(o,["toUserId"]);case"feishu":return ag(t,["user","group"]),ac(o,t==="user"?["openId"]:["chatId"]);case"dingtalk":return ag(t,["user","group"]),ac(o,t==="user"?["userId"]:["openConversationId"]);case"wecom":return ag(t,["user","group"]),ac(o,["chatId"]);case"qq":return ag(t,["user","group"]),ac(o,t==="user"?["userOpenId"]:["groupOpenId"]);case"slack":return ag(t,["conversation","thread"]),ac(o,t==="conversation"?["channelId"]:["channelId","threadTs"]);case"telegram":{ag(t,["chat","topic"]),u_(o,t==="chat"?["chatId"]:["chatId","messageThreadId"],"route");let i=OQ(o.chatId,"route.chatId");if(!/^-?\d+$/.test(i))throw ic("route.chatId must be a decimal string");if(t==="chat")return{chatId:i};if(!Number.isSafeInteger(o.messageThreadId)||o.messageThreadId<=0)throw ic("route.messageThreadId must be a positive integer");return{chatId:i,messageThreadId:o.messageThreadId}}case"discord":return ag(t,["channel"]),ac(o,["channelId"]);case"whatsapp":{ag(t,["user","group"]);let i=ac(o,["jid"]);if(!(t==="user"?/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(i.jid):/^\d{5,32}(?:-\d{1,32})?@g\.us$/.test(i.jid)))throw ic(`route.jid must be a ${t} WhatsApp JID`);return i}default:throw new TypeError(`Unsupported delivery channel: ${n}`)}}function _p(n,t,{targetIdRequired:o=!0}={}){if(!bQ(n))throw new TypeError(`Unsupported delivery channel: ${n}`);u_(t,o?["targetId","name","kind","route"]:["name","kind","route"],"target");let i={};return o&&(i.targetId=OQ(t.targetId,"target.targetId")),t.name!==void 0&&(i.name=YEe(t.name)),i.kind=OQ(t.kind,"target.kind"),i.route=jEe(n,i.kind,t.route),i}function La({channel:n,workspaces:t,coreController:o,stateFor:i}){if(!bQ(n))throw new TypeError(`Unsupported delivery channel: ${n}`);if(!t||typeof t!="object")throw new TypeError("delivery adapter requires a workspace store");if(!o||typeof o!="object")throw new TypeError("delivery adapter requires a proactive text controller");if(typeof i!="function")throw new TypeError("delivery adapter requires a bot state getter");return Object.freeze({channel:n,ownsBot:e=>t.has(e),listTargets:e=>t.listDeliveryTargets(e),async listSuggestions(e){let a=await i(e);if(!a||typeof a.snapshot!="function")throw new TypeError("delivery suggestion state cannot be inspected");return zY(n,a.snapshot()?.sessions).map(r=>_p(n,r,{targetIdRequired:!1}))},createTarget:(e,a)=>t.createDeliveryTarget(e,_p(n,a)),updateTarget:(e,a,A)=>t.updateDeliveryTarget(e,a,_p(n,A,{targetIdRequired:!1})),deleteTarget:(e,a)=>t.deleteDeliveryTarget(e,a),async sendText(e,a,A,r={}){let s=_p(n,a);if(typeof o.sendProactiveText!="function")throw new TypeError("delivery controller cannot send proactive text");return await o.sendProactiveText(e,s,A,r),{sent:!0}}})}var VY=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function JEe(n){if(!Array.isArray(n)||n.length===0)return[...VY];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...VY]}var MQ=class{#e;#A;#t;#r;#g;#a;#n;#i=null;#I=null;#l=0;#o=!1;#s=!1;#c;#p;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=JEe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#a=A,this.#n=r,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#s||this.#o?this:(this.#s=!0,this.#d(0),this)}async close(){this.#o||(this.#o=!0,this.#i!==null&&this.#n(this.#i),this.#i=null,await this.#I?.catch(()=>{}),this.#p?.(null),this.#p=null)}#d(t){this.#o||(this.#i=this.#a(()=>{this.#i=null,this.#h()},t),this.#i?.unref?.())}async#h(){if(this.#o||this.#I)return;let t=this.#E();this.#I=t;try{await t}finally{this.#I===t&&(this.#I=null)}}async#E(){try{if(await this.#A.ensureRunning(),this.#o)return;let t=await this.#e.initialize();if(this.#o)return;this.#p?.(t),this.#p=null;let{configured:o,connected:i}=t.totals;if(i{let A={namespace:"commands",method:"execute",args:{agentId:i,line:e,images:[]},signal:a.signal};try{return await o.invoke(A)}catch(r){if(r?.name!=="TypertGatewayError"||r.code!=="arguments-invalid"||r.endpoint!=="commands/execute"||r.message!=='typert gateway: commands/execute: args fields do not match the descriptor: unexpected "images"')throw r;return a.signal?.throwIfAborted(),o.invoke({...A,args:{agentId:i,line:e}})}}}}import{randomUUID as f_}from"node:crypto";var _Q=new WeakMap;function qEe(n){let t=n?.failure;return t&&typeof t=="object"&&typeof t.code=="string"&&typeof t.message=="string"?{code:t.code,message:t.message,details:t.details&&typeof t.details=="object"?t.details:{}}:n?.name==="AbortError"||n?.name==="RemoteInvocationCancelled"?{code:"cancelled",message:n instanceof Error?n.message:"Harness request was cancelled",details:{}}:{code:"internal",message:n instanceof Error?n.message:String(n),details:{}}}function dn(n,t){return Promise.resolve().then(t).then(o=>({rpcId:n.rpcId,result:{ok:!0,value:o}}),o=>({rpcId:n.rpcId,result:{ok:!1,error:qEe(o)}}))}function WY(n,t,o,i){return{namespace:n,method:t,args:o,...i===void 0?{}:{signal:i}}}function TQ(n,t){let o=new Error(n);return o.name="UserQuestionError",o.code=t,o}function zEe(n,t){return!n||typeof n!="object"||n.sessionId!==t.sessionId||!n.answer||typeof n.answer!="object"||!Array.isArray(n.answer.answers)||n.answer.answers.length!==t.questions.length?!1:n.answer.answers.every((o,i)=>{let e=t.questions[i];if(!o||typeof o!="object"||o.id!==e.id||!Array.isArray(o.selected)||o.selected.some(r=>typeof r!="string")||new Set(o.selected).size!==o.selected.length||o.custom!==void 0&&typeof o.custom!="string")return!1;let a=o.custom?.trim();if(a!==void 0&&!a||e.multiSelect!==!0&&(a!==void 0&&o.selected.length>0||o.selected.length>1))return!1;let A=new Set(e.options?.map(r=>r.label)??[]);return o.selected.every(r=>A.has(r))})}function VEe(n){if(n?.type==="event"&&n.event&&typeof n.event=="object")return[{event:n.event}];let t=n?.type==="chunks"?n.event:null;if(!t||typeof t!="object")throw new Error("Harness returned an invalid session history record");let{data:o}=t,i=t.type,e=i==="chunkrow/tool-call-chunks"?o?.args:o?.texts;if(!o||!Array.isArray(e)||e.length===0||e.some(A=>typeof A!="string")||!Array.isArray(o.dt)||o.dt.length!==e.length-1)throw new Error("Harness returned an invalid packed session chunk");let a=t.time;return e.map((A,r)=>{r>0&&(a+=o.dt[r-1]);let s;if(i==="chunkrow/text-chunks")s={type:"text-delta",index:o.index,text:A};else if(i==="chunkrow/reasoning-chunks")s={type:"reasoning-delta",index:o.index,text:A};else if(i==="chunkrow/tool-call-chunks")s={type:"tool-call-delta",index:o.index,id:o.id,...Object.hasOwn(o,"name")?{name:o.name}:{},argumentsDelta:A};else throw new Error(`Harness returned an unsupported packed session chunk: ${String(i)}`);return{event:{type:"assistant/chunk",seq:t.seq+r,time:a,data:{turn:o.turn,step:o.step,chunk:s}}}})}function ZY(n){if(!Array.isArray(n))throw new Error("Harness returned invalid session history records");return n.flatMap(VEe)}var Q_=class{#e=[];#A=null;#t=!1;#r;#g;#a;constructor(t,o){this.#r=t,this.#a=o,this.#g=()=>this.close(),t?.addEventListener("abort",this.#g,{once:!0}),t?.aborted&&this.close()}push(t){if(!this.#t)if(this.#A){let o=this.#A;this.#A=null,o({value:t,done:!1})}else this.#e.push(t)}next(){return this.#e.length>0?Promise.resolve({value:this.#e.shift(),done:!1}):this.#t?Promise.resolve({value:void 0,done:!0}):new Promise(t=>{this.#A=t})}return(){return this.close(),Promise.resolve({value:void 0,done:!0})}close(){if(!this.#t&&(this.#t=!0,this.#r?.removeEventListener("abort",this.#g),this.#a?.(),this.#a=null,this.#A)){let t=this.#A;this.#A=null,t({value:void 0,done:!0})}}[Symbol.asyncIterator](){return this}},y_=class{#e;#A;#t=new Set;#r=new Map;#g=new Map;#a=new Map;#n=[];#i=!1;constructor(t,o,i){this.#e=o,this.#A=i,this.host=Object.freeze({describe:e=>dn(e,()=>({ready:!0,transport:"typert"}))}),this.workspace=Object.freeze({list:(e,a)=>dn(e,()=>this.#o(a)),create:(e,a)=>dn(e,()=>this.#I("workspace","create",{request:e.payload},a))}),this.sessions=Object.freeze({list:(e,a)=>dn(e,()=>this.#I("session","list",{_request:e.payload},a)),create:(e,a)=>dn(e,()=>this.#I("session","create",{request:e.payload},a)),history:(e,a)=>dn(e,()=>this.#c(e.payload,a)),prompt:(e,a)=>dn(e,()=>this.#I("session","prompt",{request:{requestId:e.rpcId,...e.payload}},a)),cancel:(e,a)=>dn(e,()=>this.#I("session","cancel",{request:{sessionId:e.payload.sessionId}},a)),models:(e,a)=>dn(e,()=>this.#h(e.payload.sessionId,a)),selectModel:(e,a)=>dn(e,()=>this.#I("session","selectModel",{request:e.payload},a))}),this.llm=Object.freeze({models:(e,a)=>dn(e,async()=>{let A=await this.#d(a);return{groups:A.groups,failures:A.failures}})}),this.events=Object.freeze({mux:(e,a)=>this.#E(a)}),this.respond=e=>Promise.resolve(this.#m(e)),typeof t?.on=="function"&&(this.#n.push(t.on("session/event",(e,a)=>{let A=e?.id;typeof A!="string"||!a||typeof a!="object"||(Number.isSafeInteger(a.seq)&&this.#p(A,a.seq),this.#C({type:"session/event",sessionId:A,event:a}))},{global:!0})),this.#n.push(t.on("approval/request",(e,a)=>this.#Q(e,a),{global:!0,prepend:!0})),this.#n.push(t.on("user-questions/request",(e,a)=>this.#y(e,a),{global:!0,prepend:!0})))}async#I(t,o,i,e){return this.#e.invoke(WY(t,o,i,e))}async#l(t,o,i,e){let a=new AbortController,A=e?AbortSignal.any([e,a.signal]):a.signal,r;try{r=(await this.#e.stream(WY(t,o,i,A)))[Symbol.asyncIterator]();let g=await r.next();if(g.done)throw new Error(`Harness ${t}.${o} stream ended before its baseline`);return g.value}finally{a.abort(new DOMException("Baseline received","AbortError")),await Promise.resolve(r?.return?.()).catch(()=>{})}}async#o(t){let o=await this.#l("workspace","follow",{},t);if(o?.type!=="baseline"||!o.value||typeof o.value!="object")throw new Error("Harness workspace.follow returned no baseline");return o.value}async#s(t,o,i){let e=await this.#l("session","follow",{request:{address:{kind:"session",sessionId:t},maxMessages:o}},i);if(e?.type!=="snapshot"||!Number.isSafeInteger(e.cursor))throw new Error("Harness session.follow returned no snapshot");return this.#p(t,e.cursor),e}async#c(t,o){let{sessionId:i,maxMessages:e=50,beforeSeq:a}=t,A=this.#a.get(i);if(A===void 0){let s=await this.#s(i,e,o);if(A=this.#a.get(i)??s.cursor,a===void 0&&A===s.cursor)return{events:ZY(s.records),hasMore:s.hasMore===!0,...s.projections===void 0?{}:{projections:s.projections}}}let r=await this.#I("session","page",{request:{address:{kind:"session",sessionId:i},throughSeq:A,maxMessages:e,...a===void 0?{}:{beforeSeq:a}}},o);return{events:ZY(r.records),hasMore:r.hasMore===!0}}#p(t,o){let i=this.#a.get(t);(i===void 0||o>i)&&this.#a.set(t,o)}#d(t){return this.#I("session","modelCatalog",{},t)}async#h(t,o){let[i,e]=await Promise.all([this.#d(o),this.#I("session","list",{_request:{}},o)]),a=e?.items?.find(s=>s?.sessionId===t);if(!a){let s=new Error(`session "${t}" not found`);throw s.failure={code:"session-not-found",message:s.message,details:{sessionId:t}},s}let A=a.projections?.values?.modelSelection,r=A?.next??A?.lastUsed??i.default;return{current:r,routable:i.routableProviders.includes(r.provider),groups:i.groups,failures:i.failures}}#E(t){let o;o=new Q_(t,()=>this.#t.delete(o)),this.#t.add(o);for(let i of this.#r.values())o.push(this.#B(i));for(let i of this.#g.values())o.push(this.#S(i));return o}#C(t,o=f_()){let i={rpcId:o,payload:t};for(let e of this.#t)e.push(i)}#f(t){let o=t?.session?.id??t?.id;return typeof o!="string"||!t?.session||!Array.isArray(t.session.events)?null:HY(this.#A,o,t.session.events)?{sessionId:o,session:t.session}:null}#B(t){return{rpcId:t.rpcId,payload:{type:"question/requested",sessionId:t.sessionId,questions:t.questions}}}#y(t,o){let i=this.#f(t?.agent);return i?t.signal?.aborted?Promise.reject(TQ("ask_user_question was aborted before the user answered","ASK_ABORTED")):new Promise((e,a)=>{let A={rpcId:f_(),sessionId:i.sessionId,questions:t.questions,signal:t.signal,settle:(s,g)=>{this.#r.delete(A.rpcId)&&(t.signal?.removeEventListener("abort",r),this.#C({type:"question/resolved",sessionId:A.sessionId,questionRpcId:A.rpcId,outcome:s}),s==="answered"?e(g):a(g))}},r=()=>A.settle("cancelled",TQ("ask_user_question was aborted before the user answered","ASK_ABORTED"));this.#r.set(A.rpcId,A),t.signal?.addEventListener("abort",r,{once:!0}),this.#C(this.#B(A).payload,A.rpcId)}):o()}#S(t){return{rpcId:t.rpcId,payload:{type:"approval/requested",sessionId:t.sessionId,approvalId:t.approvalId,toolName:t.toolName,...t.callId===void 0?{}:{callId:t.callId},...t.reason===void 0?{}:{reason:t.reason}}}}#Q(t,o){let i=this.#f(t?.agent);if(!i)return o();if(t.signal?.aborted)return Promise.resolve("cancelled");let e=new Set([...this.#g.values()].map(r=>r.approvalId)),a=new Set,A;for(let r=i.session.events.length-1;r>=0;r-=1){let s=i.session.events[r];if(s.type==="approval/decided")a.add(s.data?.id);else if(s.type==="approval/asked"){let g=s.data?.id;if(!g||a.has(g)||e.has(g)||(t.callId??null)!==(s.data?.callId??null))continue;A=g;break}}return A===void 0?o():new Promise(r=>{let s={rpcId:f_(),sessionId:i.sessionId,approvalId:A,toolName:t.toolName,callId:t.callId,reason:t.reason,settle:c=>{this.#g.delete(s.rpcId)&&(t.signal?.removeEventListener("abort",g),this.#C({type:"approval/resolved",sessionId:s.sessionId,approvalId:s.approvalId,outcome:c}),r(c))}},g=()=>s.settle("cancelled");this.#g.set(s.rpcId,s),t.signal?.addEventListener("abort",g,{once:!0}),this.#C(this.#S(s).payload,s.rpcId)})}#m(t){let o=this.#g.get(t?.rpcId);if(o){let a=t?.result?.value;return t?.result?.ok!==!0||!a||typeof a!="object"||a.sessionId!==o.sessionId||a.approvalId!==o.approvalId||a.outcome!=="allowed-once"&&a.outcome!=="rejected"?{accepted:!1,reason:"bad-response"}:(o.settle(a.outcome),{accepted:!0})}let i=this.#r.get(t?.rpcId);if(!i)return{accepted:!1,reason:"not-pending"};if(t?.result?.ok!==!0)return t?.result?.error?.code!=="cancelled"?{accepted:!1,reason:"bad-response"}:(i.settle("cancelled",TQ("the user cancelled ask_user_question","ASK_CANCELLED")),{accepted:!0});if(!zEe(t.result.value,i))return{accepted:!1,reason:"bad-response"};let e={answers:t.result.value.answer.answers.map(a=>({id:a.id,selected:[...a.selected],...a.custom===void 0?{}:{custom:a.custom}}))};return i.settle("answered",e),{accepted:!0}}dispose(){if(!this.#i){this.#i=!0;for(let t of[...this.#t])t.close();for(let t of[...this.#g.values()])t.settle("cancelled");for(let t of[...this.#r.values()])t.settle("cancelled",TQ("dsh-im interaction adapter was disposed","ASK_ABORTED"));for(let t of this.#n.splice(0).reverse())t?.()}}};function XY(n){let t=n?.root??n;if(!t||!["object","function"].includes(typeof t))throw new TypeError("dsh-im requires a Cordis Host context");let o=_Q.get(t);if(o)return o;let i=n?.typertGateway;if(!i||typeof i.invoke!="function"||typeof i.stream!="function")throw new TypeError("dsh-im requires the modern Host Typert gateway");let e=new y_(n,i,t);return _Q.set(t,e),typeof n.effect=="function"&&n.effect(()=>()=>{_Q.get(t)===e&&_Q.delete(t),e.dispose()},"dsh-im: modern Harness compatibility API"),e}function WEe(n,t){return n&&Object.hasOwn(n,t)?n[t]:typeof n?.get=="function"?n.get(t):void 0}function Aa(n,t={}){return t.harnessBaseUrl!==void 0?{baseUrl:new URL(t.harnessBaseUrl)}:{apiProxy:WEe(n,"apiProxy")??XY(n),interactionScope:n.root??n}}import{randomUUID as ZEe}from"node:crypto";function XEe(n){if(typeof n?.get!="function")return;let t;try{t=n.get("agents")}catch{return}if(t!=null){if(typeof t.get!="function")throw new TypeError('dsh-im requires a callable AgentRegistry when ctx.get("agents") is present');return t}}function $Ee(n,t,o){if(n?.status!=="running")return!1;let i=n?.session?.events;if(!Array.isArray(i))return!1;let e=null,a=!1;for(let A of i){if(A?.type==="turn/start"){e=A.data?.turn??null,a=!1;continue}if(A?.type==="turn/end"&&A.data?.turn===e){e=null,a=!1;continue}e===t&&A?.type==="user/message"&&A.data?.source?.rpcId===o&&(a=!0)}return e===t&&a}function $Y(n){if(!n||typeof n!="object"||Object.isFrozen(n))return n;for(let t of Object.values(n))$Y(t);return Object.freeze(n)}function eCe(n){return $Y({id:ZEe(),role:"user",content:[{type:"text",text:n}],source:{kind:"user"}})}function ACe(n){let t=new Error("Session is busy with an active turn or maintenance task",{cause:n});return t.code="agent-busy",t}function tCe(n){return({sessionId:t,expectedTurn:o,promptRpcId:i,action:e,text:a})=>{let A=n.get(t);if(A){if(!$Ee(A,o,i))return!1;if(e==="stop")return A.cancel({kind:"user"},{keepInbox:!0}),!0;if(e==="steer")return typeof a!="string"||!a.trim()?!1:(A.inject(eCe(a)),!0);throw new TypeError(`Unsupported Harness control action: ${String(e)}`)}}}function rCe(n){return({sessionId:t,operation:o})=>{if(typeof o!="function")throw new TypeError("maintenance operation is required");let i=n.get(t);if(!i)return o();try{return i.runMaintenance(e=>{if(n.get(t)!==i){let a=new Error("Session agent changed before maintenance started");throw a.code="agent-unavailable",a}return o(e)})}catch(e){throw ACe(e)}}}function aCe(n){return({sessionId:t,workspace:o,files:i,signal:e})=>{let A=n.get(t)?.session?.header?.cwd,r=typeof A=="string"&&A?A:o;if(typeof r!="string"||!r)throw new Do("inbound-file-workspace-unavailable","The Harness Session workspace is unavailable for inbound files.");return IY({files:i},{workspace:r,signal:e})}}function Ha(n,t={}){let{controlExecutor:o,sessionMaintenanceExecutor:i,fileIngressExecutor:e}=t;if(o!==void 0&&typeof o!="function")throw new TypeError("controlExecutor must be a function");if(i!==void 0&&typeof i!="function")throw new TypeError("sessionMaintenanceExecutor must be a function");if(e!==void 0&&typeof e!="function")throw new TypeError("fileIngressExecutor must be a function");let a=o&&i&&e?void 0:XEe(n);return{controlExecutor:o??(a?tCe(a):void 0),sessionMaintenanceExecutor:i??(a?rCe(a):void 0),fileIngressExecutor:e??aCe(a??{get:()=>{}})}}function nCe(n){let t=bI(n.dshHome??process.env.DSH_HOME??UE(oCe(),".dsh")),o=bI(n.dataDir??UE(t,"integrations","dsh-dingtalk"));return{root:o,config:bI(n.configPath??UE(o,"config.json")),bots:bI(n.botsDir??UE(o,"bots")),workspaces:bI(n.workspacesPath??UE(o,"workspaces.json"))}}async function m_(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-dingtalk requires ctx.credentials");let i=Aa(n,t),e=o.ConfigStore??rQ,a=o.DeviceAuth??iQ,A=o.StateStore??SQ,r=o.HarnessClient??yQ,s=o.Controller??wE,g=o.Runtime??kE,c=o.createConnectionSupervisor??B_,I=typeof n.logger=="function"?n.logger("dsh-dingtalk"):n.logger??console,d=()=>Ra(n),B=nCe(t),f=await new e(B.config).load(),Q=bI(t.workspace??process.cwd()),y=o.WorkspaceStore??ea,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=typeof f.list=="function",T=_?f.list():[];_&&await m.reconcile(T.map(Ae=>Ae.botId)),await Promise.all(T.map(Ae=>m.ensure(Ae.botId,{defaultAgentPreset:t.agentPreset})));let R=typeof f.remove=="function"?Pa(f,{workspaces:m}):f,L=o.deviceAuth??new a({baseUrl:t.registrationBaseUrl}),U=new Map,F=Ae=>bI(B.bots,Ae,"state.json"),q=async Ae=>{let ie=U.get(Ae);return ie||(ie=await new A(F(Ae)).load(),U.set(Ae,ie)),ie},z=Ua(n,o.commandExecutor),{controlExecutor:j,sessionMaintenanceExecutor:P,fileIngressExecutor:J}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),H=new r({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...z?{commandExecutor:z}:{},...j?{controlExecutor:j}:{},...P?{sessionMaintenanceExecutor:P}:{},...J?{fileIngressExecutor:J}:{}}),N=new s({deviceAuth:L,credentials:n.credentials,configStore:R,logger:I,createRuntime:async({botId:Ae,config:ie,clientSecret:De})=>{let fe=await q(Ae);await m.ensure(Ae,{defaultAgentPreset:t.agentPreset});let _e=Ga(H,{botId:Ae,workspaces:m,state:fe,agentPresetCatalog:d});return new g({config:ie,clientSecret:De,harness:_e.harness,state:_e.state,contextEnhancement:{botId:Ae,getSettings:()=>m.contextEnhancementFor(Ae)},replyTimeoutMs:t.replyTimeoutMs??6e5,maxMessageChars:t.maxMessageChars??4e3,connectTimeoutMs:t.connectTimeoutMs??15e3,logger:{error:(...Ee)=>I.error?.(`[${Ae}]`,...Ee),warn:(...Ee)=>I.warn?.(`[${Ae}]`,...Ee),info:(...Ee)=>I.info?.(`[${Ae}]`,...Ee),debug:(...Ee)=>I.debug?.(`[${Ae}]`,...Ee)}})},deleteState:async({botId:Ae})=>{let ie=U.get(Ae);if(U.delete(Ae),ie&&typeof ie.remove=="function")await ie.remove();else try{await iCe(F(Ae))}catch(De){if(De?.code!=="ENOENT")throw De}}}),k=Fa(N,{workspaces:m,stateFor:q,agentPresetCatalog:d}),V=c({controller:k,harness:H,logger:I,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:k,deliveryAdapter:La({channel:"dingtalk",workspaces:m,coreController:N,stateFor:q}),ready:V.ready,async close(){await V.close(),await k.close(),H.stopManagedProcess()}}}import ICe from"qrcode";var wi="bot.context-enhancement.set";function Ka(n){try{return!n||typeof n!="object"||Array.isArray(n)||Reflect.ownKeys(n).length!==2||!Object.hasOwn(n,"botId")||!Object.hasOwn(n,"config")||typeof n.botId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)?!1:(mp(n.config),!0)}catch{return!1}}var sCe=new Set(["loopback","trusted-host"]);function hr(n){if(n===void 0)return"loopback";if(sCe.has(n))return n;throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"')}import{isAbsolute as gCe}from"node:path";var Di="bot.workspace.set";function xa(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).every(t=>["botId","workspace"].includes(t))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&typeof n.workspace=="string"&&n.workspace.length<=4096&&gCe(n.workspace.trim())}function Ya(n){return["workspace-not-absolute","workspace-not-found","workspace-not-directory","workspace-bot-not-found","agent-preset-invalid","agent-preset-unavailable","context-enhancement-invalid"].includes(n?.code)?{code:n.code,message:n.message}:null}var Oi="bot.preset.set";function cCe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ja(n){return cCe(n)&&Object.keys(n).every(t=>["botId","agentPreset"].includes(t))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&(n.agentPreset===null||typeof n.agentPreset=="string"&&WM.test(n.agentPreset))}var A1="/dingtalk",Kt=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi,approveSender:"bot.sender.approve",revokeSender:"bot.sender.revoke"}),t1=Object.freeze(Object.values(Kt)),lCe=new Set(["clientSecret","client_secret","deviceCode","device_code","secretRef","staffId","senderStaffId","verificationUrl","verificationUri","userCode"]);function w_(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function oc(n,t){return w_(n)&&Object.keys(n).every(o=>t.includes(o))}function MI(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function e1(n,t){return typeof n=="string"&&n.trim().length>0&&n.length<=t}function pCe(n,t){return w_(t)?n===Kt.status?oc(t,[])?null:"connection.status does not accept fields.":n===Kt.beginProvisioning?oc(t,["locale"])&&(t.locale===void 0||t.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Kt.pollProvisioning,Kt.cancelProvisioning].includes(n)?oc(t,["attemptId"])&&MI(t.attemptId)?null:`${n} requires an attemptId.`:n===Kt.bindCredentials?oc(t,["clientId","clientSecret"])&&e1(t.clientId,256)&&e1(t.clientSecret,1024)?null:"bot.bind-credentials requires Client ID and Client Secret.":n===Kt.reconnectBot?oc(t,["botId","sendTest"])&&MI(t.botId)&&(t.sendTest===void 0||t.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Kt.deleteBot?oc(t,["botId","confirm"])&&MI(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Kt.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Kt.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===Kt.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":n===Kt.approveSender?oc(t,["botId","requestId","confirm"])&&MI(t.botId)&&MI(t.requestId)&&t.confirm===!0?null:"bot.sender.approve requires botId, requestId, and confirm=true.":n===Kt.revokeSender?oc(t,["botId","senderKey","confirm"])&&MI(t.botId)&&MI(t.senderKey)&&t.confirm===!0?null:"bot.sender.revoke requires botId, senderKey, and confirm=true.":"Unknown DingTalk endpoint.":"Payload must be an object."}function NQ(n){return{ok:!1,error:{code:"bad-request",message:n}}}function HE(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function dCe(){return{ok:!1,error:{code:"dingtalk-operation-failed",message:"\u9489\u9489\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}function Tp(n){if(Array.isArray(n))return n.map(Tp);if(!w_(n))return n;let t={};for(let[o,i]of Object.entries(n))lCe.has(o)||(t[o]=Tp(i));return t}async function hCe(n){return ICe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function S_(n,t){return!n||typeof n.verificationUrl!="string"?Tp(n):Tp({...n,qrCodeDataUrl:await t(n.verificationUrl)})}async function ig(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await S_(o.provisioning,t)),Tp(o)}function ECe(n){for(let t of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot","approveSender","revokeSender"])if(typeof n?.[t]!="function")throw new TypeError(`A complete DingTalk controller is required (${t})`)}function r1(n,{encodeQr:t=hCe}={}){ECe(n);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return HE();if(!t1.includes(e))return NQ("Unknown DingTalk endpoint.");let r=pCe(e,a);if(r)return NQ(r);try{let s;if(e===Kt.status)s=await ig(await n.status(),i);else if(e===Kt.beginProvisioning){let g=await n.startProvisioning({signal:A});if(A?.aborted)return await n.cancelProvisioning(g.attemptId),HE();s=await S_(g,i)}else if(e===Kt.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return NQ("The provisioning attempt no longer exists.");s=await S_(g,i)}else if(e===Kt.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return NQ("The provisioning attempt no longer exists.");s=Tp(s)}else if(e===Kt.bindCredentials)s=await ig(await n.bindCredentials(a),i);else if(e===Kt.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return HE();let c;if(a.sendTest===!0)if(!g?.bots?.some(d=>d?.botId===a.botId&&d?.connected===!0)||typeof n.sendConnectionTest!="function")c=ir(Ir("\u9489\u9489\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=ir()}catch(d){c=ir(d)}s=await ig({...g,...c?{testMessage:c}:{}},i)}else if(e===Kt.deleteBot)s=await ig(await n.deleteBot(a.botId),i);else if(e===Kt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await ig(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===Kt.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>ig(g,i))}else if(e===Kt.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await ig(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else e===Kt.approveSender?s=await ig(await n.approveSender(a.botId,a.requestId),i):s=await ig(await n.revokeSender(a.botId,a.senderKey),i);return A?.aborted?HE():{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?HE():g?{ok:!1,error:g}:dCe()}}}function RQ(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(A1,r1(t,o),{authority:hr(i)})}async function a1(n,t={}){if(t?.controller)return RQ(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await m_(n,t,t.internals),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=RQ(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-dingtalk: close bot connections"),e}import{createHash as CCe}from"node:crypto";import{mkdir as uCe,readFile as BCe,rename as fCe,unlink as QCe,writeFile as yCe}from"node:fs/promises";import{dirname as mCe}from"node:path";var D_=Object.freeze({version:1,bots:Object.freeze([])});function og(n){return typeof n=="string"&&n.trim()?n.trim():null}function i1(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function KE(n,{botPrefix:t,tokenRefPrefix:o}){let i=og(n);if(!i)throw new TypeError("platformId is required");let e=CCe("sha256").update(i).digest("hex").slice(0,24);return{botId:`${t}_${e}`,tokenRef:`${o}_${e.toUpperCase()}`}}function kQ(n,t){let o=og(n)??"";return o.length<=10?o?`${o.slice(0,3)}\u2022\u2022\u2022`:t:`${o.slice(0,6)}\u2022\u2022\u2022\u2022${o.slice(-4)}`}var Np=class{#e;#A;#t;#r;#g;#a;#n;#i=D_;#I=Promise.resolve();constructor(t,{channel:o,botPrefix:i,tokenRefPrefix:e,normalizeBotExtension:a=()=>({})}){if(typeof a!="function")throw new TypeError("normalizeBotExtension must be a function");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=new RegExp(`^${i1(i)}_[a-f0-9]{24}$`),this.#n=new RegExp(`^${i1(e)}_[A-F0-9]{24}$`)}async load(){try{let t=this.#o(JSON.parse(await BCe(this.#e,"utf8")));if(!t)throw new Error(`dsh-im ${this.#A} config contains invalid bot data`);this.#i=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#i=D_}return this}list(){return structuredClone(this.#i.bots)}get(t){let o=this.#i.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByPlatformId(t){let o=this.#i.bots.find(i=>i.platformId===t);return o?structuredClone(o):null}async save(t){let o=this.#l(t);if(!o)throw new Error(`Refusing to persist incomplete ${this.#A} bot data`);return this.#s(i=>{let e=i.find(r=>r.platformId===o.platformId&&r.botId!==o.botId),a=i.find(r=>r.tokenRef===o.tokenRef&&r.botId!==o.botId);if(e||a)throw new Error(`Duplicate ${this.#A} bot identity`);let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!this.#a.test(t))throw new TypeError(`Invalid ${this.#A} bot id`);return this.#s(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#I.then(async()=>{try{await QCe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#i=D_});this.#I=t.then(()=>{},()=>{}),await t}#l(t){if(!t||typeof t!="object")return null;let o=og(t.platformId),i=og(t.botId),e=og(t.tokenRef),a=og(t.name);if(!o||!i||!e||!a||!this.#a.test(i)||!this.#n.test(e))return null;let A=KE(o,{botPrefix:this.#t,tokenRefPrefix:this.#r});if(A.botId!==i||A.tokenRef!==e)return null;let r=this.#g(t);return!r||typeof r!="object"||Array.isArray(r)?null:Object.freeze({botId:i,platformId:o,tokenRef:e,name:a,username:og(t.username),createdAt:og(t.createdAt)??new Date().toISOString(),connectedAt:og(t.connectedAt),...r})}#o(t){if(!t||t.version!==1||!Array.isArray(t.bots))return null;let o=t.bots.map(A=>this.#l(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||a.has(A.tokenRef))return null;i.add(A.botId),e.add(A.platformId),a.add(A.tokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#s(t){let o,i=this.#I.then(async()=>{let e=[...this.#i.bots];o=t(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#c(a),this.#i=a});return this.#I=i.then(()=>{},()=>{}),await i,o}async#c(t){await uCe(mCe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await yCe(o,`${JSON.stringify(t,null,2)} `,{encoding:"utf8",mode:384}),await fCe(o,this.#e)}};var o1=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function n1(n){return KE(n,o1)}function s1(n){return kQ(n,w("Discord\u673A\u5668\u4EBA"))}var vQ=class extends Np{constructor(t){super(t,{channel:"Discord",...o1})}};function xE(n){return typeof n=="string"&&n.trim()?n.trim():null}function YE(n,t){return Object.freeze({code:n,message:t})}var Rp=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l=new Map;#o=new Map;#s=new Map;#c=0;#p=!1;constructor({descriptor:t,credentials:o,configStore:i,inspectToken:e,deriveIdentity:a,maskPlatformId:A,createRuntime:r,deleteState:s=async()=>{},logger:g=console}){if(!t?.key||!t?.label||!t?.connectionLabel)throw new TypeError("TokenBotController requires a channel descriptor");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError(`${t.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${t.label} requires a config store`);if(typeof e!="function"||typeof a!="function"||typeof A!="function"||typeof r!="function")throw new TypeError(`${t.label} controller dependencies are incomplete`);this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g}async initialize(){if(this.#p)return this.status();for(let t of this.#t.list())await this.#f(t.botId,async()=>{if(this.#p||this.#l.get(t.botId)?.status?.ready)return;let o=await this.#E(t.tokenRef);if(!o){this.#o.set(t.botId,YE("missing-token",w("{label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002",{label:this.#e.label})));return}try{await this.#d(t,o),this.#o.delete(t.botId)}catch(i){this.#o.set(t.botId,YE("connection-failed",w("{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002",{label:this.#e.label}))),this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${t.botId} failed to initialize:`,i)}finally{this.#B()}});return this.status()}async bindCredentials({token:t}={}){if(this.#p)throw new Error(`${this.#e.label} controller is closed`);let o=xE(t);if(!o)throw new TypeError(`${this.#e.label} Bot Token is required`);let i=await this.#r(o),e=xE(i?.platformId),a=xE(i?.name);if(!e||!a)throw new Error(`${this.#e.label} returned an invalid bot identity`);let A=this.#g(e);return await this.#f(A.botId,async()=>{if(this.#p)throw new Error(`${this.#e.label} controller is closed`);let r=this.#t.getByPlatformId(e),s=await this.#A.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:a,username:xE(i.username),createdAt:r?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(A.tokenRef,o);try{await this.#t.save(g)}catch(c){throw await this.#C(A.tokenRef,s),c}try{await this.#d(g,o),this.#o.delete(A.botId)}catch(c){this.#o.set(A.botId,YE("connection-failed",w("{label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002",{label:this.#e.label}))),this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${A.botId} credential connection failed:`,c)}this.#B()}),this.status()}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#f(t,async()=>{let i=await this.#E(o.tokenRef);if(!i)throw new Error(`${this.#e.label} bot token is missing`);try{await this.#d(o,i),this.#o.delete(t)}catch(e){throw this.#o.set(t,YE("connection-failed",w("{label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{label:this.#e.label}))),e}finally{this.#B()}}),this.status()}async updateBotConfig(t,o){if(this.#p)throw new Error(`${this.#e.label} controller is closed`);if(typeof o!="function")throw new TypeError("Bot config update must be a function");return await this.#f(t,async()=>{if(this.#p)throw new Error(`${this.#e.label} controller is closed`);let i=this.#t.get(t);if(!i)throw new Error(`Unknown ${this.#e.label} bot`);let e=await this.#E(i.tokenRef);if(!e)throw new Error(`${this.#e.label} bot token is missing`);if(this.#p)throw new Error(`${this.#e.label} controller is closed`);let a=o(i),A=await this.#t.save(a);try{await this.#d(A,e),this.#o.delete(t)}catch(r){throw this.#o.set(t,YE("connection-failed",w("{label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{label:this.#e.label}))),r}finally{this.#B()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return this.#f(t,async()=>{let i=this.#l.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let a=new Error(w("{label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5",{label:this.#e.label}));throw a.code="test-target-unavailable",a}let e=w("{name}\uFF08{id}\uFF09",{name:o.name,id:this.#a(o.platformId)});return await i.sendConnectionTest(ba(e,w("{label}\u673A\u5668\u4EBA",{label:this.#e.label}))),{sent:!0}})}async sendProactiveText(t,o,i,e={}){if(!this.#t.get(t))throw new Error(`Unknown ${this.#e.label} bot`);return this.#f(t,async()=>{let A=this.#l.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("{label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5",{label:this.#e.label}));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#f(t,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#h(t);try{await this.#A.unset(o.tokenRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#d(o,i.value).catch(()=>{})),new Error(`Unable to remove the ${this.#e.label} bot safely.`,{cause:e})}await this.#i({botId:t,config:o}).catch(e=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${t} state cleanup failed:`,e)}),this.#o.delete(t),this.#B()}),this.status()}status(){let t=this.#t.list().map(i=>{let e=this.#l.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#o.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:a,configured:!0,bot:{name:i.name,username:i.username,idMasked:this.#a(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?w("{label}{connectionLabel}\u8FD0\u884C\u6B63\u5E38",{label:this.#e.label,connectionLabel:w(this.#e.connectionLabel)}):A==="error"?w("{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5",{label:this.#e.label}):w("{label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",{label:this.#e.label}),lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},lastMessageError:Vr(e?.lastMessageError),error:structuredClone(this.#o.get(i.botId)??null)}}),o=t.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#c,state:t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o}}}async close(){this.#p||(this.#p=!0,await Promise.allSettled([...this.#s.values()]),await Promise.allSettled([...this.#l.keys()].map(t=>this.#h(t))))}async#d(t,o){if(this.#p)throw new Error(`${this.#e.label} controller is closed`);if(await this.#h(t.botId),this.#p)throw new Error(`${this.#e.label} controller is closed`);let i=await this.#n({botId:t.botId,config:t,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#e.label} runtime`);this.#l.set(t.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#l.delete(t.botId),e}}async#h(t){let o=this.#l.get(t);this.#l.delete(t),await o?.stop().catch(i=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${t} failed to stop cleanly:`,i)})}async#E(t){let o=await this.#A.resolve(t).catch(()=>{});return xE(o?.value)}async#C(t,o){o?.value?await this.#A.set(t,o.value).catch(()=>{}):await this.#A.unset(t).catch(()=>{})}#f(t,o){let a=(this.#s.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#s.get(t)===a&&this.#s.delete(t)});return this.#s.set(t,a),a}#B(){this.#c+=1}};import{createHash as SCe}from"node:crypto";var wCe="https://discord.com/api/v10/",DCe=12e4,OCe=new Set([50001,50013]),bCe=new Set([40005]);function Xn(n){return typeof n=="string"&&n.trim()?n.trim():null}function g1(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}function O_(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function MCe(n,t){if(!Number.isInteger(n)||n<1)throw new TypeError(`${t} must be a positive integer`);return n}function I1(n,t){return t?.providerCode!==void 0&&(n.providerCode=t.providerCode),t?.retry_after!==void 0&&(n.retry_after=t.retry_after,n.retryAfter=t.retry_after),Number.isInteger(t?.status)&&(n.status=t.status),n}function _Ce(n){let t=Number(n?.providerCode),o=Number(n?.status),i=Xn(n?.message)??"",e="artifact-provider-rejected",a="Discord rejected the attachment.";o===401||o===403||OCe.has(t)?(e="artifact-permission-required",a="Discord denied permission to send the attachment."):o===413||bCe.has(t)||/(?:request|attachment|file).{0,24}too large/i.test(i)?(e="artifact-too-large",a="The attachment exceeds Discord's size limit."):o===429?(e="artifact-rate-limited",a="Discord rate-limited attachment delivery."):o>=500&&(e="artifact-delivery-uncertain",a="Discord attachment delivery result is uncertain.");let A=new Error(a,{cause:n});return A.code=e,I1(A,n)}function TCe(n){let t=new Error("Discord attachment delivery result is uncertain",{cause:n});return t.code="artifact-delivery-uncertain",I1(t,n)}function NCe(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),t?.addEventListener("abort",()=>{clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function Ja(n,t){let o=Xn(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${t}`);return o}function c1(n){let t=Xn(n);if(!t)throw new TypeError("A Discord reaction emoji is required");return t}function RCe(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var jE=class{#e;#A;#t;#r;constructor({token:t,fetchImpl:o=fetch,baseUrl:i=wCe,fileUploadTimeoutMs:e=DCe}){if(!RCe(t))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#e=t.trim(),this.#A=o,this.#t=new URL(i),this.#r=MCe(e,"fileUploadTimeoutMs")}getCurrentUser(t={}){return this.#g("users/@me",{...t,method:"GET"})}getGatewayBot(t={}){return this.#g("gateway/bot",{...t,method:"GET"})}getChannel({channelId:t,signal:o}={}){return this.#g(`channels/${Ja(t,"channel id")}`,{method:"GET",signal:o})}startThreadFromMessage({channelId:t,messageId:o,name:i,signal:e}={}){let a=Xn(i);if(!a||[...a].length>100)throw new TypeError("Discord thread name must contain 1-100 characters");if(e?.aborted)throw O_(e);return this.#g(`channels/${Ja(t,"channel id")}/messages/${Ja(o,"message id")}/threads`,{method:"POST",signal:e,body:{name:a}})}createMessage({channelId:t,content:o,replyToMessageId:i,signal:e}){return this.#g(`channels/${Ja(t,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:Ja(i,"message id"),channel_id:Ja(t,"channel id"),fail_if_not_exists:!1}}:{}}})}async createFileMessage({channelId:t,file:o,replyToMessageId:i,signal:e}){if(!o||typeof o!="object"||typeof o.fileName!="string"||!o.fileName||!Buffer.isBuffer(o.bytes))throw new TypeError("A Discord attachment is required");let a=Xn(o.deliveryKey)??Xn(o.artifactId),A=a?SCe("sha256").update(a).digest("hex").slice(0,25):void 0,r=new FormData;r.append("payload_json",JSON.stringify({allowed_mentions:{parse:[],replied_user:!1},attachments:[{id:0,filename:o.fileName}],...A?{nonce:A,enforce_nonce:!0}:{},...i?{message_reference:{message_id:Ja(i,"message id"),channel_id:Ja(t,"channel id"),fail_if_not_exists:!1}}:{}})),r.append("files[0]",new Blob([o.bytes],{type:o.mediaType??"application/octet-stream"}),o.fileName);let s=Ja(t,"channel id");if(e?.aborted)throw O_(e);let g=g1(e,this.#r);try{return await this.#g(`channels/${s}/messages`,{method:"POST",signal:g,timeoutMs:this.#r,body:r,multipart:!0})}catch(c){throw e?.aborted?O_(e):c?.code?.startsWith?.("discord-")?_Ce(c):TCe(c)}}editMessage({channelId:t,messageId:o,content:i,signal:e}){return this.#g(`channels/${Ja(t,"channel id")}/messages/${Ja(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:t,signal:o}){return this.#g(`channels/${Ja(t,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async addOwnReaction({channelId:t,messageId:o,emoji:i,signal:e}={}){let a=c1(i);return await this.#g(`channels/${Ja(t,"channel id")}/messages/${Ja(o,"message id")}/reactions/${encodeURIComponent(a)}/@me`,{method:"PUT",signal:e,expectBody:!1,retry:!1}),a}removeOwnReaction({channelId:t,messageId:o,emoji:i,signal:e}={}){let a=c1(i);return this.#g(`channels/${Ja(t,"channel id")}/messages/${Ja(o,"message id")}/reactions/${encodeURIComponent(a)}/@me`,{method:"DELETE",signal:e,expectBody:!1,retry:!1})}async#g(t,{method:o,body:i,signal:e,timeoutMs:a=15e3,expectBody:A=!0,retry:r=!0,multipart:s=!1}){let g;try{g=await this.#A(new URL(t,this.#t),{method:o,headers:{authorization:`Bot ${this.#e}`,...s?{}:{"content-type":"application/json"},"user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 1.1.0)"},...i===void 0?{}:{body:s?i:JSON.stringify(i)},signal:g1(e,a),redirect:"error"})}catch(I){throw I?.name==="AbortError"||I?.name==="TimeoutError"?I:new Error(`Discord ${o} transport failed`)}let c=null;if(A||g.status===429||!g.ok)try{c=await g.json()}catch{if(A){let I=new Error(`Discord ${o} returned invalid JSON`);throw I.status=g?.status,I}}if(g.status===429&&r){let I=Math.min(1e4,Math.max(50,Number(c?.retry_after)*1e3||1e3));return await NCe(I,e),this.#g(t,{method:o,body:i,signal:e,timeoutMs:a,expectBody:A,retry:!1,multipart:s})}if(!g.ok){let I=new Error(Xn(c?.message)??`Discord API failed with HTTP ${g.status}`);I.code=`discord-${g.status}`,I.status=g.status,(Number.isInteger(c?.code)||typeof c?.code=="string")&&(I.providerCode=c.code);let d=Number(c?.retry_after);throw Number.isFinite(d)&&d>=0&&(I.retry_after=d,I.retryAfter=d),I}return A?c:null}};async function l1(n,t={}){let i=await new jE({token:n,...t}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:Xn(i.global_name)??Xn(i.username)??w("Discord\u673A\u5668\u4EBA"),username:Xn(i.username)}}var kCe=Object.freeze({success(){},error(){},clear(){},settled:()=>Promise.resolve()});function p1(n,t){!n||typeof n!="object"||(n[t]=(n[t]??0)+1)}async function vCe(n,t){let o=AbortSignal.timeout(t),i,e=new Promise((a,A)=>{i=()=>A(o.reason??new DOMException("Timed out","TimeoutError")),o.addEventListener("abort",i,{once:!0})});try{return await Promise.race([n(o),e])}finally{o.removeEventListener("abort",i)}}function PQ({adapter:n,target:t,reactions:o,status:i,logger:e=console,label:a="channel",timeoutMs:A=2e3}={}){if(!t||typeof n?.addReaction!="function"||typeof n?.removeReaction!="function"||typeof o?.processing!="string"||!o.processing||!Number.isSafeInteger(A)||A<=0)return kCe;let r=null,s=!1,g=async(B,f)=>{try{let Q=await vCe(f,A);return p1(i,B==="add"?"reactionsAdded":"reactionsRemoved"),{ok:!0,value:Q}}catch(Q){return p1(i,"reactionErrors"),e.warn?.(`[dsh-im:${a}] status reaction ${B} failed:`,Q?.message??Q?.name??String(Q)),{ok:!1,value:null}}},c=async B=>{if(r!==null){let Q=r;r=null,await g("remove",y=>n.removeReaction(t,Q,{signal:y}))}if(typeof B!="string"||!B)return;let f=await g("add",Q=>n.addReaction(t,B,{signal:Q}));f.ok&&f.value!==void 0&&f.value!==null&&(r=f.value)},I=c(o.processing),d=B=>{s||(s=!0,I=I.then(()=>c(B),()=>c(B)),I.catch(()=>{}))};return Object.freeze({success:()=>d(o.success),error:()=>d(o.error),clear:()=>d(null),settled:()=>I})}var d1="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",PCe="\u4EFB\u52A1\u5DF2\u5B8C\u6210\u3002";function bi(n){return typeof n=="string"?n.trim():""}function GCe(n,t,o){return t.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!Wt(n)&&!Lt(n)&&!!bi(n.content)}function FCe(n,t,o){let i=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim().slice(0,255)||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u7684\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:i});case"artifact-permission-required":return o?.key==="slack"?w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 Slack \u5E94\u7528\u7F3A\u5C11 files:write \u6743\u9650\u3002\u8BF7\u66F4\u65B0 Manifest\u3001\u91CD\u65B0\u5B89\u88C5\u5E94\u7528\u5E76\u91CD\u65B0\u8FDE\u63A5\u673A\u5668\u4EBA\u540E\u91CD\u8BD5\u3002",{name:i}):o?.key==="discord"?w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11 Discord \u7684 Send Messages\u3001Attach Files \u6216 Read Message History \u6743\u9650\u3002",{name:i}):o?.key==="telegram"?w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 Telegram \u4E0D\u5141\u8BB8\u673A\u5668\u4EBA\u5728\u5F53\u524D\u804A\u5929\u53D1\u9001\u6587\u6863\uFF0C\u8BF7\u68C0\u67E5\u804A\u5929\u6743\u9650\u3002",{name:i}):w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u673A\u5668\u4EBA\u6CA1\u6709\u6587\u4EF6\u53D1\u9001\u6743\u9650\uFF0C\u8BF7\u68C0\u67E5\u6E20\u9053\u6743\u9650\u3002",{name:i});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u6E20\u9053\u5927\u5C0F\u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002",{name:i});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u672A\u53D1\u9001\u3002",{name:i});case"artifact-invalid":case"artifact-changed":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:i});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u5F53\u524D\u6E20\u9053\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:i});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002",{name:i});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:i})}}function Xi(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0}}var $n=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l=new Map;#o=new Map;#s=new Map;#c=new Map;#p=new Set;#d=new Set;#h;#E=new mi;constructor({descriptor:t,bot:o,harness:i,state:e,contextEnhancement:a,status:A=Xi(),logger:r=console,replyTimeoutMs:s=6e5,signal:g}){if(!t?.key||!t?.label)throw new TypeError("A channel descriptor is required");if(!o||typeof o.sendText!="function")throw new TypeError("A bot client is required");if(!i||!e)throw new TypeError("Harness client and state store are required");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#h=new Ci({label:t.key,logger:r})}get status(){return structuredClone(this.#a)}accept(t,{contextSnapshot:o}={}){if(this.#I?.aborted)return Promise.resolve();let i=bi(t?.conversationId),e=t?.kind==="group"?"group":"direct",a={...t,kind:e,conversationId:i},A=bi(a.messageId),r=bi(a.senderId);if(!A||!r||!i||a.senderIsBot===!0||this.#r.hasSeen(A)||this.#c.has(A))return Promise.resolve();this.#c.set(A,o===void 0?Xr(this.#g,t?.kind):o);let s=PQ({adapter:this.#A,target:a.kind==="direct"||a.addressed===!0?a.reactionTarget:null,reactions:this.#e.reactions,status:this.#a,logger:this.#n,label:this.#e.key});a.statusReaction=s;let g=this.#C(a,A,r);return g.then(()=>s.success(),()=>s.error()),g}#C(t,o,i){t.kind==="direct"&&Eo(this.#r,t.connectionTestTarget??t.replyTarget);let e=`${t.kind}:${t.conversationId}`,a=this.#o.get(e),A=bi(t.content),r=So(A);if(r&&t.kind==="group"&&t.addressed===!0)return this.#f(t,o,qn());if(r&&t.kind==="direct"){if(/^\/batch$/iu.test(A)&&(this.#l.has(e)||a||this.#h.hasPending(e)))return this.#f(t,o,wo());let d=this.#E.handle(e,A,{plainText:!!A&&t.plainText!==!1&&!Wt(t)&&!Lt(t)});if(d.handled)return d.kind==="submit"?this.#B({...t,content:d.prompt,batchSubmission:{token:d.token}},o,i,e):this.#f(t,o,d.message)}else if(t.kind==="direct"&&this.#E.status(e).phase==="collecting"){let I=this.#E.handle(e,A,{plainText:!!A&&t.plainText!==!1&&!Wt(t)&&!Lt(t)});if(I.handled)return this.#f(t,o,I.message)}let g=t.kind==="direct"&&this.#E.status(e).phase==="collecting"?null:fi(A)?qi:Lt(t)?null:zi(A)?Qi:Vi(A)?Wi:Zi(A)?yi:null;if(g&&(t.kind!=="group"||t.addressed===!0)){let I;return I=this.#y(t,o,e,g).finally(()=>{this.#c.delete(o),this.#d.delete(I)}),this.#d.add(I),I}let c=this.#h.claimReply({key:e,actor:i,messageId:o,text:Wt(t)||Lt(t)?"":t.content,addressed:t.kind!=="group"||t.addressed===!0,hasPendingQuestion:!!a,questionCompletion:a?.submitting||a?.claimedReplyMessageId?a.queue:null,isQuestionPending:()=>this.#o.has(e),send:I=>this.#A.sendText(t.replyTarget,I)});if(c){let I;return I=c.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#c.delete(o),this.#p.delete(I)}),this.#p.add(I),I}if(a&&a.actor!==i)return this.#B(t,o,i,e);if(a?.submitting||a?.claimedReplyMessageId)return this.#B(t,o,i,e);if(a){GCe(t,a,i)&&(a.claimedReplyMessageId=o);let d=(a.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#m(t,o,i,e,a)).finally(()=>{this.#c.delete(o),a.claimedReplyMessageId===o&&(a.claimedReplyMessageId=null),a.queue===d&&(a.queue=null)});return a.queue=d,d}return this.#B(t,o,i,e)}#f(t,o,i){let e;return e=(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),i&&await this.#A.sendText(t.replyTarget,i),this.#a.lastError=null)})().catch(async a=>{if(this.#I?.aborted){t.statusReaction?.clear();return}t.statusReaction?.error(),this.#a.lastError=a?.message??String(a);let A=tt(this.#a,a);this.#n.error?.(`[dsh-im:${this.#e.key}] failed to process a batch input message [${A.referenceId}]:`,a)}).finally(()=>{this.#c.delete(o),this.#d.delete(e)}),this.#d.add(e),e}#B(t,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1}={}){let s=(this.#l.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(t,o,i,e,{alreadyRecorded:A})).finally(()=>{a&&this.#c.delete(o),this.#l.get(e)===s&&this.#l.delete(e)});return this.#l.set(e,s),s}async waitForIdle(){await Promise.allSettled([...this.#l.values(),...[...this.#o.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#p,...this.#d])}async#y(t,o,i,e){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString();let a=t.replyTarget;try{let A=await e(bi(t.content),this.#t,this.#r,i,{signal:this.#I,isDirect:t.kind==="direct",hasImages:Wt(t),hasFiles:Lt(t),pendingInteraction:this.#o.has(i)||this.#h.hasPending(i),control:{owner:this,key:i}});A?.stopped&&await Promise.allSettled([this.#M(i),this.#h.closeRoute(i)]);for(let r of A?.messages??[A?.message])r&&await this.#A.sendText(a,r);this.#a.lastError=null}catch(A){if(A?.code==="turn-stopped"||this.#I?.aborted){t.statusReaction?.clear();return}t.statusReaction?.error(),this.#a.lastError=A?.message??String(A);let r=tt(this.#a,A);this.#n.error?.(`[dsh-im:${this.#e.key}] failed to process a command [${r.referenceId}]:`,A),await this.#A.sendText(a,dt(r)).catch(()=>{})}}sendConnectionTest(t){return ec({state:this.#r,text:t,channelLabel:w("{label}\u673A\u5668\u4EBA",{label:this.#e.label}),send:(o,i)=>this.#A.sendText(o,i)})}sendProactiveText(t,o,{signal:i}={}){return i?.throwIfAborted(),this.#A.sendText(t,o)}async#S(t,o,i=[],e){let a=await bo({artifacts:i,baseReceipt:e,deliveryId:o,channelKey:this.#e.key,signal:this.#I,sendImage:typeof this.#A.sendImage=="function"?A=>this.#A.sendImage(t,A):void 0,sendFile:typeof this.#A.sendFile=="function"?A=>this.#A.sendFile(t,A):void 0,onFailure:(A,r)=>tt(this.#a,r,{userMessage:FCe(A?.fileName,r,this.#e),reason:r?.code}),sendFailureNotice:(A,r,s)=>this.#A.sendText(t,dt(s)),logger:this.#n});return this.#a.artifactsSent=(this.#a.artifactsSent??0)+a.artifactsSent,this.#a.artifactSendErrors=(this.#a.artifactSendErrors??0)+a.artifactSendErrors,{receipt:a.receipt,userVisible:a.userVisible,artifactSendErrors:a.artifactSendErrors}}async#Q(t,o,i,e,{alreadyRecorded:a=!1}={}){if(!a){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString()}let A=t.replyTarget,r=bi(t.content),s=t.batchSubmission,g=null,c=!1;try{if(this.#I?.throwIfAborted(),t.kind==="group"&&t.addressed!==!0){this.#a.messagesRejected+=1,this.#a.lastRejectedAt=new Date().toISOString();return}let I=Wt(t),d=Lt(t);if(!r&&!I&&!d){await this.#A.sendText(A,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002"));return}let B=r.toLowerCase();if(!I&&!d&&B==="/help"){await this.#A.sendText(A,[w("{label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002",{label:this.#e.label}),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` -`));return}if(!I&&!d&&B==="/status"){await this.#t.ensureRunning({signal:this.#I}),await this.#A.sendText(A,w("{label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002",{label:this.#e.label}));return}let f=!I&&!d?await Qo(r,this.#t,e):null;if(f){for(let J of f.messages??[f.message])await this.#A.sendText(A,J);return}if(!I&&!d&&B==="/new"){await this.#r.clearSession(e),await this.#A.sendText(A,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"));return}let Q=!I&&!d?await Bi(r,this.#t,this.#r,e,{signal:this.#I}):null;if(Q){await this.#A.sendText(A,Q.message);return}await this.#A.sendTyping?.(A).catch(J=>{this.#n.warn?.(`[dsh-im:${this.#e.key}] typing indicator failed:`,J)});let y=!1;if(typeof this.#A.openDeliveryStream=="function")try{g=await this.#A.openDeliveryStream(A),c=!0}catch(J){this.#n.warn?.(`[dsh-im:${this.#e.key}] unable to start a semantic reply stream; using final delivery:`,J)}else if(typeof this.#A.openStream=="function")try{g=await this.#A.openStream(A)}catch(J){this.#n.warn?.(`[dsh-im:${this.#e.key}] unable to start a streamed reply; using text:`,J)}let m=I?await Bo(t,{signal:this.#I}):void 0,_=this.#c.get(o);_&&(m=mo(m??r,_,()=>({channel:this.#e.key,senderId:i,senderName:t.contextSource?.()?.senderName})));let{answer:T,artifacts:R=[]}=await ui({harness:this.#t,state:this.#r,key:e,text:r,content:m,createOptions:this.#I?{signal:this.#I}:void 0,existsOptions:this.#I?{signal:this.#I}:void 0,askOptions:{timeoutMs:this.#i,signal:this.#I,control:{owner:this,key:e},onUpdate:g?async J=>{let U=J.type==="text"?J.text:J.type==="tool"?w("\u6B63\u5728\u4F7F\u7528{name}\u2026",{name:J.name}):J.text;if(U){let N=J.type==="text"?"markdown":"plain";await g.update(c?Vn(U,N):U)}}:void 0,onInteraction:J=>this.#u(J,{key:e,actor:i,target:A,requiresMention:t.kind==="group"&&t.requiresMention!==!1}),onInteractionResolved:J=>this.#b(J),files:t.files}});s&&this.#E.complete(e,s.token);let F=!bi(T)&&R.length>0,K=F?w(PCe):T,L=F?"plain":"markdown",q=null,z=null;if(g)try{let J=await g.finish(c?Vn(K,L):K);y=!0,z=Zt({deliveryId:o,presentation:J?.presentation??g.presentation??`${this.#e.key}-stream`,providerMessageIds:[...ka(g),...ka(J)],deliveryOutcome:J?.deliveryOutcome,reason:J?.reason})}catch(J){g.cancel?.(),this.#n.warn?.(`[dsh-im:${this.#e.key}] streamed reply finalization failed; using text:`,J)}if(!y)try{let J=typeof this.#A.sendDelivery=="function"?await this.#A.sendDelivery(A,Vn(K,L)):await this.#A.sendText(A,K);z=Zt({deliveryId:o,presentation:J?.presentation??`${this.#e.key}-text`,providerMessageIds:ka(J),deliveryOutcome:J?.deliveryOutcome,reason:J?.reason})}catch(J){q=Ma(J)}let j=z?.deliveryOutcome==="unknown";z?.deliveryOutcome==="failed"?q=Ma(new Error(`Final text delivery failed (${z.reason??"unknown"})`),{uncertain:!1}):j&&(q=Ma(new Error(`Final text delivery outcome is unknown (${z.reason??"unknown"})`)));let P=await this.#S(A,o,R,z);if(q&&(!P.userVisible||j))throw q.deliveryReceipt=P.receipt,q;return q&&P.artifactSendErrors===0&&tt(this.#a,q),P.userVisible&&(this.#a.messagesReplied+=1,this.#a.lastReplyAt=new Date().toISOString(),this.#a.lastError=null,!q&&P.artifactSendErrors===0&&Co(this.#a)),P.receipt}catch(I){let d=I?.code==="turn-stopped";s&&d&&this.#E.complete(e,s.token);let B=s&&!d?this.#E.fail(e,s.token):null;if(d){if(t.statusReaction?.clear(),g)try{await g.finish(w("\u5DF2\u505C\u6B62\u3002"))}catch{g.cancel?.()}return}if(this.#I?.aborted){t.statusReaction?.clear(),g?.cancel?.();return}t.statusReaction?.error(),this.#a.lastError=I?.message??String(I);let f=async T=>{let R=typeof g?.fail=="function"?"fail":typeof g?.finish=="function"?"finish":null;if(!R)return!1;try{let F=await g[R](T);return R==="fail"?!!F&&F.deliveryOutcome!=="failed":F!==!1&&F?.deliveryOutcome!=="failed"}catch(F){return this.#n.warn?.(`[dsh-im:${this.#e.key}] unable to finalize the failed stream:`,F),!1}},Q=fo(I),y=Oo(I),m=tt(this.#a,I,{userMessage:y??Q,reason:Ji(I)?.reason}),_=B?.retained?`${dt(m)} +`));return}if(!I&&!d&&B==="/status"){await this.#t.ensureRunning({signal:this.#I}),await this.#A.sendText(A,w("{label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002",{label:this.#e.label}));return}let f=!I&&!d?await Qo(r,this.#t,e):null;if(f){for(let J of f.messages??[f.message])await this.#A.sendText(A,J);return}if(!I&&!d&&B==="/new"){await this.#r.clearSession(e),await this.#A.sendText(A,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"));return}let Q=!I&&!d?await Bi(r,this.#t,this.#r,e,{signal:this.#I}):null;if(Q){await this.#A.sendText(A,Q.message);return}await this.#A.sendTyping?.(A).catch(J=>{this.#n.warn?.(`[dsh-im:${this.#e.key}] typing indicator failed:`,J)});let y=!1;if(typeof this.#A.openDeliveryStream=="function")try{g=await this.#A.openDeliveryStream(A),c=!0}catch(J){this.#n.warn?.(`[dsh-im:${this.#e.key}] unable to start a semantic reply stream; using final delivery:`,J)}else if(typeof this.#A.openStream=="function")try{g=await this.#A.openStream(A)}catch(J){this.#n.warn?.(`[dsh-im:${this.#e.key}] unable to start a streamed reply; using text:`,J)}let m=I?await Bo(t,{signal:this.#I}):void 0,_=this.#c.get(o);_&&(m=mo(m??r,_,()=>({channel:this.#e.key,senderId:i,senderName:t.contextSource?.()?.senderName})));let{answer:T,artifacts:R=[]}=await ui({harness:this.#t,state:this.#r,key:e,text:r,content:m,createOptions:this.#I?{signal:this.#I}:void 0,existsOptions:this.#I?{signal:this.#I}:void 0,askOptions:{timeoutMs:this.#i,signal:this.#I,control:{owner:this,key:e},onUpdate:g?async J=>{let H=J.type==="text"?J.text:J.type==="tool"?w("\u6B63\u5728\u4F7F\u7528{name}\u2026",{name:J.name}):J.text;if(H){let N=J.type==="text"?"markdown":"plain";await g.update(c?Vn(H,N):H)}}:void 0,onInteraction:J=>this.#u(J,{key:e,actor:i,target:A,requiresMention:t.kind==="group"&&t.requiresMention!==!1}),onInteractionResolved:J=>this.#b(J),files:t.files}});s&&this.#E.complete(e,s.token);let L=!bi(T)&&R.length>0,U=L?w(PCe):T,F=L?"plain":"markdown",q=null,z=null;if(g)try{let J=await g.finish(c?Vn(U,F):U);y=!0,z=Zt({deliveryId:o,presentation:J?.presentation??g.presentation??`${this.#e.key}-stream`,providerMessageIds:[...ka(g),...ka(J)],deliveryOutcome:J?.deliveryOutcome,reason:J?.reason})}catch(J){g.cancel?.(),this.#n.warn?.(`[dsh-im:${this.#e.key}] streamed reply finalization failed; using text:`,J)}if(!y)try{let J=typeof this.#A.sendDelivery=="function"?await this.#A.sendDelivery(A,Vn(U,F)):await this.#A.sendText(A,U);z=Zt({deliveryId:o,presentation:J?.presentation??`${this.#e.key}-text`,providerMessageIds:ka(J),deliveryOutcome:J?.deliveryOutcome,reason:J?.reason})}catch(J){q=Ma(J)}let j=z?.deliveryOutcome==="unknown";z?.deliveryOutcome==="failed"?q=Ma(new Error(`Final text delivery failed (${z.reason??"unknown"})`),{uncertain:!1}):j&&(q=Ma(new Error(`Final text delivery outcome is unknown (${z.reason??"unknown"})`)));let P=await this.#S(A,o,R,z);if(q&&(!P.userVisible||j))throw q.deliveryReceipt=P.receipt,q;return q&&P.artifactSendErrors===0&&tt(this.#a,q),P.userVisible&&(this.#a.messagesReplied+=1,this.#a.lastReplyAt=new Date().toISOString(),this.#a.lastError=null,!q&&P.artifactSendErrors===0&&Co(this.#a)),P.receipt}catch(I){let d=I?.code==="turn-stopped";s&&d&&this.#E.complete(e,s.token);let B=s&&!d?this.#E.fail(e,s.token):null;if(d){if(t.statusReaction?.clear(),g)try{await g.finish(w("\u5DF2\u505C\u6B62\u3002"))}catch{g.cancel?.()}return}if(this.#I?.aborted){t.statusReaction?.clear(),g?.cancel?.();return}t.statusReaction?.error(),this.#a.lastError=I?.message??String(I);let f=async T=>{let R=typeof g?.fail=="function"?"fail":typeof g?.finish=="function"?"finish":null;if(!R)return!1;try{let L=await g[R](T);return R==="fail"?!!L&&L.deliveryOutcome!=="failed":L!==!1&&L?.deliveryOutcome!=="failed"}catch(L){return this.#n.warn?.(`[dsh-im:${this.#e.key}] unable to finalize the failed stream:`,L),!1}},Q=fo(I),y=Oo(I),m=tt(this.#a,I,{userMessage:y??Q,reason:Ji(I)?.reason}),_=B?.retained?`${dt(m)} ${B.message}`:dt(m);if(this.#n.error?.(`[dsh-im:${this.#e.key}] failed to process a message [${m.referenceId}]:`,I),await f(_))return I.deliveryReceipt;g?.cancel?.();try{await this.#A.sendText(A,_)}catch(T){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send the safe error reply:`,T)}return I.deliveryReceipt}finally{await Promise.allSettled([this.#M(e),this.#h.closeRoute(e)])}}async#m(t,o,i,e,a){if(this.#I?.aborted){t.statusReaction?.clear();return}let A=this.#o.get(e),r=a.claimedReplyMessageId===o;if(!A||A!==a||A.submitting)return r&&(!A||A!==a)?this.#D(t,o):this.#B(t,o,i,e,{releaseMessageId:!1});if(this.#r.hasSeen(o))return;if(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),t.kind==="group"&&t.addressed!==!0){this.#a.messagesRejected+=1,this.#a.lastRejectedAt=new Date().toISOString();return}let s=t.replyTarget,g=bi(t.content);if(!g||Wt(t)||Lt(t)){try{await this.#A.sendText(s,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002"))}catch(d){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to reject a non-text interaction reply:`,d)}return}let c=this.#o.get(e);if(!c||c!==a||c.submitting)return r&&(!c||c!==a)?this.#D(t,o,{alreadyRecorded:!0}):this.#B(t,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(c.target=s,c.needsPresentation){let d=c.presentationTask!==null;try{await this.#R(c)}catch(f){t.statusReaction?.error(),this.#a.lastError=w("{label}\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",{label:this.#e.label}),this.#n.error?.(`[dsh-im:${this.#e.key}] failed to retry an interaction question:`,f),c.interaction.reconnect?.();return}let B=this.#o.get(e);if(!B||B!==a||B.submitting)return r&&(!B||B!==a)?this.#D(t,o,{alreadyRecorded:!0}):this.#B(t,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(!d)return}let I=c.questions[c.index];if(I){if(c.answers.push(Ei(I,g)),c.index+=1,c.indexthis.#A.sendText(e,c)});if(t?.kind!=="question")return;let A=t?.payload?.questions,r=bi(t?.interactionId)||bi(t?.rpcId);if(!bi(t?.rpcId)||!r||!bi(t?.sessionId)||!Array.isArray(A)||A.length===0||A.some(c=>!di(c))){this.#n.warn?.(`[dsh-im:${this.#e.key}] ignored an invalid Harness question interaction`);return}if(t.recovered===!0){await this.#k(t,`${this.#e.label} safely cancelled an interaction left by an earlier client.`);try{await this.#A.sendText(e,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002"))}catch(c){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send an interaction recovery notice:`,c)}return}let s=this.#o.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#R(s);return}if(this.#s.has(r))return;if(s){this.#n.warn?.(`[dsh-im:${this.#e.key}] cancelled a second pending Harness question`),await this.#k(t,`${this.#e.label} is already handling another user interaction.`);return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,requiresMention:a,questions:A,answers:[],index:0,target:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationTask:null};this.#o.set(o,g),this.#s.set(r,o),await this.#R(g)}async#b(t){if(t?.kind==="approval"){await this.#h.handleResolved(t);return}let o=bi(t?.interactionId);if(t?.kind!=="question"||!o)return;let i=this.#s.get(o);i&&this.#T(i,o)}#R(t){if(t.presentationTask)return t.presentationTask;let o=t.questions[t.index];if(!o)return Promise.resolve();let i=(async()=>{await this.#A.sendText(t.target,hi(o,t.index,t.questions.length,{requiresMention:t.requiresMention})),t.needsPresentation=!1})();return t.presentationTask=i,i.then(()=>{t.presentationTask===i&&(t.presentationTask=null)},()=>{t.presentationTask===i&&(t.presentationTask=null)}),i}async#D(t,o,{alreadyRecorded:i=!1}={}){if(!i){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString()}try{await this.#A.sendText(t.replyTarget,w(d1))}catch(e){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send an expired interaction notice:`,e)}}#w(t,o){let i=this.#o.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#o.delete(t),this.#s.delete(i.interactionId),i)}#T(t,o){return this.#w(t,o)!==null}async#k(t,o){try{await t.respond({ok:!1,error:{code:"cancelled",message:o,details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){if(i?.code!=="interaction-not-pending")throw i}}async#M(t){let o=this.#w(t);if(!(!o||o.kind!=="question"))try{await this.#k(o.interaction,`The ${this.#e.label} interaction ended before the user answered.`)}catch(i){this.#n.warn?.(`[dsh-im:${this.#e.key}] failed to cancel a pending Harness interaction:`,i)}}};var b_=Object.freeze({key:"discord",label:"Discord",connectionLabel:" Gateway \u957F\u8FDE\u63A5",reactions:Object.freeze({processing:"\u{1F440}",success:"\u2705",error:"\u274C"})}),GQ=class extends $n{constructor(t){super({descriptor:b_,...t})}};var JE=class extends Rp{constructor(t){super({...t,descriptor:b_,inspectToken:t.inspectToken??l1,deriveIdentity:n1,maskPlatformId:s1})}};var FQ=class extends lr{constructor(t){super({...t,rpcIdPrefix:"discord",logPrefix:"dsh-discord"})}};function es(n,t){let o=typeof n=="string"?n.trim():"";if(!o)return[];let i=[],e=o;for(;e.length>t;){let a=e.lastIndexOf(` -`,t);anull,logger:r=console}){let s,g=[],c=null,I=null,d=null,B=!1,f=n,Q=()=>{B||I!==null||d||!c||(I=setTimeout(()=>{I=null;let y=c;c=null;let m=es(y,t)[0]??n;d=Promise.resolve(m===f?void 0:e(s,m)).then(()=>{f=m}).catch(_=>r.warn?.("[dsh-im] streamed message update failed:",_)).finally(()=>{d=null,Q()})},o),I?.unref?.())};return{get messageId(){return s},get providerMessageIds(){return[...g]},async start(){return s=await i(n),(typeof s=="string"&&s.trim()||Number.isSafeInteger(s))&&g.push(String(s)),this},update(y){B||typeof y!="string"||!y.trim()||(c=y,Q())},async finish(y){if(B)throw new Error("Message stream is already closed");B=!0,I!==null&&clearTimeout(I),I=null,c=null,await d?.catch(()=>{});let m=es(y,t),_=m[0]??w("\u5904\u7406\u5B8C\u6210\u3002");_!==f&&await e(s,_),f=_;for(let T of m.slice(1)){let R=await a(T),F=A(R);(typeof F=="string"&&F.trim()||Number.isSafeInteger(F))&&g.push(String(F))}},cancel(){B=!0,c=null,I!==null&&clearTimeout(I),I=null}}}async function h1(n){try{await n?.body?.cancel?.()}catch{}}function LCe(n,t){return!Array.isArray(t)||t.some(o=>typeof o=="string"&&(n.hostname===o||o.startsWith(".")&&(n.hostname===o.slice(1)||n.hostname.endsWith(o))))}async function kp(n,{fetchImpl:t=fetch,headers:o,signal:i,allowedHosts:e}={}){let a=new URL(n);if(a.protocol!=="https:")throw new Error("File download URL must use HTTPS");if(!LCe(a,e))throw new Error("File download URL is not hosted by the messaging platform");let A=await t(a,{method:"GET",headers:o,signal:i,redirect:"manual"});if(Number.isInteger(A?.status)&&A.status>=300&&A.status<400){await h1(A);let r=new Error(`File download redirect was blocked (HTTP ${A.status})`);throw r.code="file-redirect-blocked",r}if(!A?.ok){await h1(A);let r=new Error(`File download failed with HTTP ${A?.status??"unknown"}`);throw r.code="file-http-error",r.status=A?.status,r}if(A.body?.[Symbol.asyncIterator])return{stream:A.body};if(typeof A.arrayBuffer=="function"){let r=Buffer.from(await A.arrayBuffer());return{stream:(async function*(){yield r})()}}throw new Error("File download returned no readable body")}var UCe=37377,HCe=5e3,E1=Object.freeze([1e3,3e3,5e3,1e4,3e4]),KCe=0,xCe=5,YCe=10,jCe=11,JCe=12,qCe=new Set([YCe,jCe,JCe]),zCe=new Set(["image/jpeg","image/png","image/webp","image/gif"]),VCe=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]),B1=Object.freeze(["cdn.discordapp.com"]);function WCe(n){let t=new URL(n);if(t.protocol!=="wss:")throw new Error("Discord returned an insecure Gateway URL");return t.searchParams.set("v","10"),t.searchParams.set("encoding","json"),t.href}function M_(n,t,o){if(typeof n.addEventListener=="function")n.addEventListener(t,o);else if(typeof n.on=="function")n.on(t,o);else throw new TypeError("Discord WebSocket does not support events")}function ZCe(n){return typeof n=="string"?n:typeof n?.data=="string"?n.data:Buffer.isBuffer(n)?n.toString("utf8"):Buffer.isBuffer(n?.data)?n.data.toString("utf8"):null}function XCe(n){if(n===4004){let o=new Error(w("Discord Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002"));return o.code="discord-401",o}if(n===4013||n===4014){let o=new Error(w("Discord Gateway Intents \u914D\u7F6E\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 Developer Portal \u7684 Bot \u8BBE\u7F6E\u3002"));return o.code="discord-intents",o}let t=new Error(`Discord Gateway closed (${n||"unknown"})`);return t.code="discord-gateway-closed",t}function f1(n,t){return typeof n!="string"?"":n.replace(new RegExp(`<@!?${t}>`,"g"),"").trim()}function $Ce(n,t){return[...f1(n?.content??"",t).replace(/\s+/g," ").trim()||"DeepSeek Harness"].slice(0,100).join("")}function N_(n){return qCe.has(Number(n?.type))}function Q1(n,t){return N_(n)&&String(n?.id??"")===String(t?.id??"")&&String(n?.parent_id??"")===String(t?.channel_id??"")}function __(n,t){return n?.id&&t?.(n),n}function _I(n,t,o,{fromSourceMessage:i=!1,fallback:e=null,notice:a=null}={}){let A=String(t?.id??n.conversationId),r=N_(t),s=r&&String(t?.owner_id??"")===String(o),g=r&&t?.parent_id?String(t.parent_id):A;return{...n,conversationId:A,addressed:n.addressed||s,requiresMention:r?!s:n.kind==="group",replyTarget:{channelId:A,...!i&&n.replyTarget?.replyToMessageId?{replyToMessageId:n.replyTarget.replyToMessageId}:{},...a?{notice:a}:{}},connectionTestTarget:{channelId:A},conversationRoute:{peerId:g,...r?{threadId:A,managed:s}:{},...e?{fallback:e}:{}}}}function eue(n){let t=Number(n?.status);return!Number.isInteger(t)||t>=500}function C1(n){let t=new Error("Discord Thread creation result is uncertain",{cause:n});return t.code="discord-thread-create-uncertain",t}async function Aue(n,t,{signal:o,onChannel:i}={}){try{let e=__(await n.getChannel({channelId:String(t.id),signal:o}),i);return Q1(e,t)?e:null}catch(e){if(e?.status===404)return null;throw e}}async function u1(n,t,o){try{await n.createMessage({channelId:t.replyTarget.channelId,replyToMessageId:t.replyTarget.replyToMessageId,content:"Thread \u521B\u5EFA\u7ED3\u679C\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u3002\u82E5\u5DF2\u521B\u5EFA\uFF0C\u8BF7\u5728\u5BF9\u5E94 Thread \u4E2D\u91CD\u8BD5\uFF1B\u82E5\u672A\u521B\u5EFA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0 @\u673A\u5668\u4EBA\u3002",signal:o})}catch(i){if(o?.aborted)throw o.reason??i}}function y1(n){let t=typeof n?.content_type=="string"?n.content_type.split(";",1)[0].trim().toLowerCase():"";if(zCe.has(t))return t;let o=typeof n?.filename=="string"?n.filename.toLowerCase():"";for(let[i,e]of VCe)if(o.endsWith(i))return e;return null}function m1(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function tue(n,t){let o=y1(n);return!o||typeof n?.url!="string"?null:{name:typeof n.filename=="string"?n.filename:void 0,mediaType:o,size:m1(n.size),load:i=>uo(n.url,{...i,fetchImpl:t,allowedHosts:B1})}}function rue(n,t){if(y1(n)||typeof n?.url!="string"||!n.url)return null;let o=typeof n.content_type=="string"&&n.content_type?n.content_type.split(";",1)[0].trim().toLowerCase():void 0;return{name:typeof n.filename=="string"&&n.filename?n.filename:String(n.id??"discord-file"),...o?{mediaType:o}:{},size:m1(n.size),load:({signal:i}={})=>kp(n.url,{fetchImpl:t,signal:i,allowedHosts:B1})}}function aue(n,t,{fetchImpl:o=fetch}={}){if(!n?.id||!n?.channel_id||!n?.author?.id||Number(n.type)===21)return null;let i=!n.guild_id,e=i||n.mentions?.some(a=>String(a?.id)===String(t));return{messageId:String(n.id),senderId:String(n.author.id),contextSource:()=>({senderName:[n.member?.nick,n.author.global_name,n.author.username].find(a=>typeof a=="string"&&a.trim())}),senderIsBot:n.author.bot===!0,kind:i?"direct":"group",conversationId:String(n.channel_id),content:f1(n.content??"",t),plainText:(!Array.isArray(n.attachments)||n.attachments.length===0)&&(!Array.isArray(n.sticker_items)||n.sticker_items.length===0)&&!n.poll,images:Array.isArray(n.attachments)?n.attachments.map(a=>tue(a,o)).filter(Boolean):[],files:Array.isArray(n.attachments)?n.attachments.map(a=>rue(a,o)).filter(Boolean):[],addressed:e,replyTarget:{channelId:String(n.channel_id),replyToMessageId:String(n.id)},reactionTarget:{channelId:String(n.channel_id),messageId:String(n.id)},connectionTestTarget:{channelId:String(n.channel_id)}}}async function iue(n,t,{api:o,channel:i,fetchImpl:e=fetch,signal:a,onChannel:A}={}){let r=aue(n,t,{fetchImpl:e});if(!r||r.senderIsBot)return r;if(a?.throwIfAborted(),r.kind==="direct")return _I(r,{id:r.conversationId,type:1},t);if(!o||typeof o.getChannel!="function")throw new TypeError("Discord route resolution requires the Discord API");let s=__(i??await o.getChannel({channelId:r.conversationId,signal:a}),A);if(N_(s)||!r.addressed)return _I(r,s,t);let g=Number(s?.type);if(g!==KCe&&g!==xCe)return _I(r,s,t,{fallback:"unsupported-channel",notice:"\u5F53\u524D\u9891\u9053\u4E0D\u652F\u6301\u81EA\u52A8\u521B\u5EFA Thread\uFF0C\u5DF2\u76F4\u63A5\u5728\u5F53\u524D\u9891\u9053\u56DE\u590D\u3002"});a?.throwIfAborted();let c;try{if(c=__(await o.startThreadFromMessage({channelId:r.conversationId,messageId:r.messageId,name:$Ce(n,t),signal:a}),A),!Q1(c,n))throw new Error("Discord returned an invalid thread for the source message")}catch(I){let d;try{d=await Aue(o,n,{signal:AbortSignal.timeout(HCe),onChannel:A})}catch(B){throw a?.aborted?a.reason??I:(await u1(o,r,a),C1(B))}if(d)return _I(r,d,t,{fromSourceMessage:!0});if(a?.aborted)throw a.reason??I;if(eue(I))throw await u1(o,r,a),C1(I);return _I(r,s,t,{fallback:"thread-create-failed",notice:"\u65E0\u6CD5\u521B\u5EFA Thread\uFF0C\u5DF2\u76F4\u63A5\u5728\u5F53\u524D\u9891\u9053\u56DE\u590D\u3002"})}return _I(r,c,t,{fromSourceMessage:!0})}var T_=class{#e;#A;#t=new WeakSet;constructor({api:t,signal:o}){this.#e=t,this.#A=o}async sendText(t,o){let i=!this.#t.has(t)&&t?.notice?String(t.notice):null,e=es(i?`${i} +`,t);anull,logger:r=console}){let s,g=[],c=null,I=null,d=null,B=!1,f=n,Q=()=>{B||I!==null||d||!c||(I=setTimeout(()=>{I=null;let y=c;c=null;let m=es(y,t)[0]??n;d=Promise.resolve(m===f?void 0:e(s,m)).then(()=>{f=m}).catch(_=>r.warn?.("[dsh-im] streamed message update failed:",_)).finally(()=>{d=null,Q()})},o),I?.unref?.())};return{get messageId(){return s},get providerMessageIds(){return[...g]},async start(){return s=await i(n),(typeof s=="string"&&s.trim()||Number.isSafeInteger(s))&&g.push(String(s)),this},update(y){B||typeof y!="string"||!y.trim()||(c=y,Q())},async finish(y){if(B)throw new Error("Message stream is already closed");B=!0,I!==null&&clearTimeout(I),I=null,c=null,await d?.catch(()=>{});let m=es(y,t),_=m[0]??w("\u5904\u7406\u5B8C\u6210\u3002");_!==f&&await e(s,_),f=_;for(let T of m.slice(1)){let R=await a(T),L=A(R);(typeof L=="string"&&L.trim()||Number.isSafeInteger(L))&&g.push(String(L))}},cancel(){B=!0,c=null,I!==null&&clearTimeout(I),I=null}}}async function h1(n){try{await n?.body?.cancel?.()}catch{}}function LCe(n,t){return!Array.isArray(t)||t.some(o=>typeof o=="string"&&(n.hostname===o||o.startsWith(".")&&(n.hostname===o.slice(1)||n.hostname.endsWith(o))))}async function kp(n,{fetchImpl:t=fetch,headers:o,signal:i,allowedHosts:e}={}){let a=new URL(n);if(a.protocol!=="https:")throw new Error("File download URL must use HTTPS");if(!LCe(a,e))throw new Error("File download URL is not hosted by the messaging platform");let A=await t(a,{method:"GET",headers:o,signal:i,redirect:"manual"});if(Number.isInteger(A?.status)&&A.status>=300&&A.status<400){await h1(A);let r=new Error(`File download redirect was blocked (HTTP ${A.status})`);throw r.code="file-redirect-blocked",r}if(!A?.ok){await h1(A);let r=new Error(`File download failed with HTTP ${A?.status??"unknown"}`);throw r.code="file-http-error",r.status=A?.status,r}if(A.body?.[Symbol.asyncIterator])return{stream:A.body};if(typeof A.arrayBuffer=="function"){let r=Buffer.from(await A.arrayBuffer());return{stream:(async function*(){yield r})()}}throw new Error("File download returned no readable body")}var UCe=37377,HCe=5e3,E1=Object.freeze([1e3,3e3,5e3,1e4,3e4]),KCe=0,xCe=5,YCe=10,jCe=11,JCe=12,qCe=new Set([YCe,jCe,JCe]),zCe=new Set(["image/jpeg","image/png","image/webp","image/gif"]),VCe=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]),B1=Object.freeze(["cdn.discordapp.com"]);function WCe(n){let t=new URL(n);if(t.protocol!=="wss:")throw new Error("Discord returned an insecure Gateway URL");return t.searchParams.set("v","10"),t.searchParams.set("encoding","json"),t.href}function M_(n,t,o){if(typeof n.addEventListener=="function")n.addEventListener(t,o);else if(typeof n.on=="function")n.on(t,o);else throw new TypeError("Discord WebSocket does not support events")}function ZCe(n){return typeof n=="string"?n:typeof n?.data=="string"?n.data:Buffer.isBuffer(n)?n.toString("utf8"):Buffer.isBuffer(n?.data)?n.data.toString("utf8"):null}function XCe(n){if(n===4004){let o=new Error(w("Discord Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002"));return o.code="discord-401",o}if(n===4013||n===4014){let o=new Error(w("Discord Gateway Intents \u914D\u7F6E\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 Developer Portal \u7684 Bot \u8BBE\u7F6E\u3002"));return o.code="discord-intents",o}let t=new Error(`Discord Gateway closed (${n||"unknown"})`);return t.code="discord-gateway-closed",t}function f1(n,t){return typeof n!="string"?"":n.replace(new RegExp(`<@!?${t}>`,"g"),"").trim()}function $Ce(n,t){return[...f1(n?.content??"",t).replace(/\s+/g," ").trim()||"DeepSeek Harness"].slice(0,100).join("")}function N_(n){return qCe.has(Number(n?.type))}function Q1(n,t){return N_(n)&&String(n?.id??"")===String(t?.id??"")&&String(n?.parent_id??"")===String(t?.channel_id??"")}function __(n,t){return n?.id&&t?.(n),n}function _I(n,t,o,{fromSourceMessage:i=!1,fallback:e=null,notice:a=null}={}){let A=String(t?.id??n.conversationId),r=N_(t),s=r&&String(t?.owner_id??"")===String(o),g=r&&t?.parent_id?String(t.parent_id):A;return{...n,conversationId:A,addressed:n.addressed||s,requiresMention:r?!s:n.kind==="group",replyTarget:{channelId:A,...!i&&n.replyTarget?.replyToMessageId?{replyToMessageId:n.replyTarget.replyToMessageId}:{},...a?{notice:a}:{}},connectionTestTarget:{channelId:A},conversationRoute:{peerId:g,...r?{threadId:A,managed:s}:{},...e?{fallback:e}:{}}}}function eue(n){let t=Number(n?.status);return!Number.isInteger(t)||t>=500}function C1(n){let t=new Error("Discord Thread creation result is uncertain",{cause:n});return t.code="discord-thread-create-uncertain",t}async function Aue(n,t,{signal:o,onChannel:i}={}){try{let e=__(await n.getChannel({channelId:String(t.id),signal:o}),i);return Q1(e,t)?e:null}catch(e){if(e?.status===404)return null;throw e}}async function u1(n,t,o){try{await n.createMessage({channelId:t.replyTarget.channelId,replyToMessageId:t.replyTarget.replyToMessageId,content:"Thread \u521B\u5EFA\u7ED3\u679C\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u3002\u82E5\u5DF2\u521B\u5EFA\uFF0C\u8BF7\u5728\u5BF9\u5E94 Thread \u4E2D\u91CD\u8BD5\uFF1B\u82E5\u672A\u521B\u5EFA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0 @\u673A\u5668\u4EBA\u3002",signal:o})}catch(i){if(o?.aborted)throw o.reason??i}}function y1(n){let t=typeof n?.content_type=="string"?n.content_type.split(";",1)[0].trim().toLowerCase():"";if(zCe.has(t))return t;let o=typeof n?.filename=="string"?n.filename.toLowerCase():"";for(let[i,e]of VCe)if(o.endsWith(i))return e;return null}function m1(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function tue(n,t){let o=y1(n);return!o||typeof n?.url!="string"?null:{name:typeof n.filename=="string"?n.filename:void 0,mediaType:o,size:m1(n.size),load:i=>uo(n.url,{...i,fetchImpl:t,allowedHosts:B1})}}function rue(n,t){if(y1(n)||typeof n?.url!="string"||!n.url)return null;let o=typeof n.content_type=="string"&&n.content_type?n.content_type.split(";",1)[0].trim().toLowerCase():void 0;return{name:typeof n.filename=="string"&&n.filename?n.filename:String(n.id??"discord-file"),...o?{mediaType:o}:{},size:m1(n.size),load:({signal:i}={})=>kp(n.url,{fetchImpl:t,signal:i,allowedHosts:B1})}}function aue(n,t,{fetchImpl:o=fetch}={}){if(!n?.id||!n?.channel_id||!n?.author?.id||Number(n.type)===21)return null;let i=!n.guild_id,e=i||n.mentions?.some(a=>String(a?.id)===String(t));return{messageId:String(n.id),senderId:String(n.author.id),contextSource:()=>({senderName:[n.member?.nick,n.author.global_name,n.author.username].find(a=>typeof a=="string"&&a.trim())}),senderIsBot:n.author.bot===!0,kind:i?"direct":"group",conversationId:String(n.channel_id),content:f1(n.content??"",t),plainText:(!Array.isArray(n.attachments)||n.attachments.length===0)&&(!Array.isArray(n.sticker_items)||n.sticker_items.length===0)&&!n.poll,images:Array.isArray(n.attachments)?n.attachments.map(a=>tue(a,o)).filter(Boolean):[],files:Array.isArray(n.attachments)?n.attachments.map(a=>rue(a,o)).filter(Boolean):[],addressed:e,replyTarget:{channelId:String(n.channel_id),replyToMessageId:String(n.id)},reactionTarget:{channelId:String(n.channel_id),messageId:String(n.id)},connectionTestTarget:{channelId:String(n.channel_id)}}}async function iue(n,t,{api:o,channel:i,fetchImpl:e=fetch,signal:a,onChannel:A}={}){let r=aue(n,t,{fetchImpl:e});if(!r||r.senderIsBot)return r;if(a?.throwIfAborted(),r.kind==="direct")return _I(r,{id:r.conversationId,type:1},t);if(!o||typeof o.getChannel!="function")throw new TypeError("Discord route resolution requires the Discord API");let s=__(i??await o.getChannel({channelId:r.conversationId,signal:a}),A);if(N_(s)||!r.addressed)return _I(r,s,t);let g=Number(s?.type);if(g!==KCe&&g!==xCe)return _I(r,s,t,{fallback:"unsupported-channel",notice:"\u5F53\u524D\u9891\u9053\u4E0D\u652F\u6301\u81EA\u52A8\u521B\u5EFA Thread\uFF0C\u5DF2\u76F4\u63A5\u5728\u5F53\u524D\u9891\u9053\u56DE\u590D\u3002"});a?.throwIfAborted();let c;try{if(c=__(await o.startThreadFromMessage({channelId:r.conversationId,messageId:r.messageId,name:$Ce(n,t),signal:a}),A),!Q1(c,n))throw new Error("Discord returned an invalid thread for the source message")}catch(I){let d;try{d=await Aue(o,n,{signal:AbortSignal.timeout(HCe),onChannel:A})}catch(B){throw a?.aborted?a.reason??I:(await u1(o,r,a),C1(B))}if(d)return _I(r,d,t,{fromSourceMessage:!0});if(a?.aborted)throw a.reason??I;if(eue(I))throw await u1(o,r,a),C1(I);return _I(r,s,t,{fallback:"thread-create-failed",notice:"\u65E0\u6CD5\u521B\u5EFA Thread\uFF0C\u5DF2\u76F4\u63A5\u5728\u5F53\u524D\u9891\u9053\u56DE\u590D\u3002"})}return _I(r,c,t,{fromSourceMessage:!0})}var T_=class{#e;#A;#t=new WeakSet;constructor({api:t,signal:o}){this.#e=t,this.#A=o}async sendText(t,o){let i=!this.#t.has(t)&&t?.notice?String(t.notice):null,e=es(i?`${i} ${o}`:o,1900),a=[];for(let[A,r]of e.entries()){let s=await this.#e.createMessage({channelId:t.channelId,content:r,replyToMessageId:A===0?t.replyToMessageId:void 0,signal:this.#A});i&&A===0&&this.#t.add(t),typeof s?.id=="string"&&s.id&&a.push(s.id)}return{providerMessageIds:a}}sendTyping(t){return this.#e.sendTyping({channelId:t.channelId,signal:this.#A})}sendFile(t,o){return this.#e.createFileMessage({channelId:t.channelId,file:o,replyToMessageId:t.replyToMessageId,signal:this.#A})}addReaction(t,o,{signal:i}={}){return this.#e.addOwnReaction({channelId:t.channelId,messageId:t.messageId,emoji:o,signal:this.#r(i)})}removeReaction(t,o,{signal:i}={}){return this.#e.removeOwnReaction({channelId:t.channelId,messageId:t.messageId,emoji:o,signal:this.#r(i)})}async openStream(t){let o=!this.#t.has(t)&&t?.notice?String(t.notice):null,i=a=>o?`${o} ${a}`:a;return LQ({limit:o?1800:1900,create:async a=>{let A=await this.#e.createMessage({channelId:t.channelId,content:i(a),replyToMessageId:t.replyToMessageId,signal:this.#A});return o&&this.#t.add(t),A.id},edit:(a,A)=>this.#e.editMessage({channelId:t.channelId,messageId:a,content:i(A),signal:this.#A}),sendRemainder:a=>this.#e.createMessage({channelId:t.channelId,content:a,signal:this.#A}),messageIdForResult:a=>a?.id}).start()}#r(t){return t??this.#A}};function oue(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...Xi()}}var qE=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s=oue();#c=null;#p=null;#d=null;#h=null;#E=null;#C=null;#f=null;#B=null;#y=null;#S=!0;#Q=null;#m=0;#u=0;#b=!0;#R=null;#D=new Map;#w=new Map;constructor({config:t,token:o,harness:i,state:e,contextEnhancement:a,logger:A=console,replyTimeoutMs:r=6e5,connectTimeoutMs:s=2e4,createApi:g=d=>new jE(d),createWebSocket:c=d=>new WebSocket(d),random:I=Math.random}){if(!t||!o||!i||!e)throw new TypeError("DiscordRuntime requires config, token, Harness, and state");if(typeof c!="function")throw new TypeError("DiscordRuntime requires WebSocket");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c,this.#o=I}get status(){return structuredClone(this.#s)}async sendConnectionTest(t){if(!this.#s.ready||!this.#p){let o=new Error("Discord bot is not connected");throw o.code="test-target-unavailable",o}return this.#p.sendConnectionTest(t)}async sendProactiveText(t,o,i={}){if(!this.#s.ready||!this.#p){let a=new Error("Discord bot is not connected");throw a.code="bot-not-connected",a}let e=typeof t?.route?.channelId=="string"?t.route.channelId.trim():"";if(t?.kind!=="channel"||!e){let a=new TypeError("Invalid Discord proactive delivery target");throw a.code="invalid-target",a}return this.#p.sendProactiveText({channelId:e},o,i)}async start(){return this.#s.ready&&this.#h?this.status:this.#R?this.#R:(this.#R=this.#T().finally(()=>{this.#R=null}),this.#R)}async#T(){await this.stop(),this.#b=!1,this.#f=null,this.#C=null,this.#B=null,this.#m=0,this.#D.clear(),this.#w.clear(),this.#s.startedAt=new Date().toISOString(),this.#s.connectionState="connecting",this.#s.lastError=null,await this.#t.ensureRunning(),this.#s.harnessReachable=!0;let t=new AbortController;this.#d=t;let o=this.#I({token:this.#A});this.#c=o;try{let[i,e]=await Promise.all([o.getCurrentUser({signal:t.signal}),o.getGatewayBot({signal:t.signal})]);if(String(i?.id??"")!==this.#e.platformId||i?.bot!==!0)throw new Error("Discord token identity does not match the saved bot");this.#E=e?.url;let a=new T_({api:o,signal:t.signal});this.#p=new GQ({bot:a,harness:this.#t,state:this.#r,contextEnhancement:this.#g,status:this.#s,logger:this.#a,replyTimeoutMs:this.#n,signal:t.signal});let A;try{await Promise.race([this.#k(!1),new Promise((r,s)=>{A=setTimeout(()=>s(new Error("Discord Gateway did not become ready in time")),this.#i)})])}finally{clearTimeout(A)}return this.status}catch(i){throw this.#s.ready=!1,this.#s.connectionState="failed",this.#s.lastError=i?.message??String(i),await this.stop(),i}}#k(t){if(this.#b)return Promise.reject(new Error("Discord runtime is stopped"));let o=++this.#u,i=WCe(t&&this.#C?this.#C:this.#E),e=this.#l(i);this.#h=e;let a=!1;return new Promise((A,r)=>{let s=()=>{if(a||o!==this.#u)return;a=!0,this.#m=0;let g=Date.now();this.#s.ready=!0,this.#s.connectionState="connected",this.#s.lastCheckedAt=g,this.#s.lastConnectedAt=g,this.#s.lastError=null,A()};M_(e,"message",g=>{if(o!==this.#u||this.#b)return;let c=ZCe(g);if(!c)return;let I;try{I=JSON.parse(c)}catch{this.#a.warn?.("[dsh-im:discord] ignored malformed Gateway JSON");return}if(Number.isSafeInteger(I.s)&&(this.#B=I.s),I.op===10){this.#U(I.d?.heartbeat_interval,e,o),t&&this.#f?this.#_(e,{op:6,d:{token:this.#A,session_id:this.#f,seq:this.#B}}):this.#_(e,{op:2,d:{token:this.#A,intents:UCe,properties:{os:process.platform,browser:"dsh-im",device:"dsh-im"}}});return}if(I.op===11){this.#S=!0,this.#s.lastCheckedAt=Date.now();return}if(I.op===1){this.#v(e);return}if(I.op===7){e.close(4e3,"Reconnect requested");return}if(I.op===9){I.d!==!0&&(this.#f=null,this.#C=null,this.#B=null),e.close(4e3,"Invalid session");return}if(I.op===0){if(I.t==="READY")this.#f=I.d?.session_id??null,this.#C=I.d?.resume_gateway_url??null,s();else if(I.t==="RESUMED")s();else if(I.t==="GUILD_CREATE")for(let d of[...I.d?.channels??[],...I.d?.threads??[]])this.#M(d);else if(I.t==="CHANNEL_CREATE"||I.t==="CHANNEL_UPDATE"||I.t==="THREAD_CREATE"||I.t==="THREAD_UPDATE")this.#M(I.d);else if(I.t==="CHANNEL_DELETE"||I.t==="THREAD_DELETE")I.d?.id&&this.#D.delete(String(I.d.id));else if(I.t==="THREAD_LIST_SYNC")for(let d of I.d?.threads??[])this.#M(d);else if(I.t==="MESSAGE_CREATE"){let d=this.#p;I.d&&d&&this.#L(I.d,d).catch(B=>{o!==this.#u||this.#b||this.#a.error?.(`[dsh-im:discord] bot ${this.#e.botId} message handling failed:`,B)})}}}),M_(e,"close",(g={})=>{if(o!==this.#u)return;if(this.#P(),this.#h===e&&(this.#h=null),this.#b){a||r(new DOMException("Stopped","AbortError"));return}let c=XCe(Number(g.code)||0);if(this.#s.ready=!1,this.#s.connectionState="connecting",this.#s.lastError=c.message,a||(a=!0,r(c)),c.code==="discord-401"||c.code==="discord-intents"){this.#s.connectionState="failed";return}this.#N()}),M_(e,"error",()=>{o!==this.#u||this.#b||(this.#s.lastError="Discord Gateway WebSocket error")})})}#M(t){t?.id&&this.#D.set(String(t.id),t)}async#L(t,o){let i=String(t?.id??"");if(!i||this.#r.hasSeen(i))return;let e=this.#w.get(i);if(!e){let a=Xr(this.#g,t.guild_id?"group":"direct"),A=iue(t,this.#e.platformId,{api:this.#c,channel:this.#D.get(String(t.channel_id)),signal:this.#d?.signal,onChannel:r=>this.#M(r)});e={pendingRoute:A,contextSnapshot:a},this.#w.set(i,e),A.finally(()=>{this.#w.get(i)===e&&this.#w.delete(i)}).catch(()=>{})}try{let a=await e.pendingRoute;a&&await o.accept(a,{contextSnapshot:e.contextSnapshot})}catch(a){throw a?.code==="discord-thread-create-uncertain"&&await this.#r.markSeen(i),a}}#_(t,o){t.readyState===1&&t.send(JSON.stringify(o))}#U(t,o,i){if(this.#P(),!Number.isFinite(t)||t<1e3){o.close(4e3,"Invalid heartbeat interval");return}this.#S=!0;let e=a=>{this.#y=setTimeout(()=>{if(!(this.#b||i!==this.#u||this.#h!==o)){if(!this.#S){o.close(4e3,"Heartbeat was not acknowledged");return}this.#v(o),e(t)}},a),this.#y?.unref?.()};e(Math.floor(t*this.#o()))}#v(t){this.#S=!1,this.#_(t,{op:1,d:this.#B})}#P(){this.#y!==null&&clearTimeout(this.#y),this.#y=null,this.#S=!0}#N(){if(this.#b||this.#Q!==null)return;let t=E1[Math.min(this.#m,E1.length-1)];this.#m+=1,this.#Q=setTimeout(()=>{this.#Q=null,this.#k(!!this.#f).catch(o=>{this.#b||(this.#a.warn?.("[dsh-im:discord] Gateway reconnect failed:",o),this.#N())})},t),this.#Q?.unref?.()}async stop(){this.#b=!0,this.#u+=1,this.#d?.abort(),this.#d=null,this.#Q!==null&&clearTimeout(this.#Q),this.#Q=null,this.#P();let t=this.#h,o=this.#p;this.#h=null,this.#p=null,this.#c=null,this.#w.clear();try{t&&t.readyState<2&&t.close(1e3,"Plugin stopped")}catch(i){this.#a.warn?.(`[dsh-im:discord] bot ${this.#e.botId} failed to close Gateway:`,i)}return await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#s.ready=!1,this.#s.connectionState="idle",this.status}};import{mkdir as nue,readFile as sue,rename as gue,unlink as cue,writeFile as Iue}from"node:fs/promises";import{dirname as lue}from"node:path";var UQ=Object.freeze({version:1,sessions:{},seenMessageIds:[],cursor:null});function pue(n){if(!n||typeof n!="object")return structuredClone(UQ);let t={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&o&&typeof i=="string"&&i&&(t[o]=i);return{version:1,sessions:t,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string"&&o).slice(-1e3):[],cursor:Number.isSafeInteger(n.cursor)&&n.cursor>=0?n.cursor:null}}var As=class{#e;#A=structuredClone(UQ);#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{this.#A=pue(JSON.parse(await sue(this.#e,"utf8")))}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=structuredClone(UQ),await this.#r()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){this.#A.sessions[t]=o,await this.#r()}async clearSession(t){delete this.#A.sessions[t],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(t){return this.#A.seenMessageIds.includes(t)}async markSeen(t){this.hasSeen(t)||(this.#A.seenMessageIds.push(t),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}cursor(){return this.#A.cursor}async setCursor(t){if(!Number.isSafeInteger(t)||t<0)throw new TypeError("Invalid update cursor");this.#A.cursor=t,await this.#r()}snapshot(){return structuredClone(this.#A)}async remove(){try{await cue(this.#e)}catch(t){if(t?.code!=="ENOENT")throw t}this.#A=structuredClone(UQ)}async#r(){let t=`${JSON.stringify(this.#A,null,2)} -`,o=this.#t.then(async()=>{await nue(lue(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await Iue(i,t,{encoding:"utf8",mode:384}),await gue(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var HQ=class extends As{};import{unlink as hue}from"node:fs/promises";import{homedir as Eue}from"node:os";import{join as zE,resolve as TI}from"node:path";var S1=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function due(n){if(!Array.isArray(n)||n.length===0)return[...S1];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...S1]}var R_=class{#e;#A;#t;#r;#g;#a;#n;#i;#I=null;#l=null;#o=0;#s=!1;#c=!1;#p;#d;constructor({channel:t,controller:o,harness:i,logger:e=console,retryDelaysMs:a,healthyIntervalMs:A=15e3,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:s=clearTimeout}){if(!t)throw new TypeError("TokenConnectionSupervisor requires a channel");if(!o||typeof o.initialize!="function"||typeof o.status!="function")throw new TypeError("TokenConnectionSupervisor requires a controller");if(!i||typeof i.ensureRunning!="function")throw new TypeError("TokenConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=due(a),this.#a=Number.isFinite(A)&&A>=0?A:15e3,this.#n=r,this.#i=s,this.#p=new Promise(g=>{this.#d=g})}get ready(){return this.#p}start(){return this.#c||this.#s?this:(this.#c=!0,this.#h(0),this)}async close(){this.#s||(this.#s=!0,this.#I!==null&&this.#i(this.#I),this.#I=null,await this.#l?.catch(()=>{}),this.#d?.(null),this.#d=null)}#h(t){this.#s||(this.#I=this.#n(()=>{this.#I=null,this.#E()},t),this.#I?.unref?.())}async#E(){if(this.#s||this.#l)return;let t=this.#C();this.#l=t;try{await t}finally{this.#l===t&&(this.#l=null)}}async#C(){try{if(await this.#t.ensureRunning(),this.#s)return;let t=await this.#A.initialize();if(this.#s)return;this.#d?.(t),this.#d=null;let{configured:o,connected:i}=t.totals;if(iRa(n),F=k_(t,e),K=await new d(F.config).load(),L=TI(t.workspace??process.cwd()),q=o.WorkspaceStore??ea,z=o.workspaces??await new q(F.workspaces,{defaultWorkspace:L}).load(),j=K.list();await z.reconcile(j.map(Qe=>Qe.botId)),await Promise.all(j.map(Qe=>z.ensure(Qe.botId,{defaultAgentPreset:t.agentPreset})));let P=typeof K.remove=="function"?Pa(K,{workspaces:z}):K,J=new Map,U=Qe=>TI(F.bots,Qe,"state.json"),N=async Qe=>{let Le=J.get(Qe);return Le||(Le=await new B(U(Qe)).load(),J.set(Qe,Le)),Le},k=Ua(n,o.commandExecutor),{controlExecutor:V,sessionMaintenanceExecutor:Ae,fileIngressExecutor:ie}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),De=new f({...I,workspace:L,autostart:!1,dshBin:t.dshBin??"dsh",...k?{commandExecutor:k}:{},...V?{controlExecutor:V}:{},...Ae?{sessionMaintenanceExecutor:Ae}:{},...ie?{fileIngressExecutor:ie}:{}}),fe=new Q({credentials:n.credentials,configStore:P,logger:T,...o.inspectToken?{inspectToken:o.inspectToken}:{},createRuntime:async({botId:Qe,config:Le,token:AA})=>{let aA=await N(Qe);await z.ensure(Qe,{defaultAgentPreset:t.agentPreset});let He=Ga(De,{botId:Qe,workspaces:z,state:aA,agentPresetCatalog:R});return new y({...m,config:Le,token:AA,harness:He.harness,state:He.state,contextEnhancement:{botId:Qe,getSettings:()=>z.contextEnhancementFor(Qe)},replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??2e4,logger:{error:(...ce)=>T.error?.(`[${Qe}]`,...ce),warn:(...ce)=>T.warn?.(`[${Qe}]`,...ce),info:(...ce)=>T.info?.(`[${Qe}]`,...ce),debug:(...ce)=>T.debug?.(`[${Qe}]`,...ce)}})},deleteState:async({botId:Qe})=>{let Le=J.get(Qe);if(J.delete(Qe),Le&&typeof Le.remove=="function")await Le.remove();else try{await hue(U(Qe))}catch(AA){if(AA?.code!=="ENOENT")throw AA}}}),_e=Fa(fe,{workspaces:z,stateFor:N,agentPresetCatalog:R}),Ee=_({channel:e,controller:_e,harness:De,logger:T,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:_e,...bQ(e)?{deliveryAdapter:La({channel:e,workspaces:z,coreController:fe,stateFor:N})}:{},ready:Ee.ready,async close(){await Ee.close(),await _e.close(),De.stopManagedProcess()}}}function v_(n,t={},o={}){return KQ(n,t,o,{channel:"discord",ConfigStore:vQ,StateStore:HQ,HarnessClient:FQ,Controller:JE,Runtime:qE})}var ta=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),Cue=Object.freeze(Object.values(ta)),uue=new Set(["token","botToken","tokenRef","platformId","secret","secretRef"]),Bue=new Set(["telegram-transport-error","telegram-timeout","telegram-response-invalid"]);function G_(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function xQ(n,t){return G_(n)&&Object.keys(n).every(o=>t.includes(o))}function w1(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function fue(n){return typeof n=="string"&&n.trim().length>=20&&n.length<=4096}function Que(n,t){return G_(t)?n===ta.status?xQ(t,[])?null:"connection.status does not accept fields.":n===ta.bindCredentials?xQ(t,["token"])&&fue(t.token)?null:"bot.bind-credentials requires a Bot Token.":n===ta.reconnectBot?xQ(t,["botId","sendTest"])&&w1(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId.":n===ta.deleteBot?xQ(t,["botId","confirm"])&&w1(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===ta.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===ta.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===ta.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown bot endpoint.":"Payload must be an object."}function P_(n){if(Array.isArray(n))return n.map(P_);if(!G_(n))return n;let t={};for(let[o,i]of Object.entries(n))uue.has(o)||(t[o]=P_(i));return t}function yue(n,t){let o=Ya(t);return o||(t?.code==="webhook-configured"?{code:"webhook-configured",message:t.message}:t?.code==="telegram-401"||t?.code==="discord-401"?{code:"invalid-token",message:`${n} Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002`}:n==="Telegram"&&Bue.has(t?.code)?{code:"telegram-network-error",message:"\u65E0\u6CD5\u8BBF\u95EE Telegram Bot API\u3002\u8BF7\u68C0\u67E5\u7F51\u7EDC\u6216\u4EE3\u7406\u8BBE\u7F6E\uFF1BNode.js 22.21+ \u53EF\u8BBE\u7F6E NODE_USE_ENV_PROXY=1\uFF0C\u5E76\u914D\u7F6E HTTPS_PROXY\u3001HTTP_PROXY \u548C NO_PROXY\uFF0C\u7136\u540E\u91CD\u542F dsh web\u3002"}:t?.code==="discord-intents"?{code:"discord-intents",message:t.message}:{code:`${n.toLowerCase()}-operation-failed`,message:`${n} \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`})}function YQ(n,{channel:t}){for(let o of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[o]!="function")throw new TypeError(`A complete ${t} controller is required (${o})`);return async(o,i,e)=>{if(e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!Cue.includes(o))return{ok:!1,error:{code:"bad-request",message:`Unknown ${t} endpoint.`}};let a=Que(o,i);if(a)return{ok:!1,error:{code:"bad-request",message:a}};try{let A;if(o===ta.status)A=await n.status();else if(o===ta.bindCredentials)A=await n.bindCredentials(i);else if(o===ta.reconnectBot){if(A=await n.reconnectBot(i.botId),e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(i.sendTest===!0){let r=null;try{if(A?.bots?.find(s=>s?.botId===i.botId)?.connected!==!0){let s=new Error("Bot is not connected");throw s.code="test-target-unavailable",s}if(typeof n.sendConnectionTest!="function"){let s=new Error("Connection test is unavailable");throw s.code="test-target-unavailable",s}await n.sendConnectionTest(i.botId)}catch(s){r=s}A={...A,testMessage:ir(r)}}}else if(o===ta.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");A=await n.updateWorkspace(i.botId,i.workspace)}else if(o===ta.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");A=await n.updateContextEnhancement(i.botId,i.config)}else if(o===ta.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");A=await n.updateAgentPreset(i.botId,i.agentPreset)}else A=await n.deleteBot(i.botId);return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:P_(A)}}catch(A){return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:yue(t,A)}}}}function D1(n,t,{channel:o,rpcChannel:i,authority:e}){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(i,YQ(t,{channel:o}),{authority:hr(e)})}var O1="/discord",b1=ta,mue=Object.freeze(Object.values(b1));function jQ(n,t,o){return D1(n,t,{channel:"Discord",rpcChannel:O1,authority:o})}async function M1(n,t={}){if(t?.controller)return jQ(n,t.controller,t.rpcAuthority);let o=await v_(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=jQ(n,o.controller,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Discord bot connections"),e}import{homedir as jue}from"node:os";import{join as H_,resolve as K_}from"node:path";import{mkdir as Sue,readFile as wue,rename as Due,unlink as Oue,writeFile as bue}from"node:fs/promises";import{dirname as Mue,isAbsolute as _ue}from"node:path";var Pp="office-harness.v1",_1="/office",Gp=Object.freeze({status:"connection.status",configure:"connector.configure",reconnect:"connector.reconnect",test:"connector.test",remove:"connector.remove"}),hn=Object.freeze({stream:"/api/harness/connector/stream",heartbeat:"/api/harness/connector/heartbeat",job:"/api/harness/connector/jobs/:id",accept:"/api/harness/connector/jobs/:id/accept",renew:"/api/harness/connector/jobs/:id/renew",progress:"/api/harness/connector/jobs/:id/progress",approval:"/api/harness/connector/jobs/:id/approval",result:"/api/harness/connector/jobs/:id/result",fail:"/api/harness/connector/jobs/:id/fail"});function VE(n){let t=new URL(typeof n=="string"?n.trim():""),o=t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname);if(t.protocol!=="https:"&&!o)throw new TypeError("AI Office URL must use HTTPS (HTTP is allowed only for loopback testing)");if(t.username||t.password||t.search||t.hash)throw new TypeError("AI Office URL must be a bare origin");return t.pathname="/",t}function JQ(n){let t=VE(n);return Object.fromEntries(Object.entries(hn).map(([o,i])=>[o,new URL(i,t).toString()]))}var Tue=/^[a-z][a-z0-9-]{1,63}$/,Nue=/^[a-z0-9][a-z0-9_-]{2,63}$/i;function Fp(n){return typeof n=="string"&&n.trim()?n.trim():null}function T1(n,{kind:t}){if(!n||typeof n!="object"||Array.isArray(n))return null;let o={};for(let[i,e]of Object.entries(n)){let a=Fp(i),A=Fp(e);if(!a||!Tue.test(a)||!A||t==="workspace"&&!_ue(A)||t==="preset"&&A.length>8e3)return null;o[a]=A}return Object.freeze(o)}function qQ(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let t;try{t=VE(n.baseUrl).origin}catch{return null}let o=Fp(n.deviceId),i=Fp(n.deviceTokenRef),e=T1(n.workspaces??{},{kind:"workspace"}),a=T1(n.instructionPresets??{},{kind:"preset"}),A=Number(n.maxConcurrency??1),r=Number(n.heartbeatSeconds??30);return!o||!Nue.test(o)||!i||!/^DSH_OFFICE_DEVICE_TOKEN_[A-F0-9]{24}$/.test(i)||!e||!a||!Number.isInteger(A)||A<1||A>4||!Number.isInteger(r)||r<10||r>300?null:Object.freeze({version:1,protocolVersion:Pp,baseUrl:t,deviceId:o,deviceTokenRef:i,maxConcurrency:A,heartbeatSeconds:r,workspaces:e,instructionPresets:a,createdAt:Fp(n.createdAt)??new Date().toISOString(),updatedAt:Fp(n.updatedAt)??new Date().toISOString()})}var zQ=class{#e;#A=null;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=qQ(JSON.parse(await wue(this.#e,"utf8")));if(!t)throw new Error("dsh-im AI Office config is invalid");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=null}return this}get(){return this.#A?structuredClone(this.#A):null}async save(t){let o=qQ(t);if(!o)throw new Error("Refusing to persist invalid AI Office configuration");let i=this.#t.then(async()=>{await Sue(Mue(this.#e),{recursive:!0,mode:448});let e=`${this.#e}.tmp`;await bue(e,`${JSON.stringify(o,null,2)} +`,o=this.#t.then(async()=>{await nue(lue(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await Iue(i,t,{encoding:"utf8",mode:384}),await gue(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var HQ=class extends As{};import{unlink as hue}from"node:fs/promises";import{homedir as Eue}from"node:os";import{join as zE,resolve as TI}from"node:path";var S1=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function due(n){if(!Array.isArray(n)||n.length===0)return[...S1];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...S1]}var R_=class{#e;#A;#t;#r;#g;#a;#n;#i;#I=null;#l=null;#o=0;#s=!1;#c=!1;#p;#d;constructor({channel:t,controller:o,harness:i,logger:e=console,retryDelaysMs:a,healthyIntervalMs:A=15e3,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:s=clearTimeout}){if(!t)throw new TypeError("TokenConnectionSupervisor requires a channel");if(!o||typeof o.initialize!="function"||typeof o.status!="function")throw new TypeError("TokenConnectionSupervisor requires a controller");if(!i||typeof i.ensureRunning!="function")throw new TypeError("TokenConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=due(a),this.#a=Number.isFinite(A)&&A>=0?A:15e3,this.#n=r,this.#i=s,this.#p=new Promise(g=>{this.#d=g})}get ready(){return this.#p}start(){return this.#c||this.#s?this:(this.#c=!0,this.#h(0),this)}async close(){this.#s||(this.#s=!0,this.#I!==null&&this.#i(this.#I),this.#I=null,await this.#l?.catch(()=>{}),this.#d?.(null),this.#d=null)}#h(t){this.#s||(this.#I=this.#n(()=>{this.#I=null,this.#E()},t),this.#I?.unref?.())}async#E(){if(this.#s||this.#l)return;let t=this.#C();this.#l=t;try{await t}finally{this.#l===t&&(this.#l=null)}}async#C(){try{if(await this.#t.ensureRunning(),this.#s)return;let t=await this.#A.initialize();if(this.#s)return;this.#d?.(t),this.#d=null;let{configured:o,connected:i}=t.totals;if(iRa(n),L=k_(t,e),U=await new d(L.config).load(),F=TI(t.workspace??process.cwd()),q=o.WorkspaceStore??ea,z=o.workspaces??await new q(L.workspaces,{defaultWorkspace:F}).load(),j=U.list();await z.reconcile(j.map(Qe=>Qe.botId)),await Promise.all(j.map(Qe=>z.ensure(Qe.botId,{defaultAgentPreset:t.agentPreset})));let P=typeof U.remove=="function"?Pa(U,{workspaces:z}):U,J=new Map,H=Qe=>TI(L.bots,Qe,"state.json"),N=async Qe=>{let Le=J.get(Qe);return Le||(Le=await new B(H(Qe)).load(),J.set(Qe,Le)),Le},k=Ua(n,o.commandExecutor),{controlExecutor:V,sessionMaintenanceExecutor:Ae,fileIngressExecutor:ie}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),De=new f({...I,workspace:F,autostart:!1,dshBin:t.dshBin??"dsh",...k?{commandExecutor:k}:{},...V?{controlExecutor:V}:{},...Ae?{sessionMaintenanceExecutor:Ae}:{},...ie?{fileIngressExecutor:ie}:{}}),fe=new Q({credentials:n.credentials,configStore:P,logger:T,...o.inspectToken?{inspectToken:o.inspectToken}:{},createRuntime:async({botId:Qe,config:Le,token:AA})=>{let aA=await N(Qe);await z.ensure(Qe,{defaultAgentPreset:t.agentPreset});let He=Ga(De,{botId:Qe,workspaces:z,state:aA,agentPresetCatalog:R});return new y({...m,config:Le,token:AA,harness:He.harness,state:He.state,contextEnhancement:{botId:Qe,getSettings:()=>z.contextEnhancementFor(Qe)},replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??2e4,logger:{error:(...ce)=>T.error?.(`[${Qe}]`,...ce),warn:(...ce)=>T.warn?.(`[${Qe}]`,...ce),info:(...ce)=>T.info?.(`[${Qe}]`,...ce),debug:(...ce)=>T.debug?.(`[${Qe}]`,...ce)}})},deleteState:async({botId:Qe})=>{let Le=J.get(Qe);if(J.delete(Qe),Le&&typeof Le.remove=="function")await Le.remove();else try{await hue(H(Qe))}catch(AA){if(AA?.code!=="ENOENT")throw AA}}}),_e=Fa(fe,{workspaces:z,stateFor:N,agentPresetCatalog:R}),Ee=_({channel:e,controller:_e,harness:De,logger:T,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:_e,...bQ(e)?{deliveryAdapter:La({channel:e,workspaces:z,coreController:fe,stateFor:N})}:{},ready:Ee.ready,async close(){await Ee.close(),await _e.close(),De.stopManagedProcess()}}}function v_(n,t={},o={}){return KQ(n,t,o,{channel:"discord",ConfigStore:vQ,StateStore:HQ,HarnessClient:FQ,Controller:JE,Runtime:qE})}var ta=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),Cue=Object.freeze(Object.values(ta)),uue=new Set(["token","botToken","tokenRef","platformId","secret","secretRef"]),Bue=new Set(["telegram-transport-error","telegram-timeout","telegram-response-invalid"]);function G_(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function xQ(n,t){return G_(n)&&Object.keys(n).every(o=>t.includes(o))}function w1(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function fue(n){return typeof n=="string"&&n.trim().length>=20&&n.length<=4096}function Que(n,t){return G_(t)?n===ta.status?xQ(t,[])?null:"connection.status does not accept fields.":n===ta.bindCredentials?xQ(t,["token"])&&fue(t.token)?null:"bot.bind-credentials requires a Bot Token.":n===ta.reconnectBot?xQ(t,["botId","sendTest"])&&w1(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId.":n===ta.deleteBot?xQ(t,["botId","confirm"])&&w1(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===ta.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===ta.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===ta.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown bot endpoint.":"Payload must be an object."}function P_(n){if(Array.isArray(n))return n.map(P_);if(!G_(n))return n;let t={};for(let[o,i]of Object.entries(n))uue.has(o)||(t[o]=P_(i));return t}function yue(n,t){let o=Ya(t);return o||(t?.code==="webhook-configured"?{code:"webhook-configured",message:t.message}:t?.code==="telegram-401"||t?.code==="discord-401"?{code:"invalid-token",message:`${n} Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002`}:n==="Telegram"&&Bue.has(t?.code)?{code:"telegram-network-error",message:"\u65E0\u6CD5\u8BBF\u95EE Telegram Bot API\u3002\u8BF7\u68C0\u67E5\u7F51\u7EDC\u6216\u4EE3\u7406\u8BBE\u7F6E\uFF1BNode.js 22.21+ \u53EF\u8BBE\u7F6E NODE_USE_ENV_PROXY=1\uFF0C\u5E76\u914D\u7F6E HTTPS_PROXY\u3001HTTP_PROXY \u548C NO_PROXY\uFF0C\u7136\u540E\u91CD\u542F dsh web\u3002"}:t?.code==="discord-intents"?{code:"discord-intents",message:t.message}:{code:`${n.toLowerCase()}-operation-failed`,message:`${n} \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`})}function YQ(n,{channel:t}){for(let o of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[o]!="function")throw new TypeError(`A complete ${t} controller is required (${o})`);return async(o,i,e)=>{if(e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!Cue.includes(o))return{ok:!1,error:{code:"bad-request",message:`Unknown ${t} endpoint.`}};let a=Que(o,i);if(a)return{ok:!1,error:{code:"bad-request",message:a}};try{let A;if(o===ta.status)A=await n.status();else if(o===ta.bindCredentials)A=await n.bindCredentials(i);else if(o===ta.reconnectBot){if(A=await n.reconnectBot(i.botId),e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(i.sendTest===!0){let r=null;try{if(A?.bots?.find(s=>s?.botId===i.botId)?.connected!==!0){let s=new Error("Bot is not connected");throw s.code="test-target-unavailable",s}if(typeof n.sendConnectionTest!="function"){let s=new Error("Connection test is unavailable");throw s.code="test-target-unavailable",s}await n.sendConnectionTest(i.botId)}catch(s){r=s}A={...A,testMessage:ir(r)}}}else if(o===ta.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");A=await n.updateWorkspace(i.botId,i.workspace)}else if(o===ta.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");A=await n.updateContextEnhancement(i.botId,i.config)}else if(o===ta.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");A=await n.updateAgentPreset(i.botId,i.agentPreset)}else A=await n.deleteBot(i.botId);return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:P_(A)}}catch(A){return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:yue(t,A)}}}}function D1(n,t,{channel:o,rpcChannel:i,authority:e}){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(i,YQ(t,{channel:o}),{authority:hr(e)})}var O1="/discord",b1=ta,mue=Object.freeze(Object.values(b1));function jQ(n,t,o){return D1(n,t,{channel:"Discord",rpcChannel:O1,authority:o})}async function M1(n,t={}){if(t?.controller)return jQ(n,t.controller,t.rpcAuthority);let o=await v_(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=jQ(n,o.controller,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Discord bot connections"),e}import{homedir as jue}from"node:os";import{join as H_,resolve as K_}from"node:path";import{mkdir as Sue,readFile as wue,rename as Due,unlink as Oue,writeFile as bue}from"node:fs/promises";import{dirname as Mue,isAbsolute as _ue}from"node:path";var Pp="office-harness.v1",_1="/office",Gp=Object.freeze({status:"connection.status",configure:"connector.configure",reconnect:"connector.reconnect",test:"connector.test",remove:"connector.remove"}),hn=Object.freeze({stream:"/api/harness/connector/stream",heartbeat:"/api/harness/connector/heartbeat",job:"/api/harness/connector/jobs/:id",accept:"/api/harness/connector/jobs/:id/accept",renew:"/api/harness/connector/jobs/:id/renew",progress:"/api/harness/connector/jobs/:id/progress",approval:"/api/harness/connector/jobs/:id/approval",result:"/api/harness/connector/jobs/:id/result",fail:"/api/harness/connector/jobs/:id/fail"});function VE(n){let t=new URL(typeof n=="string"?n.trim():""),o=t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname);if(t.protocol!=="https:"&&!o)throw new TypeError("AI Office URL must use HTTPS (HTTP is allowed only for loopback testing)");if(t.username||t.password||t.search||t.hash)throw new TypeError("AI Office URL must be a bare origin");return t.pathname="/",t}function JQ(n){let t=VE(n);return Object.fromEntries(Object.entries(hn).map(([o,i])=>[o,new URL(i,t).toString()]))}var Tue=/^[a-z][a-z0-9-]{1,63}$/,Nue=/^[a-z0-9][a-z0-9_-]{2,63}$/i;function Fp(n){return typeof n=="string"&&n.trim()?n.trim():null}function T1(n,{kind:t}){if(!n||typeof n!="object"||Array.isArray(n))return null;let o={};for(let[i,e]of Object.entries(n)){let a=Fp(i),A=Fp(e);if(!a||!Tue.test(a)||!A||t==="workspace"&&!_ue(A)||t==="preset"&&A.length>8e3)return null;o[a]=A}return Object.freeze(o)}function qQ(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let t;try{t=VE(n.baseUrl).origin}catch{return null}let o=Fp(n.deviceId),i=Fp(n.deviceTokenRef),e=T1(n.workspaces??{},{kind:"workspace"}),a=T1(n.instructionPresets??{},{kind:"preset"}),A=Number(n.maxConcurrency??1),r=Number(n.heartbeatSeconds??30);return!o||!Nue.test(o)||!i||!/^DSH_OFFICE_DEVICE_TOKEN_[A-F0-9]{24}$/.test(i)||!e||!a||!Number.isInteger(A)||A<1||A>4||!Number.isInteger(r)||r<10||r>300?null:Object.freeze({version:1,protocolVersion:Pp,baseUrl:t,deviceId:o,deviceTokenRef:i,maxConcurrency:A,heartbeatSeconds:r,workspaces:e,instructionPresets:a,createdAt:Fp(n.createdAt)??new Date().toISOString(),updatedAt:Fp(n.updatedAt)??new Date().toISOString()})}var zQ=class{#e;#A=null;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=qQ(JSON.parse(await wue(this.#e,"utf8")));if(!t)throw new Error("dsh-im AI Office config is invalid");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=null}return this}get(){return this.#A?structuredClone(this.#A):null}async save(t){let o=qQ(t);if(!o)throw new Error("Refusing to persist invalid AI Office configuration");let i=this.#t.then(async()=>{await Sue(Mue(this.#e),{recursive:!0,mode:448});let e=`${this.#e}.tmp`;await bue(e,`${JSON.stringify(o,null,2)} `,{mode:384}),await Due(e,this.#e),this.#A=o});return this.#t=i.then(()=>{},()=>{}),await i,this.get()}async clear(){let t=this.#t.then(async()=>{try{await Oue(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=null});this.#t=t.then(()=>{},()=>{}),await t}};import{createHash as xue}from"node:crypto";import{setTimeout as Hue}from"node:timers/promises";function F_(n,t){let o=new Error(`AI Office ${n} failed: HTTP ${t.status}`);return o.code=t.status===401?"invalid-device-token":t.status===404?"office-hook-unavailable":t.status===409?"office-job-conflict":"office-transport-failed",o}function Lp(n,t="office-transport-failed",o){let i=new Error(n,o===void 0?void 0:{cause:o});return i.code=t,i}function L_(n,t){return t?.aborted||n?.name==="AbortError"}function Rue(n){let t="message",o,i=[];for(let a of n.split(/\r?\n/))a.startsWith("event:")?t=a.slice(6).trim()||"message":a.startsWith("id:")?o=a.slice(3).trim()||void 0:a.startsWith("data:")&&i.push(a.slice(5).trimStart());if(i.length===0)return null;let e;try{e=JSON.parse(i.join(` `))}catch{throw new Error("AI Office SSE returned invalid JSON")}return{id:o,type:typeof e?.type=="string"?e.type:t,data:e}}var VQ=class{#e;#A;#t;#r;constructor({baseUrl:t,deviceId:o,token:i,fetchImpl:e=fetch}){this.#e=t,this.#A=o,this.#t=i,this.#r=e}hooks(){return JQ(this.#e)}#g(t={}){return{authorization:`Bearer ${this.#t}`,"x-harness-device-id":this.#A,...t}}async heartbeat(t,{signal:o}={}){let i;try{i=await this.#r(new URL(hn.heartbeat,this.#e),{method:"POST",headers:this.#g({accept:"application/json","content-type":"application/json"}),body:JSON.stringify(t),signal:o,redirect:"error"})}catch(a){throw L_(a,o)?a:Lp("AI Office heartbeat request could not be completed",void 0,a)}if(!i.ok)throw F_("heartbeat",i);let e;try{e=await i.json()}catch(a){throw Lp("AI Office heartbeat returned invalid JSON","office-protocol-mismatch",a)}if(!e||typeof e!="object"||e.ok!==!0||e.protocolVersion!==Pp)throw Lp("AI Office heartbeat protocol does not match","office-protocol-mismatch");return e}async#a(t,{method:o="POST",body:i,leaseToken:e,signal:a}={}){let A=this.#g({accept:"application/json"});i!==void 0&&(A["content-type"]="application/json"),e&&(A["x-harness-lease-token"]=e);let r;try{r=await this.#r(new URL(t,this.#e),{method:o,headers:A,...i===void 0?{}:{body:JSON.stringify(i)},signal:a,redirect:"error",cache:"no-store"})}catch(s){throw L_(s,a)?s:Lp("AI Office Job request could not be completed",void 0,s)}if(!r.ok)throw F_("Job request",r);try{return await r.json()}catch(s){throw Lp("AI Office Job returned invalid JSON","office-protocol-mismatch",s)}}async getJob(t,o={}){return this.#a(hn.job.replace(":id",t),{...o,method:"GET"})}async acceptJob(t,o={}){return this.#a(hn.accept.replace(":id",t),o)}async renewJob(t,o,i={}){return this.#a(hn.renew.replace(":id",t),{...i,leaseToken:o})}async progressJob(t,o,i,e={}){return this.#a(hn.progress.replace(":id",t),{...e,leaseToken:o,body:i})}async requestApproval(t,o,i,e={}){return this.#a(hn.approval.replace(":id",t),{...e,leaseToken:o,body:i})}async completeJob(t,o,i,e={}){return this.#a(hn.result.replace(":id",t),{...e,leaseToken:o,body:i})}async failJob(t,o,i,e={}){return this.#a(hn.fail.replace(":id",t),{...e,leaseToken:o,body:i})}async stream({signal:t,lastEventId:o,onOpen:i,onEvent:e}){let a=this.#g({accept:"text/event-stream"});o&&(a["last-event-id"]=o);let A;try{A=await this.#r(new URL(hn.stream,this.#e),{method:"GET",headers:a,signal:t,redirect:"error",cache:"no-store"})}catch(c){throw L_(c,t)?c:Lp("AI Office SSE request could not be completed",void 0,c)}if(!A.ok)throw F_("stream",A);if(!A.headers.get("content-type")?.toLowerCase().includes("text/event-stream"))throw new Error("AI Office stream did not return text/event-stream");if(!A.body)throw new Error("AI Office stream returned no body");i?.();let r=A.body.getReader(),s=new TextDecoder,g="";for(;;){let{value:c,done:I}=await r.read();if(I)break;g=`${g}${s.decode(c,{stream:!0})}`.replaceAll(`\r `,` @@ -327,8 +327,8 @@ ${a}`:a;return LQ({limit:o?1800:1900,create:async a=>{let A=await this.#e.create `),questions:o}}function Uue(n,t){return new Promise((o,i)=>{if(n.controller.signal.aborted)return i(n.controller.signal.reason??Up());let e=()=>{n.approvals.delete(t),i(n.controller.signal.reason??Up())};n.controller.signal.addEventListener("abort",e,{once:!0}),n.approvals.set(t,{resolve(a){n.controller.signal.removeEventListener("abort",e),n.approvals.delete(t),o(a)}})})}var WQ=class{#e;#A;#t;#r;#g;#a=new Map;#n=new Set;#i=new Set;#I=!1;#l={running:0,completed:0,failed:0,lastJobId:null,lastJobAt:null};constructor({config:t,transport:o,createHarness:i,logger:e=console,sleepImpl:a=kue}){if(!t||!o||typeof i!="function")throw new TypeError("OfficeJobExecutor requires config, transport, and createHarness");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a}get status(){return structuredClone(this.#l)}offer(t){return this.#I||!N1.test(t)||this.#a.has(t)||this.#n.has(t)||this.#i.has(t)?!1:(this.#n.add(t),this.#o(),!0)}handleEvent(t){let o=qa(t?.data?.jobId,80);if(!N1.test(o))return!1;if(t.type==="job.available")return this.offer(o);if(t.type==="job.cancel")return this.cancel(o);if(t.type==="approval.reply"){let i=this.#a.get(o),e=qa(t.data?.approvalId,180),a=i?.approvals.get(e);return a?(a.resolve({decision:t.data?.decision==="approved"?"approved":"rejected",answer:qa(t.data?.answer)}),!0):!1}return!1}cancel(t){this.#n.delete(t);let o=this.#a.get(t);return o?(o.cancelled=!0,o.controller.abort(Up()),o.sessionId&&o.harness&&o.harness.rpc("session.cancel",{sessionId:o.sessionId,keepInbox:!0},1e4).catch(()=>{}),!0):!1}async close(){this.#I=!0,this.#n.clear();for(let t of this.#a.values())t.controller.abort(Up());await Promise.allSettled([...this.#a.values()].map(t=>t.task))}#o(){for(;!this.#I&&this.#a.size0;){let t=this.#n.values().next().value;this.#n.delete(t);let o={controller:new AbortController,approvals:new Map,harness:null,sessionId:null,leaseToken:null,cancelled:!1,lastProgressAt:0,lastProgress:"",task:null};o.task=this.#s(t,o).finally(()=>{this.#a.delete(t),this.#l.running=this.#a.size,this.#o()}),this.#a.set(t,o),this.#l.running=this.#a.size,o.task.catch(i=>this.#r.warn?.("[dsh-im:office] Job task ended:",i.message))}}async#s(t,o){let i=o.controller.signal,e=null;try{let A=(await this.#A.getJob(t,{signal:i}))?.job;if(!A||A.id!==t)throw new Error("Office returned an invalid Job payload");let r=await this.#A.acceptJob(t,{signal:i});if(!qa(r?.leaseToken,200))throw new Error("Office returned an invalid Job lease");o.leaseToken=r.leaseToken,e=this.#c(t,o);let s=this.#e.workspaces[A.workspaceAlias],g=this.#e.instructionPresets[A.instructionPreset];if(!s||!g){let I=new Error(w("Office Job \u5F15\u7528\u4E86\u672C\u673A\u672A\u914D\u7F6E\u7684 Workspace/Preset alias\u3002"));throw I.code="office-job-alias-invalid",I}o.harness=this.#t({workspace:s}),await this.#d(t,o,{kind:"status",message:w("\u5DF2\u9886\u53D6 Job\uFF0C\u51C6\u5907 Workspace alias\uFF1A{alias}",{alias:A.workspaceAlias})},!0),o.sessionId=await o.harness.createSession({signal:i,workspace:s}),await this.#d(t,o,{kind:"status",message:w("Harness Session \u5DF2\u521B\u5EFA\u3002"),sessionId:o.sessionId},!0);let c=await o.harness.ask(o.sessionId,Fue(A,g),{timeoutMs:30*6e4,signal:i,onUpdate:I=>this.#p(t,o,I),onInteraction:I=>this.#h(t,o,I),onInteractionResolved:I=>{let d=qa(I?.interactionId,180);o.approvals.get(d)?.resolve({decision:"rejected",answer:""})}});if(i.aborted)throw i.reason??Up();await this.#A.completeJob(t,o.leaseToken,{resultMarkdown:c,sessionId:o.sessionId},{signal:i}),this.#l.completed+=1,this.#E(t)}catch(a){if(!o.cancelled&&o.leaseToken&&(await this.#A.failJob(t,o.leaseToken,{error:Gue(a),...o.sessionId?{sessionId:o.sessionId}:{}}).catch(()=>{}),this.#l.failed+=1),a?.code==="office-job-conflict"||a?.code==="office-hook-unavailable"){this.#E(t);return}!o.cancelled&&!i.aborted&&this.#r.warn?.(`[dsh-im:office] Job ${t} failed:`,a.message)}finally{o.controller.abort(Up()),await e?.catch(()=>{}),this.#l.lastJobId=t,this.#l.lastJobAt=new Date().toISOString()}}async#c(t,o){for(;!o.controller.signal.aborted;){try{await this.#g(vue,void 0,{signal:o.controller.signal})}catch{return}try{await this.#A.renewJob(t,o.leaseToken,{signal:o.controller.signal})}catch(i){if(o.controller.signal.aborted)return;o.cancelled=!0,o.controller.abort(i),o.sessionId&&o.harness&&o.harness.rpc("session.cancel",{sessionId:o.sessionId,keepInbox:!0},1e4).catch(()=>{});return}try{let e=(await this.#A.getJob(t,{signal:o.controller.signal}))?.job?.approval;e&&(e.status==="approved"||e.status==="rejected")&&o.approvals.get(e.id)?.resolve({decision:e.status,answer:qa(e.answer)})}catch(i){if(o.controller.signal.aborted)return;this.#r.warn?.(`[dsh-im:office] Job ${t} approval poll failed; will retry after the next renewal:`,i.message)}}}async#p(t,o,i){let e=i?.type==="tool"?w("\u6B63\u5728\u4F7F\u7528 {tool}\u2026",{tool:qa(i.name,160)||w("Harness \u5DE5\u5177")}):qa(i?.text,4e3);if(!e)return;let a=`${i.type}:${e}`;if(a===o.lastProgress)return;let A=Date.now();i.type==="text"&&A-o.lastProgressAt<1e3||(o.lastProgress=a,o.lastProgressAt=A,await this.#d(t,o,{kind:i.type==="tool"?"tool":i.type==="text"?"text":"status",message:e,...o.sessionId?{sessionId:o.sessionId}:{}}))}#d(t,o,i,e=!1){let a=this.#A.progressJob(t,o.leaseToken,i,{signal:o.controller.signal});return e?a:a.catch(A=>{this.#r.debug?.("[dsh-im:office] ignored a progress delivery failure:",A.message)})}async#h(t,o,i){let e=Lue(i);if(!e){i?.kind==="approval"&&typeof i.respond=="function"&&await i.respond({ok:!0,value:{sessionId:i.sessionId,approvalId:i.payload?.approvalId,outcome:"rejected"}});return}let a=Uue(o,e.id);try{await this.#A.requestApproval(t,o.leaseToken,e,{signal:o.controller.signal});let A=await a;if(e.kind==="approval"){await i.respond({ok:!0,value:{sessionId:i.sessionId,approvalId:i.payload.approvalId,outcome:A.decision==="approved"?"allowed-once":"rejected"}});return}if(A.decision!=="approved"){await i.respond({ok:!1,error:{code:"cancelled",message:"The AI Office user rejected this question.",details:{}}});return}let r=qa(A.answer).split(/\r?\n/);await i.respond({ok:!0,value:{sessionId:i.sessionId,answer:{answers:e.questions.map((s,g)=>Ei(s,r[g]||r[0]||""))}}})}catch(A){throw o.approvals.delete(e.id),A}}#E(t){this.#i.add(t),!(this.#i.size<=Pue)&&this.#i.delete(this.#i.values().next().value)}};var R1=Object.freeze([1e3,3e3,1e4,3e4]);function Kue(n){let t=typeof n?.code=="string"?n.code:"office-connection-failed",o={"invalid-device-token":w("AI Office \u62D2\u7EDD\u4E86 Device Token\u3002"),"office-hook-unavailable":w("AI Office Connector Hook \u5C1A\u672A\u5C31\u7EEA\u3002"),"office-protocol-mismatch":w("AI Office Connector \u534F\u8BAE\u7248\u672C\u4E0D\u517C\u5BB9\u3002"),"office-transport-failed":w("\u672C\u673A\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE AI Office\u3002")};return{code:t,message:o[t]??w("AI Office \u8FDE\u63A5\u5DF2\u4E2D\u65AD\u3002")}}var Hp=class{#e;#A;#t;#r;#g;#a=null;#n=null;#i;#I;constructor({config:t,token:o,logger:i=console,transport:e,createHarness:a,jobExecutor:A,sleepImpl:r=Hue}){this.#e=t,this.#A=o,this.#t=i,this.#g=r,this.#r=e??new VQ({baseUrl:t.baseUrl,deviceId:t.deviceId,token:o}),this.#i={state:"idle",connected:!1,startedAt:null,lastHeartbeatAt:null,lastEventAt:null,lastEventId:null,lastEventType:null,reconnects:0,jobsOffered:0,error:null},this.#I=A??(a?new WQ({config:t,transport:this.#r,createHarness:a,logger:i}):null)}get status(){return structuredClone({...this.#i,...this.#I?{jobs:this.#I.status}:{}})}capabilities(){return{protocolVersion:Pp,deviceId:this.#e.deviceId,workspaces:Object.keys(this.#e.workspaces),instructionPresets:Object.keys(this.#e.instructionPresets),maxConcurrency:this.#e.maxConcurrency}}async testConnection(t){return await this.#r.heartbeat({...this.capabilities(),probe:!0},{signal:t}),{ok:!0}}start(){return this.#n?this.status:(this.#a=new AbortController,this.#i.startedAt=new Date().toISOString(),this.#i.state="connecting",this.#n=this.#l(this.#a.signal).finally(()=>{this.#n=null}),this.#n.catch(t=>{this.#a?.signal.aborted||this.#t.error?.("[dsh-im:office] connector stopped:",t)}),this.status)}async#l(t){let o=0;for(;!t.aborted;){let i=new AbortController,e=AbortSignal.any([t,i.signal]);try{let a=await this.#r.heartbeat(this.capabilities(),{signal:e});this.#s(a?.jobs),this.#i.lastHeartbeatAt=new Date().toISOString();let A=!1,r=this.#o(e,()=>{A&&!e.aborted&&(o=0)}),s=this.#r.stream({signal:e,lastEventId:this.#i.lastEventId,onOpen:()=>{this.#i.connected=!0,this.#i.state="connected",this.#i.error=null,A=!0},onEvent:async g=>{this.#i.lastEventAt=new Date().toISOString(),this.#i.lastEventId=g.id??this.#i.lastEventId,this.#i.lastEventType=g.type,g.type==="job.available"&&(this.#i.jobsOffered+=1),this.#I?.handleEvent(g)}});await Promise.race([s,r])}catch(a){if(t.aborted)break;i.abort(),this.#i.connected=!1,this.#i.state="reconnecting",this.#i.error=Kue(a),this.#i.reconnects+=1;let A=R1[Math.min(o,R1.length-1)];o+=1;try{await this.#g(A,void 0,{signal:t})}catch{break}}finally{i.abort()}}this.#i.connected=!1,this.#i.state="idle"}async#o(t,o){for(;!t.aborted;){await this.#g(this.#e.heartbeatSeconds*1e3,void 0,{signal:t});let i=await this.#r.heartbeat(this.capabilities(),{signal:t});this.#s(i?.jobs),this.#i.lastHeartbeatAt=new Date().toISOString(),o?.()}}#s(t){if(Array.isArray(t))for(let o of t)typeof o?.id=="string"&&this.#I?.offer(o.id)&&(this.#i.jobsOffered+=1)}async stop(){let t=this.#n;return this.#a?.abort(),this.#a=null,t&&await t.catch(()=>{}),await this.#I?.close(),this.#i.connected=!1,this.#i.state="idle",this.status}};function U_(n){return typeof n=="string"&&n.trim()?n.trim():null}function Yue(n,t){return`DSH_OFFICE_DEVICE_TOKEN_${xue("sha256").update(`${n} ${t}`).digest("hex").slice(0,24).toUpperCase()}`}var ZQ=class{#e;#A;#t;#r;#g=null;#a=Promise.resolve();constructor({credentials:t,configStore:o,logger:i=console,createRuntime:e}){if(!t?.resolve||!t?.set||!t?.unset)throw new TypeError("AI Office requires the Harness credential provider");if(!o?.get||!o?.save||!o?.clear)throw new TypeError("AI Office requires a config store");this.#e=t,this.#A=o,this.#t=i,this.#r=e??(a=>new Hp(a))}async initialize(){let t=this.#A.get();if(t){let o=await this.#e.resolve(t.deviceTokenRef).catch(()=>{});o?.value&&await this.#i(t,o.value)}return this.status()}async configure(t={}){return this.#l(async()=>{let o=this.#A.get(),i=U_(t.baseUrl),e=U_(t.deviceId);if(!i||!e)throw new TypeError("Office URL and Device ID are required");let a=VE(i).origin,A=Yue(a,e),r=U_(t.deviceToken),s=await this.#e.resolve(A).catch(()=>{}),g=r??s?.value;if(!g||g.length<32)throw new TypeError("Device Token must contain at least 32 characters");let c=new Date().toISOString(),I=qQ({version:1,baseUrl:a,deviceId:e,deviceTokenRef:A,maxConcurrency:t.maxConcurrency,heartbeatSeconds:t.heartbeatSeconds,workspaces:t.workspaces,instructionPresets:t.instructionPresets,createdAt:o?.createdAt??c,updatedAt:c});if(!I)throw new TypeError("AI Office connector configuration is invalid");await this.#e.set(A,g);try{await this.#A.save(I)}catch(d){throw s?.value?await this.#e.set(A,s.value).catch(()=>{}):await this.#e.unset(A).catch(()=>{}),d}return o?.deviceTokenRef&&o.deviceTokenRef!==A&&await this.#e.unset(o.deviceTokenRef).catch(()=>{}),await this.#i(I,g),this.status()})}async reconnect(){return this.#l(async()=>{let t=this.#A.get();if(!t)throw new Error("AI Office connector is not configured");return await this.#i(t),this.status()})}async test(){let t=this.#A.get();if(!t)throw new Error("AI Office connector is not configured");let o=await this.#n(t),i=this.#r({config:t,token:o,logger:this.#t});try{await i.testConnection(AbortSignal.timeout(1e4))}finally{await i.stop().catch(()=>{})}return{tested:!0,snapshot:await this.status()}}async remove(){return this.#l(async()=>{let t=this.#A.get();return await this.#I(),t?.deviceTokenRef&&await this.#e.unset(t.deviceTokenRef).catch(()=>{}),await this.#A.clear(),this.status()})}async status(){let t=this.#A.get();if(!t)return{schemaVersion:1,configured:!1,connected:!1,state:"unconfigured"};let o=await this.#e.resolve(t.deviceTokenRef).catch(()=>{}),i=this.#g?.status??null;return{schemaVersion:1,configured:!0,connected:i?.connected===!0,state:i?.state??(o?.value?"idle":"missing-token"),config:{protocolVersion:t.protocolVersion,baseUrl:t.baseUrl,deviceId:t.deviceId,maxConcurrency:t.maxConcurrency,heartbeatSeconds:t.heartbeatSeconds,workspaces:t.workspaces,instructionPresets:t.instructionPresets,hooks:JQ(t.baseUrl)},health:i,tokenConfigured:!!o?.value}}async close(){await this.#a.catch(()=>{}),await this.#I()}async#n(t){let o=await this.#e.resolve(t.deviceTokenRef).catch(()=>{});if(!o?.value)throw new Error("AI Office Device Token is missing");return o.value}async#i(t,o){await this.#I();let i=o??await this.#n(t),e=this.#r({config:t,token:i,logger:this.#t});this.#g=e,e.start()}async#I(){let t=this.#g;this.#g=null,t&&await t.stop()}#l(t){let o=this.#a.then(t,t);return this.#a=o.then(()=>{},()=>{}),o}};function Jue(n={}){let t=K_(n.dshHome??process.env.DSH_HOME??H_(jue(),".dsh")),o=K_(n.dataDir??H_(t,"integrations","dsh-office"));return{root:o,config:K_(n.configPath??H_(o,"config.json"))}}async function k1(n,t={},o={}){let i=Aa(n,t),e=o.ConfigStore??zQ,a=o.Controller??ZQ,A=o.Runtime??Hp,r=o.HarnessClient??lr,s=Jue(t),g=await new e(s.config).load(),c=typeof n.logger=="function"?n.logger("dsh-im:office"):n.logger??console,I=o.createHarness??(({workspace:B})=>new r({...i,workspace:B,autostart:!1,dshBin:t.dshBin??"dsh",rpcIdPrefix:"office",logPrefix:"dsh-im:office"})),d=new a({credentials:n.credentials,configStore:g,logger:c,createRuntime:B=>new A({...B,createHarness:I,...o.transport?{transport:o.transport}:{}})});return await d.initialize(),{controller:d,close:()=>d.close(),paths:s}}function x_(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function WE(n,t){return x_(n)&&Object.keys(n).every(o=>t.includes(o))}function que(n){return WE(n,["baseUrl","deviceId","deviceToken","maxConcurrency","heartbeatSeconds","workspaces","instructionPresets"])&&typeof n.baseUrl=="string"&&typeof n.deviceId=="string"&&(n.deviceToken===void 0||typeof n.deviceToken=="string")&&x_(n.workspaces)&&x_(n.instructionPresets)}function zue(n){for(let t of["status","configure","reconnect","test","remove"])if(typeof n?.[t]!="function")throw new TypeError(`AI Office controller requires ${t}()`);return async(t,o,i)=>{if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};try{let e;if(t===Gp.status&&WE(o,[]))e=await n.status();else if(t===Gp.configure&&que(o))e=await n.configure(o);else if(t===Gp.reconnect&&WE(o,[]))e=await n.reconnect();else if(t===Gp.test&&WE(o,[]))e=await n.test();else if(t===Gp.remove&&WE(o,["confirm"])&&o.confirm===!0)e=await n.remove();else return{ok:!1,error:{code:"bad-request",message:"Invalid AI Office connector request."}};return{ok:!0,value:e}}catch(e){let a=e?.code==="invalid-device-token"?"invalid-device-token":e?.code==="office-hook-unavailable"?"office-hook-unavailable":"office-operation-failed",A=a==="invalid-device-token"?"AI Office Device Token \u65E0\u6548\u3002":a==="office-hook-unavailable"?"AI Office Hook \u5C1A\u672A\u4E0A\u7EBF\u6216\u5730\u5740\u4E0D\u6B63\u786E\u3002":e instanceof TypeError?e.message:"AI Office \u8FDE\u63A5\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";return{ok:!1,error:{code:a,message:A}}}}}function Y_(n,t,o){return n.connection.rpc.handle(_1,zue(t),{authority:hr(o)})}async function v1(n,t={}){if(t.controller)return Y_(n,t.controller,t.rpcAuthority);let o=await k1(n,t,t.internals??{}),i=Y_(n,o.controller,t.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close AI Office connector"),i}var Vue=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]);function Wue(n){let t=n?.client_id??n?.appId,o=n?.client_secret??n?.appSecret;if(typeof t!="string"||t.length===0||typeof o!="string"||o.length===0)throw new TypeError("Feishu registration returned invalid credentials");return{appId:t,appSecret:o,userInfo:n?.user_info??n?.userInfo}}async function Zue(n){return typeof n.status!="function"?{}:await n.status()}function Xue(n){return n?.connected===!0?!0:n?.ready===!0&&n?.feishuLongConnectionState==="connected"&&n?.harnessReachable===!0}var XQ=class{#e;#A;#t;#r;#g=!1;#a=null;constructor({createProvisioningManager:t,credentialStore:o,connectionManager:i,registrationOptions:e={}}={}){if(typeof t!="function")throw new TypeError("createProvisioningManager is required");if(!o||typeof o.save!="function"||typeof o.clear!="function")throw new TypeError("credentialStore.save/clear are required");if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("connectionManager.connect/disconnect are required");if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registrationOptions must be an object");if(this.#e=o,this.#A=i,this.#t=structuredClone(e),this.#r=t({onCredentials:a=>this.#n(a)}),!this.#r||typeof this.#r.start!="function"||typeof this.#r.status!="function"||typeof this.#r.cancel!="function")throw new TypeError("The provisioning manager must implement start/status/cancel")}async startRegistration(){return this.#a=null,await this.#r.start(structuredClone(this.#t)),this.status()}async cancelRegistration(){return await this.#r.cancel(),this.status()}async disconnect(){await this.#r.cancel(),await this.#A.disconnect();try{await this.#e.clear(),this.#g=!1,this.#a=null}catch{this.#a={code:"credential_removal_failed",message:"Unable to remove the Feishu credentials."}}return this.status()}async status(){let t=await this.#r.status(),o=await Zue(this.#A),i=Xue(o),e=this.#g;if(typeof this.#e.configured=="function")try{e=await this.#e.configured()}catch{e=this.#g}let a="unconfigured";return i?a="connected":Vue.has(t?.state)?a="registering":t?.state==="saving"?a="connecting":this.#a||t?.state==="error"?a="error":e&&(a="disconnected"),{phase:a,connected:i,configured:e,registration:t,connection:o,error:this.#a??t?.error??null}}async close(){await this.#r.cancel(),await this.#A.disconnect()}async#n(t){let o=Wue(t);try{await this.#e.save(o),this.#g=!0,await this.#A.connect(o),this.#a=null}catch{throw this.#a={code:"connection_failed",message:"The bot was created, but its connection could not be started."},new Error("Unable to activate the Feishu connection.")}}};function j_(n){return new XQ(n)}import{homedir as Gke}from"node:os";import{join as Rd,resolve as Oc}from"node:path";import{unlink as Fke}from"node:fs/promises";var Uv={};Pr(Uv,{AESCipher:()=>Iu,AccessTokenError:()=>Od,Aily:()=>Ev,AppType:()=>cs,CAppTicket:()=>cu,CTenantAccessToken:()=>iu,CardActionHandler:()=>lv,Client:()=>vm,ClientAssertionError:()=>Va,DefaultCache:()=>Nm,Domain:()=>Is,EventDispatcher:()=>Gm,LarkChannel:()=>xm,LarkChannelError:()=>Pt,LoggerLevel:()=>ro,LoggerProxy:()=>Sc,WSClient:()=>Lm,adaptDefault:()=>ZTe,adaptExpress:()=>XTe,adaptKoa:()=>$Te,adaptKoaRouter:()=>e0e,createLarkChannel:()=>FNe,defaultHttpInstance:()=>bd,defaultLogger:()=>fg,generateChallenge:()=>pu,internalCache:()=>lu,messageCard:()=>t0e,normalize:()=>RW,normalizeBotAdded:()=>TW,normalizeCardAction:()=>_W,normalizeComment:()=>NW,normalizeReaction:()=>Mv,registerApp:()=>p0e,withAll:()=>jTe,withHelpDeskCredential:()=>qTe,withTenantKey:()=>JTe,withTenantToken:()=>zTe,withUserAccessToken:()=>VTe});function ZE(n,t){return function(){return n.apply(t,arguments)}}var{toString:$ue}=Object.prototype,{getPrototypeOf:nc}=Object,{iterator:eC,toStringTag:F1}=Symbol,XE=(({hasOwnProperty:n})=>(t,o)=>n.call(t,o))(Object.prototype),L1=n=>typeof n=="string"&&(n==="__proto__"||n==="constructor"||n==="prototype"),U1=(n,t,o)=>n===Object.prototype||!o&&t===null,eBe=n=>{if(!Object.isExtensible(n))return!1;let t=Object.getOwnPropertyNames(n);return Object.getOwnPropertySymbols&&t.push(...Object.getOwnPropertySymbols(n)),t.every(o=>{if(L1(o))return!1;let i=Object.getOwnPropertyDescriptor(n,o);return!!i&&i.configurable&&i.writable===!0})},$E=(n,t)=>{let o=n,i=[];for(;o!=null;){if(i.indexOf(o)!==-1)return!1;i.push(o);let e=nc(o);if(U1(o,e,o===n))return!1;if(XE(o,t))return!0;o=e}return!1},ABe=(n,t)=>n!=null&&$E(n,t)?n[t]:void 0,tBe=n=>{if(n==null||typeof n!="object"&&typeof n!="function")return n;let t=nc(n);if(t===null&&eBe(n))return n;let o=Object.create(null),i=Object.create(null),e=[],a=n;for(;a!=null&&e.indexOf(a)===-1;){e.push(a);let A=a===n?t:nc(a);if(U1(a,A,a===n))break;let r=Object.getOwnPropertyNames(a);Object.getOwnPropertySymbols&&r.push(...Object.getOwnPropertySymbols(a));for(let s of r)L1(s)||XE(i,s)||(o[s]=n[s],i[s]=!0);a=A}return o},q_=(n=>t=>{let o=$ue.call(t);return n[o]||(n[o]=o.slice(8,-1).toLowerCase())})(Object.create(null)),Mo=n=>(n=n.toLowerCase(),t=>q_(t)===n),ey=n=>t=>typeof t===n,{isArray:RI}=Array,kI=ey("undefined");function Kp(n){return n!==null&&!kI(n)&&n.constructor!==null&&!kI(n.constructor)&&Mi(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}var H1=Mo("ArrayBuffer");function rBe(n){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(n):t=n&&n.buffer&&H1(n.buffer),t}var aBe=ey("string"),Mi=ey("function"),K1=ey("number"),xp=n=>n!==null&&typeof n=="object",iBe=n=>n===!0||n===!1,$Q=n=>{if(!xp(n))return!1;let t=nc(n);return(t===null||t===Object.prototype||nc(t)===null)&&!$E(n,F1)&&!$E(n,eC)},oBe=n=>{if(!xp(n)||Kp(n))return!1;try{return Object.keys(n).length===0&&Object.getPrototypeOf(n)===Object.prototype}catch{return!1}},nBe=Mo("Date"),sBe=Mo("File"),gBe=n=>!!(n&&typeof n.uri<"u"),cBe=n=>n&&typeof n.getParts<"u",IBe=Mo("Blob"),lBe=Mo("FileList"),pBe=Mo("Set"),dBe=n=>xp(n)&&Mi(n.pipe);function hBe(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var P1=hBe(),G1=typeof P1.FormData<"u"?P1.FormData:void 0,EBe=n=>{if(!n)return!1;if(G1&&n instanceof G1)return!0;let t=nc(n);if(!t||t===Object.prototype||!Mi(n.append))return!1;let o=q_(n);return o==="formdata"||o==="object"&&Mi(n.toString)&&n.toString()==="[object FormData]"},CBe=Mo("URLSearchParams"),[uBe,BBe,fBe,QBe]=["ReadableStream","Request","Response","Headers"].map(Mo),yBe=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function AC(n,t,{allOwnKeys:o=!1}={}){if(n===null||typeof n>"u")return;let i,e;if(typeof n!="object"&&(n=[n]),RI(n))for(i=0,e=n.length;i0;)if(e=o[i],t===e.toLowerCase())return e;return null}var NI=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Y1=n=>!kI(n)&&n!==NI;function J_(...n){let{caseless:t,skipUndefined:o}=Y1(this)&&this||{},i={},e=(a,A)=>{if(A==="__proto__"||A==="constructor"||A==="prototype")return;let r=t&&typeof A=="string"&&x1(i,A)||A,s=XE(i,r)?i[r]:void 0;$Q(s)&&$Q(a)?i[r]=J_(s,a):$Q(a)?i[r]=J_({},a):RI(a)?i[r]=a.slice():(!o||!kI(a))&&(i[r]=a)};for(let a=0,A=n.length;a(AC(t,(e,a)=>{o&&Mi(e)?Object.defineProperty(n,a,{__proto__:null,value:ZE(e,o),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(n,a,{__proto__:null,value:e,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),n),SBe=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),wBe=(n,t,o,i)=>{n.prototype=Object.create(t.prototype,i),Object.defineProperty(n.prototype,"constructor",{__proto__:null,value:n,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(n,"super",{__proto__:null,value:t.prototype}),o&&Object.assign(n.prototype,o)},DBe=(n,t,o,i)=>{let e,a,A,r={};if(t=t||{},n==null)return t;do{for(e=Object.getOwnPropertyNames(n),a=e.length;a-- >0;)A=e[a],(!i||i(A,n,t))&&!r[A]&&(t[A]=n[A],r[A]=!0);n=o!==!1&&nc(n)}while(n&&(!o||o(n,t))&&n!==Object.prototype);return t},OBe=(n,t,o)=>{n=String(n),(o===void 0||o>n.length)&&(o=n.length),o-=t.length;let i=n.indexOf(t,o);return i!==-1&&i===o},bBe=n=>{if(!n)return null;if(RI(n))return n;let t=n.length;if(!K1(t))return null;let o=new Array(t);for(;t-- >0;)o[t]=n[t];return o},MBe=(n=>t=>n&&t instanceof n)(typeof Uint8Array<"u"&&nc(Uint8Array)),_Be=(n,t)=>{let i=(n&&n[eC]).call(n),e;for(;(e=i.next())&&!e.done;){let a=e.value;t.call(n,a[0],a[1])}},TBe=(n,t)=>{let o,i=[];for(;(o=n.exec(t))!==null;)i.push(o);return i},NBe=Mo("HTMLFormElement"),RBe=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(o,i,e){return i.toUpperCase()+e}),{propertyIsEnumerable:kBe}=Object.prototype,vBe=Mo("RegExp"),j1=(n,t)=>{let o=Object.getOwnPropertyDescriptors(n),i={};AC(o,(e,a)=>{let A;(A=t(e,a,n))!==!1&&(i[a]=A||e)}),Object.defineProperties(n,i)},PBe=n=>{j1(n,(t,o)=>{if(Mi(n)&&["arguments","caller","callee"].includes(o))return!1;let i=n[o];if(Mi(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+o+"'")})}})},GBe=(n,t)=>{let o={},i=e=>{e.forEach(a=>{o[a]=!0})};return RI(n)?i(n):i(String(n).split(t)),o},FBe=()=>{},LBe=(n,t)=>n!=null&&Number.isFinite(n=+n)?n:t;function UBe(n){return!!(n&&Mi(n.append)&&n[F1]==="FormData"&&n[eC])}var HBe=n=>{let t=new WeakSet,o=i=>{if(xp(i)){if(t.has(i))return;if(Kp(i))return i;if(!("toJSON"in i)){t.add(i);let e;if(pBe(i)){e=[];for(let a of i){let A=o(a);!kI(A)&&e.push(A)}}else e=RI(i)?[]:{},AC(i,(a,A)=>{let r=o(a);!kI(r)&&(e[A]=r)});return t.delete(i),e}}return i};return o(n)},KBe=Mo("AsyncFunction"),xBe=n=>n&&(xp(n)||Mi(n))&&Mi(n.then)&&Mi(n.catch),J1=((n,t)=>n?setImmediate:t?((o,i)=>(NI.addEventListener("message",({source:e,data:a})=>{e===NI&&a===o&&i.length&&i.shift()()},!1),e=>{i.push(e),NI.postMessage(o,"*")}))(`axios@${Math.random()}`,[]):o=>setTimeout(o))(typeof setImmediate=="function",Mi(NI.postMessage)),YBe=typeof queueMicrotask<"u"?queueMicrotask.bind(NI):typeof process<"u"&&process.nextTick||J1,q1=n=>n!=null&&Mi(n[eC]),jBe=n=>n!=null&&$E(n,eC)&&q1(n),Z={isArray:RI,isArrayBuffer:H1,isBuffer:Kp,isFormData:EBe,isArrayBufferView:rBe,isString:aBe,isNumber:K1,isBoolean:iBe,isObject:xp,isPlainObject:$Q,isEmptyObject:oBe,isReadableStream:uBe,isRequest:BBe,isResponse:fBe,isHeaders:QBe,isUndefined:kI,isDate:nBe,isFile:sBe,isReactNativeBlob:gBe,isReactNative:cBe,isBlob:IBe,isRegExp:vBe,isFunction:Mi,isStream:dBe,isURLSearchParams:CBe,isTypedArray:MBe,isFileList:lBe,forEach:AC,merge:J_,extend:mBe,trim:yBe,stripBOM:SBe,inherits:wBe,toFlatObject:DBe,kindOf:q_,kindOfTest:Mo,endsWith:OBe,toArray:bBe,forEachEntry:_Be,matchAll:TBe,isHTMLForm:NBe,hasOwnProperty:XE,hasOwnProp:XE,hasOwnInPrototypeChain:$E,getSafeProp:ABe,toSafeFlatObject:tBe,reduceDescriptors:j1,freezeMethods:PBe,toObjectSet:GBe,toCamelCase:RBe,noop:FBe,toFiniteNumber:LBe,findKey:x1,global:NI,isContextDefined:Y1,isSpecCompliantForm:UBe,toJSONObject:HBe,isAsyncFn:KBe,isThenable:xBe,setImmediate:J1,asap:YBe,isIterable:q1,isSafeIterable:jBe};var JBe=Z.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),z1=n=>{let t={},o,i,e;return n&&n.split(` `).forEach(function(A){e=A.indexOf(":"),o=A.substring(0,e).trim().toLowerCase(),i=A.substring(e+1).trim();let r=Z.hasOwnProp(t,o);!o||r&&Z.hasOwnProp(JBe,o)||(o==="set-cookie"?r?t[o].push(i):t[o]=[i]:t[o]=r?t[o]+", "+i:i)}),t};function qBe(n){let t=0,o=n.length;for(;tt;){let i=n.charCodeAt(o-1);if(i!==9&&i!==32)break;o-=1}return t===0&&o===n.length?n:n.slice(t,o)}var zBe=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),VBe=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function z_(n,t){return Z.isArray(n)?n.map(o=>z_(o,t)):qBe(String(n).replace(t,""))}var V1=n=>z_(n,zBe),WBe=n=>z_(n,VBe);function Yp(n){let t=Object.create(null);return Z.forEach(n.toJSON(),(o,i)=>{t[i]=WBe(o)}),t}var W1=Symbol("internals");function tC(n){return n&&String(n).trim().toLowerCase()}function Ay(n){return n===!1||n==null?n:Z.isArray(n)?n.map(Ay):V1(String(n))}function ZBe(n){let t=Object.create(null),o=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=o.exec(n);)t[i[1]]=i[2];return t}var XBe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function V_(n){let t=0,o=n.length;for(;tt;){let i=n.charCodeAt(o-1);if(i!==9&&i!==32)break;o-=1}return t===0&&o===n.length?n:n.slice(t,o)}function $Be(n){let t=n.length-1;if(t<1||n.charCodeAt(0)!==34||n.charCodeAt(t)!==34)return n;let o="";for(let i=1;i=t))return n;o+=n[i]}return o}function efe(n){let t=Object.create(null),o=String(n),i=0,e=!1,a=!1;function A(r){let s=V_(o.slice(i,r)),g=s.indexOf("=");if(g<1)return;let c=V_(s.slice(0,g));if(!XBe.test(c))return;let I=c.toLowerCase();if(I==="__proto__"||I==="constructor"||I==="prototype")return;let d=V_(s.slice(g+1));t[I]=$Be(d)}for(let r=0;r/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(n.trim());function W_(n,t,o,i,e){if(Z.isFunction(i))return i.call(this,t,o);if(e&&(t=o),!!Z.isString(t)){if(Z.isString(i))return t.indexOf(i)!==-1;if(Z.isRegExp(i))return i.test(t)}}function tfe(n){return n.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,o,i)=>o.toUpperCase()+i)}function rfe(n,t){let o=Z.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(n,i+o,{__proto__:null,value:function(e,a,A){return this[i].call(this,t,e,a,A)},configurable:!0})})}var jp=class{constructor(t){t&&this.set(t)}set(t,o,i){let e=this;function a(r,s,g){let c=tC(s);if(!c)return;let I=Z.findKey(e,c);(!I||e[I]===void 0||g===!0||g===void 0&&e[I]!==!1)&&(e[I||s]=Ay(r))}let A=(r,s)=>Z.forEach(r,(g,c)=>a(g,c,s));if(Z.isPlainObject(t)||t instanceof this.constructor)A(t,o);else if(Z.isString(t)&&(t=t.trim())&&!Afe(t))A(z1(t),o);else if(Z.isObject(t)&&Z.isSafeIterable(t)){let r=Object.create(null),s,g;for(let c of t){if(!Z.isArray(c))throw new TypeError("Object iterator must return a key-value pair");g=c[0],Z.hasOwnProp(r,g)?(s=r[g],r[g]=Z.isArray(s)?[...s,c[1]]:[s,c[1]]):r[g]=c[1]}A(r,o)}else t!=null&&a(o,t,i);return this}get(t,o){if(t=tC(t),t){let i=Z.findKey(this,t);if(i){let e=this[i];if(!o)return e;if(o===!0)return ZBe(e);if(Z.isFunction(o))return o.call(this,e,i);if(Z.isRegExp(o))return o.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,o){if(t=tC(t),t){let i=Z.findKey(this,t);return!!(i&&this[i]!==void 0&&(!o||W_(this,this[i],i,o)))}return!1}delete(t,o){let i=this,e=!1;function a(A){if(A=tC(A),A){let r=Z.findKey(i,A);r&&(!o||W_(i,i[r],r,o))&&(delete i[r],e=!0)}}return Z.isArray(t)?t.forEach(a):a(t),e}clear(t){let o=Object.keys(this),i=o.length,e=!1;for(;i--;){let a=o[i];(!t||W_(this,this[a],a,t,!0))&&(delete this[a],e=!0)}return e}normalize(t){let o=this,i={};return Z.forEach(this,(e,a)=>{let A=Z.findKey(i,a);if(A){o[A]=Ay(e),delete o[a];return}let r=t?tfe(a):String(a).trim();r!==a&&delete o[a],o[r]=Ay(e),i[r]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let o=Object.create(null);return Z.forEach(this,(i,e)=>{i!=null&&i!==!1&&(o[e]=t&&Z.isArray(i)?i.join(", "):i)}),o}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,o])=>t+": "+o).join(` -`)}getSetCookie(){let t=this.get("set-cookie");return Z.isArray(t)?t:t==null||t===!1?[]:[t]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static parseParameters(t){return efe(t)}static concat(t,...o){let i=new this(t);return o.forEach(e=>i.set(e)),i}static accessor(t){let i=(this[W1]=this[W1]={accessors:{}}).accessors,e=this.prototype;function a(A){let r=tC(A);i[r]||(rfe(e,A),i[r]=!0)}return Z.isArray(t)?t.forEach(a):a(t),this}};jp.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Z.reduceDescriptors(jp.prototype,({value:n},t)=>{let o=t[0].toUpperCase()+t.slice(1);return{get:()=>n,set(i){this[o]=i}}});Z.freezeMethods(jp);var Ut=jp;var rC="[REDACTED ****]";function afe(n){if(Z.hasOwnProp(n,"toJSON"))return!0;let t=Object.getPrototypeOf(n);for(;t&&t!==Object.prototype;){if(Z.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function ife(n,t){let o=new Set(t.map(a=>String(a).toLowerCase())),i=[],e=a=>{if(a===null||typeof a!="object"||Z.isBuffer(a))return a;if(i.indexOf(a)!==-1)return;a instanceof Ut&&(a=a.toJSON()),i.push(a);let A;if(Z.isArray(a))A=[],a.forEach((r,s)=>{let g=e(r);Z.isUndefined(g)||(A[s]=g)});else{if(!Z.isPlainObject(a)&&afe(a))return i.pop(),a;A=Object.create(null);for(let[r,s]of Object.entries(a)){let g=o.has(r.toLowerCase())?rC:e(s);Z.isUndefined(g)||(A[r]=g)}}return i.pop(),A};return e(n)}function Z1(n){try{return String(n)}catch{return""}}function ofe(n){return n.errors.map(o=>{try{return o&&o.message?Z1(o.message):Z1(o)}catch{return""}}).filter(Boolean).join("; ")||n.name||"AggregateError"}var Ca=class n extends Error{static from(t,o,i,e,a,A){let r=t.message;!r&&Z.isArray(t.errors)&&t.errors.length&&(r=ofe(t));let s=new n(r,o||t.code,i,e,a);return Object.defineProperty(s,"cause",{__proto__:null,value:t,writable:!0,enumerable:!1,configurable:!0}),s.name=t.name,t.status!=null&&s.status==null&&(s.status=t.status),A&&Object.assign(s,A),s}constructor(t,o,i,e,a){super(t),Object.defineProperty(this,"message",{__proto__:null,value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,o&&(this.code=o),i&&(this.config=i),e&&(this.request=e),a&&(this.response=a,this.status=a.status)}toJSON(){let t=this.config,o=t&&Z.hasOwnProp(t,"redact")?t.redact:void 0,i=Z.isArray(o)&&o.length>0?ife(t,o):Z.toJSONObject(t);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:i,code:this.code,status:this.status}}};Ca.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";Ca.ERR_BAD_OPTION="ERR_BAD_OPTION";Ca.ECONNABORTED="ECONNABORTED";Ca.ETIMEDOUT="ETIMEDOUT";Ca.ECONNREFUSED="ECONNREFUSED";Ca.ERR_NETWORK="ERR_NETWORK";Ca.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";Ca.ERR_DEPRECATED="ERR_DEPRECATED";Ca.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";Ca.ERR_BAD_REQUEST="ERR_BAD_REQUEST";Ca.ERR_CANCELED="ERR_CANCELED";Ca.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";Ca.ERR_INVALID_URL="ERR_INVALID_URL";Ca.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var ye=Ca;var $j=Je(Xj(),1),Iy=$j.default;var ly={isBufferAvailable(){return typeof Buffer<"u"},from(n){return Buffer.from(n)}};var fT=100;function BT(n){return Z.isPlainObject(n)||Z.isArray(n)}function eJ(n){return Z.endsWith(n,"[]")?n.slice(0,-2):n}function uT(n,t,o){return n?n.concat(t).map(function(e,a){return e=eJ(e),!o&&a?"["+e+"]":e}).join(o?".":""):t}function jQe(n){return Z.isArray(n)&&!n.some(BT)}var JQe=Z.toFlatObject(Z,{},null,function(t){return/^is[A-Z]/.test(t)});function qQe(n,t,o){if(!Z.isObject(n))throw new TypeError("target must be an object");t=t||new(Iy||FormData);let i=(_,T)=>{let R=Z.getSafeProp(o,_);return Z.isUndefined(R)?T:R},e=i("metaTokens",!0),a=i("visitor")||Q,A=i("dots",!1),r=i("indexes",!1),s=i("Blob")||typeof Blob<"u"&&Blob,g=i("maxDepth",fT),c=s&&Z.isSpecCompliantForm(t),I=[];if(!Z.isFunction(a))throw new TypeError("visitor must be a function");function d(_){if(_===null)return"";if(Z.isDate(_))return _.toISOString();if(Z.isBoolean(_))return _.toString();if(!c&&Z.isBlob(_))throw new ye("Blob is not supported. Use a Buffer instead.");if(Z.isArrayBuffer(_)||Z.isTypedArray(_)){if(c&&typeof s=="function")return new s([_]);if(ly&&ly.isBufferAvailable())return ly.from(_);throw new ye("Blob is not supported. Use a Buffer instead.",ye.ERR_NOT_SUPPORT)}return _}function B(_){if(_>g)throw new ye("Object is too deeply nested ("+_+" levels). Max depth: "+g,ye.ERR_FORM_DATA_DEPTH_EXCEEDED)}function f(_,T){if(g===1/0)return JSON.stringify(_);let R=[];return JSON.stringify(_,function(K,L){if(!Z.isObject(L))return L;for(;R.length&&R[R.length-1]!==this;)R.pop();return R.push(L),B(T+R.length-1),L})}function Q(_,T,R){let F=_;if(Z.isReactNative(t)&&Z.isReactNativeBlob(_))return t.append(uT(R,T,A),d(_)),!1;if(_&&!R&&typeof _=="object"){if(Z.endsWith(T,"{}"))T=e?T:T.slice(0,-2),_=f(_,1);else if(Z.isArray(_)&&jQe(_)||(Z.isFileList(_)||Z.endsWith(T,"[]"))&&(F=Z.toArray(_)))return T=eJ(T),F.forEach(function(L,q){!(Z.isUndefined(L)||L===null)&&t.append(r===!0?uT([T],q,A):r===null?T:T+"[]",d(L))}),!1}return BT(_)?!0:(t.append(uT(R,T,A),d(_)),!1)}let y=Object.assign(JQe,{defaultVisitor:Q,convertValue:d,isVisitable:BT});function m(_,T,R=0){if(!Z.isUndefined(_)){if(B(R),I.indexOf(_)!==-1)throw new Error("Circular reference detected in "+T.join("."));I.push(_),Z.forEach(_,function(K,L){(!(Z.isUndefined(K)||K===null)&&a.call(t,K,Z.isString(L)?L.trim():L,T,y))===!0&&m(K,T?T.concat(L):[L],R+1)}),I.pop()}}if(!Z.isObject(n))throw new TypeError("data must be an object");return m(n),t}var cc=qQe;function AJ(n){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(n).replace(/[!'()~]|%20/g,function(i){return t[i]})}function tJ(n,t){this._pairs=[],n&&cc(n,this,t)}var rJ=tJ.prototype;rJ.append=function(t,o){this._pairs.push([t,o])};rJ.toString=function(t){let o=t?i=>t.call(this,i,AJ):AJ;return this._pairs.map(function(e){return o(e[0])+"="+o(e[1])},"").join("&")};var aJ=tJ;function zQe(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function PI(n,t,o){if(!t)return n;n=n||"";let i=Z.isFunction(o)?{serialize:o}:o,e=Z.getSafeProp(i,"encode")||zQe,a=Z.getSafeProp(i,"serialize"),A;if(a?A=a(t,i):A=Z.isURLSearchParams(t)?t.toString():new aJ(t,i).toString(e),A){let r=n.indexOf("#");r!==-1&&(n=n.slice(0,r)),n+=(n.indexOf("?")===-1?"?":"&")+A}return n}var gC=Symbol("internals");function oJ(n){return n?n.length:0}function iJ(n){if(n)for(;n.length&&n[n.length-1]===null;)n.pop()}function cC(n,t){let o=n.handlers,i=oJ(o);o!==t.handlersRef?(t.handlersRef=o,t.handlerEntries.clear()):i!==t.handlersLength&&(i?t.handlerEntries.forEach(function(a,A){o[a.index]!==a.handler&&t.handlerEntries.delete(A)}):t.handlerEntries.clear()),t.handlersLength=i}var QT=class{constructor(){this.handlers=[],this[gC]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(t,o,i){let e={fulfilled:t,rejected:o,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null},a=this[gC];this.handlers==null&&(this.handlers=[]),cC(this,a);let A=a.nextId++;return this.handlers.push(e),a.handlerEntries.set(A,{handler:e,index:this.handlers.length-1}),a.handlersLength=this.handlers.length,A}eject(t){let o=this[gC];cC(this,o);let i=o.handlerEntries.get(t);if(i){if(o.handlerEntries.delete(t),this.handlers[i.index]!==i.handler)return;this.handlers[i.index]=null,o.iterationDepth||(iJ(this.handlers),o.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],cC(this,this[gC]))}forEach(t){let o=this[gC];cC(this,o),o.iterationDepth++;try{Z.forEach(this.handlers,function(e){e!==null&&t(e)})}finally{--o.iterationDepth||(cC(this,o),iJ(this.handlers),o.handlersLength=oJ(this.handlers))}}},yT=QT;var Ic={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0};import WQe from"crypto";import VQe from"url";var nJ=VQe.URLSearchParams;var mT="abcdefghijklmnopqrstuvwxyz",sJ="0123456789",gJ={DIGIT:sJ,ALPHA:mT,ALPHA_DIGIT:mT+mT.toUpperCase()+sJ},ZQe=(n=16,t=gJ.ALPHA_DIGIT)=>{let o="",{length:i}=t,e=new Uint32Array(n);WQe.randomFillSync(e);for(let a=0;awT,hasStandardBrowserEnv:()=>XQe,hasStandardBrowserWebWorkerEnv:()=>$Qe,navigator:()=>ST,origin:()=>eye});var wT=typeof window<"u"&&typeof document<"u",ST=typeof navigator=="object"&&navigator||void 0,XQe=wT&&(!ST||["ReactNative","NativeScript","NS"].indexOf(ST.product)<0),$Qe=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",eye=wT&&window.location.href||"http://localhost";var Ct={...DT,...cJ};function OT(n,t){return cc(n,new Ct.classes.URLSearchParams,{visitor:function(o,i,e,a){return Ct.isNode&&Z.isBuffer(o)?(this.append(i,o.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}var IJ=fT;function lJ(n){if(n>IJ)throw new ye("FormData field is too deeply nested ("+n+" levels). Max depth: "+IJ,ye.ERR_FORM_DATA_DEPTH_EXCEEDED)}function Aye(n){let t=[],o=/[^.[\]]+|\[([^.[\]]*)]/g,i;for(;(i=o.exec(n))!==null;)lJ(t.length),t.push(i[0]==="[]"?"":i[1]||i[0]);return t}function tye(n){let t={},o=Object.keys(n),i,e=o.length,a;for(i=0;i=o.length;return A=!A&&Z.isArray(e)?e.length:A,s?(Z.hasOwnProp(e,A)?e[A]=Z.isArray(e[A])?e[A].concat(i):[e[A],i]:e[A]=i,!r):((!Z.hasOwnProp(e,A)||!Z.isObject(e[A]))&&(e[A]=[]),t(o,i,e[A],a)&&Z.isArray(e[A])&&(e[A]=tye(e[A])),!r)}if(Z.isFormData(n)&&Z.isFunction(n.entries)){let o={};return Z.forEachEntry(n,(i,e)=>{t(Aye(i),e,o,0)}),o}return null}var py=rye;var aye=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),dy=aye;var Wp=(n,t)=>n!=null&&Z.hasOwnProp(n,t)?n[t]:void 0;function iye(n,t,o){if(Z.isString(n))try{return(t||JSON.parse)(n),Z.trim(n)}catch(i){if(i.name!=="SyntaxError")throw i}return(o||JSON.stringify)(n)}var bT={transitional:Ic,adapter:["xhr","http","fetch"],transformRequest:[function(t,o){let i=o.getContentType()||"",e=i.indexOf("application/json")>-1,a=Z.isObject(t);if(a&&Z.isHTMLForm(t)&&(t=new FormData(t)),Z.isFormData(t))return e?JSON.stringify(py(t)):t;if(Z.isArrayBuffer(t)||Z.isBuffer(t)||Z.isStream(t)||Z.isFile(t)||Z.isBlob(t)||Z.isReadableStream(t))return t;if(Z.isArrayBufferView(t))return t.buffer;if(Z.isURLSearchParams(t))return o.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let r;if(a){let s=Wp(this,"formSerializer");if(i.indexOf("application/x-www-form-urlencoded")>-1)return OT(t,s).toString();if((r=Z.isFileList(t))||i.indexOf("multipart/form-data")>-1){let g=Wp(this,"env"),c=g&&g.FormData;return cc(r?{"files[]":t}:t,c&&new c,s)}}return a||e?(o.setContentType("application/json",!1),iye(t)):t}],transformResponse:[function(t){let o=Wp(this,"transitional")||bT.transitional,i=o&&o.forcedJSONParsing,e=Wp(this,"responseType"),a=e==="json";if(Z.isResponse(t)||Z.isReadableStream(t))return t;if(t&&Z.isString(t)&&(i&&!e||a)){let r=!(o&&o.silentJSONParsing)&&a;try{return JSON.parse(t,Wp(this,"parseReviver"))}catch(s){if(r)throw s.name==="SyntaxError"?ye.from(s,ye.ERR_BAD_RESPONSE,this,null,Wp(this,"response")):s}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ct.classes.FormData,Blob:Ct.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Z.forEach(dy,n=>{bT.headers[n]={}});var Zp=bT;function IC(n,t){let o=this||Zp,i=t||o,e=Ut.from(i.headers),a=i.data;return Z.forEach(n,function(r){a=r.call(o,a,e.normalize(),t?t.status:void 0)}),e.normalize(),a}function lC(n){return!!(n&&n.__CANCEL__)}var MT=class extends ye{constructor(t,o,i){super(t??"canceled",ye.ERR_CANCELED,o,i),this.name="CanceledError",this.__CANCEL__=!0}},$i=MT;function ts(n,t,o){let i=o.config.validateStatus;!o.status||!i||i(o.status)?n(o):t(new ye("Request failed with status code "+o.status,o.status>=400&&o.status<500?ye.ERR_BAD_REQUEST:ye.ERR_BAD_RESPONSE,o.config,o.request,o))}function _T(n){return typeof n!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(n)}function TT(n,t){if(!t)return n;let o=n.length;for(;o>0&&n.charCodeAt(o-1)===47;)o--;return n.slice(0,o)+"/"+t.replace(/^\/+/,"")}var oye=/[\t\n\r]/g;function pC(n){if(typeof n!="string")return n;let t=0;for(;t`${o}${i}${rC}`)}function gye(n){let t=n.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${rC}@`),o=t.indexOf("#"),e=(o===-1?t:t.slice(0,o)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${rC}`);return o===-1?e:`${e}#${sye(t.slice(o+1))}`}function pJ(n,t){if(typeof n=="string"){let o=pC(n);if(nye.test(o))throw new ye(`Invalid URL ${JSON.stringify(gye(o))}: missing "//" after protocol`,ye.ERR_INVALID_URL,t)}}function GI(n,t,o,i){pJ(t,i);let e=!_T(t);return n&&(e||o===!1)?(pJ(n,i),TT(n,t)):t}var cye={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function Iye(n){try{return new URL(n)}catch{return null}}function dJ(n){var t=(typeof n=="string"?Iye(n):n)||{},o=t.protocol,i=t.host,e=t.port;if(typeof i!="string"||!i||typeof o!="string"||(o=o.split(":",1)[0],i=i.replace(/:\d*$/,""),e=parseInt(e)||cye[o]||0,!lye(i,e)))return"";var a=NT(o+"_proxy")||NT("all_proxy");return a&&a.indexOf("://")===-1&&(a=o+"://"+a),a}function lye(n,t){var o=NT("no_proxy").toLowerCase();return o?o==="*"?!1:o.split(/[,\s]/).every(function(i){if(!i)return!0;var e=i.match(/^(.+):(\d+)$/),a=e?e[1]:i,A=e?parseInt(e[2]):0;return A&&A!==t?!0:/^[.*]/.test(a)?(a.charAt(0)==="*"&&(a=a.slice(1)),!n.endsWith(a)):n!==a}):!0}function NT(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}var l0=Je(KT(),1),uq=Je(PJ(),1);import Eq from"http";import Cq from"https";import Jme from"http2";import qme from"util";import{resolve as aq}from"path";import _o from"zlib";var ng="1.20.0";function KI(n){let t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(n);return t&&t[1]||""}var lme=/^([^,;/]+\/[^,;/]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;function A0(n,t,o){let i=o&&o.Blob||Ct.classes.Blob,e=KI(n);if(t===void 0&&i&&(t=!0),e==="data"){n=e.length?n.slice(e.length+1):n;let a=lme.exec(n);if(!a)throw new ye("Invalid URL",ye.ERR_INVALID_URL);let A=a[1],r=a[2],s=a[3]?"base64":"utf8",g=a[4],c="";A?c=r?A+r:A:r&&(c="text/plain"+r);let I=s==="base64"?Buffer.from(g,"base64"):Buffer.from(decodeURIComponent(g),s);if(t){if(!i)throw new ye("Blob is not supported",ye.ERR_NOT_SUPPORT);return new i([I],{type:c})}return I}throw new ye("Unsupported protocol "+e,ye.ERR_NOT_SUPPORT)}import Cn from"stream";var pme=["content-type","content-length"];function yC(n,t,o){if(o!=="content-only"){n.set(t);return}Object.entries(t||{}).forEach(([i,e])=>{pme.includes(i.toLowerCase())&&n.set(i,e)})}import dme from"stream";var t0=Symbol("internals"),r0=class extends dme.Transform{constructor(t){t=Z.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,e)=>!Z.isUndefined(e[i])),super({readableHighWaterMark:t.chunkSize});let o=this[t0]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(o.isCaptured||(o.isCaptured=!0))})}_read(t){let o=this[t0];return o.onReadCallback&&o.onReadCallback(),super._read(t)}_transform(t,o,i){let e=this[t0],a=e.maxRate,A=this.readableHighWaterMark,r=e.timeWindow,s=1e3/r,g=a/s,c=e.minChunkSize!==!1?Math.max(e.minChunkSize,g*.01):0,I=(B,f)=>{let Q=Buffer.byteLength(B);e.bytesSeen+=Q,e.bytes+=Q,e.isCaptured&&this.emit("progress",e.bytesSeen),this.push(B)?process.nextTick(f):e.onReadCallback=()=>{e.onReadCallback=null,process.nextTick(f)}},d=(B,f)=>{let Q=Buffer.byteLength(B),y=null,m=A,_,T=0;if(a){let R=Date.now();(!e.ts||(T=R-e.ts)>=r)&&(e.ts=R,_=g-e.bytes,e.bytes=_<0?-_:0,T=0),_=g-e.bytes}if(a){if(_<=0)return setTimeout(()=>{f(null,B)},r-T);_m&&Q-m>c&&(y=B.subarray(m),B=B.subarray(0,m)),I(B,y?()=>{process.nextTick(f,null,y)}:f)};d(t,function B(f,Q){if(f)return i(f);Q?d(Q,B):i(null)})}},a0=r0;import{EventEmitter as zme}from"events";import Eme from"util";import{Readable as Cme}from"stream";var{asyncIterator:GJ}=Symbol,hme=async function*(n){n.stream?yield*n.stream():n.arrayBuffer?yield await n.arrayBuffer():n[GJ]?yield*n[GJ]():yield n},fy=hme;var ume=Ct.ALPHABET.ALPHA_DIGIT+"-_",mC=typeof TextEncoder=="function"?new TextEncoder:new Eme.TextEncoder,xI=`\r -`,Bme=mC.encode(xI),fme=2,i0=class{constructor(t,o){let{escapeName:i}=this.constructor,e=Z.isString(o),a=`Content-Disposition: form-data; name="${i(t)}"${!e&&o.name?`; filename="${i(o.name)}"`:""}${xI}`;if(e)o=mC.encode(String(o).replace(/\r?\n|\r\n?/g,xI));else{let A=String(o.type||"application/octet-stream").replace(/[\r\n]/g,"");a+=`Content-Type: ${A}${xI}`}this.headers=mC.encode(a+xI),this.contentLength=e?o.byteLength:o.size,this.size=this.headers.byteLength+this.contentLength+fme,this.name=t,this.value=o}async*encode(){yield this.headers;let{value:t}=this;Z.isTypedArray(t)?yield t:yield*fy(t),yield Bme}static escapeName(t){return String(t).replace(/[\r\n"]/g,o=>({"\r":"%0D","\n":"%0A",'"':"%22"})[o])}},Qme=(n,t,o)=>{let{tag:i="form-data-boundary",size:e=25,boundary:a=i+"-"+Ct.generateString(e,ume)}=o||{};if(!Z.isFormData(n))throw new TypeError("FormData instance required");if(a.length<1||a.length>70)throw new Error("boundary must be 1-70 characters long");let A=mC.encode("--"+a+xI),r=mC.encode("--"+a+"--"+xI),s=r.byteLength,g=Array.from(n.entries()).map(([I,d])=>{let B=new i0(I,d);return s+=B.size,B});s+=A.byteLength*g.length,s=Z.toFiniteNumber(s);let c={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(s)&&(c["Content-Length"]=s),t&&t(c),Cme.from((async function*(){for(let I of g)yield A,yield*I.encode();yield r})())},FJ=Qme;import yme from"stream";var o0=class extends yme.Transform{__transform(t,o,i){this.push(t),i()}_transform(t,o,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let e=Buffer.alloc(2);e[0]=120,e[1]=156,this.push(e,o)}this.__transform(t,o,i)}},LJ=o0;import mme from"http2";import Sme from"util";var n0=class{constructor(){this.sessions=Object.create(null)}getSession(t,o){o=Object.assign(Object.create(null),{sessionTimeout:1e3},o);let i=this.sessions[t];if(i){let I=i.length;for(let d=0;d{if(a)return;a=!0,A&&(clearTimeout(A),A=null);let I=i,d=I.length,B=d;for(;B--;)if(I[B][0]===e){d===1?delete this.sessions[t]:I.splice(B,1),e.closed||e.close();return}},s=e.request,{sessionTimeout:g}=o;if(g!=null){let I=0;e.request=function(){let d=s.apply(this,arguments);return I++,A&&(clearTimeout(A),A=null),d.once("close",()=>{--I||(A=setTimeout(()=>{A=null,r()},g))}),d}}e.once("close",r),e.once("error",r);let c=[e,o];return i?i.push(c):i=this.sessions[t]=[c],e}},UJ=n0;var wme=(n,t)=>Z.isAsyncFn(n)?function(...o){let i=o.pop();n.apply(this,o).then(e=>{try{t?i(null,...t(e)):i(null,e)}catch(a){i(a)}},i)}:n,HJ=wme;var Dme=new Set(["localhost","0.0.0.0"]),YJ=n=>{let t=n.length;for(;t&&n.charCodeAt(t-1)===46;)t--;return t===n.length?n:n.slice(0,t)},jJ=n=>{let t=n.split(".");return t.length!==4||t[0]!=="127"?!1:t.every(o=>/^\d+$/.test(o)&&Number(o)>=0&&Number(o)<=255)},s0=n=>{if(/^0[xX][0-9a-fA-F]+$/.test(n)){let t=parseInt(n.slice(2),16);return Number.isFinite(t)?t:null}if(n.length>1&&/^0[0-7]+$/.test(n)){let t=parseInt(n,8);return Number.isFinite(t)?t:null}if(n.length>1&&/^0[0-9]+$/.test(n))return null;if(/^[0-9]+$/.test(n)){let t=parseInt(n,10);return Number.isFinite(t)?t:null}return null},JJ=n=>{if(typeof n!="string"||!n||n.indexOf(":")!==-1)return n;let t=n;if(t.charAt(0)==="["&&t.charAt(t.length-1)==="]"&&(t=t.slice(1,-1)),t=YJ(t),!/^[0-9.xXa-fA-F]+$/.test(t))return n;let o=t.split(".");if(o.some(c=>c===""))return n;if(o.length===4){let c=o.map(s0);return c.some(I=>I===null||I<0||I>255)?n:c.join(".")}if(o.length>4||o.length===1)return n;let i=o.slice(0,-1),e=o[o.length-1],a=4-i.length,A=s0(e);if(A===null)return n;let r=(1<<8*a)-1;if(A<0||A>r)return n;let s=new Array(a).fill(0);for(let c=a-1,I=A;c>=0;c--,I>>=8)s[c]=I&255;let g=i.map(s0);return g.some(c=>c===null||c<0||c>255)?n:[...g,...s].join(".")},g0=n=>/^0{1,4}$/.test(n),Ome=n=>{if(n==="::")return!0;let t=n.indexOf("::");if(t!==-1){if(t!==n.lastIndexOf("::"))return!1;let i=n.slice(0,t),e=n.slice(t+2),a=i?i.split(":"):[],A=e?e.split(":"):[];return a.length+A.length<8&&a.every(g0)&&A.every(g0)}let o=n.split(":");return o.length===8&&o.every(g0)},bme=n=>{if(n==="::1")return!0;let t=n.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return jJ(t[1]);let o=n.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(o){let e=parseInt(o[1],16);return e>=32512&&e<=32767}let i=n.split(":");if(i.length===8){for(let e=0;e<7;e++)if(!/^0+$/.test(i[e]))return!1;return/^0*1$/.test(i[7])}return!1},KJ=n=>n?Dme.has(n)||jJ(n)||Ome(n)?!0:bme(n):!1,Mme={http:80,https:443,ws:80,wss:443,ftp:21},_me=n=>{let t=n,o=0;if(t.charAt(0)==="["){let a=t.indexOf("]");if(a!==-1){let A=t.slice(1,a),r=t.slice(a+1);return r.charAt(0)===":"&&/^\d+$/.test(r.slice(1))&&(o=Number.parseInt(r.slice(1),10)),[A,o]}}let i=t.indexOf(":"),e=t.lastIndexOf(":");return i!==-1&&i===e&&/^\d+$/.test(t.slice(e+1))&&(o=Number.parseInt(t.slice(e+1),10),t=t.slice(0,e)),[t,o]},Tme=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i,Nme=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i,qJ=n=>{if(typeof n!="string"||n.indexOf(":")===-1)return n;let t=n.match(Tme);if(t)return t[1];let o=n.match(Nme);if(o){let i=parseInt(o[1],16),e=parseInt(o[2],16);return`${i>>8}.${i&255}.${e>>8}.${e&255}`}return n},Rme=/^(?:0|[1-9]\d{0,2})$/,zJ=n=>{let t=n.split(".");return t.length===4&&t.every(o=>Rme.test(o)&&Number(o)<=255)?t.map(Number):null},kme=/^[0-9a-f]{1,4}$/i,vme=n=>{let t=n.split("::");if(t.length>2)return null;let o=t[0]?t[0].split(":"):[];if(t.length===2){let i=t[1]?t[1].split(":"):[],e=8-o.length-i.length;if(e<1)return null;o.push(...new Array(e).fill("0"),...i)}return o.length!==8||o.some(i=>!kme.test(i))?null:o.flatMap(i=>{let e=Number.parseInt(i,16);return[e>>8&255,e&255]})},VJ=n=>typeof n!="string"||!n?null:n.indexOf(":")!==-1?vme(n):zJ(n),xJ=n=>{if(!n)return n;n.charAt(0)==="["&&n.charAt(n.length-1)==="]"&&(n=n.slice(1,-1));let t=YJ(n),o=JJ(t);return o!==t?o:qJ(t)},Pme=n=>{let t=n,o=t.charAt(0)==="[",i=t.charAt(t.length-1)==="]",e=t.includes("[")||t.includes("]");if(o||i){if(!o||!i||(t=t.slice(1,-1),t.indexOf(":")===-1||t.includes("[")||t.includes("]")))return null}else if(e)return null;if(!t||t.charAt(t.length-1)===".")return null;let a=t.indexOf(":")!==-1;if(a)try{t=new URL(`http://[${t}]/`).hostname.slice(1,-1)}catch{return null}else if(t=JJ(t),!zJ(t))return null;return{normalized:qJ(t),wasIPv6:a}},Gme=/^(.+)\/(0|[1-9]\d{0,2})$/,Fme=n=>{if(n.indexOf("/")===-1)return;let t=Gme.exec(n);if(!t)return null;let o=Number(t[2]),i=Pme(t[1]);if(!i)return null;let{normalized:e,wasIPv6:a}=i;if(a&&e.indexOf(":")===-1){if(o<96)return null;o-=96}let A=VJ(e);return!A||o>A.length*8?null:{bytes:A,prefix:o}},Lme=(n,t,o)=>{let i=o>>3;for(let a=0;a{if(!A)return!1;if(A==="*")return!0;let r=Fme(A);if(r!==void 0)return r!==null&&!!a&&a.length===r.bytes.length&&Lme(a,r.bytes,r.prefix);let[s,g]=_me(A);return s=xJ(s),!s||g&&g!==i?!1:(s.charAt(0)==="*"&&(s=s.slice(1)),s.charAt(0)==="."?e.endsWith(s):e===s||KJ(e)&&KJ(s))})}function Ume(n,t){n=n||10;let o=new Array(n),i=new Array(n),e=0,a=0,A;return t=t!==void 0?t:1e3,function(s){let g=Date.now(),c=i[a];A||(A=g),o[e]=s,i[e]=g;let I=a,d=0;for(;I!==e;)d+=o[I++],I=I%n;if(e=(e+1)%n,e===a&&(a=(a+1)%n),g-A{o=I,e=null,a&&(clearTimeout(a),a=null),n(...c)};return[(...c)=>{let I=Date.now(),d=I-o;d>=i?A(c,I):(e=c,a||(a=setTimeout(()=>{a=null,A(e)},i-d)))},()=>e&&A(e),(...c)=>A(c)]}var ZJ=Hme;var sg=(n,t,o=3)=>{let i=0,e=WJ(50,250);return ZJ(a=>{if(!a||!Z.isNumber(a.loaded))return;let A=a.loaded,r=a.lengthComputable?a.total:void 0,s=Math.max(0,r!=null?Math.min(A,r):A),g=Math.max(0,s-i),c=e(g);i=Math.max(i,s);let I={loaded:s,total:r,progress:r?s/r:void 0,bytes:g,rate:c||void 0,estimated:c&&r?(r-s)/c:void 0,event:a,lengthComputable:r!=null,[t?"download":"upload"]:!0};n(I)},o)},td=(n,t)=>{let o=n!=null;return[i=>t[0]({lengthComputable:o,total:n,loaded:i}),t[1]]},rd=(n,t=Z.asap)=>(...o)=>t(()=>n(...o));var XJ=n=>n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102,eq=(n,t,o)=>t+2n<=57?n-48:(n&223)-55,Kme=n=>n>=65&&n<=90||n>=97&&n<=122||n>=48&&n<=57||n===43||n===47||n===45||n===95,xme=n=>n===9||n===10||n===12||n===13||n===32,Yme=n=>{let t=Math.floor(n/4),o=n%4;return t*3+(o===2?1:o===3?2:0)},Aq=n=>{let t=n.length,o=0;return t>0&&n.charCodeAt(t-1)===61&&(o++,t>1&&n.charCodeAt(t-2)===61&&o++),Math.floor((t-o)*3/4)},jme=n=>{let t=n.length,o=0,i=0,e=!1;for(let a=0;a0){e=!0;continue}o++}}return e||i>2||i>0&&(o+i)%4!==0||o%4===1?Aq(n):Yme(o)},tq=(n,t)=>{if(!n||typeof n!="string"||!n.startsWith("data:"))return 0;let o=n.indexOf(",");if(o<0)return 0;let i=n.slice(5,o),e=n.slice(o+1);if(/;base64/i.test(i))return t(e);let A=0;for(let r=0,s=e.length;r=55296&&g<=56319&&r+1=56320&&c<=57343?(A+=4,r++):A+=3}else A+=3}return A};function I0(n){let t=typeof n=="string"?n.indexOf("#"):-1;return tq(t===-1?n:n.slice(0,t),jme)}function rq(n){return tq(n,Aq)}var iq={flush:_o.constants.Z_SYNC_FLUSH,finishFlush:_o.constants.Z_SYNC_FLUSH},Vme={flush:_o.constants.BROTLI_OPERATION_FLUSH,finishFlush:_o.constants.BROTLI_OPERATION_FLUSH},Wme={flush:_o.constants.ZSTD_e_flush,finishFlush:_o.constants.ZSTD_e_flush},Bq=Z.isFunction(_o.createBrotliDecompress),fq=Z.isFunction(_o.createZstdDecompress),Qq="gzip, compress, deflate"+(Bq?", br":""),Zme=Qq+(fq?", zstd":""),oq=typeof process<"u"&&process.nextTick?process.nextTick.bind(process):Z.asap,{http:Xme,https:$me}=uq.default,p0=/https:?/,nq=Symbol("axios.http.socketListener"),Qy=Symbol("axios.http.currentReq");function eSe(n){let t=this[Qy];t&&!t.destroyed&&t.destroy(n)}var yq=Symbol("axios.http.installedTunnel"),ASe=new Map,sq=new WeakMap,gq={22:21,24:5};function tSe(n=process.versions&&process.versions.node){if(!n)return!1;let[t,o]=n.split(".").map(i=>Number(i));return!Number.isInteger(t)||!Number.isInteger(o)?!1:t>24?!0:gq[t]!=null&&o>=gq[t]}function cq(n,t=process.versions&&process.versions.node){if(!tSe(t))return!1;let o=n&&n.options;return!!(o&&Z.hasOwnProp(o,"proxyEnv")&&o.proxyEnv!=null)}function rSe(n,t,o){return p0.test(n.protocol)?o||Cq.globalAgent:t||Eq.globalAgent}function aSe(n,t){let o=n.protocol+"//"+n.hostname+":"+(n.port||"")+"#"+(n.auth||""),i=t?sq.get(t)||sq.set(t,new Map).get(t):ASe,e=i.get(o);if(e)return e;let a=t&&t.options?{...t.options,...n}:n;if(e=new l0.default(a),t&&t.options){let A={...t.options},r=e.callback;e.callback=function(g,c){return r.call(this,g,{...A,...c})}}return e[yq]=!0,i.set(o,e),e}var Iq=Ct.protocols.map(n=>n+":"),lq=n=>{if(!Z.isString(n))return n;try{return decodeURIComponent(n)}catch{return n}},pq=(n,[t,o])=>(n.on("end",o).on("error",o),t),iSe=new UJ;function oSe(n,t,o){n.beforeRedirects.proxy&&n.beforeRedirects.proxy(n),n.beforeRedirects.auth&&n.beforeRedirects.auth(n),n.beforeRedirects.sensitiveHeaders&&n.beforeRedirects.sensitiveHeaders(n,o),n.beforeRedirects.config&&n.beforeRedirects.config(n,t,o)}function nSe(n,t){n&&Object.keys(n).forEach(o=>{t.has(o.toLowerCase())&&delete n[o]})}function sSe(n,t){if(!t)return!1;try{return new URL(t.url).origin===new URL(n.href).origin}catch{return!1}}function mq(n,t,o,i,e,a,A=!0){let r=t,s=rSe(n,a,e);if(!r&&r!==!1&&A&&!cq(s)){let g=dJ(o);g&&(c0(o)||(r=new URL(g)))}if(i&&n.headers)for(let g of Object.keys(n.headers))g.toLowerCase()==="proxy-authorization"&&delete n.headers[g];if(i&&n.agent&&n.agent[yq]&&(n.agent=void 0),r){let g=r instanceof URL,c=Q=>g||Z.hasOwnProp(r,Q)?r[Q]:void 0,I=c("username"),d=c("password"),B=Z.hasOwnProp(r,"auth")?r.auth:void 0;if(I&&(B=(I||"")+":"+(d||"")),B){let Q=typeof B=="object",y=Q&&Z.hasOwnProp(B,"username")?B.username:void 0,m=Q&&Z.hasOwnProp(B,"password")?B.password:void 0;if(!!(y||m))B=(y||"")+":"+(m||"");else if(Q)throw new ye("Invalid proxy authorization",ye.ERR_BAD_OPTION,{proxy:r})}if(p0.test(n.protocol)){if(!(e instanceof l0.default)){let Q=c("hostname")||c("host"),y=c("port"),m=c("protocol"),_=m?m.includes(":")?m:`${m}:`:"http:",T=Q&&Q.includes(":")&&!Q.startsWith("[")?`[${Q}]`:Q,R=new URL(`${_}//${T}${y?":"+y:""}`),F={protocol:R.protocol,hostname:R.hostname.replace(/^\[|\]$/g,""),port:R.port,auth:B&&typeof B=="string"?B:void 0};R.protocol==="https:"&&(F.ALPNProtocols=["http/1.1"]);let K=aSe(F,e);n.agent=K,n.agents&&(n.agents.https=K)}}else{if(B){let _=Buffer.from(B,"utf8").toString("base64");n.headers["Proxy-Authorization"]="Basic "+_}let Q=!1;for(let _ of Object.keys(n.headers))if(_.toLowerCase()==="host"){Q=!0;break}Q||(n.headers.host=n.hostname+(n.port?":"+n.port:""));let y=c("hostname")||c("host");n.hostname=y,n.host=y,n.port=c("port"),n.path=o;let m=c("protocol");m&&(n.protocol=m.includes(":")?m:`${m}:`)}}return n.beforeRedirects.proxy=function(c){mq(c,t,c.href,!0,e,a,A)},!!(r||t!==!1&&A&&cq(s))}var gSe=typeof process<"u"&&Z.kindOf(process)==="process",cSe=n=>new Promise((t,o)=>{let i,e,a=(s,g)=>{e||(e=!0,i&&i(s,g))},A=s=>{a(s),t(s)},r=s=>{a(s,!0),o(s)};n(A,r,s=>i=s).catch(r)}),ISe=({address:n,family:t})=>{if(!Z.isString(n))throw new ye("address must be a string",ye.ERR_BAD_OPTION_VALUE);return{address:n,family:t||(n.indexOf(".")<0?6:4)}},dq=(n,t)=>ISe(Z.isObject(n)?n:{address:n,family:t}),hq=new WeakMap,lSe=n=>{let t=hq.get(n);if(t)return t;let o=HJ(n,i=>Z.isArray(i)?i:[i]);return t=(i,e,a)=>{o(i,e,(A,r,s)=>{if(A)return a(A);let g;try{g=Z.isArray(r)?r.map(c=>dq(c)):[dq(r,s)]}catch(c){return a(c)}e.all?a(A,g):a(A,g[0].address,g[0].family)})},hq.set(n,t),t},pSe={request(n,t){let o=n.protocol+"//"+n.hostname+":"+(n.port||(n.protocol==="https:"?443:80)),{http2Options:i,headers:e}=n,a=iSe.getSession(o,i),{HTTP2_HEADER_SCHEME:A,HTTP2_HEADER_METHOD:r,HTTP2_HEADER_PATH:s,HTTP2_HEADER_STATUS:g}=Jme.constants,c={[A]:n.protocol.replace(":",""),[r]:n.method,[s]:n.path};Z.forEach(e,(d,B)=>{B.charAt(0)!==":"&&(c[B]=d)});let I=a.request(c);return I.once("response",d=>{let B=I;d=Object.assign({},d);let f=d[g];delete d[g],B.headers=d,B.statusCode=+f,t(B)}),I}},Sq=gSe&&function(t){return cSe(async function(i,e,a){let A=we=>Z.getSafeProp(t,we),r=A("transitional")||Ic,s=A("data"),g=A("lookup"),c=A("family"),I=A("httpVersion");I===void 0&&(I=1);let d=I,B=A("http2Options"),f=A("httpAgent"),Q=A("httpsAgent"),y=A("proxy"),m=A("responseType"),_=A("responseEncoding"),T=A("socketPath"),R=A("method").toUpperCase(),F=A("maxRedirects"),K=A("maxBodyLength"),L=A("maxContentLength"),q=A("decompress"),z,j=!1,P,J;try{I=+I}catch{throw new ye("Invalid protocol version: value is not a number",ye.ERR_BAD_OPTION_VALUE,t)}if(Number.isNaN(I))throw new ye(`Invalid protocol version: '${d}' is not a number`,ye.ERR_BAD_OPTION_VALUE,t);if(I!==1&&I!==2)throw new ye(`Unsupported protocol version '${I}'`,ye.ERR_BAD_OPTION_VALUE,t);let U=I===2;g&&(g=lSe(g));let N=new zme;function k(we){try{N.emit("abort",!we||we.type?new $i(null,t,P):we)}catch{}}function V(){J&&(clearTimeout(J),J=null)}function Ae(){let we=A("timeout"),Ke=we?"timeout of "+we+"ms exceeded":"timeout exceeded",Ve=A("timeoutErrorMessage");return Ve&&(Ke=Ve),new ye(Ke,r.clarifyTimeoutError?ye.ETIMEDOUT:ye.ECONNABORTED,t,P)}N.once("abort",e);let ie=()=>{V(),t.cancelToken&&t.cancelToken.unsubscribe(k),t.signal&&t.signal.removeEventListener("abort",k),N.removeAllListeners()};(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(k),t.signal&&(t.signal.aborted?k():t.signal.addEventListener("abort",k))),a((we,Ke)=>{if(z=!0,V(),Ke){j=!0,ie();return}let{data:Ve}=we;if(Ve instanceof Cn.Readable||Ve instanceof Cn.Duplex){let NA=Cn.finished(Ve,()=>{NA(),ie()})}else ie()});let De=GI(A("baseURL"),A("url"),A("allowAbsoluteUrls"),t),fe=T?"http://localhost":Ct.hasBrowserEnv?Ct.origin:void 0,_e=new URL(De,fe),Ee=_e.protocol||Iq[0];if(Ee==="data:"){if(L>-1){let Ke=String(A("url")||De||"");if(rq(Ke)>L)return e(new ye("maxContentLength size of "+L+" exceeded",ye.ERR_BAD_RESPONSE,t))}let we;if(R!=="GET")return ts(i,e,{status:405,statusText:"method not allowed",headers:{},config:t});try{we=A0(A("url"),m==="blob",{Blob:t.env&&t.env.Blob})}catch(Ke){throw ye.from(Ke,ye.ERR_BAD_REQUEST,t)}return m==="text"?(we=we.toString(_),(!_||_==="utf8")&&(we=Z.stripBOM(we))):m==="stream"&&(we=Cn.Readable.from(we)),ts(i,e,{data:we,status:200,statusText:"OK",headers:new Ut,config:t})}if(Iq.indexOf(Ee)===-1)return e(new ye("Unsupported protocol "+Ee,ye.ERR_BAD_REQUEST,t));let Qe=Ut.from(t.headers).normalize();Qe.set("User-Agent","axios/"+ng,!1);let{onUploadProgress:Le,onDownloadProgress:AA}=t,aA=t.maxRate,He,ce;if(Z.isSpecCompliantForm(s)){let we=Qe.getContentType(/boundary=([-_\w\d]{10,70})/i);s=FJ(s,Ke=>{Qe.set(Ke)},{tag:`axios-${ng}-boundary`,boundary:we&&we[1]||void 0})}else if(Z.isFormData(s)&&Z.isFunction(s.getHeaders)&&s.getHeaders!==Object.prototype.getHeaders){if(yC(Qe,s.getHeaders(),A("formDataHeaderPolicy")),!Qe.hasContentLength())try{let we=await qme.promisify(s.getLength).call(s);Number.isFinite(we)&&we>=0&&Qe.setContentLength(we)}catch{}}else if(Z.isBlob(s)||Z.isFile(s))s.size&&Qe.setContentType(s.type||"application/octet-stream"),Qe.setContentLength(s.size||0),s=Cn.Readable.from(fy(s));else if(s&&!Z.isStream(s)){if(!Buffer.isBuffer(s))if(Z.isArrayBuffer(s))s=Buffer.from(new Uint8Array(s));else if(Z.isString(s))s=Buffer.from(s,"utf-8");else return e(new ye("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",ye.ERR_BAD_REQUEST,t));if(Qe.setContentLength(s.length,!1),K>-1&&s.length>K)return e(new ye("Request body larger than maxBodyLength limit",ye.ERR_BAD_REQUEST,t))}let Be=Z.toFiniteNumber(Qe.getContentLength());Z.isArray(aA)?(He=aA[0],ce=aA[1]):He=ce=aA,s&&(Le||He)&&(Z.isStream(s)||(s=Cn.Readable.from(s,{objectMode:!1})),s=Cn.pipeline([s,new a0({maxRate:Z.toFiniteNumber(He)})],Z.noop),Le&&s.on("progress",pq(s,td(Be,sg(rd(Le,oq),!1,3)))));let We,Ye=A("auth");if(Ye){let we=Z.getSafeProp(Ye,"username")||"",Ke=Z.getSafeProp(Ye,"password")||"";We=we+":"+Ke}if(!We&&(_e.username||_e.password)){let we=lq(_e.username),Ke=lq(_e.password);We=we+":"+Ke}We&&Qe.delete("authorization");let Re;try{Re=PI(_e.pathname+_e.search,A("params"),A("paramsSerializer")).replace(/^\?/,"")}catch(we){return e(ye.from(we,ye.ERR_BAD_REQUEST,t,null,null,{url:A("url"),exists:!0}))}Qe.set("Accept-Encoding",Z.hasOwnProp(r,"advertiseZstdAcceptEncoding")&&r.advertiseZstdAcceptEncoding===!0?Zme:Qq,!1),U&&g&&(B=Object.assign(Object.create(null),B,{lookup:g}));let Ze=Object.assign(Object.create(null),{path:Re,method:R,headers:Yp(Qe),agents:{http:f,https:Q},auth:We,protocol:Ee,family:c,beforeRedirect:oSe,beforeRedirects:Object.create(null),http2Options:B,createConnection:void 0});!Z.isUndefined(g)&&(Ze.lookup=g);let iA=!1;if(T){if(typeof T!="string")return e(new ye("socketPath must be a string",ye.ERR_BAD_OPTION_VALUE,t));let we=A("allowedSocketPaths");if(we!=null){let Ke=Array.isArray(we)?we:[we],Ve=aq(T);if(!Ke.some(wA=>typeof wA=="string"&&aq(wA)===Ve))return e(new ye(`socketPath "${T}" is not permitted by allowedSocketPaths`,ye.ERR_BAD_OPTION_VALUE,t))}Ze.socketPath=T}else Ze.hostname=_e.hostname.startsWith("[")?_e.hostname.slice(1,-1):_e.hostname,Ze.port=_e.port,iA=mq(Ze,y,Ee+"//"+_e.hostname+(_e.port?":"+_e.port:"")+Ze.path,!1,Q,f,!U);let gA,WA=!1,FA=!1,Me=p0.test(Ze.protocol);if(Ze.agent==null&&(Ze.agent=Me?Q:f),U){if(iA)return e(new ye("HTTP/2 requests with a proxy are not supported",ye.ERR_NOT_SUPPORT,t));gA=pSe}else{let we=A("transport");if(we)gA=we;else if(F===0)gA=Me?Cq:Eq,WA=!0;else{FA=!0,Ze.sensitiveHeaders=[],F&&(Ze.maxRedirects=F);let Ke=A("beforeRedirect");if(Ke&&(Ze.beforeRedirects.config=Ke),We){let NA=_e.origin,wA=We;Ze.beforeRedirects.auth=function(JA){try{new URL(JA.href).origin===NA&&(JA.auth=wA)}catch{}}}let Ve=A("sensitiveHeaders");if(Ve!=null){if(!Z.isArray(Ve))return e(new ye("sensitiveHeaders must be an array of strings",ye.ERR_BAD_OPTION_VALUE,t));let NA=new Set;for(let wA of Ve){if(!Z.isString(wA))return e(new ye("sensitiveHeaders must be an array of strings",ye.ERR_BAD_OPTION_VALUE,t));NA.add(wA.toLowerCase())}NA.size&&(Ze.sensitiveHeaders=Array.from(NA),Ze.beforeRedirects.sensitiveHeaders=function(LA,JA){sSe(LA,JA)||nSe(LA.headers,NA)})}gA=Me?$me:Xme}}K>-1?Ze.maxBodyLength=K:Ze.maxBodyLength=1/0,Ze.insecureHTTPParser=!!A("insecureHTTPParser"),P=gA.request(Ze,function(Ke){if(V(),P.destroyed)return;let Ve=[Ke],NA=Z.toFiniteNumber(Ke.headers["content-length"]);if(AA||ce){let lt=new a0({maxRate:Z.toFiniteNumber(ce)});AA&<.on("progress",pq(lt,td(NA,sg(rd(AA,oq),!0,3)))),Ve.push(lt)}let wA=Ke,LA=Ke.req||P;if(q!==!1&&Ke.headers["content-encoding"])switch((R==="HEAD"||Ke.statusCode===204)&&delete Ke.headers["content-encoding"],(Ke.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Ve.push(_o.createUnzip(iq)),delete Ke.headers["content-encoding"];break;case"deflate":Ve.push(new LJ),Ve.push(_o.createUnzip(iq)),delete Ke.headers["content-encoding"];break;case"br":Bq&&(Ve.push(_o.createBrotliDecompress(Vme)),delete Ke.headers["content-encoding"]);break;case"zstd":fq&&(Ve.push(_o.createZstdDecompress(Wme)),delete Ke.headers["content-encoding"]);break}wA=Ve.length>1?Cn.pipeline(Ve,Z.noop):Ve[0];let JA={status:Ke.statusCode,statusText:Ke.statusMessage,headers:new Ut(Ke.headers),config:t,request:LA};if(m==="stream"){if(L>-1){let lt=L,wt=wA;async function*pe(){let Ie=0;for await(let be of wt){if(Ie+=be.length,Ie>lt)throw new ye("maxContentLength size of "+lt+" exceeded",ye.ERR_BAD_RESPONSE,t,LA);yield be}}wA=Cn.Readable.from(pe(),{objectMode:!1})}JA.data=wA,ts(i,e,JA)}else{let lt=[],wt=0;wA.on("data",function(Ie){lt.push(Ie),wt+=Ie.length,L>-1&&wt>L&&(j=!0,wA.destroy(),k(new ye("maxContentLength size of "+L+" exceeded",ye.ERR_BAD_RESPONSE,t,LA)))}),wA.on("aborted",function(){if(j)return;let Ie=new ye("stream has been aborted",ye.ERR_BAD_RESPONSE,t,LA,JA);wA.destroy(Ie),e(Ie)}),wA.on("error",function(Ie){j||e(ye.from(Ie,null,t,LA,JA))}),wA.on("end",function(){try{let Ie=lt.length===1?lt[0]:Buffer.concat(lt);m!=="arraybuffer"&&(Ie=Ie.toString(_),(!_||_==="utf8")&&(Ie=Z.stripBOM(Ie))),JA.data=Ie}catch(Ie){return e(ye.from(Ie,null,t,JA.request,JA))}ts(i,e,JA)})}N.once("abort",lt=>{wA.destroyed||(wA.emit("error",lt),wA.destroy())})}),N.once("abort",we=>{P.close?P.close():P.destroy(we)}),P.on("error",function(Ke){e(ye.from(Ke,null,t,P))});let CA=new Set;if(P.on("socket",function(Ke){typeof Ke.setKeepAlive=="function"&&Ke.setKeepAlive(!0,1e3*60),Ke[nq]||(Ke.on("error",eSe),Ke[nq]=!0),Ke[Qy]=P,CA.add(Ke)}),P.once("close",function(){V();for(let Ke of CA)Ke[Qy]===P&&(Ke[Qy]=null);CA.clear()}),A("timeout")){let we=parseInt(A("timeout"),10);if(Number.isNaN(we)){k(new ye("error trying to parse `config.timeout` to int",ye.ERR_BAD_OPTION_VALUE,t,P));return}let Ke=function(){z||k(Ae())};WA&&we>0&&(J=setTimeout(Ke,we)),P.setTimeout(we,Ke)}else P.setTimeout(0);if(Z.isStream(s)){let we=!1,Ke=!1;s.on("end",()=>{we=!0}),s.once("error",NA=>{Ke=!0,P.destroy(NA)}),s.on("close",()=>{!we&&!Ke&&k(new $i("Request stream has been aborted",t,P))});let Ve=s;if(K>-1&&!FA){let NA=K,wA=0;Ve=Cn.pipeline([s,new Cn.Transform({transform(LA,JA,lt){if(wA+=LA.length,wA>NA)return lt(new ye("Request body larger than maxBodyLength limit",ye.ERR_BAD_REQUEST,t,P));lt(null,LA)}})],Z.noop),Ve.on("error",LA=>{P.destroyed||P.destroy(LA)})}Ve.pipe(P)}else s&&P.write(s),P.end()})};var wq=Ct.hasStandardBrowserEnv?((n,t)=>o=>(o=new URL(o,Ct.origin),n.protocol===o.protocol&&n.host===o.host&&(t||n.port===o.port)))(new URL(Ct.origin),Ct.navigator&&/(msie|trident)/i.test(Ct.navigator.userAgent)):()=>!0;var Dq=Ct.hasStandardBrowserEnv?{write(n,t,o,i,e,a,A){if(typeof document>"u")return;let r=[`${n}=${encodeURIComponent(t)}`];Z.isNumber(o)&&r.push(`expires=${new Date(o).toUTCString()}`),Z.isString(i)&&r.push(`path=${i}`),Z.isString(e)&&r.push(`domain=${e}`),a===!0&&r.push("secure"),Z.isString(A)&&r.push(`SameSite=${A}`),document.cookie=r.join("; ")},read(n){if(typeof document>"u")return null;let t=document.cookie.split(";");for(let o=0;on instanceof Ut?{...n}:n,dSe=n=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(n).concat(Object.getOwnPropertySymbols(n).filter(t=>Object.getOwnPropertyDescriptor(n,t).enumerable)):Object.keys(n);function un(n,t){n=n||{},t=t||{};let o=Object.create(null);Object.defineProperty(o,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function i(c,I,d,B){return Z.isPlainObject(c)&&Z.isPlainObject(I)?Z.merge.call({caseless:B},c,I):Z.isPlainObject(I)?Z.merge({},I):Z.isArray(I)?I.slice():I}function e(c,I,d,B){if(Z.isUndefined(I)){if(!Z.isUndefined(c))return i(void 0,c,d,B)}else return i(c,I,d,B)}function a(c,I){if(!Z.isUndefined(I))return i(void 0,I)}function A(c,I){if(Z.isUndefined(I)){if(!Z.isUndefined(c))return i(void 0,c)}else return i(void 0,I)}function r(c){let I=Z.hasOwnProp(t,"transitional")?t.transitional:void 0;if(!Z.isUndefined(I))if(Z.isPlainObject(I)){if(Z.hasOwnProp(I,c))return I[c]}else return;let d=Z.hasOwnProp(n,"transitional")?n.transitional:void 0;if(Z.isPlainObject(d)&&Z.hasOwnProp(d,c))return d[c]}function s(c,I,d){if(Z.hasOwnProp(t,d))return i(c,I);if(Z.hasOwnProp(n,d))return i(void 0,c)}let g={url:a,method:a,data:a,baseURL:A,transformRequest:A,transformResponse:A,paramsSerializer:A,timeout:A,timeoutErrorMessage:A,withCredentials:A,withXSRFToken:A,adapter:A,responseType:A,xsrfCookieName:A,xsrfHeaderName:A,onUploadProgress:A,onDownloadProgress:A,decompress:A,maxContentLength:A,maxBodyLength:A,beforeRedirect:A,transport:A,httpAgent:A,httpsAgent:A,cancelToken:A,socketPath:A,allowedSocketPaths:A,responseEncoding:A,validateStatus:s,headers:(c,I,d)=>e(Oq(c),Oq(I),d,!0)};return Z.forEach(dSe({...n,...t}),function(I){if(I==="__proto__"||I==="constructor"||I==="prototype")return;let d=Z.hasOwnProp(g,I)?g[I]:e,B=Z.hasOwnProp(n,I)?n[I]:void 0,f=Z.hasOwnProp(t,I)?t[I]:void 0,Q=d(B,f,I);Z.isUndefined(Q)&&d!==s||(o[I]=Q)}),Z.hasOwnProp(t,"validateStatus")&&Z.isUndefined(t.validateStatus)&&r("validateStatusUndefinedResolves")===!1&&(Z.hasOwnProp(n,"validateStatus")?o.validateStatus=i(void 0,n.validateStatus):delete o.validateStatus),o}var hSe=n=>encodeURIComponent(n).replace(/%([0-9A-F]{2})/gi,(t,o)=>String.fromCharCode(parseInt(o,16)));function ESe(n){let t=un({},n),o=d=>Z.hasOwnProp(t,d)?t[d]:void 0,i=o("data"),e=o("withXSRFToken"),a=o("xsrfHeaderName"),A=o("xsrfCookieName"),r=o("headers"),s=o("auth"),g=o("baseURL"),c=o("allowAbsoluteUrls"),I=o("url");if(t.headers=r=Ut.from(r),t.url=PI(GI(g,I,c,t),o("params"),o("paramsSerializer")),s){let d=Z.getSafeProp(s,"username")||"",B=Z.getSafeProp(s,"password")||"";try{r.set("Authorization","Basic "+btoa(d+":"+(B?hSe(B):"")))}catch(f){throw ye.from(f,ye.ERR_BAD_OPTION_VALUE,n)}}if(Z.isFormData(i)){let d=Z.getSafeProp(i,"getHeaders");Ct.hasStandardBrowserEnv||Ct.hasStandardBrowserWebWorkerEnv||Z.isReactNative(i)?r.setContentType(void 0):Z.isFunction(d)&&yC(r,d.call(i),o("formDataHeaderPolicy"))}if(Ct.hasStandardBrowserEnv&&(Z.isFunction(e)&&(e=e(t)),e===!0||e==null&&wq(t.url))){let B=a&&A&&Dq.read(A);B&&r.set(a,B)}return t}var yy=ESe;var CSe=typeof XMLHttpRequest<"u",bq=CSe&&function(n){return new Promise(function(o,i){let e=yy(n),a=e.data,A=Ut.from(e.headers).normalize(),{responseType:r,onUploadProgress:s,onDownloadProgress:g}=e,c,I,d,B,f,Q;function y(){B&&B(),f&&f(),e.cancelToken&&e.cancelToken.unsubscribe(c),e.signal&&e.signal.removeEventListener("abort",c)}let m=new XMLHttpRequest;m.open(e.method.toUpperCase(),e.url,!0),m.timeout=e.timeout;function _(R){if(!m)return;if(m.status===0&&(KI(pC(e.url))||KI(Ct.origin))!=="file"&&!(m.responseURL&&m.responseURL.startsWith("file:"))){i(new ye("Request aborted",ye.ECONNABORTED,n,m)),y(),m=null;return}try{R?Q&&Q(R):f&&f()}catch(q){setTimeout(()=>{throw q})}if(!m)return;let F=Ut.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),L={data:!r||r==="text"||r==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:F,config:n,request:m};ts(function(z){o(z),y()},function(z){i(z),y()},L),m=null}"onloadend"in m?m.onloadend=_:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.startsWith("file:"))||setTimeout(_)},m.onabort=function(){m&&(i(new ye("Request aborted",ye.ECONNABORTED,n,m)),y(),m=null)},m.onerror=function(F){let K=F&&F.message?F.message:"Network Error",L=new ye(K,ye.ERR_NETWORK,n,m);L.event=F||null,i(L),y(),m=null},m.ontimeout=function(){let F=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",K=e.transitional||Ic;e.timeoutErrorMessage&&(F=e.timeoutErrorMessage),i(new ye(F,K.clarifyTimeoutError?ye.ETIMEDOUT:ye.ECONNABORTED,n,m)),y(),m=null},a===void 0&&A.setContentType(null),"setRequestHeader"in m&&Z.forEach(Yp(A),function(F,K){m.setRequestHeader(K,F)}),Z.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),r&&r!=="json"&&(m.responseType=e.responseType),g&&([d,f,Q]=sg(g,!0),m.addEventListener("progress",d)),s&&m.upload&&([I,B]=sg(s),m.upload.addEventListener("progress",I),m.upload.addEventListener("loadend",B)),(e.cancelToken||e.signal)&&(c=R=>{m&&(i(!R||R.type?new $i(null,n,m):R),m.abort(),y(),m=null)},e.cancelToken&&e.cancelToken.subscribe(c),e.signal&&(e.signal.aborted?c():e.signal.addEventListener("abort",c)));let T=KI(e.url);if(T&&!Ct.protocols.includes(T)){i(new ye("Unsupported protocol "+T+":",ye.ERR_BAD_REQUEST,n)),y();return}m.send(a||null)})};var uSe=(n,t)=>{if(n=n?n.filter(Boolean):[],!t&&!n.length)return;let o=new AbortController,i=!1,e=function(s){if(!i){i=!0,A();let g=s instanceof Error?s:this.reason;o.abort(g instanceof ye?g:new $i(g instanceof Error?g.message:g))}},a=t&&setTimeout(()=>{a=null,e(new ye(`timeout of ${t}ms exceeded`,ye.ETIMEDOUT))},t),A=()=>{n&&(a&&clearTimeout(a),a=null,n.forEach(s=>{s.unsubscribe?s.unsubscribe(e):s.removeEventListener("abort",e)}),n=null)};n.forEach(s=>{if(!i){if(s.aborted){e.call(s);return}s.addEventListener("abort",e,{once:!0})}});let{signal:r}=o;return r.unsubscribe=()=>Z.asap(A),r},Mq=uSe;var BSe=function*(n,t){let o=n.byteLength;if(!t||o{let e=fSe(n,t),a=0,A,r=s=>{A||(A=!0,i&&i(s))};return new ReadableStream({async pull(s){try{let{done:g,value:c}=await e.next();if(g){r(),s.close();return}let I=c.byteLength;if(o){let d=a+=I;o(d)}s.enqueue(new Uint8Array(c))}catch(g){throw r(g),g}},cancel(s){return r(s),e.return()}},{highWaterMark:2})};var _q=64*1024,ySe={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},{isFunction:my}=Z,mSe=n=>encodeURIComponent(n).replace(/%([0-9A-F]{2})/gi,(t,o)=>String.fromCharCode(parseInt(o,16))),Tq=n=>{if(!Z.isString(n))return n;try{return decodeURIComponent(n)}catch{return n}},Nq=(n,...t)=>{try{return!!n(...t)}catch{return!1}},SSe=n=>{let t=n.indexOf("://"),o=n;return t!==-1&&(o=o.slice(t+3)),o.includes("@")||o.includes(":")},wSe=n=>{let t=Z.global!==void 0&&Z.global!==null?Z.global:globalThis,{ReadableStream:o,TextEncoder:i}=t;n=Z.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},n);let{fetch:e,Request:a,Response:A}=n,r=e?my(e):typeof fetch=="function",s=my(a),g=my(A);if(!r)return!1;let c=r&&my(o),I=r&&(typeof i=="function"?(m=>_=>m.encode(_))(new i):async m=>new Uint8Array(await new a(m).arrayBuffer())),d=s&&c&&Nq(()=>{let m=!1,_=new a(Ct.origin,{body:new o,method:"POST",get duplex(){return m=!0,"half"}}),T=_.headers.has("Content-Type");return _.body!=null&&_.body.cancel(),m&&!T}),B=g&&c&&Nq(()=>Z.isReadableStream(new A("").body)),f={stream:B&&(m=>m.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!f[m]&&(f[m]=(_,T)=>{let R=_&&_[m];if(R)return R.call(_);throw new ye(`Response type '${m}' is not supported`,ye.ERR_NOT_SUPPORT,T)})});let Q=async m=>{if(m==null)return 0;if(Z.isBlob(m))return m.size;if(Z.isSpecCompliantForm(m))return(await new a(Ct.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(Z.isArrayBufferView(m)||Z.isArrayBuffer(m))return m.byteLength;if(Z.isURLSearchParams(m)&&(m=m+""),Z.isString(m))return(await I(m)).byteLength},y=async(m,_)=>{let T=Z.toFiniteNumber(m.getContentLength());return T??Q(_)};return async m=>{let{url:_,method:T,data:R,signal:F,cancelToken:K,timeout:L,onDownloadProgress:q,onUploadProgress:z,responseType:j,headers:P,withCredentials:J="same-origin",fetchOptions:U,maxContentLength:N,maxBodyLength:k,maxRedirects:V}=yy(m),Ae=Z.isNumber(N)&&N>-1,ie=Z.isNumber(k)&&k>-1,De=He=>Z.hasOwnProp(m,He)?m[He]:void 0,fe=e||fetch;j=j?(j+"").toLowerCase():"text";let _e=Mq([F,K&&K.toAbortSignal()],L),Ee=null,Qe=_e&&_e.unsubscribe&&(()=>{_e.unsubscribe()}),Le,AA=null,aA=()=>new ye("Request body larger than maxBodyLength limit",ye.ERR_BAD_REQUEST,m,Ee);try{let He,ce=De("auth");if(ce){let Me=Z.getSafeProp(ce,"username")||"",CA=Z.getSafeProp(ce,"password")||"";He={username:Me,password:CA}}if(SSe(_)){let Me=new URL(_,Ct.origin);if(!He&&(Me.username||Me.password)){let CA=Tq(Me.username),we=Tq(Me.password);He={username:CA,password:we}}(Me.username||Me.password)&&(Me.username="",Me.password="",_=Me.href)}if(He&&(P.delete("authorization"),P.set("Authorization","Basic "+btoa(mSe((He.username||"")+":"+(He.password||""))))),Ae&&typeof _=="string"&&_.startsWith("data:")&&I0(_)>N)throw new ye("maxContentLength size of "+N+" exceeded",ye.ERR_BAD_RESPONSE,m,Ee);if(ie&&T!=="get"&&T!=="head"){let Me=await Q(R);if(typeof Me=="number"&&isFinite(Me)&&(Le=Me,Me>k))throw aA()}let Be=ie&&(Z.isReadableStream(R)||Z.isStream(R)),We=(Me,CA,we)=>d0(Me,_q,Ke=>{if(ie&&Ke>k)throw AA=aA();CA&&CA(Ke)},we);if(d&&T!=="get"&&T!=="head"&&(z||Be)){if(Le=Le??await y(P,R),Le!==0||Be){let Me=new a(_,{method:"POST",body:R,duplex:"half"}),CA;if(Z.isFormData(R)&&(CA=Me.headers.get("content-type"))&&P.setContentType(CA),Me.body){let[we,Ke]=z&&td(Le,sg(rd(z)))||[];R=We(Me.body,we,Ke)}}}else if(Be&&!s&&c&&T!=="get"&&T!=="head")R=We(R);else if(Be&&s&&!d&&T!=="get"&&T!=="head")throw new ye("Stream request bodies are not supported by the current fetch implementation",ye.ERR_NOT_SUPPORT,m,Ee);Z.isString(J)||(J=J?"include":"omit");let Ye=s&&"credentials"in a.prototype;if(Z.isFormData(R)){let Me=P.getContentType();Me&&/^multipart\/form-data/i.test(Me)&&!/boundary=/i.test(Me)&&P.delete("content-type")}P.set("User-Agent","axios/"+ng,!1);let Re=U==null?U:Object.assign(Object.create(null),U);Re&&(delete Re.body,delete Re.headers,delete Re.method,delete Re.signal,delete Re.duplex,delete Re.credentials);let Ze=Object.assign(Object.create(null),Re,{signal:_e,method:T.toUpperCase(),headers:Yp(P.normalize()),body:R,duplex:"half",credentials:Ye?J:void 0});s&&(Z.forEach(ySe,(Me,CA)=>{Ze[CA]===void 0&&(Ze[CA]=Me)}),Ze.signal===void 0&&(Ze.signal=null),Ze.body===void 0&&(Ze.body=null)),V===0&&(Ze.redirect="manual",Re&&(Re.redirect="manual")),Ee=s&&new a(_,Ze);let iA=await(s?fe(Ee,Re):fe(_,Ze)),gA=Ut.from(iA.headers);if(Ae){let Me=Z.toFiniteNumber(gA.getContentLength());if(Me!=null&&Me>N)throw new ye("maxContentLength size of "+N+" exceeded",ye.ERR_BAD_RESPONSE,m,Ee)}let WA=B&&(j==="stream"||j==="response");if(B&&iA.body&&(q||Ae||WA&&Qe)){let Me={};["status","statusText","headers"].forEach(wA=>{Me[wA]=iA[wA]});let CA=Z.toFiniteNumber(gA.getContentLength()),[we,Ke]=q&&td(CA,sg(rd(q),!0))||[],Ve=0,NA=wA=>{if(Ae&&(Ve=wA,Ve>N))throw new ye("maxContentLength size of "+N+" exceeded",ye.ERR_BAD_RESPONSE,m,Ee);we&&we(wA)};iA=new A(d0(iA.body,_q,NA,()=>{Ke&&Ke(),Qe&&Qe()}),Me)}j=j||"text";let FA=await f[Z.findKey(f,j)||"text"](iA,m);if(Ae&&!B&&!WA){let Me;if(FA!=null&&(typeof FA.byteLength=="number"?Me=FA.byteLength:typeof FA.size=="number"?Me=FA.size:typeof FA=="string"&&(Me=typeof i=="function"?new i().encode(FA).byteLength:FA.length)),typeof Me=="number"&&Me>N)throw new ye("maxContentLength size of "+N+" exceeded",ye.ERR_BAD_RESPONSE,m,Ee)}return!WA&&Qe&&Qe(),await new Promise((Me,CA)=>{ts(Me,CA,{data:FA,headers:Ut.from(iA.headers),status:iA.status,statusText:iA.statusText,config:m,request:Ee})})}catch(He){if(Qe&&Qe(),_e&&_e.aborted&&_e.reason instanceof ye){let ce=_e.reason;throw ce.config=m,Ee&&(ce.request=Ee),He!==ce&&Object.defineProperty(ce,"cause",{__proto__:null,value:He,writable:!0,enumerable:!1,configurable:!0}),ce}if(AA)throw Ee&&!AA.request&&(AA.request=Ee),AA;if(He instanceof ye)throw Ee&&!He.request&&(He.request=Ee),He;if(He&&He.name==="TypeError"&&/Load failed|fetch/i.test(He.message)){let ce=new ye("Network Error",ye.ERR_NETWORK,m,Ee,He&&He.response);throw Object.defineProperty(ce,"cause",{__proto__:null,value:He.cause||He,writable:!0,enumerable:!1,configurable:!0}),ce}throw ye.from(He,He&&He.code,m,Ee,He&&He.response)}}},DSe=new Map,h0=n=>{let t=n&&n.env||{},{fetch:o,Request:i,Response:e}=t,a=[i,e,o],A=a.length,r=A,s,g,c=DSe;for(;r--;)s=a[r],g=c.get(s),g===void 0&&c.set(s,g=r?new Map:wSe(t)),c=g;return g},TnA=h0();var E0={http:Sq,xhr:bq,fetch:{get:h0}};Z.forEach(E0,(n,t)=>{if(n){try{Object.defineProperty(n,"name",{__proto__:null,value:t})}catch{}Object.defineProperty(n,"adapterName",{__proto__:null,value:t})}});var Rq=n=>`- ${n}`,bSe=n=>Z.isFunction(n)||n===null||n===!1;function MSe(n,t){n=Z.isArray(n)?n:[n];let{length:o}=n,i,e,a={};for(let A=0;A`adapter ${s} `+(g===!1?"is not supported by the environment":"is not available in the build")),r=o?A.length>1?`since : +`)}getSetCookie(){let t=this.get("set-cookie");return Z.isArray(t)?t:t==null||t===!1?[]:[t]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static parseParameters(t){return efe(t)}static concat(t,...o){let i=new this(t);return o.forEach(e=>i.set(e)),i}static accessor(t){let i=(this[W1]=this[W1]={accessors:{}}).accessors,e=this.prototype;function a(A){let r=tC(A);i[r]||(rfe(e,A),i[r]=!0)}return Z.isArray(t)?t.forEach(a):a(t),this}};jp.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Z.reduceDescriptors(jp.prototype,({value:n},t)=>{let o=t[0].toUpperCase()+t.slice(1);return{get:()=>n,set(i){this[o]=i}}});Z.freezeMethods(jp);var Ut=jp;var rC="[REDACTED ****]";function afe(n){if(Z.hasOwnProp(n,"toJSON"))return!0;let t=Object.getPrototypeOf(n);for(;t&&t!==Object.prototype;){if(Z.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function ife(n,t){let o=new Set(t.map(a=>String(a).toLowerCase())),i=[],e=a=>{if(a===null||typeof a!="object"||Z.isBuffer(a))return a;if(i.indexOf(a)!==-1)return;a instanceof Ut&&(a=a.toJSON()),i.push(a);let A;if(Z.isArray(a))A=[],a.forEach((r,s)=>{let g=e(r);Z.isUndefined(g)||(A[s]=g)});else{if(!Z.isPlainObject(a)&&afe(a))return i.pop(),a;A=Object.create(null);for(let[r,s]of Object.entries(a)){let g=o.has(r.toLowerCase())?rC:e(s);Z.isUndefined(g)||(A[r]=g)}}return i.pop(),A};return e(n)}function Z1(n){try{return String(n)}catch{return""}}function ofe(n){return n.errors.map(o=>{try{return o&&o.message?Z1(o.message):Z1(o)}catch{return""}}).filter(Boolean).join("; ")||n.name||"AggregateError"}var Ca=class n extends Error{static from(t,o,i,e,a,A){let r=t.message;!r&&Z.isArray(t.errors)&&t.errors.length&&(r=ofe(t));let s=new n(r,o||t.code,i,e,a);return Object.defineProperty(s,"cause",{__proto__:null,value:t,writable:!0,enumerable:!1,configurable:!0}),s.name=t.name,t.status!=null&&s.status==null&&(s.status=t.status),A&&Object.assign(s,A),s}constructor(t,o,i,e,a){super(t),Object.defineProperty(this,"message",{__proto__:null,value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,o&&(this.code=o),i&&(this.config=i),e&&(this.request=e),a&&(this.response=a,this.status=a.status)}toJSON(){let t=this.config,o=t&&Z.hasOwnProp(t,"redact")?t.redact:void 0,i=Z.isArray(o)&&o.length>0?ife(t,o):Z.toJSONObject(t);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:i,code:this.code,status:this.status}}};Ca.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";Ca.ERR_BAD_OPTION="ERR_BAD_OPTION";Ca.ECONNABORTED="ECONNABORTED";Ca.ETIMEDOUT="ETIMEDOUT";Ca.ECONNREFUSED="ECONNREFUSED";Ca.ERR_NETWORK="ERR_NETWORK";Ca.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";Ca.ERR_DEPRECATED="ERR_DEPRECATED";Ca.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";Ca.ERR_BAD_REQUEST="ERR_BAD_REQUEST";Ca.ERR_CANCELED="ERR_CANCELED";Ca.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";Ca.ERR_INVALID_URL="ERR_INVALID_URL";Ca.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var ye=Ca;var $j=Je(Xj(),1),Iy=$j.default;var ly={isBufferAvailable(){return typeof Buffer<"u"},from(n){return Buffer.from(n)}};var fT=100;function BT(n){return Z.isPlainObject(n)||Z.isArray(n)}function eJ(n){return Z.endsWith(n,"[]")?n.slice(0,-2):n}function uT(n,t,o){return n?n.concat(t).map(function(e,a){return e=eJ(e),!o&&a?"["+e+"]":e}).join(o?".":""):t}function jQe(n){return Z.isArray(n)&&!n.some(BT)}var JQe=Z.toFlatObject(Z,{},null,function(t){return/^is[A-Z]/.test(t)});function qQe(n,t,o){if(!Z.isObject(n))throw new TypeError("target must be an object");t=t||new(Iy||FormData);let i=(_,T)=>{let R=Z.getSafeProp(o,_);return Z.isUndefined(R)?T:R},e=i("metaTokens",!0),a=i("visitor")||Q,A=i("dots",!1),r=i("indexes",!1),s=i("Blob")||typeof Blob<"u"&&Blob,g=i("maxDepth",fT),c=s&&Z.isSpecCompliantForm(t),I=[];if(!Z.isFunction(a))throw new TypeError("visitor must be a function");function d(_){if(_===null)return"";if(Z.isDate(_))return _.toISOString();if(Z.isBoolean(_))return _.toString();if(!c&&Z.isBlob(_))throw new ye("Blob is not supported. Use a Buffer instead.");if(Z.isArrayBuffer(_)||Z.isTypedArray(_)){if(c&&typeof s=="function")return new s([_]);if(ly&&ly.isBufferAvailable())return ly.from(_);throw new ye("Blob is not supported. Use a Buffer instead.",ye.ERR_NOT_SUPPORT)}return _}function B(_){if(_>g)throw new ye("Object is too deeply nested ("+_+" levels). Max depth: "+g,ye.ERR_FORM_DATA_DEPTH_EXCEEDED)}function f(_,T){if(g===1/0)return JSON.stringify(_);let R=[];return JSON.stringify(_,function(U,F){if(!Z.isObject(F))return F;for(;R.length&&R[R.length-1]!==this;)R.pop();return R.push(F),B(T+R.length-1),F})}function Q(_,T,R){let L=_;if(Z.isReactNative(t)&&Z.isReactNativeBlob(_))return t.append(uT(R,T,A),d(_)),!1;if(_&&!R&&typeof _=="object"){if(Z.endsWith(T,"{}"))T=e?T:T.slice(0,-2),_=f(_,1);else if(Z.isArray(_)&&jQe(_)||(Z.isFileList(_)||Z.endsWith(T,"[]"))&&(L=Z.toArray(_)))return T=eJ(T),L.forEach(function(F,q){!(Z.isUndefined(F)||F===null)&&t.append(r===!0?uT([T],q,A):r===null?T:T+"[]",d(F))}),!1}return BT(_)?!0:(t.append(uT(R,T,A),d(_)),!1)}let y=Object.assign(JQe,{defaultVisitor:Q,convertValue:d,isVisitable:BT});function m(_,T,R=0){if(!Z.isUndefined(_)){if(B(R),I.indexOf(_)!==-1)throw new Error("Circular reference detected in "+T.join("."));I.push(_),Z.forEach(_,function(U,F){(!(Z.isUndefined(U)||U===null)&&a.call(t,U,Z.isString(F)?F.trim():F,T,y))===!0&&m(U,T?T.concat(F):[F],R+1)}),I.pop()}}if(!Z.isObject(n))throw new TypeError("data must be an object");return m(n),t}var cc=qQe;function AJ(n){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(n).replace(/[!'()~]|%20/g,function(i){return t[i]})}function tJ(n,t){this._pairs=[],n&&cc(n,this,t)}var rJ=tJ.prototype;rJ.append=function(t,o){this._pairs.push([t,o])};rJ.toString=function(t){let o=t?i=>t.call(this,i,AJ):AJ;return this._pairs.map(function(e){return o(e[0])+"="+o(e[1])},"").join("&")};var aJ=tJ;function zQe(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function PI(n,t,o){if(!t)return n;n=n||"";let i=Z.isFunction(o)?{serialize:o}:o,e=Z.getSafeProp(i,"encode")||zQe,a=Z.getSafeProp(i,"serialize"),A;if(a?A=a(t,i):A=Z.isURLSearchParams(t)?t.toString():new aJ(t,i).toString(e),A){let r=n.indexOf("#");r!==-1&&(n=n.slice(0,r)),n+=(n.indexOf("?")===-1?"?":"&")+A}return n}var gC=Symbol("internals");function oJ(n){return n?n.length:0}function iJ(n){if(n)for(;n.length&&n[n.length-1]===null;)n.pop()}function cC(n,t){let o=n.handlers,i=oJ(o);o!==t.handlersRef?(t.handlersRef=o,t.handlerEntries.clear()):i!==t.handlersLength&&(i?t.handlerEntries.forEach(function(a,A){o[a.index]!==a.handler&&t.handlerEntries.delete(A)}):t.handlerEntries.clear()),t.handlersLength=i}var QT=class{constructor(){this.handlers=[],this[gC]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(t,o,i){let e={fulfilled:t,rejected:o,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null},a=this[gC];this.handlers==null&&(this.handlers=[]),cC(this,a);let A=a.nextId++;return this.handlers.push(e),a.handlerEntries.set(A,{handler:e,index:this.handlers.length-1}),a.handlersLength=this.handlers.length,A}eject(t){let o=this[gC];cC(this,o);let i=o.handlerEntries.get(t);if(i){if(o.handlerEntries.delete(t),this.handlers[i.index]!==i.handler)return;this.handlers[i.index]=null,o.iterationDepth||(iJ(this.handlers),o.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],cC(this,this[gC]))}forEach(t){let o=this[gC];cC(this,o),o.iterationDepth++;try{Z.forEach(this.handlers,function(e){e!==null&&t(e)})}finally{--o.iterationDepth||(cC(this,o),iJ(this.handlers),o.handlersLength=oJ(this.handlers))}}},yT=QT;var Ic={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0};import WQe from"crypto";import VQe from"url";var nJ=VQe.URLSearchParams;var mT="abcdefghijklmnopqrstuvwxyz",sJ="0123456789",gJ={DIGIT:sJ,ALPHA:mT,ALPHA_DIGIT:mT+mT.toUpperCase()+sJ},ZQe=(n=16,t=gJ.ALPHA_DIGIT)=>{let o="",{length:i}=t,e=new Uint32Array(n);WQe.randomFillSync(e);for(let a=0;awT,hasStandardBrowserEnv:()=>XQe,hasStandardBrowserWebWorkerEnv:()=>$Qe,navigator:()=>ST,origin:()=>eye});var wT=typeof window<"u"&&typeof document<"u",ST=typeof navigator=="object"&&navigator||void 0,XQe=wT&&(!ST||["ReactNative","NativeScript","NS"].indexOf(ST.product)<0),$Qe=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",eye=wT&&window.location.href||"http://localhost";var Ct={...DT,...cJ};function OT(n,t){return cc(n,new Ct.classes.URLSearchParams,{visitor:function(o,i,e,a){return Ct.isNode&&Z.isBuffer(o)?(this.append(i,o.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}var IJ=fT;function lJ(n){if(n>IJ)throw new ye("FormData field is too deeply nested ("+n+" levels). Max depth: "+IJ,ye.ERR_FORM_DATA_DEPTH_EXCEEDED)}function Aye(n){let t=[],o=/[^.[\]]+|\[([^.[\]]*)]/g,i;for(;(i=o.exec(n))!==null;)lJ(t.length),t.push(i[0]==="[]"?"":i[1]||i[0]);return t}function tye(n){let t={},o=Object.keys(n),i,e=o.length,a;for(i=0;i=o.length;return A=!A&&Z.isArray(e)?e.length:A,s?(Z.hasOwnProp(e,A)?e[A]=Z.isArray(e[A])?e[A].concat(i):[e[A],i]:e[A]=i,!r):((!Z.hasOwnProp(e,A)||!Z.isObject(e[A]))&&(e[A]=[]),t(o,i,e[A],a)&&Z.isArray(e[A])&&(e[A]=tye(e[A])),!r)}if(Z.isFormData(n)&&Z.isFunction(n.entries)){let o={};return Z.forEachEntry(n,(i,e)=>{t(Aye(i),e,o,0)}),o}return null}var py=rye;var aye=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),dy=aye;var Wp=(n,t)=>n!=null&&Z.hasOwnProp(n,t)?n[t]:void 0;function iye(n,t,o){if(Z.isString(n))try{return(t||JSON.parse)(n),Z.trim(n)}catch(i){if(i.name!=="SyntaxError")throw i}return(o||JSON.stringify)(n)}var bT={transitional:Ic,adapter:["xhr","http","fetch"],transformRequest:[function(t,o){let i=o.getContentType()||"",e=i.indexOf("application/json")>-1,a=Z.isObject(t);if(a&&Z.isHTMLForm(t)&&(t=new FormData(t)),Z.isFormData(t))return e?JSON.stringify(py(t)):t;if(Z.isArrayBuffer(t)||Z.isBuffer(t)||Z.isStream(t)||Z.isFile(t)||Z.isBlob(t)||Z.isReadableStream(t))return t;if(Z.isArrayBufferView(t))return t.buffer;if(Z.isURLSearchParams(t))return o.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let r;if(a){let s=Wp(this,"formSerializer");if(i.indexOf("application/x-www-form-urlencoded")>-1)return OT(t,s).toString();if((r=Z.isFileList(t))||i.indexOf("multipart/form-data")>-1){let g=Wp(this,"env"),c=g&&g.FormData;return cc(r?{"files[]":t}:t,c&&new c,s)}}return a||e?(o.setContentType("application/json",!1),iye(t)):t}],transformResponse:[function(t){let o=Wp(this,"transitional")||bT.transitional,i=o&&o.forcedJSONParsing,e=Wp(this,"responseType"),a=e==="json";if(Z.isResponse(t)||Z.isReadableStream(t))return t;if(t&&Z.isString(t)&&(i&&!e||a)){let r=!(o&&o.silentJSONParsing)&&a;try{return JSON.parse(t,Wp(this,"parseReviver"))}catch(s){if(r)throw s.name==="SyntaxError"?ye.from(s,ye.ERR_BAD_RESPONSE,this,null,Wp(this,"response")):s}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ct.classes.FormData,Blob:Ct.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Z.forEach(dy,n=>{bT.headers[n]={}});var Zp=bT;function IC(n,t){let o=this||Zp,i=t||o,e=Ut.from(i.headers),a=i.data;return Z.forEach(n,function(r){a=r.call(o,a,e.normalize(),t?t.status:void 0)}),e.normalize(),a}function lC(n){return!!(n&&n.__CANCEL__)}var MT=class extends ye{constructor(t,o,i){super(t??"canceled",ye.ERR_CANCELED,o,i),this.name="CanceledError",this.__CANCEL__=!0}},$i=MT;function ts(n,t,o){let i=o.config.validateStatus;!o.status||!i||i(o.status)?n(o):t(new ye("Request failed with status code "+o.status,o.status>=400&&o.status<500?ye.ERR_BAD_REQUEST:ye.ERR_BAD_RESPONSE,o.config,o.request,o))}function _T(n){return typeof n!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(n)}function TT(n,t){if(!t)return n;let o=n.length;for(;o>0&&n.charCodeAt(o-1)===47;)o--;return n.slice(0,o)+"/"+t.replace(/^\/+/,"")}var oye=/[\t\n\r]/g;function pC(n){if(typeof n!="string")return n;let t=0;for(;t`${o}${i}${rC}`)}function gye(n){let t=n.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${rC}@`),o=t.indexOf("#"),e=(o===-1?t:t.slice(0,o)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${rC}`);return o===-1?e:`${e}#${sye(t.slice(o+1))}`}function pJ(n,t){if(typeof n=="string"){let o=pC(n);if(nye.test(o))throw new ye(`Invalid URL ${JSON.stringify(gye(o))}: missing "//" after protocol`,ye.ERR_INVALID_URL,t)}}function GI(n,t,o,i){pJ(t,i);let e=!_T(t);return n&&(e||o===!1)?(pJ(n,i),TT(n,t)):t}var cye={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function Iye(n){try{return new URL(n)}catch{return null}}function dJ(n){var t=(typeof n=="string"?Iye(n):n)||{},o=t.protocol,i=t.host,e=t.port;if(typeof i!="string"||!i||typeof o!="string"||(o=o.split(":",1)[0],i=i.replace(/:\d*$/,""),e=parseInt(e)||cye[o]||0,!lye(i,e)))return"";var a=NT(o+"_proxy")||NT("all_proxy");return a&&a.indexOf("://")===-1&&(a=o+"://"+a),a}function lye(n,t){var o=NT("no_proxy").toLowerCase();return o?o==="*"?!1:o.split(/[,\s]/).every(function(i){if(!i)return!0;var e=i.match(/^(.+):(\d+)$/),a=e?e[1]:i,A=e?parseInt(e[2]):0;return A&&A!==t?!0:/^[.*]/.test(a)?(a.charAt(0)==="*"&&(a=a.slice(1)),!n.endsWith(a)):n!==a}):!0}function NT(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}var l0=Je(KT(),1),uq=Je(PJ(),1);import Eq from"http";import Cq from"https";import Jme from"http2";import qme from"util";import{resolve as aq}from"path";import _o from"zlib";var ng="1.20.0";function KI(n){let t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(n);return t&&t[1]||""}var lme=/^([^,;/]+\/[^,;/]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;function A0(n,t,o){let i=o&&o.Blob||Ct.classes.Blob,e=KI(n);if(t===void 0&&i&&(t=!0),e==="data"){n=e.length?n.slice(e.length+1):n;let a=lme.exec(n);if(!a)throw new ye("Invalid URL",ye.ERR_INVALID_URL);let A=a[1],r=a[2],s=a[3]?"base64":"utf8",g=a[4],c="";A?c=r?A+r:A:r&&(c="text/plain"+r);let I=s==="base64"?Buffer.from(g,"base64"):Buffer.from(decodeURIComponent(g),s);if(t){if(!i)throw new ye("Blob is not supported",ye.ERR_NOT_SUPPORT);return new i([I],{type:c})}return I}throw new ye("Unsupported protocol "+e,ye.ERR_NOT_SUPPORT)}import Cn from"stream";var pme=["content-type","content-length"];function yC(n,t,o){if(o!=="content-only"){n.set(t);return}Object.entries(t||{}).forEach(([i,e])=>{pme.includes(i.toLowerCase())&&n.set(i,e)})}import dme from"stream";var t0=Symbol("internals"),r0=class extends dme.Transform{constructor(t){t=Z.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,e)=>!Z.isUndefined(e[i])),super({readableHighWaterMark:t.chunkSize});let o=this[t0]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(o.isCaptured||(o.isCaptured=!0))})}_read(t){let o=this[t0];return o.onReadCallback&&o.onReadCallback(),super._read(t)}_transform(t,o,i){let e=this[t0],a=e.maxRate,A=this.readableHighWaterMark,r=e.timeWindow,s=1e3/r,g=a/s,c=e.minChunkSize!==!1?Math.max(e.minChunkSize,g*.01):0,I=(B,f)=>{let Q=Buffer.byteLength(B);e.bytesSeen+=Q,e.bytes+=Q,e.isCaptured&&this.emit("progress",e.bytesSeen),this.push(B)?process.nextTick(f):e.onReadCallback=()=>{e.onReadCallback=null,process.nextTick(f)}},d=(B,f)=>{let Q=Buffer.byteLength(B),y=null,m=A,_,T=0;if(a){let R=Date.now();(!e.ts||(T=R-e.ts)>=r)&&(e.ts=R,_=g-e.bytes,e.bytes=_<0?-_:0,T=0),_=g-e.bytes}if(a){if(_<=0)return setTimeout(()=>{f(null,B)},r-T);_m&&Q-m>c&&(y=B.subarray(m),B=B.subarray(0,m)),I(B,y?()=>{process.nextTick(f,null,y)}:f)};d(t,function B(f,Q){if(f)return i(f);Q?d(Q,B):i(null)})}},a0=r0;import{EventEmitter as zme}from"events";import Eme from"util";import{Readable as Cme}from"stream";var{asyncIterator:GJ}=Symbol,hme=async function*(n){n.stream?yield*n.stream():n.arrayBuffer?yield await n.arrayBuffer():n[GJ]?yield*n[GJ]():yield n},fy=hme;var ume=Ct.ALPHABET.ALPHA_DIGIT+"-_",mC=typeof TextEncoder=="function"?new TextEncoder:new Eme.TextEncoder,xI=`\r +`,Bme=mC.encode(xI),fme=2,i0=class{constructor(t,o){let{escapeName:i}=this.constructor,e=Z.isString(o),a=`Content-Disposition: form-data; name="${i(t)}"${!e&&o.name?`; filename="${i(o.name)}"`:""}${xI}`;if(e)o=mC.encode(String(o).replace(/\r?\n|\r\n?/g,xI));else{let A=String(o.type||"application/octet-stream").replace(/[\r\n]/g,"");a+=`Content-Type: ${A}${xI}`}this.headers=mC.encode(a+xI),this.contentLength=e?o.byteLength:o.size,this.size=this.headers.byteLength+this.contentLength+fme,this.name=t,this.value=o}async*encode(){yield this.headers;let{value:t}=this;Z.isTypedArray(t)?yield t:yield*fy(t),yield Bme}static escapeName(t){return String(t).replace(/[\r\n"]/g,o=>({"\r":"%0D","\n":"%0A",'"':"%22"})[o])}},Qme=(n,t,o)=>{let{tag:i="form-data-boundary",size:e=25,boundary:a=i+"-"+Ct.generateString(e,ume)}=o||{};if(!Z.isFormData(n))throw new TypeError("FormData instance required");if(a.length<1||a.length>70)throw new Error("boundary must be 1-70 characters long");let A=mC.encode("--"+a+xI),r=mC.encode("--"+a+"--"+xI),s=r.byteLength,g=Array.from(n.entries()).map(([I,d])=>{let B=new i0(I,d);return s+=B.size,B});s+=A.byteLength*g.length,s=Z.toFiniteNumber(s);let c={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(s)&&(c["Content-Length"]=s),t&&t(c),Cme.from((async function*(){for(let I of g)yield A,yield*I.encode();yield r})())},FJ=Qme;import yme from"stream";var o0=class extends yme.Transform{__transform(t,o,i){this.push(t),i()}_transform(t,o,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let e=Buffer.alloc(2);e[0]=120,e[1]=156,this.push(e,o)}this.__transform(t,o,i)}},LJ=o0;import mme from"http2";import Sme from"util";var n0=class{constructor(){this.sessions=Object.create(null)}getSession(t,o){o=Object.assign(Object.create(null),{sessionTimeout:1e3},o);let i=this.sessions[t];if(i){let I=i.length;for(let d=0;d{if(a)return;a=!0,A&&(clearTimeout(A),A=null);let I=i,d=I.length,B=d;for(;B--;)if(I[B][0]===e){d===1?delete this.sessions[t]:I.splice(B,1),e.closed||e.close();return}},s=e.request,{sessionTimeout:g}=o;if(g!=null){let I=0;e.request=function(){let d=s.apply(this,arguments);return I++,A&&(clearTimeout(A),A=null),d.once("close",()=>{--I||(A=setTimeout(()=>{A=null,r()},g))}),d}}e.once("close",r),e.once("error",r);let c=[e,o];return i?i.push(c):i=this.sessions[t]=[c],e}},UJ=n0;var wme=(n,t)=>Z.isAsyncFn(n)?function(...o){let i=o.pop();n.apply(this,o).then(e=>{try{t?i(null,...t(e)):i(null,e)}catch(a){i(a)}},i)}:n,HJ=wme;var Dme=new Set(["localhost","0.0.0.0"]),YJ=n=>{let t=n.length;for(;t&&n.charCodeAt(t-1)===46;)t--;return t===n.length?n:n.slice(0,t)},jJ=n=>{let t=n.split(".");return t.length!==4||t[0]!=="127"?!1:t.every(o=>/^\d+$/.test(o)&&Number(o)>=0&&Number(o)<=255)},s0=n=>{if(/^0[xX][0-9a-fA-F]+$/.test(n)){let t=parseInt(n.slice(2),16);return Number.isFinite(t)?t:null}if(n.length>1&&/^0[0-7]+$/.test(n)){let t=parseInt(n,8);return Number.isFinite(t)?t:null}if(n.length>1&&/^0[0-9]+$/.test(n))return null;if(/^[0-9]+$/.test(n)){let t=parseInt(n,10);return Number.isFinite(t)?t:null}return null},JJ=n=>{if(typeof n!="string"||!n||n.indexOf(":")!==-1)return n;let t=n;if(t.charAt(0)==="["&&t.charAt(t.length-1)==="]"&&(t=t.slice(1,-1)),t=YJ(t),!/^[0-9.xXa-fA-F]+$/.test(t))return n;let o=t.split(".");if(o.some(c=>c===""))return n;if(o.length===4){let c=o.map(s0);return c.some(I=>I===null||I<0||I>255)?n:c.join(".")}if(o.length>4||o.length===1)return n;let i=o.slice(0,-1),e=o[o.length-1],a=4-i.length,A=s0(e);if(A===null)return n;let r=(1<<8*a)-1;if(A<0||A>r)return n;let s=new Array(a).fill(0);for(let c=a-1,I=A;c>=0;c--,I>>=8)s[c]=I&255;let g=i.map(s0);return g.some(c=>c===null||c<0||c>255)?n:[...g,...s].join(".")},g0=n=>/^0{1,4}$/.test(n),Ome=n=>{if(n==="::")return!0;let t=n.indexOf("::");if(t!==-1){if(t!==n.lastIndexOf("::"))return!1;let i=n.slice(0,t),e=n.slice(t+2),a=i?i.split(":"):[],A=e?e.split(":"):[];return a.length+A.length<8&&a.every(g0)&&A.every(g0)}let o=n.split(":");return o.length===8&&o.every(g0)},bme=n=>{if(n==="::1")return!0;let t=n.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return jJ(t[1]);let o=n.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(o){let e=parseInt(o[1],16);return e>=32512&&e<=32767}let i=n.split(":");if(i.length===8){for(let e=0;e<7;e++)if(!/^0+$/.test(i[e]))return!1;return/^0*1$/.test(i[7])}return!1},KJ=n=>n?Dme.has(n)||jJ(n)||Ome(n)?!0:bme(n):!1,Mme={http:80,https:443,ws:80,wss:443,ftp:21},_me=n=>{let t=n,o=0;if(t.charAt(0)==="["){let a=t.indexOf("]");if(a!==-1){let A=t.slice(1,a),r=t.slice(a+1);return r.charAt(0)===":"&&/^\d+$/.test(r.slice(1))&&(o=Number.parseInt(r.slice(1),10)),[A,o]}}let i=t.indexOf(":"),e=t.lastIndexOf(":");return i!==-1&&i===e&&/^\d+$/.test(t.slice(e+1))&&(o=Number.parseInt(t.slice(e+1),10),t=t.slice(0,e)),[t,o]},Tme=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i,Nme=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i,qJ=n=>{if(typeof n!="string"||n.indexOf(":")===-1)return n;let t=n.match(Tme);if(t)return t[1];let o=n.match(Nme);if(o){let i=parseInt(o[1],16),e=parseInt(o[2],16);return`${i>>8}.${i&255}.${e>>8}.${e&255}`}return n},Rme=/^(?:0|[1-9]\d{0,2})$/,zJ=n=>{let t=n.split(".");return t.length===4&&t.every(o=>Rme.test(o)&&Number(o)<=255)?t.map(Number):null},kme=/^[0-9a-f]{1,4}$/i,vme=n=>{let t=n.split("::");if(t.length>2)return null;let o=t[0]?t[0].split(":"):[];if(t.length===2){let i=t[1]?t[1].split(":"):[],e=8-o.length-i.length;if(e<1)return null;o.push(...new Array(e).fill("0"),...i)}return o.length!==8||o.some(i=>!kme.test(i))?null:o.flatMap(i=>{let e=Number.parseInt(i,16);return[e>>8&255,e&255]})},VJ=n=>typeof n!="string"||!n?null:n.indexOf(":")!==-1?vme(n):zJ(n),xJ=n=>{if(!n)return n;n.charAt(0)==="["&&n.charAt(n.length-1)==="]"&&(n=n.slice(1,-1));let t=YJ(n),o=JJ(t);return o!==t?o:qJ(t)},Pme=n=>{let t=n,o=t.charAt(0)==="[",i=t.charAt(t.length-1)==="]",e=t.includes("[")||t.includes("]");if(o||i){if(!o||!i||(t=t.slice(1,-1),t.indexOf(":")===-1||t.includes("[")||t.includes("]")))return null}else if(e)return null;if(!t||t.charAt(t.length-1)===".")return null;let a=t.indexOf(":")!==-1;if(a)try{t=new URL(`http://[${t}]/`).hostname.slice(1,-1)}catch{return null}else if(t=JJ(t),!zJ(t))return null;return{normalized:qJ(t),wasIPv6:a}},Gme=/^(.+)\/(0|[1-9]\d{0,2})$/,Fme=n=>{if(n.indexOf("/")===-1)return;let t=Gme.exec(n);if(!t)return null;let o=Number(t[2]),i=Pme(t[1]);if(!i)return null;let{normalized:e,wasIPv6:a}=i;if(a&&e.indexOf(":")===-1){if(o<96)return null;o-=96}let A=VJ(e);return!A||o>A.length*8?null:{bytes:A,prefix:o}},Lme=(n,t,o)=>{let i=o>>3;for(let a=0;a{if(!A)return!1;if(A==="*")return!0;let r=Fme(A);if(r!==void 0)return r!==null&&!!a&&a.length===r.bytes.length&&Lme(a,r.bytes,r.prefix);let[s,g]=_me(A);return s=xJ(s),!s||g&&g!==i?!1:(s.charAt(0)==="*"&&(s=s.slice(1)),s.charAt(0)==="."?e.endsWith(s):e===s||KJ(e)&&KJ(s))})}function Ume(n,t){n=n||10;let o=new Array(n),i=new Array(n),e=0,a=0,A;return t=t!==void 0?t:1e3,function(s){let g=Date.now(),c=i[a];A||(A=g),o[e]=s,i[e]=g;let I=a,d=0;for(;I!==e;)d+=o[I++],I=I%n;if(e=(e+1)%n,e===a&&(a=(a+1)%n),g-A{o=I,e=null,a&&(clearTimeout(a),a=null),n(...c)};return[(...c)=>{let I=Date.now(),d=I-o;d>=i?A(c,I):(e=c,a||(a=setTimeout(()=>{a=null,A(e)},i-d)))},()=>e&&A(e),(...c)=>A(c)]}var ZJ=Hme;var sg=(n,t,o=3)=>{let i=0,e=WJ(50,250);return ZJ(a=>{if(!a||!Z.isNumber(a.loaded))return;let A=a.loaded,r=a.lengthComputable?a.total:void 0,s=Math.max(0,r!=null?Math.min(A,r):A),g=Math.max(0,s-i),c=e(g);i=Math.max(i,s);let I={loaded:s,total:r,progress:r?s/r:void 0,bytes:g,rate:c||void 0,estimated:c&&r?(r-s)/c:void 0,event:a,lengthComputable:r!=null,[t?"download":"upload"]:!0};n(I)},o)},td=(n,t)=>{let o=n!=null;return[i=>t[0]({lengthComputable:o,total:n,loaded:i}),t[1]]},rd=(n,t=Z.asap)=>(...o)=>t(()=>n(...o));var XJ=n=>n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102,eq=(n,t,o)=>t+2n<=57?n-48:(n&223)-55,Kme=n=>n>=65&&n<=90||n>=97&&n<=122||n>=48&&n<=57||n===43||n===47||n===45||n===95,xme=n=>n===9||n===10||n===12||n===13||n===32,Yme=n=>{let t=Math.floor(n/4),o=n%4;return t*3+(o===2?1:o===3?2:0)},Aq=n=>{let t=n.length,o=0;return t>0&&n.charCodeAt(t-1)===61&&(o++,t>1&&n.charCodeAt(t-2)===61&&o++),Math.floor((t-o)*3/4)},jme=n=>{let t=n.length,o=0,i=0,e=!1;for(let a=0;a0){e=!0;continue}o++}}return e||i>2||i>0&&(o+i)%4!==0||o%4===1?Aq(n):Yme(o)},tq=(n,t)=>{if(!n||typeof n!="string"||!n.startsWith("data:"))return 0;let o=n.indexOf(",");if(o<0)return 0;let i=n.slice(5,o),e=n.slice(o+1);if(/;base64/i.test(i))return t(e);let A=0;for(let r=0,s=e.length;r=55296&&g<=56319&&r+1=56320&&c<=57343?(A+=4,r++):A+=3}else A+=3}return A};function I0(n){let t=typeof n=="string"?n.indexOf("#"):-1;return tq(t===-1?n:n.slice(0,t),jme)}function rq(n){return tq(n,Aq)}var iq={flush:_o.constants.Z_SYNC_FLUSH,finishFlush:_o.constants.Z_SYNC_FLUSH},Vme={flush:_o.constants.BROTLI_OPERATION_FLUSH,finishFlush:_o.constants.BROTLI_OPERATION_FLUSH},Wme={flush:_o.constants.ZSTD_e_flush,finishFlush:_o.constants.ZSTD_e_flush},Bq=Z.isFunction(_o.createBrotliDecompress),fq=Z.isFunction(_o.createZstdDecompress),Qq="gzip, compress, deflate"+(Bq?", br":""),Zme=Qq+(fq?", zstd":""),oq=typeof process<"u"&&process.nextTick?process.nextTick.bind(process):Z.asap,{http:Xme,https:$me}=uq.default,p0=/https:?/,nq=Symbol("axios.http.socketListener"),Qy=Symbol("axios.http.currentReq");function eSe(n){let t=this[Qy];t&&!t.destroyed&&t.destroy(n)}var yq=Symbol("axios.http.installedTunnel"),ASe=new Map,sq=new WeakMap,gq={22:21,24:5};function tSe(n=process.versions&&process.versions.node){if(!n)return!1;let[t,o]=n.split(".").map(i=>Number(i));return!Number.isInteger(t)||!Number.isInteger(o)?!1:t>24?!0:gq[t]!=null&&o>=gq[t]}function cq(n,t=process.versions&&process.versions.node){if(!tSe(t))return!1;let o=n&&n.options;return!!(o&&Z.hasOwnProp(o,"proxyEnv")&&o.proxyEnv!=null)}function rSe(n,t,o){return p0.test(n.protocol)?o||Cq.globalAgent:t||Eq.globalAgent}function aSe(n,t){let o=n.protocol+"//"+n.hostname+":"+(n.port||"")+"#"+(n.auth||""),i=t?sq.get(t)||sq.set(t,new Map).get(t):ASe,e=i.get(o);if(e)return e;let a=t&&t.options?{...t.options,...n}:n;if(e=new l0.default(a),t&&t.options){let A={...t.options},r=e.callback;e.callback=function(g,c){return r.call(this,g,{...A,...c})}}return e[yq]=!0,i.set(o,e),e}var Iq=Ct.protocols.map(n=>n+":"),lq=n=>{if(!Z.isString(n))return n;try{return decodeURIComponent(n)}catch{return n}},pq=(n,[t,o])=>(n.on("end",o).on("error",o),t),iSe=new UJ;function oSe(n,t,o){n.beforeRedirects.proxy&&n.beforeRedirects.proxy(n),n.beforeRedirects.auth&&n.beforeRedirects.auth(n),n.beforeRedirects.sensitiveHeaders&&n.beforeRedirects.sensitiveHeaders(n,o),n.beforeRedirects.config&&n.beforeRedirects.config(n,t,o)}function nSe(n,t){n&&Object.keys(n).forEach(o=>{t.has(o.toLowerCase())&&delete n[o]})}function sSe(n,t){if(!t)return!1;try{return new URL(t.url).origin===new URL(n.href).origin}catch{return!1}}function mq(n,t,o,i,e,a,A=!0){let r=t,s=rSe(n,a,e);if(!r&&r!==!1&&A&&!cq(s)){let g=dJ(o);g&&(c0(o)||(r=new URL(g)))}if(i&&n.headers)for(let g of Object.keys(n.headers))g.toLowerCase()==="proxy-authorization"&&delete n.headers[g];if(i&&n.agent&&n.agent[yq]&&(n.agent=void 0),r){let g=r instanceof URL,c=Q=>g||Z.hasOwnProp(r,Q)?r[Q]:void 0,I=c("username"),d=c("password"),B=Z.hasOwnProp(r,"auth")?r.auth:void 0;if(I&&(B=(I||"")+":"+(d||"")),B){let Q=typeof B=="object",y=Q&&Z.hasOwnProp(B,"username")?B.username:void 0,m=Q&&Z.hasOwnProp(B,"password")?B.password:void 0;if(!!(y||m))B=(y||"")+":"+(m||"");else if(Q)throw new ye("Invalid proxy authorization",ye.ERR_BAD_OPTION,{proxy:r})}if(p0.test(n.protocol)){if(!(e instanceof l0.default)){let Q=c("hostname")||c("host"),y=c("port"),m=c("protocol"),_=m?m.includes(":")?m:`${m}:`:"http:",T=Q&&Q.includes(":")&&!Q.startsWith("[")?`[${Q}]`:Q,R=new URL(`${_}//${T}${y?":"+y:""}`),L={protocol:R.protocol,hostname:R.hostname.replace(/^\[|\]$/g,""),port:R.port,auth:B&&typeof B=="string"?B:void 0};R.protocol==="https:"&&(L.ALPNProtocols=["http/1.1"]);let U=aSe(L,e);n.agent=U,n.agents&&(n.agents.https=U)}}else{if(B){let _=Buffer.from(B,"utf8").toString("base64");n.headers["Proxy-Authorization"]="Basic "+_}let Q=!1;for(let _ of Object.keys(n.headers))if(_.toLowerCase()==="host"){Q=!0;break}Q||(n.headers.host=n.hostname+(n.port?":"+n.port:""));let y=c("hostname")||c("host");n.hostname=y,n.host=y,n.port=c("port"),n.path=o;let m=c("protocol");m&&(n.protocol=m.includes(":")?m:`${m}:`)}}return n.beforeRedirects.proxy=function(c){mq(c,t,c.href,!0,e,a,A)},!!(r||t!==!1&&A&&cq(s))}var gSe=typeof process<"u"&&Z.kindOf(process)==="process",cSe=n=>new Promise((t,o)=>{let i,e,a=(s,g)=>{e||(e=!0,i&&i(s,g))},A=s=>{a(s),t(s)},r=s=>{a(s,!0),o(s)};n(A,r,s=>i=s).catch(r)}),ISe=({address:n,family:t})=>{if(!Z.isString(n))throw new ye("address must be a string",ye.ERR_BAD_OPTION_VALUE);return{address:n,family:t||(n.indexOf(".")<0?6:4)}},dq=(n,t)=>ISe(Z.isObject(n)?n:{address:n,family:t}),hq=new WeakMap,lSe=n=>{let t=hq.get(n);if(t)return t;let o=HJ(n,i=>Z.isArray(i)?i:[i]);return t=(i,e,a)=>{o(i,e,(A,r,s)=>{if(A)return a(A);let g;try{g=Z.isArray(r)?r.map(c=>dq(c)):[dq(r,s)]}catch(c){return a(c)}e.all?a(A,g):a(A,g[0].address,g[0].family)})},hq.set(n,t),t},pSe={request(n,t){let o=n.protocol+"//"+n.hostname+":"+(n.port||(n.protocol==="https:"?443:80)),{http2Options:i,headers:e}=n,a=iSe.getSession(o,i),{HTTP2_HEADER_SCHEME:A,HTTP2_HEADER_METHOD:r,HTTP2_HEADER_PATH:s,HTTP2_HEADER_STATUS:g}=Jme.constants,c={[A]:n.protocol.replace(":",""),[r]:n.method,[s]:n.path};Z.forEach(e,(d,B)=>{B.charAt(0)!==":"&&(c[B]=d)});let I=a.request(c);return I.once("response",d=>{let B=I;d=Object.assign({},d);let f=d[g];delete d[g],B.headers=d,B.statusCode=+f,t(B)}),I}},Sq=gSe&&function(t){return cSe(async function(i,e,a){let A=we=>Z.getSafeProp(t,we),r=A("transitional")||Ic,s=A("data"),g=A("lookup"),c=A("family"),I=A("httpVersion");I===void 0&&(I=1);let d=I,B=A("http2Options"),f=A("httpAgent"),Q=A("httpsAgent"),y=A("proxy"),m=A("responseType"),_=A("responseEncoding"),T=A("socketPath"),R=A("method").toUpperCase(),L=A("maxRedirects"),U=A("maxBodyLength"),F=A("maxContentLength"),q=A("decompress"),z,j=!1,P,J;try{I=+I}catch{throw new ye("Invalid protocol version: value is not a number",ye.ERR_BAD_OPTION_VALUE,t)}if(Number.isNaN(I))throw new ye(`Invalid protocol version: '${d}' is not a number`,ye.ERR_BAD_OPTION_VALUE,t);if(I!==1&&I!==2)throw new ye(`Unsupported protocol version '${I}'`,ye.ERR_BAD_OPTION_VALUE,t);let H=I===2;g&&(g=lSe(g));let N=new zme;function k(we){try{N.emit("abort",!we||we.type?new $i(null,t,P):we)}catch{}}function V(){J&&(clearTimeout(J),J=null)}function Ae(){let we=A("timeout"),Ke=we?"timeout of "+we+"ms exceeded":"timeout exceeded",Ve=A("timeoutErrorMessage");return Ve&&(Ke=Ve),new ye(Ke,r.clarifyTimeoutError?ye.ETIMEDOUT:ye.ECONNABORTED,t,P)}N.once("abort",e);let ie=()=>{V(),t.cancelToken&&t.cancelToken.unsubscribe(k),t.signal&&t.signal.removeEventListener("abort",k),N.removeAllListeners()};(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(k),t.signal&&(t.signal.aborted?k():t.signal.addEventListener("abort",k))),a((we,Ke)=>{if(z=!0,V(),Ke){j=!0,ie();return}let{data:Ve}=we;if(Ve instanceof Cn.Readable||Ve instanceof Cn.Duplex){let NA=Cn.finished(Ve,()=>{NA(),ie()})}else ie()});let De=GI(A("baseURL"),A("url"),A("allowAbsoluteUrls"),t),fe=T?"http://localhost":Ct.hasBrowserEnv?Ct.origin:void 0,_e=new URL(De,fe),Ee=_e.protocol||Iq[0];if(Ee==="data:"){if(F>-1){let Ke=String(A("url")||De||"");if(rq(Ke)>F)return e(new ye("maxContentLength size of "+F+" exceeded",ye.ERR_BAD_RESPONSE,t))}let we;if(R!=="GET")return ts(i,e,{status:405,statusText:"method not allowed",headers:{},config:t});try{we=A0(A("url"),m==="blob",{Blob:t.env&&t.env.Blob})}catch(Ke){throw ye.from(Ke,ye.ERR_BAD_REQUEST,t)}return m==="text"?(we=we.toString(_),(!_||_==="utf8")&&(we=Z.stripBOM(we))):m==="stream"&&(we=Cn.Readable.from(we)),ts(i,e,{data:we,status:200,statusText:"OK",headers:new Ut,config:t})}if(Iq.indexOf(Ee)===-1)return e(new ye("Unsupported protocol "+Ee,ye.ERR_BAD_REQUEST,t));let Qe=Ut.from(t.headers).normalize();Qe.set("User-Agent","axios/"+ng,!1);let{onUploadProgress:Le,onDownloadProgress:AA}=t,aA=t.maxRate,He,ce;if(Z.isSpecCompliantForm(s)){let we=Qe.getContentType(/boundary=([-_\w\d]{10,70})/i);s=FJ(s,Ke=>{Qe.set(Ke)},{tag:`axios-${ng}-boundary`,boundary:we&&we[1]||void 0})}else if(Z.isFormData(s)&&Z.isFunction(s.getHeaders)&&s.getHeaders!==Object.prototype.getHeaders){if(yC(Qe,s.getHeaders(),A("formDataHeaderPolicy")),!Qe.hasContentLength())try{let we=await qme.promisify(s.getLength).call(s);Number.isFinite(we)&&we>=0&&Qe.setContentLength(we)}catch{}}else if(Z.isBlob(s)||Z.isFile(s))s.size&&Qe.setContentType(s.type||"application/octet-stream"),Qe.setContentLength(s.size||0),s=Cn.Readable.from(fy(s));else if(s&&!Z.isStream(s)){if(!Buffer.isBuffer(s))if(Z.isArrayBuffer(s))s=Buffer.from(new Uint8Array(s));else if(Z.isString(s))s=Buffer.from(s,"utf-8");else return e(new ye("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",ye.ERR_BAD_REQUEST,t));if(Qe.setContentLength(s.length,!1),U>-1&&s.length>U)return e(new ye("Request body larger than maxBodyLength limit",ye.ERR_BAD_REQUEST,t))}let Be=Z.toFiniteNumber(Qe.getContentLength());Z.isArray(aA)?(He=aA[0],ce=aA[1]):He=ce=aA,s&&(Le||He)&&(Z.isStream(s)||(s=Cn.Readable.from(s,{objectMode:!1})),s=Cn.pipeline([s,new a0({maxRate:Z.toFiniteNumber(He)})],Z.noop),Le&&s.on("progress",pq(s,td(Be,sg(rd(Le,oq),!1,3)))));let We,Ye=A("auth");if(Ye){let we=Z.getSafeProp(Ye,"username")||"",Ke=Z.getSafeProp(Ye,"password")||"";We=we+":"+Ke}if(!We&&(_e.username||_e.password)){let we=lq(_e.username),Ke=lq(_e.password);We=we+":"+Ke}We&&Qe.delete("authorization");let Re;try{Re=PI(_e.pathname+_e.search,A("params"),A("paramsSerializer")).replace(/^\?/,"")}catch(we){return e(ye.from(we,ye.ERR_BAD_REQUEST,t,null,null,{url:A("url"),exists:!0}))}Qe.set("Accept-Encoding",Z.hasOwnProp(r,"advertiseZstdAcceptEncoding")&&r.advertiseZstdAcceptEncoding===!0?Zme:Qq,!1),H&&g&&(B=Object.assign(Object.create(null),B,{lookup:g}));let Ze=Object.assign(Object.create(null),{path:Re,method:R,headers:Yp(Qe),agents:{http:f,https:Q},auth:We,protocol:Ee,family:c,beforeRedirect:oSe,beforeRedirects:Object.create(null),http2Options:B,createConnection:void 0});!Z.isUndefined(g)&&(Ze.lookup=g);let iA=!1;if(T){if(typeof T!="string")return e(new ye("socketPath must be a string",ye.ERR_BAD_OPTION_VALUE,t));let we=A("allowedSocketPaths");if(we!=null){let Ke=Array.isArray(we)?we:[we],Ve=aq(T);if(!Ke.some(wA=>typeof wA=="string"&&aq(wA)===Ve))return e(new ye(`socketPath "${T}" is not permitted by allowedSocketPaths`,ye.ERR_BAD_OPTION_VALUE,t))}Ze.socketPath=T}else Ze.hostname=_e.hostname.startsWith("[")?_e.hostname.slice(1,-1):_e.hostname,Ze.port=_e.port,iA=mq(Ze,y,Ee+"//"+_e.hostname+(_e.port?":"+_e.port:"")+Ze.path,!1,Q,f,!H);let gA,WA=!1,FA=!1,Me=p0.test(Ze.protocol);if(Ze.agent==null&&(Ze.agent=Me?Q:f),H){if(iA)return e(new ye("HTTP/2 requests with a proxy are not supported",ye.ERR_NOT_SUPPORT,t));gA=pSe}else{let we=A("transport");if(we)gA=we;else if(L===0)gA=Me?Cq:Eq,WA=!0;else{FA=!0,Ze.sensitiveHeaders=[],L&&(Ze.maxRedirects=L);let Ke=A("beforeRedirect");if(Ke&&(Ze.beforeRedirects.config=Ke),We){let NA=_e.origin,wA=We;Ze.beforeRedirects.auth=function(JA){try{new URL(JA.href).origin===NA&&(JA.auth=wA)}catch{}}}let Ve=A("sensitiveHeaders");if(Ve!=null){if(!Z.isArray(Ve))return e(new ye("sensitiveHeaders must be an array of strings",ye.ERR_BAD_OPTION_VALUE,t));let NA=new Set;for(let wA of Ve){if(!Z.isString(wA))return e(new ye("sensitiveHeaders must be an array of strings",ye.ERR_BAD_OPTION_VALUE,t));NA.add(wA.toLowerCase())}NA.size&&(Ze.sensitiveHeaders=Array.from(NA),Ze.beforeRedirects.sensitiveHeaders=function(LA,JA){sSe(LA,JA)||nSe(LA.headers,NA)})}gA=Me?$me:Xme}}U>-1?Ze.maxBodyLength=U:Ze.maxBodyLength=1/0,Ze.insecureHTTPParser=!!A("insecureHTTPParser"),P=gA.request(Ze,function(Ke){if(V(),P.destroyed)return;let Ve=[Ke],NA=Z.toFiniteNumber(Ke.headers["content-length"]);if(AA||ce){let lt=new a0({maxRate:Z.toFiniteNumber(ce)});AA&<.on("progress",pq(lt,td(NA,sg(rd(AA,oq),!0,3)))),Ve.push(lt)}let wA=Ke,LA=Ke.req||P;if(q!==!1&&Ke.headers["content-encoding"])switch((R==="HEAD"||Ke.statusCode===204)&&delete Ke.headers["content-encoding"],(Ke.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Ve.push(_o.createUnzip(iq)),delete Ke.headers["content-encoding"];break;case"deflate":Ve.push(new LJ),Ve.push(_o.createUnzip(iq)),delete Ke.headers["content-encoding"];break;case"br":Bq&&(Ve.push(_o.createBrotliDecompress(Vme)),delete Ke.headers["content-encoding"]);break;case"zstd":fq&&(Ve.push(_o.createZstdDecompress(Wme)),delete Ke.headers["content-encoding"]);break}wA=Ve.length>1?Cn.pipeline(Ve,Z.noop):Ve[0];let JA={status:Ke.statusCode,statusText:Ke.statusMessage,headers:new Ut(Ke.headers),config:t,request:LA};if(m==="stream"){if(F>-1){let lt=F,wt=wA;async function*pe(){let Ie=0;for await(let be of wt){if(Ie+=be.length,Ie>lt)throw new ye("maxContentLength size of "+lt+" exceeded",ye.ERR_BAD_RESPONSE,t,LA);yield be}}wA=Cn.Readable.from(pe(),{objectMode:!1})}JA.data=wA,ts(i,e,JA)}else{let lt=[],wt=0;wA.on("data",function(Ie){lt.push(Ie),wt+=Ie.length,F>-1&&wt>F&&(j=!0,wA.destroy(),k(new ye("maxContentLength size of "+F+" exceeded",ye.ERR_BAD_RESPONSE,t,LA)))}),wA.on("aborted",function(){if(j)return;let Ie=new ye("stream has been aborted",ye.ERR_BAD_RESPONSE,t,LA,JA);wA.destroy(Ie),e(Ie)}),wA.on("error",function(Ie){j||e(ye.from(Ie,null,t,LA,JA))}),wA.on("end",function(){try{let Ie=lt.length===1?lt[0]:Buffer.concat(lt);m!=="arraybuffer"&&(Ie=Ie.toString(_),(!_||_==="utf8")&&(Ie=Z.stripBOM(Ie))),JA.data=Ie}catch(Ie){return e(ye.from(Ie,null,t,JA.request,JA))}ts(i,e,JA)})}N.once("abort",lt=>{wA.destroyed||(wA.emit("error",lt),wA.destroy())})}),N.once("abort",we=>{P.close?P.close():P.destroy(we)}),P.on("error",function(Ke){e(ye.from(Ke,null,t,P))});let CA=new Set;if(P.on("socket",function(Ke){typeof Ke.setKeepAlive=="function"&&Ke.setKeepAlive(!0,1e3*60),Ke[nq]||(Ke.on("error",eSe),Ke[nq]=!0),Ke[Qy]=P,CA.add(Ke)}),P.once("close",function(){V();for(let Ke of CA)Ke[Qy]===P&&(Ke[Qy]=null);CA.clear()}),A("timeout")){let we=parseInt(A("timeout"),10);if(Number.isNaN(we)){k(new ye("error trying to parse `config.timeout` to int",ye.ERR_BAD_OPTION_VALUE,t,P));return}let Ke=function(){z||k(Ae())};WA&&we>0&&(J=setTimeout(Ke,we)),P.setTimeout(we,Ke)}else P.setTimeout(0);if(Z.isStream(s)){let we=!1,Ke=!1;s.on("end",()=>{we=!0}),s.once("error",NA=>{Ke=!0,P.destroy(NA)}),s.on("close",()=>{!we&&!Ke&&k(new $i("Request stream has been aborted",t,P))});let Ve=s;if(U>-1&&!FA){let NA=U,wA=0;Ve=Cn.pipeline([s,new Cn.Transform({transform(LA,JA,lt){if(wA+=LA.length,wA>NA)return lt(new ye("Request body larger than maxBodyLength limit",ye.ERR_BAD_REQUEST,t,P));lt(null,LA)}})],Z.noop),Ve.on("error",LA=>{P.destroyed||P.destroy(LA)})}Ve.pipe(P)}else s&&P.write(s),P.end()})};var wq=Ct.hasStandardBrowserEnv?((n,t)=>o=>(o=new URL(o,Ct.origin),n.protocol===o.protocol&&n.host===o.host&&(t||n.port===o.port)))(new URL(Ct.origin),Ct.navigator&&/(msie|trident)/i.test(Ct.navigator.userAgent)):()=>!0;var Dq=Ct.hasStandardBrowserEnv?{write(n,t,o,i,e,a,A){if(typeof document>"u")return;let r=[`${n}=${encodeURIComponent(t)}`];Z.isNumber(o)&&r.push(`expires=${new Date(o).toUTCString()}`),Z.isString(i)&&r.push(`path=${i}`),Z.isString(e)&&r.push(`domain=${e}`),a===!0&&r.push("secure"),Z.isString(A)&&r.push(`SameSite=${A}`),document.cookie=r.join("; ")},read(n){if(typeof document>"u")return null;let t=document.cookie.split(";");for(let o=0;on instanceof Ut?{...n}:n,dSe=n=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(n).concat(Object.getOwnPropertySymbols(n).filter(t=>Object.getOwnPropertyDescriptor(n,t).enumerable)):Object.keys(n);function un(n,t){n=n||{},t=t||{};let o=Object.create(null);Object.defineProperty(o,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function i(c,I,d,B){return Z.isPlainObject(c)&&Z.isPlainObject(I)?Z.merge.call({caseless:B},c,I):Z.isPlainObject(I)?Z.merge({},I):Z.isArray(I)?I.slice():I}function e(c,I,d,B){if(Z.isUndefined(I)){if(!Z.isUndefined(c))return i(void 0,c,d,B)}else return i(c,I,d,B)}function a(c,I){if(!Z.isUndefined(I))return i(void 0,I)}function A(c,I){if(Z.isUndefined(I)){if(!Z.isUndefined(c))return i(void 0,c)}else return i(void 0,I)}function r(c){let I=Z.hasOwnProp(t,"transitional")?t.transitional:void 0;if(!Z.isUndefined(I))if(Z.isPlainObject(I)){if(Z.hasOwnProp(I,c))return I[c]}else return;let d=Z.hasOwnProp(n,"transitional")?n.transitional:void 0;if(Z.isPlainObject(d)&&Z.hasOwnProp(d,c))return d[c]}function s(c,I,d){if(Z.hasOwnProp(t,d))return i(c,I);if(Z.hasOwnProp(n,d))return i(void 0,c)}let g={url:a,method:a,data:a,baseURL:A,transformRequest:A,transformResponse:A,paramsSerializer:A,timeout:A,timeoutErrorMessage:A,withCredentials:A,withXSRFToken:A,adapter:A,responseType:A,xsrfCookieName:A,xsrfHeaderName:A,onUploadProgress:A,onDownloadProgress:A,decompress:A,maxContentLength:A,maxBodyLength:A,beforeRedirect:A,transport:A,httpAgent:A,httpsAgent:A,cancelToken:A,socketPath:A,allowedSocketPaths:A,responseEncoding:A,validateStatus:s,headers:(c,I,d)=>e(Oq(c),Oq(I),d,!0)};return Z.forEach(dSe({...n,...t}),function(I){if(I==="__proto__"||I==="constructor"||I==="prototype")return;let d=Z.hasOwnProp(g,I)?g[I]:e,B=Z.hasOwnProp(n,I)?n[I]:void 0,f=Z.hasOwnProp(t,I)?t[I]:void 0,Q=d(B,f,I);Z.isUndefined(Q)&&d!==s||(o[I]=Q)}),Z.hasOwnProp(t,"validateStatus")&&Z.isUndefined(t.validateStatus)&&r("validateStatusUndefinedResolves")===!1&&(Z.hasOwnProp(n,"validateStatus")?o.validateStatus=i(void 0,n.validateStatus):delete o.validateStatus),o}var hSe=n=>encodeURIComponent(n).replace(/%([0-9A-F]{2})/gi,(t,o)=>String.fromCharCode(parseInt(o,16)));function ESe(n){let t=un({},n),o=d=>Z.hasOwnProp(t,d)?t[d]:void 0,i=o("data"),e=o("withXSRFToken"),a=o("xsrfHeaderName"),A=o("xsrfCookieName"),r=o("headers"),s=o("auth"),g=o("baseURL"),c=o("allowAbsoluteUrls"),I=o("url");if(t.headers=r=Ut.from(r),t.url=PI(GI(g,I,c,t),o("params"),o("paramsSerializer")),s){let d=Z.getSafeProp(s,"username")||"",B=Z.getSafeProp(s,"password")||"";try{r.set("Authorization","Basic "+btoa(d+":"+(B?hSe(B):"")))}catch(f){throw ye.from(f,ye.ERR_BAD_OPTION_VALUE,n)}}if(Z.isFormData(i)){let d=Z.getSafeProp(i,"getHeaders");Ct.hasStandardBrowserEnv||Ct.hasStandardBrowserWebWorkerEnv||Z.isReactNative(i)?r.setContentType(void 0):Z.isFunction(d)&&yC(r,d.call(i),o("formDataHeaderPolicy"))}if(Ct.hasStandardBrowserEnv&&(Z.isFunction(e)&&(e=e(t)),e===!0||e==null&&wq(t.url))){let B=a&&A&&Dq.read(A);B&&r.set(a,B)}return t}var yy=ESe;var CSe=typeof XMLHttpRequest<"u",bq=CSe&&function(n){return new Promise(function(o,i){let e=yy(n),a=e.data,A=Ut.from(e.headers).normalize(),{responseType:r,onUploadProgress:s,onDownloadProgress:g}=e,c,I,d,B,f,Q;function y(){B&&B(),f&&f(),e.cancelToken&&e.cancelToken.unsubscribe(c),e.signal&&e.signal.removeEventListener("abort",c)}let m=new XMLHttpRequest;m.open(e.method.toUpperCase(),e.url,!0),m.timeout=e.timeout;function _(R){if(!m)return;if(m.status===0&&(KI(pC(e.url))||KI(Ct.origin))!=="file"&&!(m.responseURL&&m.responseURL.startsWith("file:"))){i(new ye("Request aborted",ye.ECONNABORTED,n,m)),y(),m=null;return}try{R?Q&&Q(R):f&&f()}catch(q){setTimeout(()=>{throw q})}if(!m)return;let L=Ut.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),F={data:!r||r==="text"||r==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:L,config:n,request:m};ts(function(z){o(z),y()},function(z){i(z),y()},F),m=null}"onloadend"in m?m.onloadend=_:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.startsWith("file:"))||setTimeout(_)},m.onabort=function(){m&&(i(new ye("Request aborted",ye.ECONNABORTED,n,m)),y(),m=null)},m.onerror=function(L){let U=L&&L.message?L.message:"Network Error",F=new ye(U,ye.ERR_NETWORK,n,m);F.event=L||null,i(F),y(),m=null},m.ontimeout=function(){let L=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",U=e.transitional||Ic;e.timeoutErrorMessage&&(L=e.timeoutErrorMessage),i(new ye(L,U.clarifyTimeoutError?ye.ETIMEDOUT:ye.ECONNABORTED,n,m)),y(),m=null},a===void 0&&A.setContentType(null),"setRequestHeader"in m&&Z.forEach(Yp(A),function(L,U){m.setRequestHeader(U,L)}),Z.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),r&&r!=="json"&&(m.responseType=e.responseType),g&&([d,f,Q]=sg(g,!0),m.addEventListener("progress",d)),s&&m.upload&&([I,B]=sg(s),m.upload.addEventListener("progress",I),m.upload.addEventListener("loadend",B)),(e.cancelToken||e.signal)&&(c=R=>{m&&(i(!R||R.type?new $i(null,n,m):R),m.abort(),y(),m=null)},e.cancelToken&&e.cancelToken.subscribe(c),e.signal&&(e.signal.aborted?c():e.signal.addEventListener("abort",c)));let T=KI(e.url);if(T&&!Ct.protocols.includes(T)){i(new ye("Unsupported protocol "+T+":",ye.ERR_BAD_REQUEST,n)),y();return}m.send(a||null)})};var uSe=(n,t)=>{if(n=n?n.filter(Boolean):[],!t&&!n.length)return;let o=new AbortController,i=!1,e=function(s){if(!i){i=!0,A();let g=s instanceof Error?s:this.reason;o.abort(g instanceof ye?g:new $i(g instanceof Error?g.message:g))}},a=t&&setTimeout(()=>{a=null,e(new ye(`timeout of ${t}ms exceeded`,ye.ETIMEDOUT))},t),A=()=>{n&&(a&&clearTimeout(a),a=null,n.forEach(s=>{s.unsubscribe?s.unsubscribe(e):s.removeEventListener("abort",e)}),n=null)};n.forEach(s=>{if(!i){if(s.aborted){e.call(s);return}s.addEventListener("abort",e,{once:!0})}});let{signal:r}=o;return r.unsubscribe=()=>Z.asap(A),r},Mq=uSe;var BSe=function*(n,t){let o=n.byteLength;if(!t||o{let e=fSe(n,t),a=0,A,r=s=>{A||(A=!0,i&&i(s))};return new ReadableStream({async pull(s){try{let{done:g,value:c}=await e.next();if(g){r(),s.close();return}let I=c.byteLength;if(o){let d=a+=I;o(d)}s.enqueue(new Uint8Array(c))}catch(g){throw r(g),g}},cancel(s){return r(s),e.return()}},{highWaterMark:2})};var _q=64*1024,ySe={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},{isFunction:my}=Z,mSe=n=>encodeURIComponent(n).replace(/%([0-9A-F]{2})/gi,(t,o)=>String.fromCharCode(parseInt(o,16))),Tq=n=>{if(!Z.isString(n))return n;try{return decodeURIComponent(n)}catch{return n}},Nq=(n,...t)=>{try{return!!n(...t)}catch{return!1}},SSe=n=>{let t=n.indexOf("://"),o=n;return t!==-1&&(o=o.slice(t+3)),o.includes("@")||o.includes(":")},wSe=n=>{let t=Z.global!==void 0&&Z.global!==null?Z.global:globalThis,{ReadableStream:o,TextEncoder:i}=t;n=Z.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},n);let{fetch:e,Request:a,Response:A}=n,r=e?my(e):typeof fetch=="function",s=my(a),g=my(A);if(!r)return!1;let c=r&&my(o),I=r&&(typeof i=="function"?(m=>_=>m.encode(_))(new i):async m=>new Uint8Array(await new a(m).arrayBuffer())),d=s&&c&&Nq(()=>{let m=!1,_=new a(Ct.origin,{body:new o,method:"POST",get duplex(){return m=!0,"half"}}),T=_.headers.has("Content-Type");return _.body!=null&&_.body.cancel(),m&&!T}),B=g&&c&&Nq(()=>Z.isReadableStream(new A("").body)),f={stream:B&&(m=>m.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!f[m]&&(f[m]=(_,T)=>{let R=_&&_[m];if(R)return R.call(_);throw new ye(`Response type '${m}' is not supported`,ye.ERR_NOT_SUPPORT,T)})});let Q=async m=>{if(m==null)return 0;if(Z.isBlob(m))return m.size;if(Z.isSpecCompliantForm(m))return(await new a(Ct.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(Z.isArrayBufferView(m)||Z.isArrayBuffer(m))return m.byteLength;if(Z.isURLSearchParams(m)&&(m=m+""),Z.isString(m))return(await I(m)).byteLength},y=async(m,_)=>{let T=Z.toFiniteNumber(m.getContentLength());return T??Q(_)};return async m=>{let{url:_,method:T,data:R,signal:L,cancelToken:U,timeout:F,onDownloadProgress:q,onUploadProgress:z,responseType:j,headers:P,withCredentials:J="same-origin",fetchOptions:H,maxContentLength:N,maxBodyLength:k,maxRedirects:V}=yy(m),Ae=Z.isNumber(N)&&N>-1,ie=Z.isNumber(k)&&k>-1,De=He=>Z.hasOwnProp(m,He)?m[He]:void 0,fe=e||fetch;j=j?(j+"").toLowerCase():"text";let _e=Mq([L,U&&U.toAbortSignal()],F),Ee=null,Qe=_e&&_e.unsubscribe&&(()=>{_e.unsubscribe()}),Le,AA=null,aA=()=>new ye("Request body larger than maxBodyLength limit",ye.ERR_BAD_REQUEST,m,Ee);try{let He,ce=De("auth");if(ce){let Me=Z.getSafeProp(ce,"username")||"",CA=Z.getSafeProp(ce,"password")||"";He={username:Me,password:CA}}if(SSe(_)){let Me=new URL(_,Ct.origin);if(!He&&(Me.username||Me.password)){let CA=Tq(Me.username),we=Tq(Me.password);He={username:CA,password:we}}(Me.username||Me.password)&&(Me.username="",Me.password="",_=Me.href)}if(He&&(P.delete("authorization"),P.set("Authorization","Basic "+btoa(mSe((He.username||"")+":"+(He.password||""))))),Ae&&typeof _=="string"&&_.startsWith("data:")&&I0(_)>N)throw new ye("maxContentLength size of "+N+" exceeded",ye.ERR_BAD_RESPONSE,m,Ee);if(ie&&T!=="get"&&T!=="head"){let Me=await Q(R);if(typeof Me=="number"&&isFinite(Me)&&(Le=Me,Me>k))throw aA()}let Be=ie&&(Z.isReadableStream(R)||Z.isStream(R)),We=(Me,CA,we)=>d0(Me,_q,Ke=>{if(ie&&Ke>k)throw AA=aA();CA&&CA(Ke)},we);if(d&&T!=="get"&&T!=="head"&&(z||Be)){if(Le=Le??await y(P,R),Le!==0||Be){let Me=new a(_,{method:"POST",body:R,duplex:"half"}),CA;if(Z.isFormData(R)&&(CA=Me.headers.get("content-type"))&&P.setContentType(CA),Me.body){let[we,Ke]=z&&td(Le,sg(rd(z)))||[];R=We(Me.body,we,Ke)}}}else if(Be&&!s&&c&&T!=="get"&&T!=="head")R=We(R);else if(Be&&s&&!d&&T!=="get"&&T!=="head")throw new ye("Stream request bodies are not supported by the current fetch implementation",ye.ERR_NOT_SUPPORT,m,Ee);Z.isString(J)||(J=J?"include":"omit");let Ye=s&&"credentials"in a.prototype;if(Z.isFormData(R)){let Me=P.getContentType();Me&&/^multipart\/form-data/i.test(Me)&&!/boundary=/i.test(Me)&&P.delete("content-type")}P.set("User-Agent","axios/"+ng,!1);let Re=H==null?H:Object.assign(Object.create(null),H);Re&&(delete Re.body,delete Re.headers,delete Re.method,delete Re.signal,delete Re.duplex,delete Re.credentials);let Ze=Object.assign(Object.create(null),Re,{signal:_e,method:T.toUpperCase(),headers:Yp(P.normalize()),body:R,duplex:"half",credentials:Ye?J:void 0});s&&(Z.forEach(ySe,(Me,CA)=>{Ze[CA]===void 0&&(Ze[CA]=Me)}),Ze.signal===void 0&&(Ze.signal=null),Ze.body===void 0&&(Ze.body=null)),V===0&&(Ze.redirect="manual",Re&&(Re.redirect="manual")),Ee=s&&new a(_,Ze);let iA=await(s?fe(Ee,Re):fe(_,Ze)),gA=Ut.from(iA.headers);if(Ae){let Me=Z.toFiniteNumber(gA.getContentLength());if(Me!=null&&Me>N)throw new ye("maxContentLength size of "+N+" exceeded",ye.ERR_BAD_RESPONSE,m,Ee)}let WA=B&&(j==="stream"||j==="response");if(B&&iA.body&&(q||Ae||WA&&Qe)){let Me={};["status","statusText","headers"].forEach(wA=>{Me[wA]=iA[wA]});let CA=Z.toFiniteNumber(gA.getContentLength()),[we,Ke]=q&&td(CA,sg(rd(q),!0))||[],Ve=0,NA=wA=>{if(Ae&&(Ve=wA,Ve>N))throw new ye("maxContentLength size of "+N+" exceeded",ye.ERR_BAD_RESPONSE,m,Ee);we&&we(wA)};iA=new A(d0(iA.body,_q,NA,()=>{Ke&&Ke(),Qe&&Qe()}),Me)}j=j||"text";let FA=await f[Z.findKey(f,j)||"text"](iA,m);if(Ae&&!B&&!WA){let Me;if(FA!=null&&(typeof FA.byteLength=="number"?Me=FA.byteLength:typeof FA.size=="number"?Me=FA.size:typeof FA=="string"&&(Me=typeof i=="function"?new i().encode(FA).byteLength:FA.length)),typeof Me=="number"&&Me>N)throw new ye("maxContentLength size of "+N+" exceeded",ye.ERR_BAD_RESPONSE,m,Ee)}return!WA&&Qe&&Qe(),await new Promise((Me,CA)=>{ts(Me,CA,{data:FA,headers:Ut.from(iA.headers),status:iA.status,statusText:iA.statusText,config:m,request:Ee})})}catch(He){if(Qe&&Qe(),_e&&_e.aborted&&_e.reason instanceof ye){let ce=_e.reason;throw ce.config=m,Ee&&(ce.request=Ee),He!==ce&&Object.defineProperty(ce,"cause",{__proto__:null,value:He,writable:!0,enumerable:!1,configurable:!0}),ce}if(AA)throw Ee&&!AA.request&&(AA.request=Ee),AA;if(He instanceof ye)throw Ee&&!He.request&&(He.request=Ee),He;if(He&&He.name==="TypeError"&&/Load failed|fetch/i.test(He.message)){let ce=new ye("Network Error",ye.ERR_NETWORK,m,Ee,He&&He.response);throw Object.defineProperty(ce,"cause",{__proto__:null,value:He.cause||He,writable:!0,enumerable:!1,configurable:!0}),ce}throw ye.from(He,He&&He.code,m,Ee,He&&He.response)}}},DSe=new Map,h0=n=>{let t=n&&n.env||{},{fetch:o,Request:i,Response:e}=t,a=[i,e,o],A=a.length,r=A,s,g,c=DSe;for(;r--;)s=a[r],g=c.get(s),g===void 0&&c.set(s,g=r?new Map:wSe(t)),c=g;return g},TnA=h0();var E0={http:Sq,xhr:bq,fetch:{get:h0}};Z.forEach(E0,(n,t)=>{if(n){try{Object.defineProperty(n,"name",{__proto__:null,value:t})}catch{}Object.defineProperty(n,"adapterName",{__proto__:null,value:t})}});var Rq=n=>`- ${n}`,bSe=n=>Z.isFunction(n)||n===null||n===!1;function MSe(n,t){n=Z.isArray(n)?n:[n];let{length:o}=n,i,e,a={};for(let A=0;A`adapter ${s} `+(g===!1?"is not supported by the environment":"is not available in the build")),r=o?A.length>1?`since : `+A.map(Rq).join(` `):" "+Rq(A[0]):"as no adapter specified";throw new ye("There is no suitable adapter to dispatch the request "+r,ye.ERR_NOT_SUPPORT)}return e}var Sy={getAdapter:MSe,adapters:E0};function C0(n){if(n.cancelToken&&n.cancelToken.throwIfRequested(),n.signal&&n.signal.aborted)throw new $i(null,n)}function SC(n){let t=Z.toSafeFlatObject(n);return C0(t),t.headers=Ut.from(Z.getSafeProp(t,"headers")),t.data=IC.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Sy.getAdapter(t.adapter||Zp.adapter,t)(t).then(function(e){C0(t),t.response=e;try{e.data=IC.call(t,t.transformResponse,e)}finally{delete t.response}return e.headers=Ut.from(e.headers),e},function(e){if(!lC(e)&&(C0(t),e&&e.response)){t.response=e.response;try{e.response.data=IC.call(t,t.transformResponse,e.response)}finally{delete t.response}e.response.headers=Ut.from(e.response.headers)}return Promise.reject(e)})}var wy={};["object","boolean","number","function","string","symbol"].forEach((n,t)=>{wy[n]=function(i){return typeof i===n||"a"+(t<1?"n ":" ")+n}});var kq={};wy.transitional=function(t,o,i){function e(a,A){return"[Axios v"+ng+"] Transitional option '"+a+"'"+A+(i?". "+i:"")}return(a,A,r)=>{if(t===!1)throw new ye(e(A," has been removed"+(o?" in "+o:"")),ye.ERR_DEPRECATED);return o&&!kq[A]&&(kq[A]=!0,console.warn(e(A," has been deprecated since v"+o+" and will be removed in the near future"))),t?t(a,A,r):!0}};wy.spelling=function(t){return(o,i)=>(console.warn(`${i} is likely a misspelling of ${t}`),!0)};function _Se(n,t,o){if(typeof n!="object"||n===null)throw new ye("options must be an object",ye.ERR_BAD_OPTION_VALUE);let i=Object.keys(n),e=i.length;for(;e-- >0;){let a=i[e],A=Object.prototype.hasOwnProperty.call(t,a)?t[a]:void 0;if(A){let r=n[a],s=r===void 0||A(r,a,n);if(s!==!0)throw new ye("option "+a+" must be "+s,ye.ERR_BAD_OPTION_VALUE);continue}if(o!==!0)throw new ye("Unknown option "+a,ye.ERR_BAD_OPTION)}}var wC={assertOptions:_Se,validators:wy};var za=wC.validators,ad=class{constructor(t){this.defaults=t||{},this.interceptors={request:new yT,response:new yT}}async request(t,o){try{return await this._request(t,o)}catch(i){if(i instanceof Error)try{let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;let a=e.stack,A="";if(typeof a=="string"){let r=a.indexOf(` `);A=r===-1?"":a.slice(r+1)}if(!i.stack)i.stack=A;else if(A){let r=A.indexOf(` @@ -341,7 +341,7 @@ ${t}`).digest("hex").slice(0,24).toUpperCase()}`}var ZQ=class{#e;#A;#t;#r;#g=nul -> Mode of event/callback subscription(\u8BA2\u9605\u65B9\u5F0F) -> - Receive events/callbacks through persistent connection(\u4F7F\u7528 \u957F\u8FDE\u63A5 \u63A5\u6536\u4E8B\u4EF6/\u56DE\u8C03)`),this.eventDispatcher=i,this.reConnect(!0)})}},hv=class{constructor(){this.sessions=new Map}set(t,o){return h(this,void 0,void 0,function*(){let i=this.sessions.get(t.toString())||{},e=QW(i,o);return this.sessions.set(t.toString(),e),!0})}get(t){return h(this,void 0,void 0,function*(){return this.sessions.get(t.toString())})}},to;(function(n){n[n.ERROR=-1]="ERROR",n[n.SUCCESS=0]="SUCCESS",n[n.EXPIRED=1]="EXPIRED",n[n.CANCELLED=2]="CANCELLED",n[n.FAILED=3]="FAILED",n[n.OTHER=4]="OTHER"})(to||(to={}));var Ev=class{constructor(t){this.completions={create:this.create.bind(this),createWithStream:this.createWithStream.bind(this),sessionRecords:{get:this.getRecords.bind(this),update:this.updateRecords.bind(this)}},this.client=t.client,this.logger=t.client.logger,this.cache=t.cache||new hv}getSessionId(t){var o;return h(this,void 0,void 0,function*(){let{sessionId:i,payload:e,options:a}=t,A=yield this.getRecords();if(i&&i in A)return A[i];let r=yield this.client.aily.v1.ailySession.create({data:e},a);if(r.code===0&&r.data){let s=(o=r.data.session)===null||o===void 0?void 0:o.id;return i&&(yield this.updateRecords({[i]:s})),s}else{this.logger.error("get aily session id error",r.msg);return}})}waitReply(t,o){var i,e;return h(this,void 0,void 0,function*(){let{sessionId:a,ailyAppId:A,message:r,sessionInfo:s,messageInfo:g,runInfo:c,skillId:I}=t,d=yield this.getSessionId({sessionId:a,payload:s,options:o});if(!d)throw to.ERROR;let B=yield this.client.aily.v1.ailySessionAilyMessage.create({path:{aily_session_id:d},data:Object.assign(Object.assign({},g),{content:r,idempotent_id:`${Date.now()}`,content_type:"MDX"})},o);if(!(B.code===0&&B.data))throw this.logger.error("create aily message error",B.msg),to.ERROR;let f=(i=B.data.message)===null||i===void 0?void 0:i.id,Q=yield this.client.aily.v1.ailySessionRun.create({path:{aily_session_id:d},data:Object.assign({app_id:A,skill_id:I},c)},o);if(!(Q.code===0&&Q.data))throw this.logger.error("create aily session run error",Q.msg),to.ERROR;let y=(e=Q.data.run)===null||e===void 0?void 0:e.id;if(!y)throw this.logger.error("run id is empty"),to.ERROR;let m=()=>h(this,void 0,void 0,function*(){return new Promise(T=>{setTimeout(()=>h(this,void 0,void 0,function*(){var R,F;let K=yield this.client.aily.v1.ailySessionRun.get({path:{aily_session_id:d,run_id:y}},o);if(!(K.code===0&&K.data)){T(3);return}switch((F=(R=K.data)===null||R===void 0?void 0:R.run)===null||F===void 0?void 0:F.status){case"QUEUED":case"IN_PROGRESS":yield h(this,void 0,void 0,function*(){let q=yield m();T(q)});case"COMPLETED":T(to.SUCCESS);case"EXPIRED":T(to.EXPIRED);case"CANCELLED":T(to.CANCELLED);case"FAILED":T(to.FAILED);default:T(to.OTHER)}}),500)})}),_=yield m();if(_!==to.SUCCESS)throw this.logger.error("aily run error"),_;return{ailySessionId:d,runId:y,messageId:f}})}create(t,o){var i,e,a,A,r;return h(this,void 0,void 0,function*(){let{ailySessionId:s,runId:g}=yield this.waitReply(t,o),c;try{for(var I=!0,d=qV(yield this.client.aily.v1.ailySessionAilyMessage.listWithIterator({path:{aily_session_id:s},params:{run_id:g,with_partial_message:!1}},o)),B;B=yield d.next(),i=B.done,!i;){A=B.value,I=!1;try{let f=A;if(!f)continue;(r=f?.messages)===null||r===void 0||r.forEach(Q=>{var y;((y=Q.sender)===null||y===void 0?void 0:y.sender_type)==="ASSISTANT"&&(c=Q)})}finally{I=!0}}}catch(f){e={error:f}}finally{try{!I&&!i&&(a=d.return)&&(yield a.call(d))}finally{if(e)throw e.error}}if(!c)throw this.logger.error("no aily reply"),to.ERROR;return c})}createWithStream(t,o){return h(this,void 0,void 0,function*(){let{ailySessionId:i,runId:e,messageId:a}=yield this.waitReply(t,o),A=()=>this.client.aily.v1.ailySessionAilyMessage.listWithIterator({path:{aily_session_id:i},params:{run_id:e,with_partial_message:!0}},o),r=!1;return{[Symbol.asyncIterator](){return Y(this,arguments,function*(){var c,I,d,B;try{for(var f=!0,Q=qV(yield S(A())),y;y=yield S(Q.next()),c=y.done,!c;){B=y.value,f=!1;try{let m=B;if(!m)continue;for(let _ of m.messages||[])if(r){if(yield yield S(_),_.status==="COMPLETED")return yield S(void 0)}else _.id===a&&_.status==="COMPLETED"&&(r=!0)}finally{f=!0}}}catch(m){I={error:m}}finally{try{!f&&!c&&(d=Q.return)&&(yield S(d.call(Q)))}finally{if(I)throw I.error}}})}}})}getRecords(){return h(this,void 0,void 0,function*(){return(yield this.cache.get(VV))||{}})}updateRecords(t){return h(this,void 0,void 0,function*(){yield this.cache.set(VV,t)})}};function Au(n,t){if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${t} must be an object`)}function tu(n,t,o){for(let i of Object.keys(n))if(!t.includes(i))throw new Error(`${o}.${i} is not allowed; allowed keys: ${t.join(", ")}`)}function a0e(n,t){if(n!==void 0){if(!Array.isArray(n))throw new Error(`${t} must be an array of strings`);return n.forEach((o,i)=>{if(typeof o!="string"||o==="")throw new Error(`${t}[${i}] must be a non-empty string`)}),n}}function i0e(n){Au(n,"addons"),tu(n,["preset","scopes","events","callbacks"],"addons");let t=0,o=(e,a)=>{var A;let r=a0e(e,a);return t+=(A=r?.length)!==null&&A!==void 0?A:0,r},i={};if(n.preset!==void 0){if(typeof n.preset!="boolean")throw new Error("addons.preset must be a boolean");i.preset=n.preset}if(n.scopes!==void 0&&(Au(n.scopes,"addons.scopes"),tu(n.scopes,["tenant","user"],"addons.scopes"),i.scopes={tenant:o(n.scopes.tenant,"addons.scopes.tenant"),user:o(n.scopes.user,"addons.scopes.user")}),n.events!==void 0&&(Au(n.events,"addons.events"),tu(n.events,["items"],"addons.events"),n.events.items!==void 0&&(Au(n.events.items,"addons.events.items"),tu(n.events.items,["tenant","user"],"addons.events.items"),i.events={items:{tenant:o(n.events.items.tenant,"addons.events.items.tenant"),user:o(n.events.items.user,"addons.events.items.user")}})),n.callbacks!==void 0&&(Au(n.callbacks,"addons.callbacks"),tu(n.callbacks,["items"],"addons.callbacks"),i.callbacks={items:o(n.callbacks.items,"addons.callbacks.items")}),t===0&&n.preset!==!1)throw new Error("addons must contain at least one scope, event or callback");return i}function o0e(n){let t=JSON.stringify(i0e(n));return _Te(Buffer.from(t,"utf8")).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ru(n,t){return{code:n,description:t}}var ZV="node-sdk",n0e="accounts.feishu.cn",s0e="accounts.larksuite.com",g0e="/oauth/v1/app/registration",XV=6;function c0e(n,t){let{avatar:o,name:i,desc:e}=t;if(o!==void 0){let a=Array.isArray(o)?o:[o];if(a.length===0)throw new Error("appPreset.avatar must contain at least 1 URL");if(a.length>XV)throw new Error(`appPreset.avatar supports at most ${XV} URLs, got ${a.length}`);a.forEach((A,r)=>{if(typeof A!="string"||A==="")throw new Error(`appPreset.avatar[${r}] must be a non-empty string`);n.searchParams.append("avatar",A)})}i!==void 0&&n.searchParams.set("name",i),e!==void 0&&n.searchParams.set("desc",e)}function mW(n,t){var o;return h(this,void 0,void 0,function*(){try{return yield bd.post(`${n}${g0e}`,new URLSearchParams(t).toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded"}})}catch(i){if(i instanceof Q0&&(!((o=i.response)===null||o===void 0)&&o.data))return i.response.data;throw i}})}function I0e(n){return mW(n,{action:"begin",archetype:"PersonalAgent",auth_method:"client_secret",request_user_info:"open_id"})}function l0e(n){return new Promise((t,o)=>{var i,e;let{baseUrl:a,interval:A}=n,r=!1,s=null,g=null,c=()=>{var B;s!==null&&(clearTimeout(s),s=null),g!==null&&(clearTimeout(g),g=null),(B=n.signal)===null||B===void 0||B.removeEventListener("abort",I)},I=()=>{c(),o(ru("abort","Registration was aborted"))};if(!((i=n.signal)===null||i===void 0)&&i.aborted)return o(ru("abort","Registration was aborted"));(e=n.signal)===null||e===void 0||e.addEventListener("abort",I,{once:!0}),g=setTimeout(()=>{c(),o(ru("expired_token","Polling timed out"))},n.expireIn);let d=()=>h(this,void 0,void 0,function*(){var B,f,Q,y,m,_;try{let T=yield mW(a,{action:"poll",device_code:n.deviceCode});if(((B=T.user_info)===null||B===void 0?void 0:B.tenant_brand)==="lark"&&!r){a=n.larkBaseUrl,r=!0,(f=n.onStatusChange)===null||f===void 0||f.call(n,{status:"domain_switched"}),d();return}if(T.client_id&&T.client_secret){c(),t({client_id:T.client_id,client_secret:T.client_secret,user_info:T.user_info});return}switch(T.error){case"authorization_pending":(Q=n.onStatusChange)===null||Q===void 0||Q.call(n,{status:"polling"});break;case"slow_down":A+=5e3,(y=n.onStatusChange)===null||y===void 0||y.call(n,{status:"slow_down",interval:A/1e3});break;case"access_denied":case"expired_token":c(),o(ru(T.error,(m=T.error_description)!==null&&m!==void 0?m:"Unknown error"));return;default:if(T.error){c(),o(ru(T.error,(_=T.error_description)!==null&&_!==void 0?_:"Unknown error"));return}break}s=setTimeout(d,A)}catch(T){c(),o(T)}});d()})}function p0e(n){var t,o,i,e;return h(this,void 0,void 0,function*(){let{domain:a,source:A,signal:r,onQRCodeReady:s,onStatusChange:g,appPreset:c,addons:I,createOnly:d,appId:B}=n;if(B!==void 0&&(typeof B!="string"||B===""))throw new Error("appId must be a non-empty string");let f=`https://${a??n0e}`,Q=yield I0e(f),y=new URL(Q.verification_uri_complete);return y.searchParams.set("from","sdk"),y.searchParams.set("source",A?`${ZV}/${A}`:ZV),y.searchParams.set("tp","sdk"),c&&c0e(y,c),I&&y.searchParams.set("addons",o0e(I)),d===!0&&y.searchParams.set("createOnly","true"),B&&y.searchParams.set("clientID",B),s({url:y.toString(),expireIn:(t=Q.expires_in)!==null&&t!==void 0?t:600}),l0e({baseUrl:f,deviceCode:Q.device_code,interval:((o=Q.interval)!==null&&o!==void 0?o:5)*1e3,expireIn:((i=Q.expires_in)!==null&&i!==void 0?i:600)*1e3,larkBaseUrl:`https://${(e=n.larkDomain)!==null&&e!==void 0?e:s0e}`,signal:r,onStatusChange:g})})}var Pt=class extends Error{constructor(t,o,i){super(o),this.name="LarkChannelError",this.code=t,this.cause=i?.cause,this.context=i?.context}},Um=class{constructor(t,o){this.opts=t,this.fire=o,this.pendingChars=0,this.lastFireAt=0}note(t){if(this.pendingChars+=t,this.pendingChars>=this.opts.chars){this.fireSoon(0);return}if(!this.timer){let o=Date.now()-this.lastFireAt,i=Math.max(0,this.opts.ms-o);this.fireSoon(i)}}fireSoon(t){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.doFire()},t)}flushNow(){return h(this,void 0,void 0,function*(){this.timer&&(clearTimeout(this.timer),this.timer=void 0),this.inFlight&&(yield this.inFlight),yield this.doFire()})}doFire(){return h(this,void 0,void 0,function*(){if(this.inFlight){this.fireSoon(this.opts.ms);return}let t=h(this,void 0,void 0,function*(){this.pendingChars=0,this.lastFireAt=Date.now(),yield this.fire()});this.inFlight=t;try{yield t}finally{this.inFlight=void 0}})}dispose(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}},Hm=class{constructor(){this.tail=Promise.resolve()}enqueue(t){let o=this.tail.then(t,t);return this.tail=o.then(()=>{},()=>{}),o}drain(){return this.tail}};function d0e(n,t){if(!n)return t;if(!t)return n;if(t.startsWith(n))return t;if(n.startsWith(t))return n;let o=Math.min(n.length,t.length);for(let i=o;i>0;i--)if(n.endsWith(t.substring(0,i)))return n+t.substring(i);return n+t}function SW(n,t){if(n.length<=t)return[n];let o=n.split(` + Receive events/callbacks through persistent connection(\u4F7F\u7528 \u957F\u8FDE\u63A5 \u63A5\u6536\u4E8B\u4EF6/\u56DE\u8C03)`),this.eventDispatcher=i,this.reConnect(!0)})}},hv=class{constructor(){this.sessions=new Map}set(t,o){return h(this,void 0,void 0,function*(){let i=this.sessions.get(t.toString())||{},e=QW(i,o);return this.sessions.set(t.toString(),e),!0})}get(t){return h(this,void 0,void 0,function*(){return this.sessions.get(t.toString())})}},to;(function(n){n[n.ERROR=-1]="ERROR",n[n.SUCCESS=0]="SUCCESS",n[n.EXPIRED=1]="EXPIRED",n[n.CANCELLED=2]="CANCELLED",n[n.FAILED=3]="FAILED",n[n.OTHER=4]="OTHER"})(to||(to={}));var Ev=class{constructor(t){this.completions={create:this.create.bind(this),createWithStream:this.createWithStream.bind(this),sessionRecords:{get:this.getRecords.bind(this),update:this.updateRecords.bind(this)}},this.client=t.client,this.logger=t.client.logger,this.cache=t.cache||new hv}getSessionId(t){var o;return h(this,void 0,void 0,function*(){let{sessionId:i,payload:e,options:a}=t,A=yield this.getRecords();if(i&&i in A)return A[i];let r=yield this.client.aily.v1.ailySession.create({data:e},a);if(r.code===0&&r.data){let s=(o=r.data.session)===null||o===void 0?void 0:o.id;return i&&(yield this.updateRecords({[i]:s})),s}else{this.logger.error("get aily session id error",r.msg);return}})}waitReply(t,o){var i,e;return h(this,void 0,void 0,function*(){let{sessionId:a,ailyAppId:A,message:r,sessionInfo:s,messageInfo:g,runInfo:c,skillId:I}=t,d=yield this.getSessionId({sessionId:a,payload:s,options:o});if(!d)throw to.ERROR;let B=yield this.client.aily.v1.ailySessionAilyMessage.create({path:{aily_session_id:d},data:Object.assign(Object.assign({},g),{content:r,idempotent_id:`${Date.now()}`,content_type:"MDX"})},o);if(!(B.code===0&&B.data))throw this.logger.error("create aily message error",B.msg),to.ERROR;let f=(i=B.data.message)===null||i===void 0?void 0:i.id,Q=yield this.client.aily.v1.ailySessionRun.create({path:{aily_session_id:d},data:Object.assign({app_id:A,skill_id:I},c)},o);if(!(Q.code===0&&Q.data))throw this.logger.error("create aily session run error",Q.msg),to.ERROR;let y=(e=Q.data.run)===null||e===void 0?void 0:e.id;if(!y)throw this.logger.error("run id is empty"),to.ERROR;let m=()=>h(this,void 0,void 0,function*(){return new Promise(T=>{setTimeout(()=>h(this,void 0,void 0,function*(){var R,L;let U=yield this.client.aily.v1.ailySessionRun.get({path:{aily_session_id:d,run_id:y}},o);if(!(U.code===0&&U.data)){T(3);return}switch((L=(R=U.data)===null||R===void 0?void 0:R.run)===null||L===void 0?void 0:L.status){case"QUEUED":case"IN_PROGRESS":yield h(this,void 0,void 0,function*(){let q=yield m();T(q)});case"COMPLETED":T(to.SUCCESS);case"EXPIRED":T(to.EXPIRED);case"CANCELLED":T(to.CANCELLED);case"FAILED":T(to.FAILED);default:T(to.OTHER)}}),500)})}),_=yield m();if(_!==to.SUCCESS)throw this.logger.error("aily run error"),_;return{ailySessionId:d,runId:y,messageId:f}})}create(t,o){var i,e,a,A,r;return h(this,void 0,void 0,function*(){let{ailySessionId:s,runId:g}=yield this.waitReply(t,o),c;try{for(var I=!0,d=qV(yield this.client.aily.v1.ailySessionAilyMessage.listWithIterator({path:{aily_session_id:s},params:{run_id:g,with_partial_message:!1}},o)),B;B=yield d.next(),i=B.done,!i;){A=B.value,I=!1;try{let f=A;if(!f)continue;(r=f?.messages)===null||r===void 0||r.forEach(Q=>{var y;((y=Q.sender)===null||y===void 0?void 0:y.sender_type)==="ASSISTANT"&&(c=Q)})}finally{I=!0}}}catch(f){e={error:f}}finally{try{!I&&!i&&(a=d.return)&&(yield a.call(d))}finally{if(e)throw e.error}}if(!c)throw this.logger.error("no aily reply"),to.ERROR;return c})}createWithStream(t,o){return h(this,void 0,void 0,function*(){let{ailySessionId:i,runId:e,messageId:a}=yield this.waitReply(t,o),A=()=>this.client.aily.v1.ailySessionAilyMessage.listWithIterator({path:{aily_session_id:i},params:{run_id:e,with_partial_message:!0}},o),r=!1;return{[Symbol.asyncIterator](){return Y(this,arguments,function*(){var c,I,d,B;try{for(var f=!0,Q=qV(yield S(A())),y;y=yield S(Q.next()),c=y.done,!c;){B=y.value,f=!1;try{let m=B;if(!m)continue;for(let _ of m.messages||[])if(r){if(yield yield S(_),_.status==="COMPLETED")return yield S(void 0)}else _.id===a&&_.status==="COMPLETED"&&(r=!0)}finally{f=!0}}}catch(m){I={error:m}}finally{try{!f&&!c&&(d=Q.return)&&(yield S(d.call(Q)))}finally{if(I)throw I.error}}})}}})}getRecords(){return h(this,void 0,void 0,function*(){return(yield this.cache.get(VV))||{}})}updateRecords(t){return h(this,void 0,void 0,function*(){yield this.cache.set(VV,t)})}};function Au(n,t){if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${t} must be an object`)}function tu(n,t,o){for(let i of Object.keys(n))if(!t.includes(i))throw new Error(`${o}.${i} is not allowed; allowed keys: ${t.join(", ")}`)}function a0e(n,t){if(n!==void 0){if(!Array.isArray(n))throw new Error(`${t} must be an array of strings`);return n.forEach((o,i)=>{if(typeof o!="string"||o==="")throw new Error(`${t}[${i}] must be a non-empty string`)}),n}}function i0e(n){Au(n,"addons"),tu(n,["preset","scopes","events","callbacks"],"addons");let t=0,o=(e,a)=>{var A;let r=a0e(e,a);return t+=(A=r?.length)!==null&&A!==void 0?A:0,r},i={};if(n.preset!==void 0){if(typeof n.preset!="boolean")throw new Error("addons.preset must be a boolean");i.preset=n.preset}if(n.scopes!==void 0&&(Au(n.scopes,"addons.scopes"),tu(n.scopes,["tenant","user"],"addons.scopes"),i.scopes={tenant:o(n.scopes.tenant,"addons.scopes.tenant"),user:o(n.scopes.user,"addons.scopes.user")}),n.events!==void 0&&(Au(n.events,"addons.events"),tu(n.events,["items"],"addons.events"),n.events.items!==void 0&&(Au(n.events.items,"addons.events.items"),tu(n.events.items,["tenant","user"],"addons.events.items"),i.events={items:{tenant:o(n.events.items.tenant,"addons.events.items.tenant"),user:o(n.events.items.user,"addons.events.items.user")}})),n.callbacks!==void 0&&(Au(n.callbacks,"addons.callbacks"),tu(n.callbacks,["items"],"addons.callbacks"),i.callbacks={items:o(n.callbacks.items,"addons.callbacks.items")}),t===0&&n.preset!==!1)throw new Error("addons must contain at least one scope, event or callback");return i}function o0e(n){let t=JSON.stringify(i0e(n));return _Te(Buffer.from(t,"utf8")).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ru(n,t){return{code:n,description:t}}var ZV="node-sdk",n0e="accounts.feishu.cn",s0e="accounts.larksuite.com",g0e="/oauth/v1/app/registration",XV=6;function c0e(n,t){let{avatar:o,name:i,desc:e}=t;if(o!==void 0){let a=Array.isArray(o)?o:[o];if(a.length===0)throw new Error("appPreset.avatar must contain at least 1 URL");if(a.length>XV)throw new Error(`appPreset.avatar supports at most ${XV} URLs, got ${a.length}`);a.forEach((A,r)=>{if(typeof A!="string"||A==="")throw new Error(`appPreset.avatar[${r}] must be a non-empty string`);n.searchParams.append("avatar",A)})}i!==void 0&&n.searchParams.set("name",i),e!==void 0&&n.searchParams.set("desc",e)}function mW(n,t){var o;return h(this,void 0,void 0,function*(){try{return yield bd.post(`${n}${g0e}`,new URLSearchParams(t).toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded"}})}catch(i){if(i instanceof Q0&&(!((o=i.response)===null||o===void 0)&&o.data))return i.response.data;throw i}})}function I0e(n){return mW(n,{action:"begin",archetype:"PersonalAgent",auth_method:"client_secret",request_user_info:"open_id"})}function l0e(n){return new Promise((t,o)=>{var i,e;let{baseUrl:a,interval:A}=n,r=!1,s=null,g=null,c=()=>{var B;s!==null&&(clearTimeout(s),s=null),g!==null&&(clearTimeout(g),g=null),(B=n.signal)===null||B===void 0||B.removeEventListener("abort",I)},I=()=>{c(),o(ru("abort","Registration was aborted"))};if(!((i=n.signal)===null||i===void 0)&&i.aborted)return o(ru("abort","Registration was aborted"));(e=n.signal)===null||e===void 0||e.addEventListener("abort",I,{once:!0}),g=setTimeout(()=>{c(),o(ru("expired_token","Polling timed out"))},n.expireIn);let d=()=>h(this,void 0,void 0,function*(){var B,f,Q,y,m,_;try{let T=yield mW(a,{action:"poll",device_code:n.deviceCode});if(((B=T.user_info)===null||B===void 0?void 0:B.tenant_brand)==="lark"&&!r){a=n.larkBaseUrl,r=!0,(f=n.onStatusChange)===null||f===void 0||f.call(n,{status:"domain_switched"}),d();return}if(T.client_id&&T.client_secret){c(),t({client_id:T.client_id,client_secret:T.client_secret,user_info:T.user_info});return}switch(T.error){case"authorization_pending":(Q=n.onStatusChange)===null||Q===void 0||Q.call(n,{status:"polling"});break;case"slow_down":A+=5e3,(y=n.onStatusChange)===null||y===void 0||y.call(n,{status:"slow_down",interval:A/1e3});break;case"access_denied":case"expired_token":c(),o(ru(T.error,(m=T.error_description)!==null&&m!==void 0?m:"Unknown error"));return;default:if(T.error){c(),o(ru(T.error,(_=T.error_description)!==null&&_!==void 0?_:"Unknown error"));return}break}s=setTimeout(d,A)}catch(T){c(),o(T)}});d()})}function p0e(n){var t,o,i,e;return h(this,void 0,void 0,function*(){let{domain:a,source:A,signal:r,onQRCodeReady:s,onStatusChange:g,appPreset:c,addons:I,createOnly:d,appId:B}=n;if(B!==void 0&&(typeof B!="string"||B===""))throw new Error("appId must be a non-empty string");let f=`https://${a??n0e}`,Q=yield I0e(f),y=new URL(Q.verification_uri_complete);return y.searchParams.set("from","sdk"),y.searchParams.set("source",A?`${ZV}/${A}`:ZV),y.searchParams.set("tp","sdk"),c&&c0e(y,c),I&&y.searchParams.set("addons",o0e(I)),d===!0&&y.searchParams.set("createOnly","true"),B&&y.searchParams.set("clientID",B),s({url:y.toString(),expireIn:(t=Q.expires_in)!==null&&t!==void 0?t:600}),l0e({baseUrl:f,deviceCode:Q.device_code,interval:((o=Q.interval)!==null&&o!==void 0?o:5)*1e3,expireIn:((i=Q.expires_in)!==null&&i!==void 0?i:600)*1e3,larkBaseUrl:`https://${(e=n.larkDomain)!==null&&e!==void 0?e:s0e}`,signal:r,onStatusChange:g})})}var Pt=class extends Error{constructor(t,o,i){super(o),this.name="LarkChannelError",this.code=t,this.cause=i?.cause,this.context=i?.context}},Um=class{constructor(t,o){this.opts=t,this.fire=o,this.pendingChars=0,this.lastFireAt=0}note(t){if(this.pendingChars+=t,this.pendingChars>=this.opts.chars){this.fireSoon(0);return}if(!this.timer){let o=Date.now()-this.lastFireAt,i=Math.max(0,this.opts.ms-o);this.fireSoon(i)}}fireSoon(t){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.doFire()},t)}flushNow(){return h(this,void 0,void 0,function*(){this.timer&&(clearTimeout(this.timer),this.timer=void 0),this.inFlight&&(yield this.inFlight),yield this.doFire()})}doFire(){return h(this,void 0,void 0,function*(){if(this.inFlight){this.fireSoon(this.opts.ms);return}let t=h(this,void 0,void 0,function*(){this.pendingChars=0,this.lastFireAt=Date.now(),yield this.fire()});this.inFlight=t;try{yield t}finally{this.inFlight=void 0}})}dispose(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}},Hm=class{constructor(){this.tail=Promise.resolve()}enqueue(t){let o=this.tail.then(t,t);return this.tail=o.then(()=>{},()=>{}),o}drain(){return this.tail}};function d0e(n,t){if(!n)return t;if(!t)return n;if(t.startsWith(n))return t;if(n.startsWith(t))return n;let o=Math.min(n.length,t.length);for(let i=o;i>0;i--)if(n.endsWith(t.substring(0,i)))return n+t.substring(i);return n+t}function SW(n,t){if(n.length<=t)return[n];let o=n.split(` `),i=[],e=[],a=0,A=null,r=()=>{if(e.length===0)return;let s=e.join(` `);A!==null&&(s+="\n```"),i.push(s),e=[],a=0,A!==null&&(e.push("```"+A),a=e[0].length)};for(let s of o){let g=s.match(/^```(\w*)$/),c=s.length+(e.length>0?1:0),I=/^#{1,6}\s/.test(s),d=a>t*.75;(a+c>t||I&&d&&e.length>0)&&r(),e.push(s),a+=c,g&&(A=A===null?g[1]||"":null)}return r(),i}var h0e=100,E0e=50,C0e="Thinking...",$V="(no content)",u0e="[Generating...]",B0e=50,f0e=` @@ -410,9 +410,9 @@ ${i.length>0?i.join(` `,resources:[]};let a=[];e.topic&&a.push(e.topic);for(let A of(i=e.options)!==null&&i!==void 0?i:[])a.push(`\u2022 ${A}`);return{content:` ${a.join(` `)} -`,resources:[]}}),PNe=new Map([["text",TNe],["post",wNe],["image",uNe],["file",hNe],["audio",INe],["video",sW],["media",sW],["sticker",MNe],["interactive",fNe],["merge_forward",yNe],["share_chat",ONe],["share_user",bNe],["location",QNe],["system",_Ne],["vote",vNe],["todo",NNe],["calendar",lNe],["general_calendar",pNe],["share_calendar_event",dNe],["folder",ENe],["hongbao",CNe],["video_chat",kNe]]);function gW(n,t,o){var i;return h(this,void 0,void 0,function*(){let e=(i=PNe.get(t))!==null&&i!==void 0?i:nW;try{return yield e(n,o)}catch{return nW(n)}})}function _W(n,t){var o,i,e,a,A,r,s,g,c,I,d,B;let f=(i=(o=n.context)===null||o===void 0?void 0:o.open_message_id)!==null&&i!==void 0?i:n.open_message_id,Q=(a=(e=n.context)===null||e===void 0?void 0:e.open_chat_id)!==null&&a!==void 0?a:n.open_chat_id,y=(A=n.operator)===null||A===void 0?void 0:A.open_id;return!f||!Q||!y?null:{messageId:f,chatId:Q,operator:{openId:y,userId:(r=n.operator)===null||r===void 0?void 0:r.user_id,name:(s=n.operator)===null||s===void 0?void 0:s.name},action:{value:(g=n.action)===null||g===void 0?void 0:g.value,tag:(I=(c=n.action)===null||c===void 0?void 0:c.tag)!==null&&I!==void 0?I:"unknown",name:(d=n.action)===null||d===void 0?void 0:d.name,option:(B=n.action)===null||B===void 0?void 0:B.option},raw:t?.includeRaw?n:void 0}}function Mv(n,t,o){var i,e,a,A;let r=n.message_id,s=(i=n.reaction_type)===null||i===void 0?void 0:i.emoji_type,g=(e=n.user_id)===null||e===void 0?void 0:e.open_id;if(!r||!s||!g)return null;let c=n.action_time,I=c?parseInt(c,10):void 0;return{messageId:r,operator:{openId:g,userId:(A=(a=n.user_id)===null||a===void 0?void 0:a.user_id)!==null&&A!==void 0?A:void 0},emojiType:s,action:t,actionTime:I!=null&&Number.isFinite(I)?I:void 0,raw:o?.includeRaw?n:void 0}}function TW(n,t){var o,i,e,a,A,r,s,g,c;let I=n.chat_id,d=(o=n.operator_id)===null||o===void 0?void 0:o.open_id;if(!I||!d)return null;let B=(r=(a=(i=n.name)!==null&&i!==void 0?i:(e=n.i18n_names)===null||e===void 0?void 0:e.zh_cn)!==null&&a!==void 0?a:(A=n.i18n_names)===null||A===void 0?void 0:A.en_us)!==null&&r!==void 0?r:(s=n.i18n_names)===null||s===void 0?void 0:s.ja_jp;return{chatId:I,operator:{openId:d,userId:(c=(g=n.operator_id)===null||g===void 0?void 0:g.user_id)!==null&&c!==void 0?c:void 0},botName:B,external:n.external,raw:t?.includeRaw?n:void 0}}function NW(n,t){var o,i,e,a,A,r,s,g,c,I,d,B,f;let Q=(o=n.file_token)!==null&&o!==void 0?o:(i=n.notice_meta)===null||i===void 0?void 0:i.file_token,y=(e=n.file_type)!==null&&e!==void 0?e:(a=n.notice_meta)===null||a===void 0?void 0:a.file_type,m=n.comment_id,_=(r=(A=n.notice_meta)===null||A===void 0?void 0:A.from_user_id)!==null&&r!==void 0?r:n.user_id,T=_?.open_id;if(!Q||!y||!m||!T)return null;let R=(c=(s=n.create_time)!==null&&s!==void 0?s:(g=n.notice_meta)===null||g===void 0?void 0:g.timestamp)!==null&&c!==void 0?c:n.action_time,F=R?parseInt(R,10):Date.now();return{fileToken:Q,fileType:y,commentId:m,replyId:n.reply_id,operator:{openId:T,userId:(I=_?.user_id)!==null&&I!==void 0?I:void 0,unionId:_?.union_id},mentionedBot:!!((f=(d=n.is_mentioned)!==null&&d!==void 0?d:(B=n.notice_meta)===null||B===void 0?void 0:B.is_mentioned)!==null&&f!==void 0?f:n.is_mention),timestamp:Number.isFinite(F)?F:Date.now(),raw:t?.includeRaw?n:void 0}}function RW(n,t){var o,i,e,a,A;return h(this,void 0,void 0,function*(){let r=n.message,s=(o=t.botIdentity)===null||o===void 0?void 0:o.openId,{mentions:g,mentionsByOpenId:c,mentionList:I,mentionAll:d,mentionedBot:B}=rNe(r.mentions,s),f=d||GNe(r.content),Q={messageId:r.message_id,botOpenId:s,mentions:g,mentionsByOpenId:c,stripBotMentions:(i=t.stripBotMentions)!==null&&i!==void 0?i:!0,fetchSubMessages:t.fetchSubMessages,resolveUserName:t.resolveUserName,batchResolveNames:t.batchResolveNames,dispatch:gW},{content:y,resources:m}=yield gW(r.content,r.message_type,Q),_=aNe(y,Q),T=n.sender.sender_id.open_id,R=(a=(e=n.sender.sender_id.user_id)!==null&&e!==void 0?e:n.sender.sender_id.union_id)!==null&&a!==void 0?a:"",F=T??R,K=T?(A=t.resolveSenderName)===null||A===void 0?void 0:A.call(t,T):void 0,L=r.create_time?parseInt(r.create_time,10):0;return{messageId:r.message_id,chatId:r.chat_id,chatType:r.chat_type,senderId:F,senderName:K,content:_,rawContentType:r.message_type,resources:m,mentions:I,mentionAll:f,mentionedBot:B,rootId:r.root_id,threadId:r.thread_id,replyToMessageId:r.parent_id,createTime:Number.isFinite(L)?L:0,raw:t.includeRaw?n:void 0}})}function GNe(n){return n?/@_all\b/.test(n):!1}var xm=class{constructor(t){var o,i,e,a,A,r,s;this.handlers={},this.connected=!1,this.opts=t,this.logger=new Sc((o=t.loggerLevel)!==null&&o!==void 0?o:ro.info,(i=t.logger)!==null&&i!==void 0?i:fg),this.rawClient=new vm({appId:t.appId,appSecret:t.appSecret,domain:(e=t.domain)!==null&&e!==void 0?e:Is.Feishu,cache:t.cache,httpInstance:t.httpInstance,logger:t.logger,loggerLevel:t.loggerLevel,source:t.source,extraUaTags:["channel"]}),this.dispatcher=new Gm({verificationToken:(a=t.webhook)===null||a===void 0?void 0:a.verificationToken,encryptKey:(A=t.webhook)===null||A===void 0?void 0:A.encryptKey,cache:t.cache,logger:t.logger,loggerLevel:t.loggerLevel}),this.sender=new yv(this.rawClient,(r=t.outbound)!==null&&r!==void 0?r:{},this.logger),this.safety=new bv({config:t.safety,policy:t.policy,cache:(s=t.cache)!==null&&s!==void 0?s:lu,logger:this.logger,onReject:g=>{var c,I;(I=(c=this.handlers).reject)===null||I===void 0||I.call(c,g)},onMessage:g=>h(this,void 0,void 0,function*(){let c=this.handlers.message;c&&(yield c(g))})})}connect(){return h(this,void 0,void 0,function*(){return this.connectPromise?this.connectPromise:(this.connectPromise=this.doConnect().catch(t=>{throw this.connectPromise=void 0,t}),this.connectPromise)})}doConnect(){var t;return h(this,void 0,void 0,function*(){this.botIdentity=yield this.fetchBotIdentity(),this.safety.setBotIdentity(this.botIdentity),this.registerDispatcherHandlers(),((t=this.opts.transport)!==null&&t!==void 0?t:"websocket")==="websocket"&&(yield this.connectWebSocket(15e3)),this.connected=!0})}connectWebSocket(t){return new Promise((o,i)=>{var e;let a=!1,A=setTimeout(()=>{a||(a=!0,i(new Pt("not_connected",`WebSocket handshake did not complete within ${t}ms`)))},t);this.rawWsClient=new Lm({appId:this.opts.appId,appSecret:this.opts.appSecret,domain:(e=this.opts.domain)!==null&&e!==void 0?e:Is.Feishu,logger:this.opts.logger,loggerLevel:this.opts.loggerLevel,httpInstance:this.opts.httpInstance,autoReconnect:!0,source:this.opts.source,extraUaTags:["channel"],agent:this.opts.agent,wsConfig:this.opts.wsConfig,handshakeTimeoutMs:this.opts.handshakeTimeoutMs,onReady:()=>{a||(a=!0,clearTimeout(A),o())},onError:r=>{a||(a=!0,clearTimeout(A),i(new Pt("not_connected",`WebSocket connect failed: ${r.message}`,{cause:r})))},onReconnecting:()=>{var r,s;return(s=(r=this.handlers).reconnecting)===null||s===void 0?void 0:s.call(r)},onReconnected:()=>{var r,s;return(s=(r=this.handlers).reconnected)===null||s===void 0?void 0:s.call(r)}}),this.rawWsClient.start({eventDispatcher:this.dispatcher})})}disconnect(){var t;return h(this,void 0,void 0,function*(){if(this.connected){try{(t=this.rawWsClient)===null||t===void 0||t.close({})}catch{}try{yield this.safety.dispose()}catch{}this.connected=!1,this.connectPromise=void 0}})}getConnectionStatus(){var t;return(t=this.rawWsClient)===null||t===void 0?void 0:t.getConnectionStatus()}on(t,o){if(typeof t=="string")return this.attachSingle(t,o);let i=[];return Object.keys(t).forEach(e=>{let a=t[e];a&&i.push(this.attachSingle(e,a))}),()=>i.forEach(e=>e())}attachSingle(t,o){return this.handlers[t]&&this.logger.warn(`channel: handler for "${t}" is being overwritten`),this.handlers[t]=o,()=>{this.handlers[t]===o&&delete this.handlers[t]}}send(t,o,i){return h(this,void 0,void 0,function*(){return this.sender.send(t,o,i)})}stream(t,o,i){return h(this,void 0,void 0,function*(){return this.sender.stream(t,o,i)})}updateCard(t,o){return h(this,void 0,void 0,function*(){yield this.sender.patchCard(t,o)})}editMessage(t,o){return h(this,void 0,void 0,function*(){yield this.rawClient.im.v1.message.update({path:{message_id:t},data:{msg_type:"text",content:JSON.stringify({text:o})}})})}recallMessage(t){return h(this,void 0,void 0,function*(){yield this.rawClient.im.v1.message.delete({path:{message_id:t}})})}addReaction(t,o){var i,e;return h(this,void 0,void 0,function*(){let a=yield this.rawClient.im.v1.messageReaction.create({path:{message_id:t},data:{reaction_type:{emoji_type:o}}}),A=(e=(i=a?.data)===null||i===void 0?void 0:i.reaction_id)!==null&&e!==void 0?e:a?.reaction_id;if(!A)throw new Pt("unknown","messageReaction.create returned no reaction_id");return A})}removeReaction(t,o){return h(this,void 0,void 0,function*(){yield this.rawClient.im.v1.messageReaction.delete({path:{message_id:t,reaction_id:o}})})}removeReactionByEmoji(t,o){var i,e;return h(this,void 0,void 0,function*(){let a=yield this.rawClient.im.v1.messageReaction.list({path:{message_id:t},params:{reaction_type:o,page_size:50}}),r=((e=(i=a?.data)===null||i===void 0?void 0:i.items)!==null&&e!==void 0?e:[]).find(s=>{var g;return((g=s.operator)===null||g===void 0?void 0:g.operator_type)==="app"});return r?.reaction_id?(yield this.removeReaction(t,r.reaction_id),!0):!1})}downloadResource(t,o){return h(this,void 0,void 0,function*(){if(o==="image"){let e=yield this.rawClient.im.v1.image.get({path:{image_key:t}});return yield cW(e)}let i=yield this.rawClient.im.v1.file.get({path:{file_key:t}});return yield cW(i)})}getChatInfo(t){var o,i;return h(this,void 0,void 0,function*(){let a=(o=(yield this.rawClient.im.v1.chat.get({path:{chat_id:t}})).data)!==null&&o!==void 0?o:{};return{chatId:t,name:a.name,description:a.description,chatType:(i=a.chat_mode)!==null&&i!==void 0?i:"group",ownerId:a.owner_id,memberCount:a.user_count}})}getChatMode(t){var o;return h(this,void 0,void 0,function*(){let e=(o=(yield this.rawClient.im.v1.chat.get({path:{chat_id:t}})).data)===null||o===void 0?void 0:o.chat_mode;return e==="p2p"?"p2p":e==="topic"?"topic":"group"})}updatePolicy(t){this.safety.updatePolicy(t)}getPolicy(){return this.safety.getPolicy()}fetchBotIdentity(){var t;return h(this,void 0,void 0,function*(){let o;try{let a=yield this.rawClient.request({url:"/open-apis/bot/v3/info",method:"GET"}),A=a.bot;if(A?.open_id)return{openId:A.open_id,name:(t=A.app_name)!==null&&t!==void 0?t:"bot"};o=new Error(`bot/v3/info response missing open_id: ${JSON.stringify(a).slice(0,200)}`)}catch(a){o=a}let i=Fv(o),e=i.code==="unknown"?"not_connected":i.code;throw new Pt(e,"could not resolve bot identity via /open-apis/bot/v3/info \u2014 required for channel to function",{cause:o})})}registerDispatcherHandlers(){var t,o;let i=A=>h(this,void 0,void 0,function*(){var r,s,g,c;try{return(s=(r=(yield this.rawClient.im.v1.message.get({path:{message_id:A}})).data)===null||r===void 0?void 0:r.items)!==null&&s!==void 0?s:[]}catch(I){return(c=(g=this.logger).warn)===null||c===void 0||c.call(g,"channel: fetchSubMessages failed",I),[]}}),e=(o=(t=this.opts.includeRawEvent)!==null&&t!==void 0?t:this.opts.includeRawInMessage)!==null&&o!==void 0?o:!1,a={botIdentity:this.botIdentity,stripBotMentions:!0,includeRaw:e,fetchSubMessages:i};this.dispatcher.register({"im.message.receive_v1":A=>h(this,void 0,void 0,function*(){try{let r=yield RW(A,a);yield this.safety.pushMessage(r)}catch(r){this.emitError(r)}}),"card.action.trigger":A=>h(this,void 0,void 0,function*(){let r=_W(A,{includeRaw:e});if(!r)return;let s=UNe(r.action);yield this.safety.pushAction(`card:${r.messageId}:${r.operator.openId}:${s}`,r.chatId,()=>h(this,void 0,void 0,function*(){let g=this.handlers.cardAction;g&&(yield g(r))}))}),"im.message.reaction.created_v1":A=>h(this,void 0,void 0,function*(){let r=Mv(A,"added",{includeRaw:e});if(!r)return;let s=IW(r);yield this.safety.pushLight(s,()=>{var g,c;return(c=(g=this.handlers).reaction)===null||c===void 0?void 0:c.call(g,r)})}),"im.message.reaction.deleted_v1":A=>h(this,void 0,void 0,function*(){let r=Mv(A,"removed",{includeRaw:e});if(!r)return;let s=IW(r);yield this.safety.pushLight(s,()=>{var g,c;return(c=(g=this.handlers).reaction)===null||c===void 0?void 0:c.call(g,r)})}),"im.chat.member.bot.added_v1":A=>{var r,s;let g=TW(A,{includeRaw:e});if(g)try{(s=(r=this.handlers).botAdded)===null||s===void 0||s.call(r,g)}catch(c){this.emitError(c)}},"drive.notice.comment_add_v1":A=>h(this,void 0,void 0,function*(){var r;let s=NW(A,{includeRaw:e});s&&(yield this.safety.pushAction(`comment:${s.fileToken}:${s.commentId}:${(r=s.replyId)!==null&&r!==void 0?r:""}`,s.fileToken,()=>h(this,void 0,void 0,function*(){let g=this.handlers.comment;g&&(yield g(s))})))})})}emitError(t){var o,i,e;let a=t instanceof Pt?t:new Pt("unknown",String((o=t?.message)!==null&&o!==void 0?o:t),{cause:t}),A=this.handlers.error;A?A(a):(e=(i=this.logger).error)===null||e===void 0||e.call(i,"channel: unhandled error",a)}};function FNe(n){return new xm(n)}function cW(n){return h(this,void 0,void 0,function*(){if(Buffer.isBuffer(n))return n;if(n instanceof Uint8Array)return Buffer.from(n);if(typeof n=="object"&&n!==null){let t=n;if(typeof t.getReadableStream=="function")return yield LNe(t.getReadableStream());if(Buffer.isBuffer(t.data))return t.data;if(t.data instanceof Uint8Array)return Buffer.from(t.data)}throw new Pt("unknown","unexpected download response type")})}function LNe(n){return new Promise((t,o)=>{let i=[];n.on("data",e=>{i.push(Buffer.isBuffer(e)?e:Buffer.from(e))}),n.on("end",()=>t(Buffer.concat(i))),n.on("error",o)})}function IW(n){var t;return`rx:${n.messageId}:${n.operator.openId}:${n.emojiType}:${n.action}:${(t=n.actionTime)!==null&&t!==void 0?t:0}`}function UNe(n){var t,o,i;let e=typeof n.value=="string"?n.value:JSON.stringify((t=n.value)!==null&&t!==void 0?t:""),a=e.length>128?e.slice(0,128):e;return`${n.tag}|${(o=n.name)!==null&&o!==void 0?o:""}|${(i=n.option)!==null&&i!==void 0?i:""}|${a}`}var _6=Je(KT(),1);var kW=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function vW(n,t){return Number.isFinite(n)&&n>=0?n:t}function HNe(n){if(!Array.isArray(n)||n.length===0)return[...kW];let t=n.map(o=>vW(o,-1)).filter(o=>o>=0);return t.length>0?t:[...kW]}function KNe(n){let t=Number.isInteger(n?.totals?.configured)?n.totals.configured:Array.isArray(n?.bots)?n.bots.length:0,o=Number.isInteger(n?.totals?.connected)?n.totals.connected:Array.isArray(n?.bots)?n.bots.filter(i=>i?.connected===!0).length:0;return{configured:t,connected:o}}var jm=class{#e;#A;#t;#r;#g;#a;#n;#i=null;#I=null;#l=0;#o=!1;#s=!1;#c;#p;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=HNe(e),this.#g=vW(a,15e3),this.#a=A,this.#n=r,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#o||this.#s?this:(this.#o=!0,this.#d(0),this)}async close(){this.#s||(this.#s=!0,this.#i!==null&&(this.#n(this.#i),this.#i=null),await this.#I?.catch(()=>{}),this.#p?.(null),this.#p=null)}#d(t){this.#s||(this.#i=this.#a(()=>{this.#i=null,this.#h()},t),this.#i?.unref?.())}async#h(){if(this.#s||this.#I)return;let t=this.#E();this.#I=t;try{await t}finally{this.#I===t&&(this.#I=null)}}async#E(){try{await this.#A.ensureRunning()}catch(t){if(this.#s)return;this.#C("Harness Host is not ready",t);return}if(!this.#s)try{if(await this.#e.initialize(),this.#s)return;let t=await this.#e.status();this.#p?.(t),this.#p=null;let o=KNe(t);if(o.connected`,resources:[]}}),PNe=new Map([["text",TNe],["post",wNe],["image",uNe],["file",hNe],["audio",INe],["video",sW],["media",sW],["sticker",MNe],["interactive",fNe],["merge_forward",yNe],["share_chat",ONe],["share_user",bNe],["location",QNe],["system",_Ne],["vote",vNe],["todo",NNe],["calendar",lNe],["general_calendar",pNe],["share_calendar_event",dNe],["folder",ENe],["hongbao",CNe],["video_chat",kNe]]);function gW(n,t,o){var i;return h(this,void 0,void 0,function*(){let e=(i=PNe.get(t))!==null&&i!==void 0?i:nW;try{return yield e(n,o)}catch{return nW(n)}})}function _W(n,t){var o,i,e,a,A,r,s,g,c,I,d,B;let f=(i=(o=n.context)===null||o===void 0?void 0:o.open_message_id)!==null&&i!==void 0?i:n.open_message_id,Q=(a=(e=n.context)===null||e===void 0?void 0:e.open_chat_id)!==null&&a!==void 0?a:n.open_chat_id,y=(A=n.operator)===null||A===void 0?void 0:A.open_id;return!f||!Q||!y?null:{messageId:f,chatId:Q,operator:{openId:y,userId:(r=n.operator)===null||r===void 0?void 0:r.user_id,name:(s=n.operator)===null||s===void 0?void 0:s.name},action:{value:(g=n.action)===null||g===void 0?void 0:g.value,tag:(I=(c=n.action)===null||c===void 0?void 0:c.tag)!==null&&I!==void 0?I:"unknown",name:(d=n.action)===null||d===void 0?void 0:d.name,option:(B=n.action)===null||B===void 0?void 0:B.option},raw:t?.includeRaw?n:void 0}}function Mv(n,t,o){var i,e,a,A;let r=n.message_id,s=(i=n.reaction_type)===null||i===void 0?void 0:i.emoji_type,g=(e=n.user_id)===null||e===void 0?void 0:e.open_id;if(!r||!s||!g)return null;let c=n.action_time,I=c?parseInt(c,10):void 0;return{messageId:r,operator:{openId:g,userId:(A=(a=n.user_id)===null||a===void 0?void 0:a.user_id)!==null&&A!==void 0?A:void 0},emojiType:s,action:t,actionTime:I!=null&&Number.isFinite(I)?I:void 0,raw:o?.includeRaw?n:void 0}}function TW(n,t){var o,i,e,a,A,r,s,g,c;let I=n.chat_id,d=(o=n.operator_id)===null||o===void 0?void 0:o.open_id;if(!I||!d)return null;let B=(r=(a=(i=n.name)!==null&&i!==void 0?i:(e=n.i18n_names)===null||e===void 0?void 0:e.zh_cn)!==null&&a!==void 0?a:(A=n.i18n_names)===null||A===void 0?void 0:A.en_us)!==null&&r!==void 0?r:(s=n.i18n_names)===null||s===void 0?void 0:s.ja_jp;return{chatId:I,operator:{openId:d,userId:(c=(g=n.operator_id)===null||g===void 0?void 0:g.user_id)!==null&&c!==void 0?c:void 0},botName:B,external:n.external,raw:t?.includeRaw?n:void 0}}function NW(n,t){var o,i,e,a,A,r,s,g,c,I,d,B,f;let Q=(o=n.file_token)!==null&&o!==void 0?o:(i=n.notice_meta)===null||i===void 0?void 0:i.file_token,y=(e=n.file_type)!==null&&e!==void 0?e:(a=n.notice_meta)===null||a===void 0?void 0:a.file_type,m=n.comment_id,_=(r=(A=n.notice_meta)===null||A===void 0?void 0:A.from_user_id)!==null&&r!==void 0?r:n.user_id,T=_?.open_id;if(!Q||!y||!m||!T)return null;let R=(c=(s=n.create_time)!==null&&s!==void 0?s:(g=n.notice_meta)===null||g===void 0?void 0:g.timestamp)!==null&&c!==void 0?c:n.action_time,L=R?parseInt(R,10):Date.now();return{fileToken:Q,fileType:y,commentId:m,replyId:n.reply_id,operator:{openId:T,userId:(I=_?.user_id)!==null&&I!==void 0?I:void 0,unionId:_?.union_id},mentionedBot:!!((f=(d=n.is_mentioned)!==null&&d!==void 0?d:(B=n.notice_meta)===null||B===void 0?void 0:B.is_mentioned)!==null&&f!==void 0?f:n.is_mention),timestamp:Number.isFinite(L)?L:Date.now(),raw:t?.includeRaw?n:void 0}}function RW(n,t){var o,i,e,a,A;return h(this,void 0,void 0,function*(){let r=n.message,s=(o=t.botIdentity)===null||o===void 0?void 0:o.openId,{mentions:g,mentionsByOpenId:c,mentionList:I,mentionAll:d,mentionedBot:B}=rNe(r.mentions,s),f=d||GNe(r.content),Q={messageId:r.message_id,botOpenId:s,mentions:g,mentionsByOpenId:c,stripBotMentions:(i=t.stripBotMentions)!==null&&i!==void 0?i:!0,fetchSubMessages:t.fetchSubMessages,resolveUserName:t.resolveUserName,batchResolveNames:t.batchResolveNames,dispatch:gW},{content:y,resources:m}=yield gW(r.content,r.message_type,Q),_=aNe(y,Q),T=n.sender.sender_id.open_id,R=(a=(e=n.sender.sender_id.user_id)!==null&&e!==void 0?e:n.sender.sender_id.union_id)!==null&&a!==void 0?a:"",L=T??R,U=T?(A=t.resolveSenderName)===null||A===void 0?void 0:A.call(t,T):void 0,F=r.create_time?parseInt(r.create_time,10):0;return{messageId:r.message_id,chatId:r.chat_id,chatType:r.chat_type,senderId:L,senderName:U,content:_,rawContentType:r.message_type,resources:m,mentions:I,mentionAll:f,mentionedBot:B,rootId:r.root_id,threadId:r.thread_id,replyToMessageId:r.parent_id,createTime:Number.isFinite(F)?F:0,raw:t.includeRaw?n:void 0}})}function GNe(n){return n?/@_all\b/.test(n):!1}var xm=class{constructor(t){var o,i,e,a,A,r,s;this.handlers={},this.connected=!1,this.opts=t,this.logger=new Sc((o=t.loggerLevel)!==null&&o!==void 0?o:ro.info,(i=t.logger)!==null&&i!==void 0?i:fg),this.rawClient=new vm({appId:t.appId,appSecret:t.appSecret,domain:(e=t.domain)!==null&&e!==void 0?e:Is.Feishu,cache:t.cache,httpInstance:t.httpInstance,logger:t.logger,loggerLevel:t.loggerLevel,source:t.source,extraUaTags:["channel"]}),this.dispatcher=new Gm({verificationToken:(a=t.webhook)===null||a===void 0?void 0:a.verificationToken,encryptKey:(A=t.webhook)===null||A===void 0?void 0:A.encryptKey,cache:t.cache,logger:t.logger,loggerLevel:t.loggerLevel}),this.sender=new yv(this.rawClient,(r=t.outbound)!==null&&r!==void 0?r:{},this.logger),this.safety=new bv({config:t.safety,policy:t.policy,cache:(s=t.cache)!==null&&s!==void 0?s:lu,logger:this.logger,onReject:g=>{var c,I;(I=(c=this.handlers).reject)===null||I===void 0||I.call(c,g)},onMessage:g=>h(this,void 0,void 0,function*(){let c=this.handlers.message;c&&(yield c(g))})})}connect(){return h(this,void 0,void 0,function*(){return this.connectPromise?this.connectPromise:(this.connectPromise=this.doConnect().catch(t=>{throw this.connectPromise=void 0,t}),this.connectPromise)})}doConnect(){var t;return h(this,void 0,void 0,function*(){this.botIdentity=yield this.fetchBotIdentity(),this.safety.setBotIdentity(this.botIdentity),this.registerDispatcherHandlers(),((t=this.opts.transport)!==null&&t!==void 0?t:"websocket")==="websocket"&&(yield this.connectWebSocket(15e3)),this.connected=!0})}connectWebSocket(t){return new Promise((o,i)=>{var e;let a=!1,A=setTimeout(()=>{a||(a=!0,i(new Pt("not_connected",`WebSocket handshake did not complete within ${t}ms`)))},t);this.rawWsClient=new Lm({appId:this.opts.appId,appSecret:this.opts.appSecret,domain:(e=this.opts.domain)!==null&&e!==void 0?e:Is.Feishu,logger:this.opts.logger,loggerLevel:this.opts.loggerLevel,httpInstance:this.opts.httpInstance,autoReconnect:!0,source:this.opts.source,extraUaTags:["channel"],agent:this.opts.agent,wsConfig:this.opts.wsConfig,handshakeTimeoutMs:this.opts.handshakeTimeoutMs,onReady:()=>{a||(a=!0,clearTimeout(A),o())},onError:r=>{a||(a=!0,clearTimeout(A),i(new Pt("not_connected",`WebSocket connect failed: ${r.message}`,{cause:r})))},onReconnecting:()=>{var r,s;return(s=(r=this.handlers).reconnecting)===null||s===void 0?void 0:s.call(r)},onReconnected:()=>{var r,s;return(s=(r=this.handlers).reconnected)===null||s===void 0?void 0:s.call(r)}}),this.rawWsClient.start({eventDispatcher:this.dispatcher})})}disconnect(){var t;return h(this,void 0,void 0,function*(){if(this.connected){try{(t=this.rawWsClient)===null||t===void 0||t.close({})}catch{}try{yield this.safety.dispose()}catch{}this.connected=!1,this.connectPromise=void 0}})}getConnectionStatus(){var t;return(t=this.rawWsClient)===null||t===void 0?void 0:t.getConnectionStatus()}on(t,o){if(typeof t=="string")return this.attachSingle(t,o);let i=[];return Object.keys(t).forEach(e=>{let a=t[e];a&&i.push(this.attachSingle(e,a))}),()=>i.forEach(e=>e())}attachSingle(t,o){return this.handlers[t]&&this.logger.warn(`channel: handler for "${t}" is being overwritten`),this.handlers[t]=o,()=>{this.handlers[t]===o&&delete this.handlers[t]}}send(t,o,i){return h(this,void 0,void 0,function*(){return this.sender.send(t,o,i)})}stream(t,o,i){return h(this,void 0,void 0,function*(){return this.sender.stream(t,o,i)})}updateCard(t,o){return h(this,void 0,void 0,function*(){yield this.sender.patchCard(t,o)})}editMessage(t,o){return h(this,void 0,void 0,function*(){yield this.rawClient.im.v1.message.update({path:{message_id:t},data:{msg_type:"text",content:JSON.stringify({text:o})}})})}recallMessage(t){return h(this,void 0,void 0,function*(){yield this.rawClient.im.v1.message.delete({path:{message_id:t}})})}addReaction(t,o){var i,e;return h(this,void 0,void 0,function*(){let a=yield this.rawClient.im.v1.messageReaction.create({path:{message_id:t},data:{reaction_type:{emoji_type:o}}}),A=(e=(i=a?.data)===null||i===void 0?void 0:i.reaction_id)!==null&&e!==void 0?e:a?.reaction_id;if(!A)throw new Pt("unknown","messageReaction.create returned no reaction_id");return A})}removeReaction(t,o){return h(this,void 0,void 0,function*(){yield this.rawClient.im.v1.messageReaction.delete({path:{message_id:t,reaction_id:o}})})}removeReactionByEmoji(t,o){var i,e;return h(this,void 0,void 0,function*(){let a=yield this.rawClient.im.v1.messageReaction.list({path:{message_id:t},params:{reaction_type:o,page_size:50}}),r=((e=(i=a?.data)===null||i===void 0?void 0:i.items)!==null&&e!==void 0?e:[]).find(s=>{var g;return((g=s.operator)===null||g===void 0?void 0:g.operator_type)==="app"});return r?.reaction_id?(yield this.removeReaction(t,r.reaction_id),!0):!1})}downloadResource(t,o){return h(this,void 0,void 0,function*(){if(o==="image"){let e=yield this.rawClient.im.v1.image.get({path:{image_key:t}});return yield cW(e)}let i=yield this.rawClient.im.v1.file.get({path:{file_key:t}});return yield cW(i)})}getChatInfo(t){var o,i;return h(this,void 0,void 0,function*(){let a=(o=(yield this.rawClient.im.v1.chat.get({path:{chat_id:t}})).data)!==null&&o!==void 0?o:{};return{chatId:t,name:a.name,description:a.description,chatType:(i=a.chat_mode)!==null&&i!==void 0?i:"group",ownerId:a.owner_id,memberCount:a.user_count}})}getChatMode(t){var o;return h(this,void 0,void 0,function*(){let e=(o=(yield this.rawClient.im.v1.chat.get({path:{chat_id:t}})).data)===null||o===void 0?void 0:o.chat_mode;return e==="p2p"?"p2p":e==="topic"?"topic":"group"})}updatePolicy(t){this.safety.updatePolicy(t)}getPolicy(){return this.safety.getPolicy()}fetchBotIdentity(){var t;return h(this,void 0,void 0,function*(){let o;try{let a=yield this.rawClient.request({url:"/open-apis/bot/v3/info",method:"GET"}),A=a.bot;if(A?.open_id)return{openId:A.open_id,name:(t=A.app_name)!==null&&t!==void 0?t:"bot"};o=new Error(`bot/v3/info response missing open_id: ${JSON.stringify(a).slice(0,200)}`)}catch(a){o=a}let i=Fv(o),e=i.code==="unknown"?"not_connected":i.code;throw new Pt(e,"could not resolve bot identity via /open-apis/bot/v3/info \u2014 required for channel to function",{cause:o})})}registerDispatcherHandlers(){var t,o;let i=A=>h(this,void 0,void 0,function*(){var r,s,g,c;try{return(s=(r=(yield this.rawClient.im.v1.message.get({path:{message_id:A}})).data)===null||r===void 0?void 0:r.items)!==null&&s!==void 0?s:[]}catch(I){return(c=(g=this.logger).warn)===null||c===void 0||c.call(g,"channel: fetchSubMessages failed",I),[]}}),e=(o=(t=this.opts.includeRawEvent)!==null&&t!==void 0?t:this.opts.includeRawInMessage)!==null&&o!==void 0?o:!1,a={botIdentity:this.botIdentity,stripBotMentions:!0,includeRaw:e,fetchSubMessages:i};this.dispatcher.register({"im.message.receive_v1":A=>h(this,void 0,void 0,function*(){try{let r=yield RW(A,a);yield this.safety.pushMessage(r)}catch(r){this.emitError(r)}}),"card.action.trigger":A=>h(this,void 0,void 0,function*(){let r=_W(A,{includeRaw:e});if(!r)return;let s=UNe(r.action);yield this.safety.pushAction(`card:${r.messageId}:${r.operator.openId}:${s}`,r.chatId,()=>h(this,void 0,void 0,function*(){let g=this.handlers.cardAction;g&&(yield g(r))}))}),"im.message.reaction.created_v1":A=>h(this,void 0,void 0,function*(){let r=Mv(A,"added",{includeRaw:e});if(!r)return;let s=IW(r);yield this.safety.pushLight(s,()=>{var g,c;return(c=(g=this.handlers).reaction)===null||c===void 0?void 0:c.call(g,r)})}),"im.message.reaction.deleted_v1":A=>h(this,void 0,void 0,function*(){let r=Mv(A,"removed",{includeRaw:e});if(!r)return;let s=IW(r);yield this.safety.pushLight(s,()=>{var g,c;return(c=(g=this.handlers).reaction)===null||c===void 0?void 0:c.call(g,r)})}),"im.chat.member.bot.added_v1":A=>{var r,s;let g=TW(A,{includeRaw:e});if(g)try{(s=(r=this.handlers).botAdded)===null||s===void 0||s.call(r,g)}catch(c){this.emitError(c)}},"drive.notice.comment_add_v1":A=>h(this,void 0,void 0,function*(){var r;let s=NW(A,{includeRaw:e});s&&(yield this.safety.pushAction(`comment:${s.fileToken}:${s.commentId}:${(r=s.replyId)!==null&&r!==void 0?r:""}`,s.fileToken,()=>h(this,void 0,void 0,function*(){let g=this.handlers.comment;g&&(yield g(s))})))})})}emitError(t){var o,i,e;let a=t instanceof Pt?t:new Pt("unknown",String((o=t?.message)!==null&&o!==void 0?o:t),{cause:t}),A=this.handlers.error;A?A(a):(e=(i=this.logger).error)===null||e===void 0||e.call(i,"channel: unhandled error",a)}};function FNe(n){return new xm(n)}function cW(n){return h(this,void 0,void 0,function*(){if(Buffer.isBuffer(n))return n;if(n instanceof Uint8Array)return Buffer.from(n);if(typeof n=="object"&&n!==null){let t=n;if(typeof t.getReadableStream=="function")return yield LNe(t.getReadableStream());if(Buffer.isBuffer(t.data))return t.data;if(t.data instanceof Uint8Array)return Buffer.from(t.data)}throw new Pt("unknown","unexpected download response type")})}function LNe(n){return new Promise((t,o)=>{let i=[];n.on("data",e=>{i.push(Buffer.isBuffer(e)?e:Buffer.from(e))}),n.on("end",()=>t(Buffer.concat(i))),n.on("error",o)})}function IW(n){var t;return`rx:${n.messageId}:${n.operator.openId}:${n.emojiType}:${n.action}:${(t=n.actionTime)!==null&&t!==void 0?t:0}`}function UNe(n){var t,o,i;let e=typeof n.value=="string"?n.value:JSON.stringify((t=n.value)!==null&&t!==void 0?t:""),a=e.length>128?e.slice(0,128):e;return`${n.tag}|${(o=n.name)!==null&&o!==void 0?o:""}|${(i=n.option)!==null&&i!==void 0?i:""}|${a}`}var _6=Je(KT(),1);var kW=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function vW(n,t){return Number.isFinite(n)&&n>=0?n:t}function HNe(n){if(!Array.isArray(n)||n.length===0)return[...kW];let t=n.map(o=>vW(o,-1)).filter(o=>o>=0);return t.length>0?t:[...kW]}function KNe(n){let t=Number.isInteger(n?.totals?.configured)?n.totals.configured:Array.isArray(n?.bots)?n.bots.length:0,o=Number.isInteger(n?.totals?.connected)?n.totals.connected:Array.isArray(n?.bots)?n.bots.filter(i=>i?.connected===!0).length:0;return{configured:t,connected:o}}var jm=class{#e;#A;#t;#r;#g;#a;#n;#i=null;#I=null;#l=0;#o=!1;#s=!1;#c;#p;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=HNe(e),this.#g=vW(a,15e3),this.#a=A,this.#n=r,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#o||this.#s?this:(this.#o=!0,this.#d(0),this)}async close(){this.#s||(this.#s=!0,this.#i!==null&&(this.#n(this.#i),this.#i=null),await this.#I?.catch(()=>{}),this.#p?.(null),this.#p=null)}#d(t){this.#s||(this.#i=this.#a(()=>{this.#i=null,this.#h()},t),this.#i?.unref?.())}async#h(){if(this.#s||this.#I)return;let t=this.#E();this.#I=t;try{await t}finally{this.#I===t&&(this.#I=null)}}async#E(){try{await this.#A.ensureRunning()}catch(t){if(this.#s)return;this.#C("Harness Host is not ready",t);return}if(!this.#s)try{if(await this.#e.initialize(),this.#s)return;let t=await this.#e.status();this.#p?.(t),this.#p=null;let o=KNe(t);if(o.connected=0?o:null}async function VNe(n,{signal:t,maxBytes:o}){if(!n||typeof n[Symbol.asyncIterator]!="function")throw new Error("Feishu image download returned no readable stream");t?.throwIfAborted();let i=()=>n.destroy?.(t.reason??new DOMException("Feishu image download aborted","AbortError"));t?.addEventListener("abort",i,{once:!0});let e=[],a=0;try{for await(let A of n){t?.throwIfAborted();let r=Buffer.from(A);if(a+=r.length,a>o)throw n.destroy?.(),new Bt("image-too-large",`Feishu image exceeds ${o} bytes`,w("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));e.push(r)}return t?.throwIfAborted(),Buffer.concat(e,a)}finally{t?.removeEventListener("abort",i)}}async function WNe(n,{signal:t}){if(!n||typeof n[Symbol.asyncIterator]!="function")throw new Error("Feishu file download returned no readable stream");t?.throwIfAborted();let o=()=>n.destroy?.(t.reason??new DOMException("Feishu file download aborted","AbortError"));t?.addEventListener("abort",o,{once:!0});let i=[],e=0;try{for await(let a of n){t?.throwIfAborted();let A=Buffer.from(a);e+=A.length,i.push(A)}return t?.throwIfAborted(),Buffer.concat(i,e)}finally{t?.removeEventListener("abort",o)}}function Kv(n){if(!n||typeof n!="object")return null;let t=n.code??n.error?.code;return Number.isSafeInteger(Number(t))?Number(t):null}async function ZNe(n,t){if(!n||typeof n[Symbol.asyncIterator]!="function")return null;t?.throwIfAborted();let o=AbortSignal.timeout(YNe),i=t?AbortSignal.any([t,o]):o,e=()=>n.destroy?.(i.reason);i.addEventListener("abort",e,{once:!0});let a=[],A=0;try{for await(let r of n){let s=Buffer.from(r);if(A+=s.length,A>xNe)return n.destroy?.(),null;a.push(s)}return Buffer.concat(a,A).toString("utf8")}catch{return t?.throwIfAborted(),null}finally{i.removeEventListener("abort",e)}}async function XNe(n,t){let o=[n],i=new Set;for(;o.length>0&&i.size<8;){let e=o.shift();if(!e||typeof e!="object"&&typeof e!="function"||i.has(e))continue;i.add(e);let a=Kv(e),A=e.response?.data??e.data;if(a===Jm)return A?.destroy?.(),a;if(A&&typeof A[Symbol.asyncIterator]=="function"){let r=await ZNe(A,t);try{let s=Kv(JSON.parse(r));if(s===Jm)return s}catch{}}else{let r=Kv(A);if(r===Jm)return r}o.push(e.cause)}return null}async function $Ne(n,t){return await XNe(n,t)!==Jm?n:new Bt("feishu-image-permission-required","Feishu image download requires the im:message:readonly tenant scope",w(jNe),{cause:n})}function eRe(n,t,o){return{async load({signal:i,maxBytes:e}){i?.throwIfAborted();let a;try{a=await t?.im?.v1?.messageResource?.get?.({path:{message_id:n.message.message_id,file_key:o},params:{type:"image"}})}catch(r){throw await $Ne(r,i)}i?.throwIfAborted();let A=zNe(a?.headers);if(A!==null&&A>e)throw a?.getReadableStream?.().destroy?.(),new Bt("image-too-large",`Feishu image declares ${A} bytes; the limit is ${e}`,w("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));return VNe(a?.getReadableStream?.(),{signal:i,maxBytes:e})}}}function ARe(n,t,o){let i=Md(o?.file_key);return i?{name:Md(o?.file_name)??"file",async load({signal:e}={}){e?.throwIfAborted();let a=await t?.im?.v1?.messageResource?.get?.({path:{message_id:n.message.message_id,file_key:i},params:{type:"file"}});return e?.throwIfAborted(),WNe(a?.getReadableStream?.(),{signal:e})}}:null}function jv(n,t){let o=n?.message?.message_type,i=Yv(n),e=JNe(n,i),a=o==="image"?Md(i?.image_key):null,A=a?[a]:e?.imageKeys??[],r=o==="file"?ARe(n,t,i):null;return{content:o==="text"?_d(n)??"":e?.text??"",images:A.map(s=>eRe(n,t,s)),files:r?[r]:[]}}function UW(n,t=9e3){if(n.length<=t)return[n];let o=[],i=n;for(;i.length>t;){let e=i.lastIndexOf(` -`,t);ei.value===t);return o>=0?o+1:0}function hu(n){return String(n??"").replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu," ").replace(/\s+/gu," ").trim()||w("\u6682\u65E0\u6807\u9898")}function Go(n,t){return JSON.stringify({schema:"2.0",header:{title:Vm(n),template:"blue"},body:{elements:t}})}function ol(){return ls(w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu")}function xW(n){let{workspaces:t=[],currentWorkspace:o=null,currentSession:i=null,sessions:e=[],archiveVisible:a=!1,presetCatalog:A=null,modelCatalog:r=null}=n||{},s=i?.id??null,g=i?.title??n?.currentSessionTitle??null,c=(Array.isArray(e)?e:[]).slice(0,20),I=c.length>0,d=Array.isArray(t)&&t.length>0,B=[];B.push({tag:"div",text:ut(w("**\u8BBE\u7F6E**"))});let f=null;if(I){let k=c.map(V=>({text:{tag:"plain_text",content:`${V.id===s?"\u2713 ":""}${hu(V.title)}`},value:V.id}));f={tag:"select_static",name:"session_pick",placeholder:{tag:"plain_text",content:s?w("\u5207\u6362\u4F1A\u8BDD"):w("\u9009\u62E9\u4F1A\u8BDD\uFF08\u5F53\u524D\u672A\u7ED1\u5B9A\uFF09")},initial_index:Td(k,s),options:k,behaviors:[{type:"callback",value:{action:"session_pick"}}]}}let Q=null;if(d){let k=t.slice(0,20).map(V=>({text:{tag:"plain_text",content:`${V===o?"\u2713 ":""}${V}`},value:V}));Q={tag:"select_static",name:"workspace_pick",placeholder:{tag:"plain_text",content:w("\u5207\u6362\u5DE5\u4F5C\u533A")},initial_index:Td(k,o),options:k,behaviors:[{type:"callback",value:{action:"workspace_pick"}}]}}let y=Array.isArray(A?.items)?A.items:[],m=A?._currentId??null,_=m===null,T=null;if(y.length>=1){let k=y.slice(0,30).map(Ae=>({text:{tag:"plain_text",content:`${Ae.id===m?"\u2713 ":""}${Ae.label}`},value:Ae.id})),V=_?qm:m;k.unshift({text:{tag:"plain_text",content:`${_?"\u2713 ":""}${w("\u8DDF\u968F\u9ED8\u8BA4")}`},value:qm}),T={tag:"select_static",name:"preset_pick",placeholder:{tag:"plain_text",content:w("\u5207\u6362\u9884\u8BBE")},initial_index:Td(k,V),options:k,behaviors:[{type:"callback",value:{action:"preset_pick"}}]}}let R=Array.isArray(r?.groups)?r.groups:[],F=r?.current,K=F?`${F.provider}/${F.model}`:null,L=[];for(let k of R)for(let V of k.models||[])L.push({id:`${k.id}/${V.id}`,name:`${k.name} - ${V.name}`});let q=null;if(L.length>1){let k=L.slice(0,30).map(V=>({text:{tag:"plain_text",content:`${V.id===K?"\u2713 ":""}${V.name}`},value:V.id}));q={tag:"select_static",name:"model_pick",placeholder:{tag:"plain_text",content:w("\u5207\u6362\u6A21\u578B")},initial_index:Td(k,K),options:k,behaviors:[{type:"callback",value:{action:"model_pick"}}]}}function z(k){return{tag:"column",width:"weighted",weight:.1,vertical_align:"center",elements:[{tag:"div",text:{tag:"plain_text",content:k}}]}}function j(k){return{tag:"column",width:"weighted",weight:1,elements:[k]}}let P=[];f&&P.push(f),Q&&P.push(Q),P.length===2?B.push({tag:"column_set",flex_mode:"none",columns:[z("\u{1F4AC}"),j(P[0]),z("\u{1F4C2}"),j(P[1])]}):P[0]&&B.push(P[0]),I||B.push({tag:"div",text:ut(w("\u5F53\u524D\u5DE5\u4F5C\u533A\u6682\u65E0\u53EF\u7528\u4F1A\u8BDD\u3002"))});let J=[],U=ls(w("\u{1F916} \u5207\u6362\u9884\u8BBE"),"presets"),N=ls(w("\u{1F9E0} \u5207\u6362\u6A21\u578B"),"models");return T?J.push(T):J.push(U),q?J.push(q):J.push(N),B.push({tag:"column_set",flex_mode:"none",columns:[z("\u{1F916}"),j(J[0]),z("\u{1F9E0}"),j(J[1])]}),B.push(il(w("\u{1F195} \u65B0\u4F1A\u8BDD"),"new",w("\u{1F4CB} \u4F1A\u8BDD/\u5173\u6CE8"),"sessions")),!I&&!d&&B.push(ls(w("\u{1F5C2} \u5DE5\u4F5C\u533A\u5217\u8868"),"workspaces")),B.push({tag:"hr"}),B.push({tag:"div",text:ut(w("**\u4EFB\u52A1\u63A7\u5236**"))}),B.push(il(w("\u23F9 \u505C\u6B62"),"stop",w("\u{1F4D0} \u538B\u7F29"),"compact")),B.push({tag:"hr"}),B.push({tag:"column_set",flex_mode:"none",columns:[{tag:"column",width:"weighted",weight:1,elements:[{tag:"div",text:ut(w("**\u8865\u5145\u6307\u4EE4**"))},{tag:"select_static",name:"steer_pick",placeholder:{tag:"plain_text",content:w("\u9009\u62E9\u8865\u5145\u6307\u4EE4")},initial_index:0,options:[...e6.map(k=>({text:{tag:"plain_text",content:w(k)},value:w(k)})),{text:{tag:"plain_text",content:w("\u270F\uFE0F \u66F4\u591A / \u81EA\u5B9A\u4E49\u2026")},value:"custom"}],behaviors:[{type:"callback",value:{action:"steer_pick"}}]}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"div",text:ut(w("\u{1F5C4} \u5F52\u6863\uFF1A{state}",{state:a?w("\u5DF2\u663E\u793A"):w("\u5DF2\u9690\u85CF")}))},ls(w("\u5207\u6362\u5F52\u6863\u663E\u793A"),"archive_toggle")]}]}),B.push({tag:"hr"}),B.push(il(w("\u{1F4CA} \u72B6\u6001"),"status",w("\u{1F4D6} \u5E2E\u52A9"),"help")),B.push({tag:"div",text:ut(w(`**\u6570\u5B57\u515C\u5E95** +`,t);ei.value===t);return o>=0?o+1:0}function hu(n){return String(n??"").replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu," ").replace(/\s+/gu," ").trim()||w("\u6682\u65E0\u6807\u9898")}function Go(n,t){return JSON.stringify({schema:"2.0",header:{title:Vm(n),template:"blue"},body:{elements:t}})}function ol(){return ls(w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu")}function xW(n){let{workspaces:t=[],currentWorkspace:o=null,currentSession:i=null,sessions:e=[],archiveVisible:a=!1,presetCatalog:A=null,modelCatalog:r=null}=n||{},s=i?.id??null,g=i?.title??n?.currentSessionTitle??null,c=(Array.isArray(e)?e:[]).slice(0,20),I=c.length>0,d=Array.isArray(t)&&t.length>0,B=[];B.push({tag:"div",text:ut(w("**\u8BBE\u7F6E**"))});let f=null;if(I){let k=c.map(V=>({text:{tag:"plain_text",content:`${V.id===s?"\u2713 ":""}${hu(V.title)}`},value:V.id}));f={tag:"select_static",name:"session_pick",placeholder:{tag:"plain_text",content:s?w("\u5207\u6362\u4F1A\u8BDD"):w("\u9009\u62E9\u4F1A\u8BDD\uFF08\u5F53\u524D\u672A\u7ED1\u5B9A\uFF09")},initial_index:Td(k,s),options:k,behaviors:[{type:"callback",value:{action:"session_pick"}}]}}let Q=null;if(d){let k=t.slice(0,20).map(V=>({text:{tag:"plain_text",content:`${V===o?"\u2713 ":""}${V}`},value:V}));Q={tag:"select_static",name:"workspace_pick",placeholder:{tag:"plain_text",content:w("\u5207\u6362\u5DE5\u4F5C\u533A")},initial_index:Td(k,o),options:k,behaviors:[{type:"callback",value:{action:"workspace_pick"}}]}}let y=Array.isArray(A?.items)?A.items:[],m=A?._currentId??null,_=m===null,T=null;if(y.length>=1){let k=y.slice(0,30).map(Ae=>({text:{tag:"plain_text",content:`${Ae.id===m?"\u2713 ":""}${Ae.label}`},value:Ae.id})),V=_?qm:m;k.unshift({text:{tag:"plain_text",content:`${_?"\u2713 ":""}${w("\u8DDF\u968F\u9ED8\u8BA4")}`},value:qm}),T={tag:"select_static",name:"preset_pick",placeholder:{tag:"plain_text",content:w("\u5207\u6362\u9884\u8BBE")},initial_index:Td(k,V),options:k,behaviors:[{type:"callback",value:{action:"preset_pick"}}]}}let R=Array.isArray(r?.groups)?r.groups:[],L=r?.current,U=L?`${L.provider}/${L.model}`:null,F=[];for(let k of R)for(let V of k.models||[])F.push({id:`${k.id}/${V.id}`,name:`${k.name} - ${V.name}`});let q=null;if(F.length>1){let k=F.slice(0,30).map(V=>({text:{tag:"plain_text",content:`${V.id===U?"\u2713 ":""}${V.name}`},value:V.id}));q={tag:"select_static",name:"model_pick",placeholder:{tag:"plain_text",content:w("\u5207\u6362\u6A21\u578B")},initial_index:Td(k,U),options:k,behaviors:[{type:"callback",value:{action:"model_pick"}}]}}function z(k){return{tag:"column",width:"weighted",weight:.1,vertical_align:"center",elements:[{tag:"div",text:{tag:"plain_text",content:k}}]}}function j(k){return{tag:"column",width:"weighted",weight:1,elements:[k]}}let P=[];f&&P.push(f),Q&&P.push(Q),P.length===2?B.push({tag:"column_set",flex_mode:"none",columns:[z("\u{1F4AC}"),j(P[0]),z("\u{1F4C2}"),j(P[1])]}):P[0]&&B.push(P[0]),I||B.push({tag:"div",text:ut(w("\u5F53\u524D\u5DE5\u4F5C\u533A\u6682\u65E0\u53EF\u7528\u4F1A\u8BDD\u3002"))});let J=[],H=ls(w("\u{1F916} \u5207\u6362\u9884\u8BBE"),"presets"),N=ls(w("\u{1F9E0} \u5207\u6362\u6A21\u578B"),"models");return T?J.push(T):J.push(H),q?J.push(q):J.push(N),B.push({tag:"column_set",flex_mode:"none",columns:[z("\u{1F916}"),j(J[0]),z("\u{1F9E0}"),j(J[1])]}),B.push(il(w("\u{1F195} \u65B0\u4F1A\u8BDD"),"new",w("\u{1F4CB} \u4F1A\u8BDD/\u5173\u6CE8"),"sessions")),!I&&!d&&B.push(ls(w("\u{1F5C2} \u5DE5\u4F5C\u533A\u5217\u8868"),"workspaces")),B.push({tag:"hr"}),B.push({tag:"div",text:ut(w("**\u4EFB\u52A1\u63A7\u5236**"))}),B.push(il(w("\u23F9 \u505C\u6B62"),"stop",w("\u{1F4D0} \u538B\u7F29"),"compact")),B.push({tag:"hr"}),B.push({tag:"column_set",flex_mode:"none",columns:[{tag:"column",width:"weighted",weight:1,elements:[{tag:"div",text:ut(w("**\u8865\u5145\u6307\u4EE4**"))},{tag:"select_static",name:"steer_pick",placeholder:{tag:"plain_text",content:w("\u9009\u62E9\u8865\u5145\u6307\u4EE4")},initial_index:0,options:[...e6.map(k=>({text:{tag:"plain_text",content:w(k)},value:w(k)})),{text:{tag:"plain_text",content:w("\u270F\uFE0F \u66F4\u591A / \u81EA\u5B9A\u4E49\u2026")},value:"custom"}],behaviors:[{type:"callback",value:{action:"steer_pick"}}]}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"div",text:ut(w("\u{1F5C4} \u5F52\u6863\uFF1A{state}",{state:a?w("\u5DF2\u663E\u793A"):w("\u5DF2\u9690\u85CF")}))},ls(w("\u5207\u6362\u5F52\u6863\u663E\u793A"),"archive_toggle")]}]}),B.push({tag:"hr"}),B.push(il(w("\u{1F4CA} \u72B6\u6001"),"status",w("\u{1F4D6} \u5E2E\u52A9"),"help")),B.push({tag:"div",text:ut(w(`**\u6570\u5B57\u515C\u5E95** **1**\u5DE5\u4F5C\u533A\u5217\u8868 \xB7 **2**\u65B0\u4F1A\u8BDD \xB7 **3**\u4F1A\u8BDD\u5217\u8868 \xB7 **4**\u72B6\u6001 **5**\u{1F527}\u8865\u5168\u6743\u9650 \xB7 **6**\u5E2E\u52A9`))}),Go(w("\u{1F916} \u52A9\u624B\u4E2D\u5FC3"),B)}function YW(n){let{items:t,defaultId:o}=n,i=n._currentId,e=t.find(s=>s.id===i),a=t.find(s=>s.id===o),A=i===null?w("\u8DDF\u968F Host \u9ED8\u8BA4{default}",{default:a?`\uFF08${a.label}\uFF09`:""}):e?`${e.label}\uFF08${e.id}\uFF09`:w("{id}\uFF08\u5DF2\u4E0D\u53EF\u7528\uFF09",{id:i}),r=[{tag:"div",text:ut(w("**\u5F53\u524D**\uFF1A{value}",{value:A}))},{tag:"div",text:ut(w("**Host \u9ED8\u8BA4**\uFF1A{value}",{value:a?`${a.label}\uFF08${a.id}\uFF09`:w("\u672A\u8BBE\u7F6E")}))},{tag:"hr"}];if(t.length>=1){let s=t.map(g=>({text:{tag:"plain_text",content:`${g.label}\uFF08${g.id}\uFF09${g.id===i?" \u2713":""}`},value:g.id}));r.push({tag:"select_static",name:"preset_pick",placeholder:{tag:"plain_text",content:w("\u9009\u62E9\u9884\u8BBE")},initial_index:i===null?0:Td(s,i),options:s,behaviors:[{type:"callback",value:{action:"preset_pick"}}]},{tag:"hr"},il(w("\u{1F504} \u8DDF\u968F\u9ED8\u8BA4"),"preset_default",w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu"))}else r.push({tag:"div",text:ut(w("\u5F53\u524D\u6CA1\u6709\u53EF\u9009\u62E9\u7684\u9884\u8BBE\u3002"))},ol());return Go(w("\u{1F916} \u9884\u8BBE\u5217\u8868"),r)}function jW(n){let{groups:t,current:o}=n,i=o?`${o.provider}/${o.model}`:null,e=[{tag:"div",text:ut(w("**\u5F53\u524D\u6A21\u578B**\uFF1A{model}",{model:i||w("\u672A\u8BBE\u7F6E")}))},{tag:"hr"}],a=0;for(let A of t)a+=A.models.length;if(a===0)e.push({tag:"div",text:ut(w("\u5F53\u524D\u6CA1\u6709\u53EF\u7528\u6A21\u578B\u3002"))},ol());else{for(let r of t){let s=r.models.map(g=>{let c=`${r.id}/${g.id}`;return`${c}${c===i?" \u2713":""}`});e.push({tag:"div",text:ut(`**${r.name}** ${s.join(` @@ -426,21 +426,21 @@ ${s.join(` `)+t)},{tag:"hr"},{tag:"div",text:ut(w(aRe))},{tag:"hr"},ol()];return Go(w("\u{1F4D6} \u5E2E\u52A9"),o)}function VW(n){if(typeof n!="string"||!/^[A-Za-z0-9_-]{16,128}$/.test(n))throw new TypeError("A safe card-action probe nonce is required");return Go(w("\u{1F9EA} \u9A8C\u8BC1\u5361\u7247\u6309\u94AE"),[{tag:"div",text:ut(w("\u6388\u6743\u5DF2\u63D0\u4EA4\u3002\u8BF7\u70B9\u51FB\u4E0B\u65B9\u6309\u94AE\uFF1B\u673A\u5668\u4EBA\u771F\u5B9E\u6536\u5230\u56DE\u8C03\u540E\u624D\u4F1A\u5224\u5B9A\u4FEE\u590D\u6210\u529F\u3002"))},{tag:"column_set",flex_mode:"none",columns:[{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:Vm(w("\u5B8C\u6210\u9A8C\u8BC1")),type:"primary",width:"fill",behaviors:[{type:"callback",value:{action:"repair_verify",nonce:n}}]}]}]}])}function WW(n,t,o,i,e=new Set){let a=o*wc,A=t.slice(a,a+wc),r=Math.max(1,Math.ceil(i/wc)),s=I=>typeof e?.has=="function"&&e.has(I),g=(I,d)=>({tag:"column_set",flex_mode:"none",horizontal_spacing:"default",columns:[{tag:"column",width:"90px",vertical_align:"center",elements:[I]},{tag:"column",width:"weighted",weight:1,vertical_align:"center",elements:[d]}]}),c=[{tag:"div",text:ut(w(`**\u5DE5\u4F5C\u533A**\uFF1A{workspace} \u5171 **{total}** \u4E2A\u4F1A\u8BDD{paging}`,{workspace:`\`${n}\``,total:i,paging:i>wc?w("\uFF08\u7B2C {page}/{pageCount} \u9875\uFF09",{page:o+1,pageCount:r}):""}))},...A.map((I,d)=>{let B=`${d+1}. ${hu(I.title)}${I.archived===!0?w("\uFF08\u5DF2\u5F52\u6863\uFF09"):""}`,f=s(I.sessionId);return g(zm(f?w("\u2B50 \u53D6\u6D88\u5173\u6CE8"):w("\u2606 \u5173\u6CE8"),f?`unwatch:${I.sessionId}`:`watch:${I.sessionId}`),zm(B,`use:${I.sessionId}`))})];return o>0&&c.push(ls(w("\u25C0 \u4E0A\u4E00\u9875"),`sessions:${o-1}`)),o+1ls(`${e+1}. ${i}${i===t?w("\uFF08\u5F53\u524D\uFF09"):""}`,`workspace:${i}`)),{tag:"hr"},ol()];return Go(w("\u{1F5C2} \u5DE5\u4F5C\u533A"),o)}function iRe(n,t){let o=new Set(n.map(e=>e.sessionId)),i=(Array.isArray(t)?t:[]).filter(e=>e?.sessionId&&!o.has(e.sessionId)).slice(0,30).map(e=>({text:{tag:"plain_text",content:hu(e.title??e.sessionId)},value:e.sessionId}));return i.length===0?null:{tag:"multi_select_static",name:"watch_add",placeholder:{tag:"plain_text",content:w("\u52FE\u9009\u8981\u5173\u6CE8\u7684\u4F1A\u8BDD")},options:i,behaviors:[{type:"callback",value:{action:"watch_add",kind:"multi"}}]}}function oRe(n){let t=n.slice(0,30).map(o=>({text:{tag:"plain_text",content:hu(o.title)},value:o.sessionId}));return t.length===0?null:{tag:"multi_select_static",name:"watch_remove",placeholder:{tag:"plain_text",content:w("\u52FE\u9009\u8981\u53D6\u6D88\u5173\u6CE8\u7684\u4F1A\u8BDD")},options:t,behaviors:[{type:"callback",value:{action:"watch_remove",kind:"multi"}}]}}function XW(n,t){let o=Array.isArray(n)?n:[],i=iRe(o,t),e=oRe(o),a=[];return o.length===0?a.push({tag:"div",text:ut(w("\u5F53\u524D\u6CA1\u6709\u5173\u6CE8\u7684\u4F1A\u8BDD\u3002\u4EFB\u52A1\u5B8C\u6210\u4F1A\u81EA\u52A8\u63A8\u9001\u7ED3\u679C\u3002"))}):a.push({tag:"div",text:ut(w("\u5F53\u524D\u5173\u6CE8 **{count}** \u4E2A\u4F1A\u8BDD\uFF1A",{count:o.length}))}),i&&a.push({tag:"hr"},{tag:"div",text:ut(w("**\u2795 \u6DFB\u52A0\u5173\u6CE8**\uFF08\u591A\u9009\u4E0B\u62C9\u52FE\u9009\uFF09"))},i),e&&a.push({tag:"hr"},{tag:"div",text:ut(w("**\u2796 \u53D6\u6D88\u5173\u6CE8**\uFF08\u591A\u9009\u4E0B\u62C9\u52FE\u9009\uFF09"))},e),a.push({tag:"hr"},il(w("\u{1F4CB} \u4F1A\u8BDD\u5217\u8868"),"sessions",w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu")),Go(w("\u{1F441} \u5173\u6CE8\u5217\u8868"),a)}function $W(n,t,o){let i=o==="completed"?w("\u5DF2\u5B8C\u6210"):o==="stopped"?w("\u5DF2\u505C\u6B62"):o==="aborted"?w("\u5DF2\u4E2D\u6B62"):o==="cancelled"?w("\u5DF2\u53D6\u6D88"):w("\u5DF2\u7ED3\u675F");return Go(w("\u2705 \u4EFB\u52A1\u5B8C\u6210"),[{tag:"div",text:ut(`**${hu(t)}** \`${n}\``)},{tag:"div",text:ut(w("**\u72B6\u6001**\uFF1A{reason}",{reason:i}))},{tag:"hr"},il(w("\u{1F4CB} \u4F1A\u8BDD\u5217\u8868"),"sessions",w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu"),{tag:"div",text:ut(w("\u7ED1\u5B9A\u8BE5\u4F1A\u8BDD\u540E\u53EF\u7EE7\u7EED\u8FFD\u95EE\uFF0C\u8F93\u5165\u6587\u5B57\u5373\u53EF\u3002"))}])}var e6=["\u7EE7\u7EED","\u52A0\u901F\u8FD0\u884C","\u603B\u7ED3\u5F53\u524D\u8FDB\u5C55","\u66F4\u7B80\u6D01\u4E9B","\u66F4\u8BE6\u7EC6\u4E9B"],Eu="__steer_custom__";function A6({hasSession:n}){let t=n?w("\u4ECE\u4E0B\u65B9\u4E0B\u62C9\u9009\u62E9\u8865\u5145\u6307\u4EE4\uFF1B\u6700\u540E\u4E00\u9879\u53EF\u81EA\u5B9A\u4E49\u8F93\u5165\u3002"):w("\u5F53\u524D\u6CA1\u6709\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u7ED1\u5B9A\u4F1A\u8BDD\u518D\u8865\u5145\u6307\u4EE4\u3002"),o=e6.map(e=>({text:{tag:"plain_text",content:w(e)},value:w(e)}));o.push({text:{tag:"plain_text",content:w("\u270F\uFE0F \u66F4\u591A / \u81EA\u5B9A\u4E49\u2026")},value:Eu});let i=[{tag:"div",text:ut(t)},{tag:"hr"},{tag:"select_static",name:"steer_quick",placeholder:{tag:"plain_text",content:w("\u9009\u62E9\u8865\u5145\u6307\u4EE4")},initial_index:0,options:o,behaviors:[{type:"callback",value:{action:"steer",source:"quick"}}]},{tag:"hr"},ls(w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu")];return Go(w("\u2795 \u8865\u5145\u6307\u4EE4"),i)}function Jv(){let n=[{tag:"div",text:ut(w("\u8F93\u5165\u8865\u5145\u6307\u4EE4\u540E\u70B9\u300C\u63D0\u4EA4\u300D\uFF0C\u53D1\u9001\u7ED9\u5F53\u524D\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"))},{tag:"hr"},{tag:"form",name:"steer_form",elements:[{tag:"input",name:"steer_text",placeholder:{tag:"plain_text",content:w("\u8F93\u5165\u4F60\u7684\u8865\u5145\u6307\u4EE4")}},{tag:"button",name:"steer_submit",text:{tag:"plain_text",content:w("\u63D0\u4EA4")},type:"primary",width:"fill",form_action_type:"submit",behaviors:[{type:"callback",value:{action:"steer",source:"form"}}]}]},{tag:"hr"},ls(w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu")];return Go(w("\u2795 \u81EA\u5B9A\u4E49\u6307\u4EE4"),n)}import{mkdir as nRe,readFile as sRe,rename as gRe,writeFile as cRe}from"node:fs/promises";import{dirname as IRe}from"node:path";var lRe=Object.freeze({version:1,sessions:{},seenMessageIds:[],watches:{},includeArchivedSessions:!1}),Zm=20;function qv(n){return n&&typeof n=="object"&&typeof n.sessionId=="string"&&n.sessionId.length>0&&typeof n.chatId=="string"&&n.chatId.length>0}var Wm=class{#e;#A=structuredClone(lRe);#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=JSON.parse(await sRe(this.#e,"utf8"));this.#A={version:1,sessions:t.sessions&&typeof t.sessions=="object"?t.sessions:{},seenMessageIds:Array.isArray(t.seenMessageIds)?t.seenMessageIds.slice(-1e3):[],watches:t.watches&&typeof t.watches=="object"?t.watches:{},includeArchivedSessions:typeof t.includeArchivedSessions=="boolean"?t.includeArchivedSessions:!1}}catch(t){if(t?.code!=="ENOENT")throw t;await this.#r()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){this.#A.sessions[t]=o,await this.#r()}async clearSession(t){delete this.#A.sessions[t],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(t){return this.#A.seenMessageIds.includes(t)}async markSeen(t){this.hasSeen(t)||(this.#A.seenMessageIds.push(t),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}snapshot(){return structuredClone(this.#A)}watchEntries(t){let o=this.#A.watches[t];return Array.isArray(o)?o.filter(qv):[]}watchEntry(t,o){return this.watchEntries(t).find(i=>i.sessionId===o)??null}async setWatch(t,o){let i=this.#A.watches[t]??[],e=i.findIndex(a=>a.sessionId===o.sessionId);e===-1?(i.length>=Zm&&i.shift(),i.push(o)):i[e]=o,this.#A.watches[t]=i,await this.#r()}async removeWatch(t,o){let i=this.#A.watches[t]??[];this.#A.watches[t]=i.filter(e=>e.sessionId!==o),await this.#r()}async clearWatches(t){delete this.#A.watches[t],await this.#r()}keysWatching(t){return Object.entries(this.#A.watches).filter(([,o])=>Array.isArray(o)&&o.some(i=>qv(i)&&i.sessionId===t)).map(([o])=>o)}watchedSessionIds(){let t=new Set;for(let o of Object.values(this.#A.watches))if(Array.isArray(o))for(let i of o)qv(i)&&t.add(i.sessionId);return[...t]}includesArchivedSessions(){return this.#A.includeArchivedSessions===!0}async setIncludeArchivedSessions(t){this.#A.includeArchivedSessions=t===!0,await this.#r()}async#r(){let t=JSON.stringify(this.#A,null,2)+` -`;this.#t=this.#t.then(async()=>{await nRe(IRe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await cRe(o,t,{encoding:"utf8",mode:384}),await gRe(o,this.#e)}),await this.#t}};var Dc=Object.freeze({MENTION:"mention",ALL:"all"});function ao(n){return n===Dc.ALL?Dc.ALL:Dc.MENTION}function Xm(n){return n===Dc.MENTION||n===Dc.ALL}var $m=()=>w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002"),dRe=30*6e4,hRe=/^\/m(?:enu)?$/i,ERe=/^\/repair(?:\s|$)/i,CRe=/^\/repair(?:\s+(qr|status|cancel|verify))?\s*$/i,t6=/^\/watch(?:\s+([^\s]+))?$/i,r6=/^\/unwatch(?:\s+([^\s]+))?$/i,uRe=/^\/watchlist$/i,BRe=/^\/(?:sessionlist|sessions)(?:\s|$)/i,fRe=/^\/workspacelist$/i,QRe=/^\d{1,2}$/,yRe=10*6e4,mRe=50,SRe=8,wRe=8,DRe=10*6e4,a6=400,ORe=10*6e4,bRe=100,MRe=50,_Re=500,TRe=5e3,NRe=5e3,RRe=15e3,kRe=1e3,g6=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]),zv=new Set([...g6,"saving"]),eS=new Set(["succeeded","expired","cancelled","error"]),vRe=new Set(["accounts.feishu.cn","open.feishu.cn","accounts.larksuite.com","open.larksuite.com"]),i6=/^\/archived(?:\s+(on|off))?$/i,PRe=/^\/(?:m(?:enu)?|new|help|status|compact|(?:sessionlist|sessions)(?:\s|$)|workspacelist|watchlist|archived(?:\s+(on|off))?)$/i,GRe=["/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"];function Cu(n){switch(n?.code){case"workspace-not-absolute":return w("\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");case"workspace-not-found":return w("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002");case"workspace-not-directory":return w("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002");case"workspace-bot-not-found":return w("\u673A\u5668\u4EBA\u6B63\u5728\u79FB\u9664\u6216\u5DF2\u91CD\u65B0\u63A5\u5165\uFF0C\u65E0\u6CD5\u64CD\u4F5C\u539F\u4F1A\u8BDD\u7684\u5DE5\u4F5C\u533A\u3002");default:return w("\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}}function FRe(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11\u98DE\u4E66\u6587\u4EF6\u4E0A\u4F20\u6743\u9650 im:resource\u3002\u8BF7\u79C1\u804A\u673A\u5668\u4EBA\u6267\u884C /repair \u547D\u4EE4\uFF0C\u6216\u8005\u5728\u300CIM\u673A\u5668\u4EBA\u300D\u8BBE\u7F6E\u9875\u70B9\u51FB\u201C\u8865\u5168\u6743\u9650\u201D\u6309\u94AE\u5E76\u626B\u7801\u3002\u5B8C\u6210\u98DE\u4E66\u8981\u6C42\u7684\u53D1\u5E03\u5BA1\u6279\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u98DE\u4E66 30 MB \u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u98DE\u4E66\u4E0D\u5141\u8BB8\u53D1\u9001\u7A7A\u6587\u4EF6\u3002",{name:o});case"artifact-changed":case"artifact-invalid":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u98DE\u4E66\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function AS(n,t){return typeof n=="string"&&n.trim()?n:t.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):n}function hA(n){return typeof n=="string"&&n.trim()?n.trim():null}function o6(n){if(n&&typeof n=="object"&&!Array.isArray(n))return n;if(typeof n!="string"||!n.trim())return{};try{let t=JSON.parse(n);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Bu(n){if(n==null)return null;if(Array.isArray(n)){for(let o of n){let i=Bu(o);if(i!==null)return i}return null}if(n&&typeof n=="object")return"value"in n?Bu(n.value):"option"in n?Bu(n.option):null;if(typeof n!="string")return null;let t=n.trim();if(!t)return null;if(t.startsWith("[")||t.startsWith("{")||t.startsWith('"'))try{let o=JSON.parse(t);if(o!==n)return Bu(o)}catch{}return t}function Qg(n){if(n==null)return[];if(Array.isArray(n))return n.flatMap(o=>Qg(o));if(n&&typeof n=="object")return"value"in n?Qg(n.value):"option"in n?Qg(n.option):[];if(typeof n!="string")return[];let t=n.trim();if(!t)return[];if(t.startsWith("[")||t.startsWith("{")||t.startsWith('"'))try{let o=JSON.parse(t);if(o!==n)return Qg(o)}catch{}return t.split(",").map(o=>o.trim()).filter(Boolean)}function Qn(n){return Number.isSafeInteger(n)&&n>=-1}function fu(n){return Number.isSafeInteger(n)&&n>=0}function rS(n){return Number.isSafeInteger(n?.watchStartedAt)&&n.watchStartedAt>=0?n.watchStartedAt:null}function tS(n){return n&&(rS(n)!==null||!Qn(n.lastSeq))}function LRe(n){return(Array.isArray(n?.events)?n.events:[]).map(t=>t?.event??t).filter(t=>t&&typeof t=="object"&&fu(t.seq)).sort((t,o)=>t.seq-o.seq)}function Qu(n){return hA(n?.sender?.sender_id?.open_id)??hA(n?.sender?.sender_id?.user_id)}function URe(n){return hA(n?.sender?.sender_id?.open_id)}function n6(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(a,n);e.unref?.();function a(){t?.removeEventListener("abort",A),o()}function A(){clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))}t?.addEventListener("abort",A,{once:!0})})}function uu(n,{botId:t}={}){let o=n&&typeof n=="object"?n:{},i=o.registration&&typeof o.registration=="object"?o.registration:o,e=hA(i.operation)??hA(o.operation);if(e&&e!=="callback_repair")throw new Error("The active Feishu operation is not a callback repair");let a=hA(i.botId)??hA(o.botId);if(t&&a&&a!==t)throw new Error("The Feishu repair belongs to another bot");let A=hA(i.state),r=i.attemptId??i.attempt,s=typeof r=="string"||Number.isFinite(r)?String(r):null;if(!A||!s)throw new Error("Feishu returned an invalid repair status");let g=hA(i.verificationUrl)??hA(i.qrCodeUrl),c=Number(i.expiresAt),I=Number(i.remainingSeconds),d=Number(i.pollIntervalMs)||Number(i.pollIntervalSeconds)*1e3;return{state:A,attemptId:s,botId:a,verificationUrl:g,expiresAt:Number.isFinite(c)?c:null,remainingSeconds:Number.isFinite(I)?I:null,pollIntervalMs:Number.isFinite(d)&&d>0?d:null,error:i.error&&typeof i.error=="object"?{code:hA(i.error.code),message:hA(i.error.message)}:null}}function s6(n,t){let o=new URL(n);if(o.protocol!=="https:"||!vRe.has(o.hostname))throw new Error("Feishu returned an untrusted repair URL");if(o.searchParams.get("tp")!=="sdk"||o.searchParams.get("clientID")!==t||o.searchParams.has("createOnly"))throw new Error("Feishu returned an invalid existing-app repair URL");if(o.toString().includes("{{client_id}}")||o.toString().includes("%7B%7Bclient_id%7D%7D"))throw new Error("Feishu returned an unresolved client id placeholder");return o.toString()}function HRe(n,t){return t.needsPresentation!==!0&&t.questions[t.index]&&Qu(n)===t.actor&&n?.message?.message_type==="text"&&hA(_d(n))}function KRe(n){for(let t of["messagesReceived","messagesReplied","messagesRejected"])n[t]??=0;n.lastMessageAt??=null,n.lastReplyAt??=null,n.lastRejectedAt??=null,n.lastError??=null,n.lastMessageError??=null}var aS=class{#e;#A;#t;#r;#g;#a=new Map;#n=new mi;#i=new Map;#I=new Map;#l=new Map;#o=new Map;#s=new Set;#c=new Set;#p=new Set;#d=new Map;#h=new Map;#E=new Map;#C=new Map;#f=new Map;#B=new Map;#y=new Map;#S=new Map;#Q=new Map;#m;#u;#b;#R;#D;#w;#T;#k;#M;#L;#_;#U=null;#v=0;#P;#N;#Y=new Map;#H=new Map;#q=null;#z=new Map;#F=new Map;#K=new Map;#G=new Map;#$;constructor({client:t,channel:o,harness:i,state:e,contextEnhancement:a,status:A,allowedSenderOpenIds:r=new Set,botId:s,appId:g,botOpenId:c,groupResponseMode:I=Dc.ALL,repair:d,repairPollIntervalMs:B=kRe,repairLinkWaitMs:f=RRe,cardDataTimeoutMs:Q=NRe,replyTimeoutMs:y=6e5,logger:m=console,signal:_}){if(!t||!i||!e||!A)throw new TypeError("Feishu bridge dependencies are required");if(d!=null){if(!d||typeof d.start!="function"||typeof d.status!="function"||typeof d.cancel!="function")throw new TypeError("Feishu repair capability requires start/status/cancel");if(!hA(s)||!hA(g))throw new TypeError("Feishu repair capability requires botId and appId")}if(!Number.isFinite(B)||B<=0||!Number.isFinite(f)||f<=0||!Number.isFinite(Q)||Q<=0)throw new TypeError("Feishu timing values must be positive numbers");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#u=A,this.#b=r,this.#T=hA(s),this.#k=hA(g),this.#M=hA(c),this.#L=ao(I),this.#_=d??null,this.#P=B,this.#N=f,this.#$=Q,this.#R=y,this.#D=m,this.#m=new Ci({label:"Feishu",logger:m}),this.#w=_,KRe(this.#u),typeof this.#t?.watchHarnessEvents=="function"&&queueMicrotask(()=>this.#Ne())}setGroupResponseMode(t){this.#L=ao(t)}#Ae(t){if(t?.message?.chat_type==="p2p")return!0;let o=Array.isArray(t?.message?.mentions)?t.message.mentions:[];return this.#M?o.some(i=>i?.id?.open_id===this.#M||i?.open_id===this.#M):o.length>0}accept(t){if(this.#w?.aborted)return Promise.resolve();let o=hA(t?.message?.message_id);if(!o||HW(t))return Promise.resolve();if(!KW(t,this.#b))return this.#u.messagesRejected+=1,this.#u.lastRejectedAt=new Date().toISOString(),this.#D.warn?.("[dsh-feishu] ignored a message from a sender outside the allowlist"),Promise.resolve();let i=this.#Ae(t);if(t?.message?.chat_type!=="p2p"&&this.#L===Dc.MENTION&&!i||this.#r.hasSeen(o)||this.#o.has(o))return Promise.resolve();let e;try{e=LW(t)}catch{return this.#u.messagesRejected+=1,this.#u.lastRejectedAt=new Date().toISOString(),Promise.resolve()}if(t.message.chat_type==="p2p"){let f=hA(t.message.chat_id);f&&Eo(this.#r,{chatId:f})}this.#o.set(o,Xr(this.#g,t.message.chat_type==="p2p"?"direct":t.message.chat_type==="group"?"group":null));let a=this.#CA(o),A=jv(t,this.#e),r=hA(A.content)??"",s=t.message.message_type==="text"?hA(_d(t))??"":"",g=t.message.message_type==="text"&&So(s),c=this.#i.get(e),I=this.#n.status(e);if(g&&t.message.chat_type!=="p2p")return this.#te(t,o,a,{message:qn()});if(t.message.chat_type==="p2p"&&(g||I.phase==="collecting")){let Q=/^\/batch$/iu.test(s)&&I.phase==="idle"&&(this.#a.has(e)||c||this.#m.hasPending(e))?{handled:!0,kind:"busy",message:wo()}:this.#n.handle(e,s,{plainText:t.message.message_type==="text"&&!!s});if(Q.handled){if(Q.kind==="submit"){let y={...t,batchSubmission:{token:Q.token},message:{...t.message,message_type:"text",content:JSON.stringify({text:Q.prompt}),mentions:[]}};return this.#j(y,o,e,a)}return this.#te(t,o,a,Q)}}if(PRe.test(r))return Promise.resolve().then(()=>this.#we(t,e,{alreadyRecorded:!1})).then(()=>this.#ee(o,a,"DONE")).catch(Q=>this.#J(t,o,a,Q)).finally(()=>this.#o.delete(o));let d=fi(r)?qi:Lt(A)?null:zi(r)?Qi:Vi(r)?Wi:Zi(r)?yi:null;if(d&&(i||d===qi)){let f=this.#Le(t,o,e,A,d),Q;return Q=f.then(()=>this.#ee(o,a,"DONE")).catch(y=>this.#J(t,o,a,y)).finally(()=>{this.#o.delete(o),this.#c.delete(Q)}),this.#c.add(Q),Q}if(this.#Qe(t,e))return Promise.resolve().then(()=>this.#ye(t,o)).then(()=>this.#ee(o,a,"DONE")).catch(Q=>this.#J(t,o,a,Q)).finally(()=>this.#o.delete(o));let B=this.#m.claimReply({key:e,actor:Qu(t),messageId:o,text:_d(t)??"",addressed:i,hasPendingQuestion:!!c,questionCompletion:c?.submitting||c?.claimedReplyMessageId?c.queue:null,isQuestionPending:()=>this.#i.has(e),send:f=>this.#O(t.message.chat_id,f)});if(B){let f=B.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1,!0)),Q;return Q=f.then(()=>this.#ee(o,a,"DONE")).catch(y=>this.#J(t,o,a,y)).finally(()=>{this.#o.delete(o),this.#s.delete(Q)}),this.#s.add(Q),Q}if(c&&Qu(t)!==c.actor)return this.#j(t,o,e,a);if(c?.submitting||c?.claimedReplyMessageId)return this.#j(t,o,e,a);if(c){HRe(t,c)&&(c.claimedReplyMessageId=o);let Q=(c.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#pA(t,o,e,c,a));c.queue=Q;let y=()=>{c.claimedReplyMessageId===o&&(c.claimedReplyMessageId=null),c.queue===Q&&(c.queue=null)},m;return m=Q.then(()=>(y(),this.#ee(o,a,"DONE")),_=>(y(),this.#J(t,o,a,_))).finally(()=>{y(),this.#o.delete(o),this.#s.delete(m)}),this.#s.add(m),m}return this.#j(t,o,e,a)}#te(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1,e?.message&&await this.#O(t.message.chat_id,e.message),this.#u.lastError=null)}).then(()=>this.#ee(o,i,"DONE")).catch(A=>this.#J(t,o,i,A)).finally(()=>{this.#o.delete(o),this.#c.delete(a)}),this.#c.add(a),a}#j(t,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1,finalize:r=!0}={}){let g=(this.#a.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#we(t,i,{alreadyRecorded:A})),c=r?g.then(async d=>(await this.#ee(o,e,"DONE"),d)).catch(d=>this.#J(t,o,e,d)):g,I;return I=c.finally(()=>{a&&this.#o.delete(o),this.#a.get(i)===I&&this.#a.delete(i)}),this.#a.set(i,I),I}#X(t,{logLabel:o="operation",logLevel:i="warn",userMessage:e,reason:a}={}){this.#u.lastError=t?.message??String(t);let A=tt(this.#u,t,{userMessage:e,reason:a});return this.#D?.[i]?.(`[dsh-feishu] ${o} failed [${A.referenceId}]:`,t?.message??String(t)),A}async#x(t,o,i={}){let e=this.#X(o,i),a=i.appendMessage?`${dt(e)} +`;this.#t=this.#t.then(async()=>{await nRe(IRe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await cRe(o,t,{encoding:"utf8",mode:384}),await gRe(o,this.#e)}),await this.#t}};var Dc=Object.freeze({MENTION:"mention",ALL:"all"});function ao(n){return n===Dc.ALL?Dc.ALL:Dc.MENTION}function Xm(n){return n===Dc.MENTION||n===Dc.ALL}var $m=()=>w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002"),dRe=30*6e4,hRe=/^\/m(?:enu)?$/i,ERe=/^\/repair(?:\s|$)/i,CRe=/^\/repair(?:\s+(qr|status|cancel|verify))?\s*$/i,t6=/^\/watch(?:\s+([^\s]+))?$/i,r6=/^\/unwatch(?:\s+([^\s]+))?$/i,uRe=/^\/watchlist$/i,BRe=/^\/(?:sessionlist|sessions)(?:\s|$)/i,fRe=/^\/workspacelist$/i,QRe=/^\d{1,2}$/,yRe=10*6e4,mRe=50,SRe=8,wRe=8,DRe=10*6e4,a6=400,ORe=10*6e4,bRe=100,MRe=50,_Re=500,TRe=5e3,NRe=5e3,RRe=15e3,kRe=1e3,g6=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]),zv=new Set([...g6,"saving"]),eS=new Set(["succeeded","expired","cancelled","error"]),vRe=new Set(["accounts.feishu.cn","open.feishu.cn","accounts.larksuite.com","open.larksuite.com"]),i6=/^\/archived(?:\s+(on|off))?$/i,PRe=/^\/(?:m(?:enu)?|new|help|status|compact|(?:sessionlist|sessions)(?:\s|$)|workspacelist|watchlist|archived(?:\s+(on|off))?)$/i,GRe=["/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"];function Cu(n){switch(n?.code){case"workspace-not-absolute":return w("\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");case"workspace-not-found":return w("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002");case"workspace-not-directory":return w("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002");case"workspace-bot-not-found":return w("\u673A\u5668\u4EBA\u6B63\u5728\u79FB\u9664\u6216\u5DF2\u91CD\u65B0\u63A5\u5165\uFF0C\u65E0\u6CD5\u64CD\u4F5C\u539F\u4F1A\u8BDD\u7684\u5DE5\u4F5C\u533A\u3002");default:return w("\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}}function FRe(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11\u98DE\u4E66\u6587\u4EF6\u4E0A\u4F20\u6743\u9650 im:resource\u3002\u8BF7\u79C1\u804A\u673A\u5668\u4EBA\u6267\u884C /repair \u547D\u4EE4\uFF0C\u6216\u8005\u5728\u300CIM\u673A\u5668\u4EBA\u300D\u8BBE\u7F6E\u9875\u70B9\u51FB\u201C\u8865\u5168\u6743\u9650\u201D\u6309\u94AE\u5E76\u626B\u7801\u3002\u5B8C\u6210\u98DE\u4E66\u8981\u6C42\u7684\u53D1\u5E03\u5BA1\u6279\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u98DE\u4E66 30 MB \u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u98DE\u4E66\u4E0D\u5141\u8BB8\u53D1\u9001\u7A7A\u6587\u4EF6\u3002",{name:o});case"artifact-changed":case"artifact-invalid":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u98DE\u4E66\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function AS(n,t){return typeof n=="string"&&n.trim()?n:t.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):n}function pA(n){return typeof n=="string"&&n.trim()?n.trim():null}function o6(n){if(n&&typeof n=="object"&&!Array.isArray(n))return n;if(typeof n!="string"||!n.trim())return{};try{let t=JSON.parse(n);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Bu(n){if(n==null)return null;if(Array.isArray(n)){for(let o of n){let i=Bu(o);if(i!==null)return i}return null}if(n&&typeof n=="object")return"value"in n?Bu(n.value):"option"in n?Bu(n.option):null;if(typeof n!="string")return null;let t=n.trim();if(!t)return null;if(t.startsWith("[")||t.startsWith("{")||t.startsWith('"'))try{let o=JSON.parse(t);if(o!==n)return Bu(o)}catch{}return t}function Qg(n){if(n==null)return[];if(Array.isArray(n))return n.flatMap(o=>Qg(o));if(n&&typeof n=="object")return"value"in n?Qg(n.value):"option"in n?Qg(n.option):[];if(typeof n!="string")return[];let t=n.trim();if(!t)return[];if(t.startsWith("[")||t.startsWith("{")||t.startsWith('"'))try{let o=JSON.parse(t);if(o!==n)return Qg(o)}catch{}return t.split(",").map(o=>o.trim()).filter(Boolean)}function Qn(n){return Number.isSafeInteger(n)&&n>=-1}function fu(n){return Number.isSafeInteger(n)&&n>=0}function rS(n){return Number.isSafeInteger(n?.watchStartedAt)&&n.watchStartedAt>=0?n.watchStartedAt:null}function tS(n){return n&&(rS(n)!==null||!Qn(n.lastSeq))}function LRe(n){return(Array.isArray(n?.events)?n.events:[]).map(t=>t?.event??t).filter(t=>t&&typeof t=="object"&&fu(t.seq)).sort((t,o)=>t.seq-o.seq)}function Qu(n){return pA(n?.sender?.sender_id?.open_id)??pA(n?.sender?.sender_id?.user_id)}function URe(n){return pA(n?.sender?.sender_id?.open_id)}function n6(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(a,n);e.unref?.();function a(){t?.removeEventListener("abort",A),o()}function A(){clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))}t?.addEventListener("abort",A,{once:!0})})}function uu(n,{botId:t}={}){let o=n&&typeof n=="object"?n:{},i=o.registration&&typeof o.registration=="object"?o.registration:o,e=pA(i.operation)??pA(o.operation);if(e&&e!=="callback_repair")throw new Error("The active Feishu operation is not a callback repair");let a=pA(i.botId)??pA(o.botId);if(t&&a&&a!==t)throw new Error("The Feishu repair belongs to another bot");let A=pA(i.state),r=i.attemptId??i.attempt,s=typeof r=="string"||Number.isFinite(r)?String(r):null;if(!A||!s)throw new Error("Feishu returned an invalid repair status");let g=pA(i.verificationUrl)??pA(i.qrCodeUrl),c=Number(i.expiresAt),I=Number(i.remainingSeconds),d=Number(i.pollIntervalMs)||Number(i.pollIntervalSeconds)*1e3;return{state:A,attemptId:s,botId:a,verificationUrl:g,expiresAt:Number.isFinite(c)?c:null,remainingSeconds:Number.isFinite(I)?I:null,pollIntervalMs:Number.isFinite(d)&&d>0?d:null,error:i.error&&typeof i.error=="object"?{code:pA(i.error.code),message:pA(i.error.message)}:null}}function s6(n,t){let o=new URL(n);if(o.protocol!=="https:"||!vRe.has(o.hostname))throw new Error("Feishu returned an untrusted repair URL");if(o.searchParams.get("tp")!=="sdk"||o.searchParams.get("clientID")!==t||o.searchParams.has("createOnly"))throw new Error("Feishu returned an invalid existing-app repair URL");if(o.toString().includes("{{client_id}}")||o.toString().includes("%7B%7Bclient_id%7D%7D"))throw new Error("Feishu returned an unresolved client id placeholder");return o.toString()}function HRe(n,t){return t.needsPresentation!==!0&&t.questions[t.index]&&Qu(n)===t.actor&&n?.message?.message_type==="text"&&pA(_d(n))}function KRe(n){for(let t of["messagesReceived","messagesReplied","messagesRejected"])n[t]??=0;n.lastMessageAt??=null,n.lastReplyAt??=null,n.lastRejectedAt??=null,n.lastError??=null,n.lastMessageError??=null}var aS=class{#e;#A;#t;#r;#g;#a=new Map;#n=new mi;#i=new Map;#I=new Map;#l=new Map;#o=new Map;#s=new Set;#c=new Set;#p=new Set;#d=new Map;#h=new Map;#E=new Map;#C=new Map;#f=new Map;#B=new Map;#y=new Map;#S=new Map;#Q=new Map;#m;#u;#b;#R;#D;#w;#T;#k;#M;#L;#_;#U=null;#v=0;#P;#N;#Y=new Map;#H=new Map;#q=null;#z=new Map;#F=new Map;#K=new Map;#G=new Map;#$;constructor({client:t,channel:o,harness:i,state:e,contextEnhancement:a,status:A,allowedSenderOpenIds:r=new Set,botId:s,appId:g,botOpenId:c,groupResponseMode:I=Dc.ALL,repair:d,repairPollIntervalMs:B=kRe,repairLinkWaitMs:f=RRe,cardDataTimeoutMs:Q=NRe,replyTimeoutMs:y=6e5,logger:m=console,signal:_}){if(!t||!i||!e||!A)throw new TypeError("Feishu bridge dependencies are required");if(d!=null){if(!d||typeof d.start!="function"||typeof d.status!="function"||typeof d.cancel!="function")throw new TypeError("Feishu repair capability requires start/status/cancel");if(!pA(s)||!pA(g))throw new TypeError("Feishu repair capability requires botId and appId")}if(!Number.isFinite(B)||B<=0||!Number.isFinite(f)||f<=0||!Number.isFinite(Q)||Q<=0)throw new TypeError("Feishu timing values must be positive numbers");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#u=A,this.#b=r,this.#T=pA(s),this.#k=pA(g),this.#M=pA(c),this.#L=ao(I),this.#_=d??null,this.#P=B,this.#N=f,this.#$=Q,this.#R=y,this.#D=m,this.#m=new Ci({label:"Feishu",logger:m}),this.#w=_,KRe(this.#u),typeof this.#t?.watchHarnessEvents=="function"&&queueMicrotask(()=>this.#Ne())}setGroupResponseMode(t){this.#L=ao(t)}#Ae(t){if(t?.message?.chat_type==="p2p")return!0;let o=Array.isArray(t?.message?.mentions)?t.message.mentions:[];return this.#M?o.some(i=>i?.id?.open_id===this.#M||i?.open_id===this.#M):o.length>0}accept(t){if(this.#w?.aborted)return Promise.resolve();let o=pA(t?.message?.message_id);if(!o||HW(t))return Promise.resolve();if(!KW(t,this.#b))return this.#u.messagesRejected+=1,this.#u.lastRejectedAt=new Date().toISOString(),this.#D.warn?.("[dsh-feishu] ignored a message from a sender outside the allowlist"),Promise.resolve();let i=this.#Ae(t);if(t?.message?.chat_type!=="p2p"&&this.#L===Dc.MENTION&&!i||this.#r.hasSeen(o)||this.#o.has(o))return Promise.resolve();let e;try{e=LW(t)}catch{return this.#u.messagesRejected+=1,this.#u.lastRejectedAt=new Date().toISOString(),Promise.resolve()}if(t.message.chat_type==="p2p"){let f=pA(t.message.chat_id);f&&Eo(this.#r,{chatId:f})}this.#o.set(o,Xr(this.#g,t.message.chat_type==="p2p"?"direct":t.message.chat_type==="group"?"group":null));let a=this.#CA(o),A=jv(t,this.#e),r=pA(A.content)??"",s=t.message.message_type==="text"?pA(_d(t))??"":"",g=t.message.message_type==="text"&&So(s),c=this.#i.get(e),I=this.#n.status(e);if(g&&t.message.chat_type!=="p2p")return this.#te(t,o,a,{message:qn()});if(t.message.chat_type==="p2p"&&(g||I.phase==="collecting")){let Q=/^\/batch$/iu.test(s)&&I.phase==="idle"&&(this.#a.has(e)||c||this.#m.hasPending(e))?{handled:!0,kind:"busy",message:wo()}:this.#n.handle(e,s,{plainText:t.message.message_type==="text"&&!!s});if(Q.handled){if(Q.kind==="submit"){let y={...t,batchSubmission:{token:Q.token},message:{...t.message,message_type:"text",content:JSON.stringify({text:Q.prompt}),mentions:[]}};return this.#j(y,o,e,a)}return this.#te(t,o,a,Q)}}if(PRe.test(r))return Promise.resolve().then(()=>this.#De(t,e,{alreadyRecorded:!1})).then(()=>this.#ee(o,a,"DONE")).catch(Q=>this.#J(t,o,a,Q)).finally(()=>this.#o.delete(o));let d=fi(r)?qi:Lt(A)?null:zi(r)?Qi:Vi(r)?Wi:Zi(r)?yi:null;if(d&&(i||d===qi)){let f=this.#Le(t,o,e,A,d),Q;return Q=f.then(()=>this.#ee(o,a,"DONE")).catch(y=>this.#J(t,o,a,y)).finally(()=>{this.#o.delete(o),this.#c.delete(Q)}),this.#c.add(Q),Q}if(this.#ye(t,e))return Promise.resolve().then(()=>this.#me(t,o)).then(()=>this.#ee(o,a,"DONE")).catch(Q=>this.#J(t,o,a,Q)).finally(()=>this.#o.delete(o));let B=this.#m.claimReply({key:e,actor:Qu(t),messageId:o,text:_d(t)??"",addressed:i,hasPendingQuestion:!!c,questionCompletion:c?.submitting||c?.claimedReplyMessageId?c.queue:null,isQuestionPending:()=>this.#i.has(e),send:f=>this.#O(t.message.chat_id,f,{replyTo:t.message.message_id})});if(B){let f=B.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1,!0)),Q;return Q=f.then(()=>this.#ee(o,a,"DONE")).catch(y=>this.#J(t,o,a,y)).finally(()=>{this.#o.delete(o),this.#s.delete(Q)}),this.#s.add(Q),Q}if(c&&Qu(t)!==c.actor)return this.#j(t,o,e,a);if(c?.submitting||c?.claimedReplyMessageId)return this.#j(t,o,e,a);if(c){HRe(t,c)&&(c.claimedReplyMessageId=o);let Q=(c.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#pA(t,o,e,c,a));c.queue=Q;let y=()=>{c.claimedReplyMessageId===o&&(c.claimedReplyMessageId=null),c.queue===Q&&(c.queue=null)},m;return m=Q.then(()=>(y(),this.#ee(o,a,"DONE")),_=>(y(),this.#J(t,o,a,_))).finally(()=>{y(),this.#o.delete(o),this.#s.delete(m)}),this.#s.add(m),m}return this.#j(t,o,e,a)}#te(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1,e?.message&&await this.#O(t.message.chat_id,e.message),this.#u.lastError=null)}).then(()=>this.#ee(o,i,"DONE")).catch(A=>this.#J(t,o,i,A)).finally(()=>{this.#o.delete(o),this.#c.delete(a)}),this.#c.add(a),a}#j(t,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1,finalize:r=!0}={}){let g=(this.#a.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#De(t,i,{alreadyRecorded:A})),c=r?g.then(async d=>(await this.#ee(o,e,"DONE"),d)).catch(d=>this.#J(t,o,e,d)):g,I;return I=c.finally(()=>{a&&this.#o.delete(o),this.#a.get(i)===I&&this.#a.delete(i)}),this.#a.set(i,I),I}#X(t,{logLabel:o="operation",logLevel:i="warn",userMessage:e,reason:a}={}){this.#u.lastError=t?.message??String(t);let A=tt(this.#u,t,{userMessage:e,reason:a});return this.#D?.[i]?.(`[dsh-feishu] ${o} failed [${A.referenceId}]:`,t?.message??String(t)),A}async#x(t,o,i={}){let e=this.#X(o,i),a=i.appendMessage?`${dt(e)} -${i.appendMessage}`:dt(e);return await this.#O(t,a).catch(()=>{}),e}async#J(t,o,i,e){if(e?.code==="turn-stopped"){await this.#Fe(o,i),e?.batchInputMessage&&await this.#O(t.message.chat_id,e.batchInputMessage).catch(()=>{});return}if(this.#w?.aborted){await this.#Fe(o,i);return}let a=Oo(e)??fo(e),A=this.#X(e,{logLabel:"message handling",logLevel:"error",userMessage:a,reason:Ji(e)?.reason});await this.#ee(o,i,"ERROR");let r=e?.batchInputMessage?`${dt(A)} +${i.appendMessage}`:dt(e);return await this.#O(t,a).catch(()=>{}),e}async#J(t,o,i,e){if(e?.code==="turn-stopped"){await this.#Fe(o,i),e?.batchInputMessage&&await this.#O(t.message.chat_id,e.batchInputMessage,{replyTo:t.message.message_id}).catch(()=>{});return}if(this.#w?.aborted){await this.#Fe(o,i);return}let a=Oo(e)??fo(e),A=this.#X(e,{logLabel:"message handling",logLevel:"error",userMessage:a,reason:Ji(e)?.reason});await this.#ee(o,i,"ERROR");let r=e?.batchInputMessage?`${dt(A)} -${e.batchInputMessage}`:dt(A);await this.#O(t.message.chat_id,r).catch(()=>{})}async waitForIdle(){for(;;){let t=[...this.#a.values(),...[...this.#i.values()].flatMap(o=>o.queue?[o.queue]:[]),...this.#s,...this.#c,...this.#p,...this.#z.values(),...[...this.#F.values()].map(o=>o.promise)];if(t.length===0||(await Promise.allSettled(t),this.#a.size===0&&this.#s.size===0&&this.#c.size===0&&this.#p.size===0&&this.#z.size===0&&this.#F.size===0&&![...this.#i.values()].some(o=>o.queue)))return}}#V(){let t=AbortSignal.timeout(this.#$);return this.#w?AbortSignal.any([this.#w,t]):t}#ae(t){return this.#i.has(t)||this.#m.hasPending(t)}async#Le(t,o,i,e,a){if(this.#w?.throwIfAborted(),this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1;let A=await a(hA(e.content)??"",this.#t,this.#r,i,{signal:this.#w,isDirect:t.message.chat_type==="p2p",hasImages:Wt(e),hasFiles:Lt(e),pendingInteraction:this.#ae(i),control:{owner:this,key:i}});A?.stopped&&await Promise.allSettled([this.#Se(i),this.#m.closeRoute(i)]);for(let r of A?.messages??[A?.message])r&&await this.#O(t.message.chat_id,r);this.#u.lastError=null}async#we(t,o,{alreadyRecorded:i=!1}={}){this.#w?.throwIfAborted();let e=t.message.message_id;if(!i){if(this.#r.hasSeen(e))return;await this.#r.markSeen(e),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1}let a=jv(t,this.#e),A=a.content,r=Wt(a),s=Lt(a),g=!r&&!s&&A?A.trim():null;if(!A&&!r&&!s){await this.#O(t.message.chat_id,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002"));return}if(g!==null&&ERe.test(g)){await this.#De(t,g);return}if(g==="/help"){await this.#O(t.message.chat_id,qW());return}if(hRe.test(g)){await this.#Z(o,t.message.chat_id);return}if(g==="/new"){if(this.#a.has(o)||this.#ae(o)){await this.#O(t.message.chat_id,w("\u5F53\u524D\u4EFB\u52A1\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u4EFB\u52A1\u6216\u7B49\u5F85\u4EFB\u52A1\u5B8C\u6210\u540E\u518D\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002"));return}await this.#r.clearSession(o),await this.#O(t.message.chat_id,w("\u5DF2\u5F00\u542F\u5168\u65B0 Harness \u4F1A\u8BDD\u3002")),await this.#Z(o,t.message.chat_id);return}if(g==="/status"){await this.#$e(o,t.message.chat_id);return}if(g==="/compact"){let f=await Bi(g,this.#t,this.#r,o,{signal:this.#w});f&&await this.#O(t.message.chat_id,f.message);return}if(BRe.test(g)){let f=g.replace(/^\/(?:sessionlist|sessions)/i,"").trim()||null;await this.#ce({chatId:t.message.chat_id,key:o},f,0);return}if(fRe.test(g)){await this.#Me({chatId:t.message.chat_id,key:o});return}if(t6.test(g)){let f=(t6.exec(g)?.[1]??"").trim()||null;await this.#Ee(o,t.message.chat_id,f);return}if(r6.test(g)){let f=(r6.exec(g)?.[1]??"").trim()||null;await this.#Ce(o,t.message.chat_id,f);return}if(uRe.test(g)){await this.#ue(o,t.message.chat_id);return}if(i6.test(g)){let Q=i6.exec(g)[1]?.toLowerCase();if(Q!=="on"&&Q!=="off"){await this.#O(t.message.chat_id,w("\u7528\u6CD5\uFF1A/archived on\uFF08\u5305\u542B\u5F52\u6863\u4F1A\u8BDD\uFF09\u6216 /archived off\uFF08\u9690\u85CF\u5F52\u6863\u4F1A\u8BDD\uFF09"));return}typeof this.#r?.setIncludeArchivedSessions=="function"&&await this.#r.setIncludeArchivedSessions(Q==="on"),await this.#O(t.message.chat_id,Q==="on"?w("\u5DF2\u5F00\u542F\uFF1A\u4F1A\u8BDD\u5217\u8868\u5305\u542B\u5F52\u6863\u4F1A\u8BDD\u3002"):w("\u5DF2\u5173\u95ED\uFF1A\u4F1A\u8BDD\u5217\u8868\u9690\u85CF\u5F52\u6863\u4F1A\u8BDD\u3002"));return}if(QRe.test(g)){let f=this.#qe(o);if(f){await this.#ze(f,Number(g),{chatId:t.message.chat_id,key:o,event:t});return}}let c=g===null?null:await Qo(A,this.#t,o);if(c){for(let f of c.messages??[c.message])await this.#O(t.message.chat_id,f);return}let I=g===null?null:await Bi(g,this.#t,this.#r,o,{signal:this.#w});if(I){await this.#O(t.message.chat_id,I.message);return}this.#D.info?.(`[dsh-feishu] processing ${t.message.chat_type} message ${e}`);let d=t.batchSubmission??null,B=!1;try{let{receipt:f,artifactSendErrors:Q,textDeliveryErrors:y=0}=await this.#lA(t,o,a,{onAskComplete:d?()=>{B=this.#n.complete(o,d.token).completed}:void 0});return this.#u.messagesReplied+=1,this.#u.lastReplyAt=new Date().toISOString(),this.#u.lastError=null,y===0&&Q===0&&Co(this.#u),f}catch(f){if(d&&!B){if(f?.code==="turn-stopped")throw this.#n.complete(o,d.token),f;let Q=this.#n.fail(o,d.token);if(Q.retained){let y=new Error(f?.message??String(f),{cause:f});throw y.code=f?.code,y.providerCode=f?.providerCode,y.method=f?.method,Number.isInteger(f?.status)&&(y.status=f.status),y.batchInputMessage=Q.message,y}}throw f}finally{await this.#Se(o),await this.#m.closeRoute(o)}}async#De(t,o){if(t?.message?.chat_type!=="p2p"){await this.#O(t.message.chat_id,w("\u4E3A\u907F\u514D\u6388\u6743\u94FE\u63A5\u66B4\u9732\uFF0C\u8BF7\u79C1\u804A\u673A\u5668\u4EBA\u53D1\u9001 /repair\u3002"));return}let i=URe(t);if(!i){await this.#O(t.message.chat_id,w("\u65E0\u6CD5\u8BC6\u522B\u5F53\u524D\u53D1\u9001\u8005\uFF0C\u672A\u53D1\u8D77\u4FEE\u590D\u3002"));return}if(!this.#_){await this.#O(t.message.chat_id,w("\u5F53\u524D Host \u7248\u672C\u6682\u4E0D\u652F\u6301\u804A\u5929\u5185\u4FEE\u590D\uFF0C\u8BF7\u5148\u66F4\u65B0\u63D2\u4EF6\u3002"));return}let e=CRe.exec(o);if(!e){await this.#O(t.message.chat_id,w("\u7528\u6CD5\uFF1A/repair\u3001/repair qr\u3001/repair status\u3001/repair cancel \u6216 /repair verify"));return}let a=e[1]?.toLowerCase()??"start",A=t.message.chat_id;if(a==="start"){await this.#Ue({actorOpenId:i,chatId:A});return}let r=this.#U;if(!r){await this.#O(A,w("\u5F53\u524D Runtime \u6CA1\u6709\u53EF\u6062\u590D\u7684\u4FEE\u590D\u4EFB\u52A1\u8BB0\u5F55\uFF08\u673A\u5668\u4EBA\u53EF\u80FD\u521A\u5B8C\u6210\u5BC6\u94A5\u66F4\u65B0\u5E76\u91CD\u542F\uFF09\u3002\u672C\u547D\u4EE4\u4E0D\u4F1A\u542F\u52A8\u65B0\u7684\u6388\u6743\uFF1B\u8BF7\u67E5\u770B\u673A\u5668\u4EBA\u53D1\u9001\u7684\u9A8C\u8BC1\u7ED3\u679C\uFF0C\u786E\u8BA4\u4E0A\u4E00\u6B21\u4EFB\u52A1\u5DF2\u7ED3\u675F\u540E\u518D\u53D1\u9001 /repair\u3002"));return}if(r.actorOpenId!==i){await this.#O(A,w("\u53E6\u4E00\u4F4D\u7528\u6237\u6B63\u5728\u4FEE\u590D\u8BE5\u673A\u5668\u4EBA\uFF0C\u672C\u6B21\u4E0D\u4F1A\u663E\u793A\u5176\u6388\u6743\u4FE1\u606F\u3002"));return}if(a==="cancel"){let g;try{let c=await this.#_.cancel(this.#ge(r));g=uu(c,{botId:this.#T}),r.snapshot=g}catch{await this.#O(A,w("\u6682\u65F6\u65E0\u6CD5\u53D6\u6D88\u4FEE\u590D\u4EFB\u52A1\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"));return}g.state==="cancelled"&&(r.stopped=!0,this.#v+=1),await this.#O(A,this.#re(g));return}let s;try{s=await this.#pe(r)}catch{await this.#O(A,w("\u6682\u65F6\u65E0\u6CD5\u67E5\u8BE2\u4FEE\u590D\u72B6\u6001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"));return}if(a==="qr"){if(!zv.has(s.state)||!r.verificationUrl){await this.#O(A,this.#re(s,{verificationFocused:!0}));return}await this.#Ye(A,r.verificationUrl,s);return}await this.#O(A,this.#re(s,{verificationFocused:a==="verify"}))}#ge(t){return{botId:this.#T,attemptId:t.attemptId,actorOpenId:t.actorOpenId,chatId:t.chatId}}async#Ue({actorOpenId:t,chatId:o}){let i=this.#U,e=!1;if(i&&zv.has(i.snapshot.state)){if(i.actorOpenId!==t){await this.#O(o,w("\u53E6\u4E00\u4F4D\u7528\u6237\u6B63\u5728\u4FEE\u590D\u8BE5\u673A\u5668\u4EBA\uFF0C\u672C\u6B21\u4E0D\u4F1A\u663E\u793A\u5176\u6388\u6743\u4FE1\u606F\u3002"));return}let r;try{r=await this.#pe(i)}catch{await this.#O(o,w("\u6682\u65F6\u65E0\u6CD5\u67E5\u8BE2\u4FEE\u590D\u72B6\u6001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"));return}if(r.state==="saving"){await this.#O(o,this.#re(r));return}if(g6.has(r.state)){let s;try{s=uu(await this.#_.cancel(this.#ge(i)),{botId:this.#T}),i.snapshot=s}catch{await this.#O(o,w("\u6682\u65F6\u65E0\u6CD5\u53D6\u6D88\u65E7\u4FEE\u590D\u4EFB\u52A1\uFF0C\u672A\u751F\u6210\u65B0\u94FE\u63A5\uFF1B\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"));return}if(!eS.has(s.state)){await this.#O(o,this.#re(s));return}i.stopped=!0,this.#v+=1,e=s.state==="cancelled"}else eS.has(r.state)&&(i.stopped=!0,this.#v+=1)}let a;try{a=uu(await this.#_.start({botId:this.#T,actorOpenId:t,chatId:o}),{botId:this.#T}),a=await this.#He(a,{actorOpenId:t,chatId:o})}catch{await this.#O(o,w("\u4FEE\u590D\u6D41\u7A0B\u6682\u65F6\u5931\u8D25\uFF0C\u73B0\u6709\u673A\u5668\u4EBA\u8FDE\u63A5\u4E0D\u53D7\u5F71\u54CD\uFF1B\u8BF7\u7A0D\u540E\u53D1\u9001 /repair \u91CD\u8BD5\u3002"));return}let A={attemptId:a.attemptId,actorOpenId:t,chatId:o,snapshot:a,verificationUrl:null,stopped:!1,announcedSaving:!1,announcedTerminal:!1};if(this.#U=A,a.verificationUrl)try{A.verificationUrl=s6(a.verificationUrl,this.#k)}catch{A.stopped=!0,await this.#_.cancel(this.#ge(A)).catch(()=>{}),await this.#O(o,w("\u98DE\u4E66\u8FD4\u56DE\u4E86\u65E0\u6CD5\u5B89\u5168\u9A8C\u8BC1\u7684\u6388\u6743\u94FE\u63A5\uFF0C\u5DF2\u4E2D\u6B62\u672C\u6B21\u4FEE\u590D\u3002"));return}if(eS.has(a.state)){A.announcedTerminal=!0,a.state!=="succeeded"&&await this.#O(o,this.#re(a));return}if(!A.verificationUrl){A.stopped=!0,await this.#O(o,w("\u98DE\u4E66\u672A\u8FD4\u56DE\u6388\u6743\u94FE\u63A5\uFF0C\u5DF2\u4E2D\u6B62\u672C\u6B21\u4FEE\u590D\u3002"));return}await this.#xe(o,A.verificationUrl,a,{restarted:e}),this.#Ke(A)}async#He(t,o){let i=t,e=Date.now()+this.#N;for(;!i.verificationUrl&&zv.has(i.state);){if(Date.now()>=e)throw new Error("Feishu repair link timed out");await n6(Math.min(100,this.#P),this.#w),i=uu(await this.#_.status({botId:this.#T,attemptId:i.attemptId,actorOpenId:o.actorOpenId,chatId:o.chatId}),{botId:this.#T})}return i}async#pe(t){let o=uu(await this.#_.status(this.#ge(t)),{botId:this.#T});if(o.attemptId!==t.attemptId)throw new Error("Feishu repair attempt changed unexpectedly");return t.snapshot=o,o.verificationUrl&&(t.verificationUrl=s6(o.verificationUrl,this.#k)),o}#Ke(t){let o=++this.#v;(async()=>{for(;!t.stopped&&this.#U===t&&this.#v===o&&!this.#w?.aborted;){let i=Math.max(250,Math.min(1e4,t.snapshot.pollIntervalMs??this.#P));if(await n6(i,this.#w),t.stopped||this.#U!==t||this.#v!==o)return;let e=await this.#pe(t);if(e.state==="saving"&&!t.announcedSaving&&(t.announcedSaving=!0,await this.#O(t.chatId,w("\u6388\u6743\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u53D1\u9001\u5E76\u7B49\u5F85\u6D4B\u8BD5\u6309\u94AE\u56DE\u8C03\uFF1B\u6536\u5230\u771F\u5B9E\u56DE\u8C03\u540E\u624D\u4F1A\u5B8C\u6210\u3002"))),eS.has(e.state)){t.stopped=!0,e.state!=="succeeded"&&!t.announcedTerminal&&(t.announcedTerminal=!0,await this.#O(t.chatId,this.#re(e)));return}}})().catch(async()=>{this.#w?.aborted||t.stopped||this.#U!==t||(t.stopped=!0,this.#D.warn?.("[dsh-feishu] callback repair status monitoring failed"),await this.#O(t.chatId,w("\u4FEE\u590D\u72B6\u6001\u67E5\u8BE2\u4E2D\u65AD\uFF0C\u73B0\u6709\u673A\u5668\u4EBA\u8FDE\u63A5\u4E0D\u53D7\u5F71\u54CD\uFF1B\u53D1\u9001 /repair status \u91CD\u8BD5\u67E5\u8BE2\u3002")).catch(()=>{}))})}async#xe(t,o,i,{restarted:e=!1}={}){let a=i.remainingSeconds??(i.expiresAt?Math.max(0,Math.ceil((i.expiresAt-Date.now())/1e3)):null),A=a===null?w("\u94FE\u63A5\u4E3A\u77ED\u671F\u6709\u6548"):w("\u94FE\u63A5\u7EA6 {minutes} \u5206\u949F\u540E\u8FC7\u671F",{minutes:Math.max(1,Math.ceil(a/60))});await this.#O(t,[e?w("\u65E7\u6388\u6743\u94FE\u63A5\u5DF2\u4F5C\u5E9F\uFF0C\u5DF2\u751F\u6210\u65B0\u7684\u4FEE\u590D\u94FE\u63A5\u3002"):w("\u{1F527} \u51C6\u5907\u8865\u5168\u6743\u9650\u4E0E\u56DE\u8C03\u3002"),w("\u672C\u6B21\u4F1A\u589E\u91CF\u6DFB\u52A0\u5F53\u524D\u7F3A\u5C11\u9879\uFF1A\u5361\u7247\u56DE\u8C03 card.action.trigger\uFF1B\u98DE\u4E66\u663E\u793A\u4E3A\u201C\u83B7\u53D6\u5355\u804A\u3001\u7FA4\u7EC4\u6D88\u606F\u201D\u7684\u79DF\u6237\u6743\u9650 im:message:readonly\uFF08\u7528\u4E8E\u8BFB\u53D6\u7528\u6237\u6D88\u606F\u4E2D\u7684\u56FE\u7247\u6216\u6587\u4EF6\uFF09\uFF1Bim:resource\uFF08\u7528\u4E8E\u4E0A\u4F20\u673A\u5668\u4EBA\u53D1\u9001\u7684\u56FE\u7247\u6216\u6587\u4EF6\uFF09\uFF1B\u4EE5\u53CA\u539F\u751F\u547D\u4EE4\u9762\u677F\u6240\u9700\u7684 application:app_slash_command:read / write\u3002\u786E\u8BA4\u9875\u53EA\u4F1A\u663E\u793A\u5F53\u524D\u7F3A\u5C11\u7684\u9879\uFF1B\u82E5\u51FA\u73B0\u4E0A\u8FF0\u8303\u56F4\u4E4B\u5916\u7684\u914D\u7F6E\uFF0C\u8BF7\u53D6\u6D88\u3002"),"",w("\u5F53\u524D\u8BBE\u5907\u76F4\u63A5\u6253\u5F00\uFF1A"),o,"",w("\u82E5\u8981\u7528\u53E6\u4E00\u53F0\u8BBE\u5907\u626B\u7801\uFF0C\u53D1\u9001 /repair qr\u3002{expiry}\u3002",{expiry:A})].join(` -`))}async#Ye(t,o,i){try{let e=await pRe.toBuffer(o,{errorCorrectionLevel:"M",margin:1,width:480,type:"png"}),a=await this.#e.im.v1.image.create({data:{image_type:"message",image:e}}),A=hA(a?.image_key)??hA(a?.data?.image_key);if(!A)throw new Error("Feishu QR upload returned no image key");let r=i.remainingSeconds??(i.expiresAt?Math.max(0,Math.ceil((i.expiresAt-Date.now())/1e3)):null),s=r===null?"":w("\uFF08\u5269\u4F59\u7EA6 {minutes} \u5206\u949F\uFF09",{minutes:Math.max(1,Math.ceil(r/60))});await this.#O(t,w("\u8BF7\u7528\u53E6\u4E00\u53F0\u8BBE\u5907\u626B\u7801\u5B8C\u6210\u6388\u6743{remaining}\u3002",{remaining:s}));let g=await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"image",content:JSON.stringify({image_key:A})}});if(g?.code&&g.code!==0)throw new Error("Feishu QR message send failed")}catch{await this.#O(t,w(`\u4E8C\u7EF4\u7801\u6682\u65F6\u65E0\u6CD5\u53D1\u9001\uFF0C\u8BF7\u76F4\u63A5\u6253\u5F00\u6388\u6743\u94FE\u63A5\uFF1A -{url}`,{url:o}))}}#re(t,{verificationFocused:o=!1}={}){if(t.state==="succeeded")return w("\u2705 \u4FEE\u590D\u5B8C\u6210\uFF1A\u5DF2\u5B9E\u6D4B\u6536\u5230 card.action.trigger\uFF0C\u83DC\u5355\u6309\u94AE\u73B0\u5728\u53EF\u7528\u3002");if(t.state==="expired"||t.error?.code==="expired_token")return w("\u6388\u6743\u94FE\u63A5\u5DF2\u8FC7\u671F\uFF1B\u5E73\u53F0\u672A\u8FD4\u56DE\u6210\u529F\u7ED3\u679C\uFF0C\u65E0\u6CD5\u786E\u8BA4\u5DF2\u4FEE\u590D\u3002\u53D1\u9001 /repair \u751F\u6210\u65B0\u94FE\u63A5\u3002");if(t.state==="cancelled"||t.error?.code==="abort")return w("\u5DF2\u53D6\u6D88\u672C\u6B21\u4FEE\u590D\u6388\u6743\uFF0C\u672A\u786E\u8BA4\u5B8C\u6210\u4FEE\u590D\u3002");if(t.error?.code==="access_denied")return w("\u4F60\u5DF2\u53D6\u6D88\u6216\u62D2\u7EDD\u6388\u6743\uFF0C\u6CA1\u6709\u786E\u8BA4\u4FEE\u590D\uFF1B\u53D1\u9001 /repair \u53EF\u91CD\u8BD5\u3002");if(t.error?.code==="card_action_probe_timeout"||t.error?.code==="card-action-probe-timeout")return w("\u6388\u6743\u5DF2\u63D0\u4EA4\uFF0C\u4F46\u672A\u6536\u5230\u6D4B\u8BD5\u6309\u94AE\u56DE\u8C03\u3002\u53EF\u80FD\u5C1A\u672A\u70B9\u51FB\u6216\u914D\u7F6E\u4ECD\u5728\u4F20\u64AD\uFF1B\u7A0D\u540E\u53D1\u9001 /repair verify \u67E5\u8BE2\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6388\u6743\u3002");if(t.state==="error")return w("\u4FEE\u590D\u6D41\u7A0B\u6682\u65F6\u5931\u8D25\uFF0C\u73B0\u6709\u673A\u5668\u4EBA\u8FDE\u63A5\u4E0D\u53D7\u5F71\u54CD\uFF1B\u53D1\u9001 /repair \u53EF\u91CD\u8BD5\u3002");if(t.state==="saving")return w("\u6388\u6743\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u7B49\u5F85\u4E13\u7528\u6D4B\u8BD5\u6309\u94AE\u7684\u771F\u5B9E\u56DE\u8C03\uFF1B\u56DE\u8C03\u5230\u8FBE\u524D\u4E0D\u4F1A\u5BA3\u544A\u6210\u529F\u3002");if(o)return w("\u6388\u6743\u5C1A\u672A\u5B8C\u6210\uFF0C\u6682\u65F6\u4E0D\u80FD\u9A8C\u8BC1\u5361\u7247\u6309\u94AE\u3002\u8BF7\u5148\u6253\u5F00\u6388\u6743\u94FE\u63A5\u5E76\u786E\u8BA4\u3002");let i=t.remainingSeconds===null?"":w("\uFF0C\u5269\u4F59\u7EA6 {minutes} \u5206\u949F",{minutes:Math.max(1,Math.ceil(t.remainingSeconds/60))});return w("\u4FEE\u590D\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u6388\u6743{remaining}\u3002\u53D1\u9001 /repair qr \u53EF\u83B7\u53D6\u4E8C\u7EF4\u7801\uFF0C/repair cancel \u53EF\u53D6\u6D88\u3002",{remaining:i})}onCardAction(t){let o=hA(t?.operator?.open_id)??hA(t?.operator?.user_id)??hA(t?.operator?.operator_id?.open_id)??hA(t?.operator?.operator_id?.user_id)??hA(t?.open_id)??hA(t?.user_id);if(!(o!==null&&(this.#b.has("*")||this.#b.has(o))))return this.#D.warn?.("[dsh-feishu] ignoring card action from an unallowed sender"),Promise.resolve();let e=o6(t?.action?.value),a=o6(t?.action?.form_value),A=hA(e.action)??hA(t?.action?.action);if(!A)return Promise.resolve();let r=Bu(t?.action?.option)??(A.endsWith("_pick")?Qg(t?.action?.options)[0]:null),s=[...new Set([...Qg(e.options),...Qg(t?.action?.options),...Qg(a[A]),...A==="watch_add"||A==="watch_remove"?Qg(t?.action?.option):[]])],g=A==="workspace_pick"&&typeof r=="string"?`workspace:${r}`:A==="session_pick"&&typeof r=="string"?`use:${r}`:A==="preset_pick"&&typeof r=="string"?`preset:select:${r}`:A==="model_pick"&&typeof r=="string"?`model:select:${r}`:A==="archive_pick"&&typeof r=="string"?`archive:${r}`:A==="steer_pick"&&typeof r=="string"?`steer:${r}`:A,c=hA(t?.context?.open_message_id)??hA(t?.open_message_id)??hA(t?.message_id),I=c?this.#H.get(c):null;if(!I){let F=hA(t?.context?.open_chat_id)??hA(t?.open_chat_id)??hA(t?.chat_id);return F&&this.#O(F,w("\u8FD9\u4E2A\u83DC\u5355\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u56DE\u590D /m \u91CD\u65B0\u6253\u5F00\u3002")).catch(()=>{}),Promise.resolve()}this.#H.delete(c),this.#H.set(c,I);let d={...I,messageId:c,selections:s,operatorOpenId:o},B=hA(e.source),f=hA(a.steer_text),Q=hA(t?.event_id)??hA(t?.header?.event_id)??hA(t?.uuid)??hA(t?.header?.uuid),y=JSON.stringify({messageId:c,resolvedAction:g,option:r,multiValues:s,source:B,formText:f}),m=g==="stop",_=g.startsWith("steer:")?g.slice(6):null,R=A==="steer"&&B==="quick"&&r!==null&&r!==Eu||A==="steer"&&B==="form"&&f!==null||_!==null&&_!==""&&!(_==="custom"||_===Eu);return this.#Je(d,y,async()=>{if(A==="steer"){if(B==="quick"&&r){if(r===Eu){await this.#W(d.chatId,Jv(),{key:d.key,updateMessageId:d.messageId});return}await this.#de(d,r);return}if(B==="form"){if(f){await this.#de(d,f);return}await this.#O(d.chatId,w("\u8BF7\u8F93\u5165\u8865\u5145\u6307\u4EE4\u540E\u518D\u63D0\u4EA4\u3002"));return}}await this.#ie(g,d)},{lane:m||R?"control":"regular",coalesceStop:m,eventId:Q,operatorOpenId:o})}#Oe(t=Date.now()){for(let[o,i]of this.#S)i<=t&&this.#S.delete(o);for(;this.#S.size>a6;){let o=this.#S.keys().next().value;if(o===void 0)break;this.#S.delete(o)}}#be(t,o=Date.now()){t&&(this.#S.delete(t),this.#S.set(t,o+DRe),this.#Oe(o))}#je(t){let o=t.key,i=Date.now(),e=this.#Q.get(o);if(e?.task||e&&i-e.at{}).finally(()=>{this.#p.delete(a);let A=this.#Q.get(o);A?.task===a&&this.#Q.set(o,{at:A.at,task:null})}),this.#Q.delete(o),this.#Q.set(o,{at:i,task:a}),this.#p.add(a);this.#Q.size>200;){let A=this.#Q.keys().next().value;if(A===void 0)break;this.#Q.delete(A)}return a}#Je(t,o,i,{lane:e="regular",coalesceStop:a=!1,eventId:A=null,operatorOpenId:r=null}={}){let s=t.key,g=A?`${s}\0${r??""}\0event:${A}`:null,c=g??`${s}\0${r??""}\0action:${o}`,I=Date.now();if(this.#Oe(I),g&&(this.#S.get(g)??0)>I)return Promise.resolve();let d=this.#f.get(c);if(d)return d;if(a){let K=this.#B.get(s);if(K){if(g)for(this.#y.delete(g),this.#y.set(g,K);this.#y.size>a6;){let L=this.#y.keys().next().value;if(L===void 0)break;this.#y.delete(L)}return K}}let B=e==="control",f=B?this.#h:this.#d,Q=B?this.#C:this.#E,y=B?wRe:SRe,m=Q.get(s)??0,_=a?y+1:y;if(m>=_)return this.#je(t);let T=f.get(s)??Promise.resolve();Q.set(s,m+1);let R,F=!1;return R=T.catch(()=>{}).then(async()=>{this.#w?.throwIfAborted(),F=!0,await i()}).catch(async K=>{this.#w?.aborted||await this.#x(t.chatId,K,{logLabel:"card action"})}).finally(()=>{if(this.#f.get(c)===R&&this.#f.delete(c),F&&g&&this.#be(g),a&&this.#B.get(s)===R&&this.#B.delete(s),a){let L=Date.now();for(let[q,z]of this.#y)z===R&&(this.#y.delete(q),this.#be(q,L))}f.get(s)===R&&f.delete(s);let K=(Q.get(s)??1)-1;K>0?Q.set(s,K):Q.delete(s),this.#p.delete(R)}),this.#f.set(c,R),a&&this.#B.set(s,R),this.#p.add(R),f.set(s,R),R}async#ie(t,{chatId:o,key:i,messageId:e=null,sessionWorkspace:a=null,sessionPage:A=0,selections:r=[]}){if(t==="sessions"||/^sessions:\d+$/.test(t)){let s=t==="sessions"?0:Number(t.slice(9));await this.#ce({chatId:o,key:i},a,s,{updateMessageId:e});return}if(t==="workspaces"){await this.#Me({chatId:o,key:i},{updateMessageId:e});return}if(t==="watchlist"){await this.#ue(i,o,{updateMessageId:e});return}if(t==="watch_add"||t==="watch_remove"){if(r.length===0){await this.#O(o,w("\u8BF7\u5148\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u4F1A\u8BDD\u3002"));return}let s=0,g=0;if(t==="watch_add"){let I=new Map;try{I=await this.#gA(a)}catch(d){this.#D.warn?.("[dsh-feishu] batch watch validation failed:",d.message)}for(let d of r){let B=I.get(d);if(!B){g+=1;continue}let f=await this.#Ee(i,o,d,{notify:!1,validatedTarget:B});f.changed?s+=1:f.ok||(g+=1)}}else for(let I of r){let d=await this.#Ce(i,o,I,{notify:!1});d.changed?s+=1:d.ok||(g+=1)}let c=s>0&&g>0?t==="watch_add"?w("\u5DF2\u6279\u91CF\u5173\u6CE8 {count} \u4E2A\u4F1A\u8BDD\uFF0C\u53E6\u6709 {failed} \u4E2A\u672A\u6210\u529F\u3002",{count:s,failed:g}):w("\u5DF2\u53D6\u6D88\u5173\u6CE8 {count} \u4E2A\u4F1A\u8BDD\uFF0C\u53E6\u6709 {failed} \u4E2A\u672A\u6210\u529F\u3002",{count:s,failed:g}):s>0?t==="watch_add"?w("\u5DF2\u6279\u91CF\u5173\u6CE8 {count} \u4E2A\u4F1A\u8BDD\u3002",{count:s}):w("\u5DF2\u53D6\u6D88\u5173\u6CE8 {count} \u4E2A\u4F1A\u8BDD\u3002",{count:s}):g>0?w("\u6240\u9009\u4F1A\u8BDD\u5747\u672A\u5904\u7406\u6210\u529F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):t==="watch_add"?w("\u6240\u9009\u4F1A\u8BDD\u5DF2\u5728\u5173\u6CE8\u5217\u8868\u4E2D\u3002"):w("\u6240\u9009\u4F1A\u8BDD\u5DF2\u4E0D\u5728\u5173\u6CE8\u5217\u8868\u4E2D\u3002");try{await this.#ue(i,o,{updateMessageId:e})}catch(I){this.#D.warn?.("[dsh-feishu] watch list refresh failed:",I.message)}await this.#O(o,c).catch(I=>{this.#D.warn?.("[dsh-feishu] watch batch summary failed:",I.message)});return}if(t==="new"){if(this.#a.has(i)||this.#ae(i)){await this.#O(o,w("\u5F53\u524D\u4EFB\u52A1\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u4EFB\u52A1\u6216\u7B49\u5F85\u4EFB\u52A1\u5B8C\u6210\u540E\u518D\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002"));return}await this.#r.clearSession(i),await this.#O(o,w("\u5DF2\u5F00\u542F\u5168\u65B0 Harness \u4F1A\u8BDD\u3002")),await this.#Z(i,o,{updateMessageId:e});return}if(t==="use:current"){let s=this.#r.sessionFor(i);if(typeof s!="string"||!s){await this.#O(o,w("\u5F53\u524D\u6CA1\u6709\u7ED1\u5B9A\u7684\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u4ECE\u4F1A\u8BDD\u5217\u8868\u9009\u62E9\u3002"));return}await this.#O(o,w("\u5DF2\u5C31\u7EEA\uFF0C\u76F4\u63A5\u53D1\u6D88\u606F\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"));return}if(t==="archive_toggle"||t==="archive:on"||t==="archive:off"){let s=t==="archive:on"?!0:t==="archive:off"?!1:!(this.#r?.includesArchivedSessions?.()??!1);await this.#r?.setIncludeArchivedSessions?.(s),await this.#O(o,s?w("\u5DF2\u5F00\u542F\uFF1A\u4F1A\u8BDD\u5217\u8868\u5305\u542B\u5F52\u6863\u4F1A\u8BDD\u3002"):w("\u5DF2\u5173\u95ED\uFF1A\u4F1A\u8BDD\u5217\u8868\u9690\u85CF\u5F52\u6863\u4F1A\u8BDD\u3002")),await this.#Z(i,o,{updateMessageId:e});return}if(t==="repair"){await this.#O(o,w("\u4FEE\u590D\u9700\u5728\u79C1\u804A\u4E2D\u9A8C\u8BC1\u63A5\u5165\u8005\u8EAB\u4EFD\uFF0C\u8BF7\u76F4\u63A5\u53D1\u9001 /repair \u5F00\u59CB\u3002"));return}if(t==="compact"){await this.#tA(i,o);return}if(t==="stop"){await this.#rA(i,o);return}if(t==="steer"){await this.#aA(i,o,{updateMessageId:e});return}if(t.startsWith("steer:")){let s=t.slice(6);if(s==="custom"){await this.#W(o,Jv(),{key:i,updateMessageId:e});return}await this.#de({key:i,chatId:o},s);return}if(t==="presets"){await this.#Ze(i,o,{updateMessageId:e});return}if(t==="models"){await this.#Xe(i,o,{updateMessageId:e});return}if(t==="status"){await this.#eA(i,o,{updateMessageId:e});return}if(t==="help"){await this.#AA(i,o,{updateMessageId:e});return}if(t==="back_to_menu"){await this.#Z(i,o,{updateMessageId:e});return}if(t==="preset_default"){await this.#Te(i,o,{updateMessageId:e});return}if(t.startsWith("preset:select:")){let s=t.slice(14);if(s===qm){await this.#Te(i,o,{updateMessageId:e});return}await this.#iA(i,o,s,{updateMessageId:e});return}if(t.startsWith("model:select:")){let s=t.slice(13);await this.#oA(i,o,s,{updateMessageId:e});return}if(t.startsWith("use:")){await this.#Ve(i,o,t.slice(4),{updateMessageId:e});return}if(t.startsWith("workspace:")){await this.#We(i,o,t.slice(10),{updateMessageId:e});return}if(t.startsWith("unwatch:")){(await this.#Ce(i,o,t.slice(8))).ok&&e&&await this.#ce({chatId:o,key:i},a,A,{updateMessageId:e});return}if(t.startsWith("watch:")){let s=t.slice(6);(await this.#Ee(i,o,s,{workspaceHint:a})).ok&&e&&await this.#ce({chatId:o,key:i},a,A,{updateMessageId:e})}}#oe(t,o){if(this.#Y.size>=mRe){let i=this.#Y.keys().next().value;i!==void 0&&this.#Y.delete(i)}this.#Y.delete(t),this.#Y.set(t,{...o,expiresAt:Date.now()+yRe})}#qe(t){let o=this.#Y.get(t);return o?o.expiresAto.archived!==!0):t}async#ce({chatId:t,key:o},i,e=0,{updateMessageId:a=null}={}){try{let A=this.#V(),r=await YM(i??"",this.#t,{signal:A});if(r.error){await this.#O(t,r.error);return}let s=await this.#t.listWorkspaceSessions(r.workspace,{signal:A}),g=this.#ne(Array.isArray(s?.sessions)?s.sessions:[]),c=s?.workspace??r.workspace;if(g.length===0){await this.#O(t,w(`\u5DE5\u4F5C\u533A\uFF1A{workspace} -\u8BE5\u5DE5\u4F5C\u533A\u6682\u65E0\u4F1A\u8BDD\u3002`,{workspace:c}));return}let I=Math.ceil(g.length/wc),d=Number.isSafeInteger(e)&&e>0?Math.min(e,I-1):0,B=new Set((this.#r.watchEntries?.(o)??[]).map(Q=>Q.sessionId)),f=g.slice(d*wc,(d+1)*wc);this.#oe(o,{kind:"sessions",sessions:f.map(Q=>({...Q,watched:B.has(Q.sessionId)}))}),await this.#W(t,WW(c,g,d,g.length,B),{key:o,updateMessageId:a,sessionWorkspace:r.workspace,sessionPage:d})}catch(A){await this.#x(t,A,{logLabel:"session list"})}}async#Me({chatId:t,key:o},{updateMessageId:i=null}={}){try{let{current:e,paths:a}=await _E(this.#t,{signal:this.#V()});this.#oe(o,{kind:"workspaces",paths:a}),await this.#W(t,ZW(a,e),{key:o,updateMessageId:i})}catch(e){await this.#x(t,e,{logLabel:"workspace list"})}}async#Ve(t,o,i,{updateMessageId:e=null}={}){try{let a=await this.#t.bindWorkspaceSession(t,i),A=String(a?.title??"").replace(/\s+/gu," ").trim()||w("\u6682\u65E0\u6807\u9898");await this.#O(o,[w(`\u5DF2\u7ED1\u5B9A\u4F1A\u8BDD\u300C{title}\u300D +${e.batchInputMessage}`:dt(A);await this.#O(t.message.chat_id,r).catch(()=>{})}async waitForIdle(){for(;;){let t=[...this.#a.values(),...[...this.#i.values()].flatMap(o=>o.queue?[o.queue]:[]),...this.#s,...this.#c,...this.#p,...this.#z.values(),...[...this.#F.values()].map(o=>o.promise)];if(t.length===0||(await Promise.allSettled(t),this.#a.size===0&&this.#s.size===0&&this.#c.size===0&&this.#p.size===0&&this.#z.size===0&&this.#F.size===0&&![...this.#i.values()].some(o=>o.queue)))return}}#V(){let t=AbortSignal.timeout(this.#$);return this.#w?AbortSignal.any([this.#w,t]):t}#ae(t){return this.#i.has(t)||this.#m.hasPending(t)}async#Le(t,o,i,e,a){if(this.#w?.throwIfAborted(),this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1;let A=await a(pA(e.content)??"",this.#t,this.#r,i,{signal:this.#w,isDirect:t.message.chat_type==="p2p",hasImages:Wt(e),hasFiles:Lt(e),pendingInteraction:this.#ae(i),control:{owner:this,key:i}});A?.stopped&&await Promise.allSettled([this.#we(i),this.#m.closeRoute(i)]);for(let r of A?.messages??[A?.message])r&&await this.#O(t.message.chat_id,r,{replyTo:t.message.message_id});this.#u.lastError=null}async#De(t,o,{alreadyRecorded:i=!1}={}){this.#w?.throwIfAborted();let e=t.message.message_id;if(!i){if(this.#r.hasSeen(e))return;await this.#r.markSeen(e),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1}let a=jv(t,this.#e),A=a.content,r=Wt(a),s=Lt(a),g=!r&&!s&&A?A.trim():null;if(!A&&!r&&!s){await this.#O(t.message.chat_id,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002"),{replyTo:t.message.message_id});return}if(g!==null&&ERe.test(g)){await this.#Oe(t,g);return}if(g==="/help"){await this.#O(t.message.chat_id,qW(),{replyTo:t.message.message_id});return}if(hRe.test(g)){await this.#Z(o,t.message.chat_id,{replyTo:t.message.message_id});return}if(g==="/new"){if(this.#a.has(o)||this.#ae(o)){await this.#O(t.message.chat_id,w("\u5F53\u524D\u4EFB\u52A1\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u4EFB\u52A1\u6216\u7B49\u5F85\u4EFB\u52A1\u5B8C\u6210\u540E\u518D\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002"),{replyTo:t.message.message_id});return}await this.#r.clearSession(o),await this.#O(t.message.chat_id,w("\u5DF2\u5F00\u542F\u5168\u65B0 Harness \u4F1A\u8BDD\u3002"),{replyTo:t.message.message_id}),await this.#Z(o,t.message.chat_id,{replyTo:t.message.message_id});return}if(g==="/status"){await this.#$e(o,t.message.chat_id,t.message.message_id);return}if(g==="/compact"){let f=await Bi(g,this.#t,this.#r,o,{signal:this.#w});f&&await this.#O(t.message.chat_id,f.message,{replyTo:t.message.message_id});return}if(BRe.test(g)){let f=g.replace(/^\/(?:sessionlist|sessions)/i,"").trim()||null;await this.#ce({chatId:t.message.chat_id,key:o,replyTo:t.message.message_id},f,0);return}if(fRe.test(g)){await this.#_e({chatId:t.message.chat_id,key:o,replyTo:t.message.message_id});return}if(t6.test(g)){let f=(t6.exec(g)?.[1]??"").trim()||null;await this.#Ce(o,t.message.chat_id,f,{replyTo:t.message.message_id});return}if(r6.test(g)){let f=(r6.exec(g)?.[1]??"").trim()||null;await this.#ue(o,t.message.chat_id,f,{replyTo:t.message.message_id});return}if(uRe.test(g)){await this.#Be(o,t.message.chat_id,{replyTo:t.message.message_id});return}if(i6.test(g)){let Q=i6.exec(g)[1]?.toLowerCase();if(Q!=="on"&&Q!=="off"){await this.#O(t.message.chat_id,w("\u7528\u6CD5\uFF1A/archived on\uFF08\u5305\u542B\u5F52\u6863\u4F1A\u8BDD\uFF09\u6216 /archived off\uFF08\u9690\u85CF\u5F52\u6863\u4F1A\u8BDD\uFF09"),{replyTo:t.message.message_id});return}typeof this.#r?.setIncludeArchivedSessions=="function"&&await this.#r.setIncludeArchivedSessions(Q==="on"),await this.#O(t.message.chat_id,Q==="on"?w("\u5DF2\u5F00\u542F\uFF1A\u4F1A\u8BDD\u5217\u8868\u5305\u542B\u5F52\u6863\u4F1A\u8BDD\u3002"):w("\u5DF2\u5173\u95ED\uFF1A\u4F1A\u8BDD\u5217\u8868\u9690\u85CF\u5F52\u6863\u4F1A\u8BDD\u3002"),{replyTo:t.message.message_id});return}if(QRe.test(g)){let f=this.#qe(o);if(f){await this.#ze(f,Number(g),{chatId:t.message.chat_id,key:o,event:t});return}}let c=g===null?null:await Qo(A,this.#t,o);if(c){for(let f of c.messages??[c.message])await this.#O(t.message.chat_id,f,{replyTo:t.message.message_id});return}let I=g===null?null:await Bi(g,this.#t,this.#r,o,{signal:this.#w});if(I){await this.#O(t.message.chat_id,I.message,{replyTo:t.message.message_id});return}this.#D.info?.(`[dsh-feishu] processing ${t.message.chat_type} message ${e}`);let d=t.batchSubmission??null,B=!1;try{let{receipt:f,artifactSendErrors:Q,textDeliveryErrors:y=0}=await this.#lA(t,o,a,{onAskComplete:d?()=>{B=this.#n.complete(o,d.token).completed}:void 0});return this.#u.messagesReplied+=1,this.#u.lastReplyAt=new Date().toISOString(),this.#u.lastError=null,y===0&&Q===0&&Co(this.#u),f}catch(f){if(d&&!B){if(f?.code==="turn-stopped")throw this.#n.complete(o,d.token),f;let Q=this.#n.fail(o,d.token);if(Q.retained){let y=new Error(f?.message??String(f),{cause:f});throw y.code=f?.code,y.providerCode=f?.providerCode,y.method=f?.method,Number.isInteger(f?.status)&&(y.status=f.status),y.batchInputMessage=Q.message,y}}throw f}finally{await this.#we(o),await this.#m.closeRoute(o)}}async#Oe(t,o){if(t?.message?.chat_type!=="p2p"){await this.#O(t.message.chat_id,w("\u4E3A\u907F\u514D\u6388\u6743\u94FE\u63A5\u66B4\u9732\uFF0C\u8BF7\u79C1\u804A\u673A\u5668\u4EBA\u53D1\u9001 /repair\u3002"));return}let i=URe(t);if(!i){await this.#O(t.message.chat_id,w("\u65E0\u6CD5\u8BC6\u522B\u5F53\u524D\u53D1\u9001\u8005\uFF0C\u672A\u53D1\u8D77\u4FEE\u590D\u3002"));return}if(!this.#_){await this.#O(t.message.chat_id,w("\u5F53\u524D Host \u7248\u672C\u6682\u4E0D\u652F\u6301\u804A\u5929\u5185\u4FEE\u590D\uFF0C\u8BF7\u5148\u66F4\u65B0\u63D2\u4EF6\u3002"));return}let e=CRe.exec(o);if(!e){await this.#O(t.message.chat_id,w("\u7528\u6CD5\uFF1A/repair\u3001/repair qr\u3001/repair status\u3001/repair cancel \u6216 /repair verify"));return}let a=e[1]?.toLowerCase()??"start",A=t.message.chat_id;if(a==="start"){await this.#Ue({actorOpenId:i,chatId:A});return}let r=this.#U;if(!r){await this.#O(A,w("\u5F53\u524D Runtime \u6CA1\u6709\u53EF\u6062\u590D\u7684\u4FEE\u590D\u4EFB\u52A1\u8BB0\u5F55\uFF08\u673A\u5668\u4EBA\u53EF\u80FD\u521A\u5B8C\u6210\u5BC6\u94A5\u66F4\u65B0\u5E76\u91CD\u542F\uFF09\u3002\u672C\u547D\u4EE4\u4E0D\u4F1A\u542F\u52A8\u65B0\u7684\u6388\u6743\uFF1B\u8BF7\u67E5\u770B\u673A\u5668\u4EBA\u53D1\u9001\u7684\u9A8C\u8BC1\u7ED3\u679C\uFF0C\u786E\u8BA4\u4E0A\u4E00\u6B21\u4EFB\u52A1\u5DF2\u7ED3\u675F\u540E\u518D\u53D1\u9001 /repair\u3002"));return}if(r.actorOpenId!==i){await this.#O(A,w("\u53E6\u4E00\u4F4D\u7528\u6237\u6B63\u5728\u4FEE\u590D\u8BE5\u673A\u5668\u4EBA\uFF0C\u672C\u6B21\u4E0D\u4F1A\u663E\u793A\u5176\u6388\u6743\u4FE1\u606F\u3002"));return}if(a==="cancel"){let g;try{let c=await this.#_.cancel(this.#ge(r));g=uu(c,{botId:this.#T}),r.snapshot=g}catch{await this.#O(A,w("\u6682\u65F6\u65E0\u6CD5\u53D6\u6D88\u4FEE\u590D\u4EFB\u52A1\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"));return}g.state==="cancelled"&&(r.stopped=!0,this.#v+=1),await this.#O(A,this.#re(g));return}let s;try{s=await this.#pe(r)}catch{await this.#O(A,w("\u6682\u65F6\u65E0\u6CD5\u67E5\u8BE2\u4FEE\u590D\u72B6\u6001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"));return}if(a==="qr"){if(!zv.has(s.state)||!r.verificationUrl){await this.#O(A,this.#re(s,{verificationFocused:!0}));return}await this.#Ye(A,r.verificationUrl,s);return}await this.#O(A,this.#re(s,{verificationFocused:a==="verify"}))}#ge(t){return{botId:this.#T,attemptId:t.attemptId,actorOpenId:t.actorOpenId,chatId:t.chatId}}async#Ue({actorOpenId:t,chatId:o}){let i=this.#U,e=!1;if(i&&zv.has(i.snapshot.state)){if(i.actorOpenId!==t){await this.#O(o,w("\u53E6\u4E00\u4F4D\u7528\u6237\u6B63\u5728\u4FEE\u590D\u8BE5\u673A\u5668\u4EBA\uFF0C\u672C\u6B21\u4E0D\u4F1A\u663E\u793A\u5176\u6388\u6743\u4FE1\u606F\u3002"));return}let r;try{r=await this.#pe(i)}catch{await this.#O(o,w("\u6682\u65F6\u65E0\u6CD5\u67E5\u8BE2\u4FEE\u590D\u72B6\u6001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"));return}if(r.state==="saving"){await this.#O(o,this.#re(r));return}if(g6.has(r.state)){let s;try{s=uu(await this.#_.cancel(this.#ge(i)),{botId:this.#T}),i.snapshot=s}catch{await this.#O(o,w("\u6682\u65F6\u65E0\u6CD5\u53D6\u6D88\u65E7\u4FEE\u590D\u4EFB\u52A1\uFF0C\u672A\u751F\u6210\u65B0\u94FE\u63A5\uFF1B\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"));return}if(!eS.has(s.state)){await this.#O(o,this.#re(s));return}i.stopped=!0,this.#v+=1,e=s.state==="cancelled"}else eS.has(r.state)&&(i.stopped=!0,this.#v+=1)}let a;try{a=uu(await this.#_.start({botId:this.#T,actorOpenId:t,chatId:o}),{botId:this.#T}),a=await this.#He(a,{actorOpenId:t,chatId:o})}catch{await this.#O(o,w("\u4FEE\u590D\u6D41\u7A0B\u6682\u65F6\u5931\u8D25\uFF0C\u73B0\u6709\u673A\u5668\u4EBA\u8FDE\u63A5\u4E0D\u53D7\u5F71\u54CD\uFF1B\u8BF7\u7A0D\u540E\u53D1\u9001 /repair \u91CD\u8BD5\u3002"));return}let A={attemptId:a.attemptId,actorOpenId:t,chatId:o,snapshot:a,verificationUrl:null,stopped:!1,announcedSaving:!1,announcedTerminal:!1};if(this.#U=A,a.verificationUrl)try{A.verificationUrl=s6(a.verificationUrl,this.#k)}catch{A.stopped=!0,await this.#_.cancel(this.#ge(A)).catch(()=>{}),await this.#O(o,w("\u98DE\u4E66\u8FD4\u56DE\u4E86\u65E0\u6CD5\u5B89\u5168\u9A8C\u8BC1\u7684\u6388\u6743\u94FE\u63A5\uFF0C\u5DF2\u4E2D\u6B62\u672C\u6B21\u4FEE\u590D\u3002"));return}if(eS.has(a.state)){A.announcedTerminal=!0,a.state!=="succeeded"&&await this.#O(o,this.#re(a));return}if(!A.verificationUrl){A.stopped=!0,await this.#O(o,w("\u98DE\u4E66\u672A\u8FD4\u56DE\u6388\u6743\u94FE\u63A5\uFF0C\u5DF2\u4E2D\u6B62\u672C\u6B21\u4FEE\u590D\u3002"));return}await this.#xe(o,A.verificationUrl,a,{restarted:e}),this.#Ke(A)}async#He(t,o){let i=t,e=Date.now()+this.#N;for(;!i.verificationUrl&&zv.has(i.state);){if(Date.now()>=e)throw new Error("Feishu repair link timed out");await n6(Math.min(100,this.#P),this.#w),i=uu(await this.#_.status({botId:this.#T,attemptId:i.attemptId,actorOpenId:o.actorOpenId,chatId:o.chatId}),{botId:this.#T})}return i}async#pe(t){let o=uu(await this.#_.status(this.#ge(t)),{botId:this.#T});if(o.attemptId!==t.attemptId)throw new Error("Feishu repair attempt changed unexpectedly");return t.snapshot=o,o.verificationUrl&&(t.verificationUrl=s6(o.verificationUrl,this.#k)),o}#Ke(t){let o=++this.#v;(async()=>{for(;!t.stopped&&this.#U===t&&this.#v===o&&!this.#w?.aborted;){let i=Math.max(250,Math.min(1e4,t.snapshot.pollIntervalMs??this.#P));if(await n6(i,this.#w),t.stopped||this.#U!==t||this.#v!==o)return;let e=await this.#pe(t);if(e.state==="saving"&&!t.announcedSaving&&(t.announcedSaving=!0,await this.#O(t.chatId,w("\u6388\u6743\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u53D1\u9001\u5E76\u7B49\u5F85\u6D4B\u8BD5\u6309\u94AE\u56DE\u8C03\uFF1B\u6536\u5230\u771F\u5B9E\u56DE\u8C03\u540E\u624D\u4F1A\u5B8C\u6210\u3002"))),eS.has(e.state)){t.stopped=!0,e.state!=="succeeded"&&!t.announcedTerminal&&(t.announcedTerminal=!0,await this.#O(t.chatId,this.#re(e)));return}}})().catch(async()=>{this.#w?.aborted||t.stopped||this.#U!==t||(t.stopped=!0,this.#D.warn?.("[dsh-feishu] callback repair status monitoring failed"),await this.#O(t.chatId,w("\u4FEE\u590D\u72B6\u6001\u67E5\u8BE2\u4E2D\u65AD\uFF0C\u73B0\u6709\u673A\u5668\u4EBA\u8FDE\u63A5\u4E0D\u53D7\u5F71\u54CD\uFF1B\u53D1\u9001 /repair status \u91CD\u8BD5\u67E5\u8BE2\u3002")).catch(()=>{}))})}async#xe(t,o,i,{restarted:e=!1}={}){let a=i.remainingSeconds??(i.expiresAt?Math.max(0,Math.ceil((i.expiresAt-Date.now())/1e3)):null),A=a===null?w("\u94FE\u63A5\u4E3A\u77ED\u671F\u6709\u6548"):w("\u94FE\u63A5\u7EA6 {minutes} \u5206\u949F\u540E\u8FC7\u671F",{minutes:Math.max(1,Math.ceil(a/60))});await this.#O(t,[e?w("\u65E7\u6388\u6743\u94FE\u63A5\u5DF2\u4F5C\u5E9F\uFF0C\u5DF2\u751F\u6210\u65B0\u7684\u4FEE\u590D\u94FE\u63A5\u3002"):w("\u{1F527} \u51C6\u5907\u8865\u5168\u6743\u9650\u4E0E\u56DE\u8C03\u3002"),w("\u672C\u6B21\u4F1A\u589E\u91CF\u6DFB\u52A0\u5F53\u524D\u7F3A\u5C11\u9879\uFF1A\u5361\u7247\u56DE\u8C03 card.action.trigger\uFF1B\u98DE\u4E66\u663E\u793A\u4E3A\u201C\u83B7\u53D6\u5355\u804A\u3001\u7FA4\u7EC4\u6D88\u606F\u201D\u7684\u79DF\u6237\u6743\u9650 im:message:readonly\uFF08\u7528\u4E8E\u8BFB\u53D6\u7528\u6237\u6D88\u606F\u4E2D\u7684\u56FE\u7247\u6216\u6587\u4EF6\uFF09\uFF1Bim:resource\uFF08\u7528\u4E8E\u4E0A\u4F20\u673A\u5668\u4EBA\u53D1\u9001\u7684\u56FE\u7247\u6216\u6587\u4EF6\uFF09\uFF1B\u4EE5\u53CA\u539F\u751F\u547D\u4EE4\u9762\u677F\u6240\u9700\u7684 application:app_slash_command:read / write\u3002\u786E\u8BA4\u9875\u53EA\u4F1A\u663E\u793A\u5F53\u524D\u7F3A\u5C11\u7684\u9879\uFF1B\u82E5\u51FA\u73B0\u4E0A\u8FF0\u8303\u56F4\u4E4B\u5916\u7684\u914D\u7F6E\uFF0C\u8BF7\u53D6\u6D88\u3002"),"",w("\u5F53\u524D\u8BBE\u5907\u76F4\u63A5\u6253\u5F00\uFF1A"),o,"",w("\u82E5\u8981\u7528\u53E6\u4E00\u53F0\u8BBE\u5907\u626B\u7801\uFF0C\u53D1\u9001 /repair qr\u3002{expiry}\u3002",{expiry:A})].join(` +`))}async#Ye(t,o,i){try{let e=await pRe.toBuffer(o,{errorCorrectionLevel:"M",margin:1,width:480,type:"png"}),a=await this.#e.im.v1.image.create({data:{image_type:"message",image:e}}),A=pA(a?.image_key)??pA(a?.data?.image_key);if(!A)throw new Error("Feishu QR upload returned no image key");let r=i.remainingSeconds??(i.expiresAt?Math.max(0,Math.ceil((i.expiresAt-Date.now())/1e3)):null),s=r===null?"":w("\uFF08\u5269\u4F59\u7EA6 {minutes} \u5206\u949F\uFF09",{minutes:Math.max(1,Math.ceil(r/60))});await this.#O(t,w("\u8BF7\u7528\u53E6\u4E00\u53F0\u8BBE\u5907\u626B\u7801\u5B8C\u6210\u6388\u6743{remaining}\u3002",{remaining:s}));let g=await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"image",content:JSON.stringify({image_key:A})}});if(g?.code&&g.code!==0)throw new Error("Feishu QR message send failed")}catch{await this.#O(t,w(`\u4E8C\u7EF4\u7801\u6682\u65F6\u65E0\u6CD5\u53D1\u9001\uFF0C\u8BF7\u76F4\u63A5\u6253\u5F00\u6388\u6743\u94FE\u63A5\uFF1A +{url}`,{url:o}))}}#re(t,{verificationFocused:o=!1}={}){if(t.state==="succeeded")return w("\u2705 \u4FEE\u590D\u5B8C\u6210\uFF1A\u5DF2\u5B9E\u6D4B\u6536\u5230 card.action.trigger\uFF0C\u83DC\u5355\u6309\u94AE\u73B0\u5728\u53EF\u7528\u3002");if(t.state==="expired"||t.error?.code==="expired_token")return w("\u6388\u6743\u94FE\u63A5\u5DF2\u8FC7\u671F\uFF1B\u5E73\u53F0\u672A\u8FD4\u56DE\u6210\u529F\u7ED3\u679C\uFF0C\u65E0\u6CD5\u786E\u8BA4\u5DF2\u4FEE\u590D\u3002\u53D1\u9001 /repair \u751F\u6210\u65B0\u94FE\u63A5\u3002");if(t.state==="cancelled"||t.error?.code==="abort")return w("\u5DF2\u53D6\u6D88\u672C\u6B21\u4FEE\u590D\u6388\u6743\uFF0C\u672A\u786E\u8BA4\u5B8C\u6210\u4FEE\u590D\u3002");if(t.error?.code==="access_denied")return w("\u4F60\u5DF2\u53D6\u6D88\u6216\u62D2\u7EDD\u6388\u6743\uFF0C\u6CA1\u6709\u786E\u8BA4\u4FEE\u590D\uFF1B\u53D1\u9001 /repair \u53EF\u91CD\u8BD5\u3002");if(t.error?.code==="card_action_probe_timeout"||t.error?.code==="card-action-probe-timeout")return w("\u6388\u6743\u5DF2\u63D0\u4EA4\uFF0C\u4F46\u672A\u6536\u5230\u6D4B\u8BD5\u6309\u94AE\u56DE\u8C03\u3002\u53EF\u80FD\u5C1A\u672A\u70B9\u51FB\u6216\u914D\u7F6E\u4ECD\u5728\u4F20\u64AD\uFF1B\u7A0D\u540E\u53D1\u9001 /repair verify \u67E5\u8BE2\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6388\u6743\u3002");if(t.state==="error")return w("\u4FEE\u590D\u6D41\u7A0B\u6682\u65F6\u5931\u8D25\uFF0C\u73B0\u6709\u673A\u5668\u4EBA\u8FDE\u63A5\u4E0D\u53D7\u5F71\u54CD\uFF1B\u53D1\u9001 /repair \u53EF\u91CD\u8BD5\u3002");if(t.state==="saving")return w("\u6388\u6743\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u7B49\u5F85\u4E13\u7528\u6D4B\u8BD5\u6309\u94AE\u7684\u771F\u5B9E\u56DE\u8C03\uFF1B\u56DE\u8C03\u5230\u8FBE\u524D\u4E0D\u4F1A\u5BA3\u544A\u6210\u529F\u3002");if(o)return w("\u6388\u6743\u5C1A\u672A\u5B8C\u6210\uFF0C\u6682\u65F6\u4E0D\u80FD\u9A8C\u8BC1\u5361\u7247\u6309\u94AE\u3002\u8BF7\u5148\u6253\u5F00\u6388\u6743\u94FE\u63A5\u5E76\u786E\u8BA4\u3002");let i=t.remainingSeconds===null?"":w("\uFF0C\u5269\u4F59\u7EA6 {minutes} \u5206\u949F",{minutes:Math.max(1,Math.ceil(t.remainingSeconds/60))});return w("\u4FEE\u590D\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u6388\u6743{remaining}\u3002\u53D1\u9001 /repair qr \u53EF\u83B7\u53D6\u4E8C\u7EF4\u7801\uFF0C/repair cancel \u53EF\u53D6\u6D88\u3002",{remaining:i})}onCardAction(t){let o=pA(t?.operator?.open_id)??pA(t?.operator?.user_id)??pA(t?.operator?.operator_id?.open_id)??pA(t?.operator?.operator_id?.user_id)??pA(t?.open_id)??pA(t?.user_id);if(!(o!==null&&(this.#b.has("*")||this.#b.has(o))))return this.#D.warn?.("[dsh-feishu] ignoring card action from an unallowed sender"),Promise.resolve();let e=o6(t?.action?.value),a=o6(t?.action?.form_value),A=pA(e.action)??pA(t?.action?.action);if(!A)return Promise.resolve();let r=Bu(t?.action?.option)??(A.endsWith("_pick")?Qg(t?.action?.options)[0]:null),s=[...new Set([...Qg(e.options),...Qg(t?.action?.options),...Qg(a[A]),...A==="watch_add"||A==="watch_remove"?Qg(t?.action?.option):[]])],g=A==="workspace_pick"&&typeof r=="string"?`workspace:${r}`:A==="session_pick"&&typeof r=="string"?`use:${r}`:A==="preset_pick"&&typeof r=="string"?`preset:select:${r}`:A==="model_pick"&&typeof r=="string"?`model:select:${r}`:A==="archive_pick"&&typeof r=="string"?`archive:${r}`:A==="steer_pick"&&typeof r=="string"?`steer:${r}`:A,c=pA(t?.context?.open_message_id)??pA(t?.open_message_id)??pA(t?.message_id),I=c?this.#H.get(c):null;if(!I){let L=pA(t?.context?.open_chat_id)??pA(t?.open_chat_id)??pA(t?.chat_id);return L&&this.#O(L,w("\u8FD9\u4E2A\u83DC\u5355\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u56DE\u590D /m \u91CD\u65B0\u6253\u5F00\u3002")).catch(()=>{}),Promise.resolve()}this.#H.delete(c),this.#H.set(c,I);let d={...I,messageId:c,selections:s,operatorOpenId:o},B=pA(e.source),f=pA(a.steer_text),Q=pA(t?.event_id)??pA(t?.header?.event_id)??pA(t?.uuid)??pA(t?.header?.uuid),y=JSON.stringify({messageId:c,resolvedAction:g,option:r,multiValues:s,source:B,formText:f}),m=g==="stop",_=g.startsWith("steer:")?g.slice(6):null,R=A==="steer"&&B==="quick"&&r!==null&&r!==Eu||A==="steer"&&B==="form"&&f!==null||_!==null&&_!==""&&!(_==="custom"||_===Eu);return this.#Je(d,y,async()=>{if(A==="steer"){if(B==="quick"&&r){if(r===Eu){await this.#W(d.chatId,Jv(),{key:d.key,updateMessageId:d.messageId});return}await this.#he(d,r);return}if(B==="form"){if(f){await this.#he(d,f);return}await this.#O(d.chatId,w("\u8BF7\u8F93\u5165\u8865\u5145\u6307\u4EE4\u540E\u518D\u63D0\u4EA4\u3002"));return}}await this.#ie(g,d)},{lane:m||R?"control":"regular",coalesceStop:m,eventId:Q,operatorOpenId:o})}#be(t=Date.now()){for(let[o,i]of this.#S)i<=t&&this.#S.delete(o);for(;this.#S.size>a6;){let o=this.#S.keys().next().value;if(o===void 0)break;this.#S.delete(o)}}#Me(t,o=Date.now()){t&&(this.#S.delete(t),this.#S.set(t,o+DRe),this.#be(o))}#je(t){let o=t.key,i=Date.now(),e=this.#Q.get(o);if(e?.task||e&&i-e.at{}).finally(()=>{this.#p.delete(a);let A=this.#Q.get(o);A?.task===a&&this.#Q.set(o,{at:A.at,task:null})}),this.#Q.delete(o),this.#Q.set(o,{at:i,task:a}),this.#p.add(a);this.#Q.size>200;){let A=this.#Q.keys().next().value;if(A===void 0)break;this.#Q.delete(A)}return a}#Je(t,o,i,{lane:e="regular",coalesceStop:a=!1,eventId:A=null,operatorOpenId:r=null}={}){let s=t.key,g=A?`${s}\0${r??""}\0event:${A}`:null,c=g??`${s}\0${r??""}\0action:${o}`,I=Date.now();if(this.#be(I),g&&(this.#S.get(g)??0)>I)return Promise.resolve();let d=this.#f.get(c);if(d)return d;if(a){let U=this.#B.get(s);if(U){if(g)for(this.#y.delete(g),this.#y.set(g,U);this.#y.size>a6;){let F=this.#y.keys().next().value;if(F===void 0)break;this.#y.delete(F)}return U}}let B=e==="control",f=B?this.#h:this.#d,Q=B?this.#C:this.#E,y=B?wRe:SRe,m=Q.get(s)??0,_=a?y+1:y;if(m>=_)return this.#je(t);let T=f.get(s)??Promise.resolve();Q.set(s,m+1);let R,L=!1;return R=T.catch(()=>{}).then(async()=>{this.#w?.throwIfAborted(),L=!0,await i()}).catch(async U=>{this.#w?.aborted||await this.#x(t.chatId,U,{logLabel:"card action"})}).finally(()=>{if(this.#f.get(c)===R&&this.#f.delete(c),L&&g&&this.#Me(g),a&&this.#B.get(s)===R&&this.#B.delete(s),a){let F=Date.now();for(let[q,z]of this.#y)z===R&&(this.#y.delete(q),this.#Me(q,F))}f.get(s)===R&&f.delete(s);let U=(Q.get(s)??1)-1;U>0?Q.set(s,U):Q.delete(s),this.#p.delete(R)}),this.#f.set(c,R),a&&this.#B.set(s,R),this.#p.add(R),f.set(s,R),R}async#ie(t,{chatId:o,key:i,messageId:e=null,sessionWorkspace:a=null,sessionPage:A=0,selections:r=[]}){if(t==="sessions"||/^sessions:\d+$/.test(t)){let s=t==="sessions"?0:Number(t.slice(9));await this.#ce({chatId:o,key:i},a,s,{updateMessageId:e});return}if(t==="workspaces"){await this.#_e({chatId:o,key:i},{updateMessageId:e});return}if(t==="watchlist"){await this.#Be(i,o,{updateMessageId:e});return}if(t==="watch_add"||t==="watch_remove"){if(r.length===0){await this.#O(o,w("\u8BF7\u5148\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u4F1A\u8BDD\u3002"));return}let s=0,g=0;if(t==="watch_add"){let I=new Map;try{I=await this.#gA(a)}catch(d){this.#D.warn?.("[dsh-feishu] batch watch validation failed:",d.message)}for(let d of r){let B=I.get(d);if(!B){g+=1;continue}let f=await this.#Ce(i,o,d,{notify:!1,validatedTarget:B});f.changed?s+=1:f.ok||(g+=1)}}else for(let I of r){let d=await this.#ue(i,o,I,{notify:!1});d.changed?s+=1:d.ok||(g+=1)}let c=s>0&&g>0?t==="watch_add"?w("\u5DF2\u6279\u91CF\u5173\u6CE8 {count} \u4E2A\u4F1A\u8BDD\uFF0C\u53E6\u6709 {failed} \u4E2A\u672A\u6210\u529F\u3002",{count:s,failed:g}):w("\u5DF2\u53D6\u6D88\u5173\u6CE8 {count} \u4E2A\u4F1A\u8BDD\uFF0C\u53E6\u6709 {failed} \u4E2A\u672A\u6210\u529F\u3002",{count:s,failed:g}):s>0?t==="watch_add"?w("\u5DF2\u6279\u91CF\u5173\u6CE8 {count} \u4E2A\u4F1A\u8BDD\u3002",{count:s}):w("\u5DF2\u53D6\u6D88\u5173\u6CE8 {count} \u4E2A\u4F1A\u8BDD\u3002",{count:s}):g>0?w("\u6240\u9009\u4F1A\u8BDD\u5747\u672A\u5904\u7406\u6210\u529F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):t==="watch_add"?w("\u6240\u9009\u4F1A\u8BDD\u5DF2\u5728\u5173\u6CE8\u5217\u8868\u4E2D\u3002"):w("\u6240\u9009\u4F1A\u8BDD\u5DF2\u4E0D\u5728\u5173\u6CE8\u5217\u8868\u4E2D\u3002");try{await this.#Be(i,o,{updateMessageId:e})}catch(I){this.#D.warn?.("[dsh-feishu] watch list refresh failed:",I.message)}await this.#O(o,c).catch(I=>{this.#D.warn?.("[dsh-feishu] watch batch summary failed:",I.message)});return}if(t==="new"){if(this.#a.has(i)||this.#ae(i)){await this.#O(o,w("\u5F53\u524D\u4EFB\u52A1\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u4EFB\u52A1\u6216\u7B49\u5F85\u4EFB\u52A1\u5B8C\u6210\u540E\u518D\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002"));return}await this.#r.clearSession(i),await this.#O(o,w("\u5DF2\u5F00\u542F\u5168\u65B0 Harness \u4F1A\u8BDD\u3002")),await this.#Z(i,o,{updateMessageId:e});return}if(t==="use:current"){let s=this.#r.sessionFor(i);if(typeof s!="string"||!s){await this.#O(o,w("\u5F53\u524D\u6CA1\u6709\u7ED1\u5B9A\u7684\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u4ECE\u4F1A\u8BDD\u5217\u8868\u9009\u62E9\u3002"));return}await this.#O(o,w("\u5DF2\u5C31\u7EEA\uFF0C\u76F4\u63A5\u53D1\u6D88\u606F\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"));return}if(t==="archive_toggle"||t==="archive:on"||t==="archive:off"){let s=t==="archive:on"?!0:t==="archive:off"?!1:!(this.#r?.includesArchivedSessions?.()??!1);await this.#r?.setIncludeArchivedSessions?.(s),await this.#O(o,s?w("\u5DF2\u5F00\u542F\uFF1A\u4F1A\u8BDD\u5217\u8868\u5305\u542B\u5F52\u6863\u4F1A\u8BDD\u3002"):w("\u5DF2\u5173\u95ED\uFF1A\u4F1A\u8BDD\u5217\u8868\u9690\u85CF\u5F52\u6863\u4F1A\u8BDD\u3002")),await this.#Z(i,o,{updateMessageId:e});return}if(t==="repair"){await this.#O(o,w("\u4FEE\u590D\u9700\u5728\u79C1\u804A\u4E2D\u9A8C\u8BC1\u63A5\u5165\u8005\u8EAB\u4EFD\uFF0C\u8BF7\u76F4\u63A5\u53D1\u9001 /repair \u5F00\u59CB\u3002"));return}if(t==="compact"){await this.#tA(i,o);return}if(t==="stop"){await this.#rA(i,o);return}if(t==="steer"){await this.#aA(i,o,{updateMessageId:e});return}if(t.startsWith("steer:")){let s=t.slice(6);if(s==="custom"){await this.#W(o,Jv(),{key:i,updateMessageId:e});return}await this.#he({key:i,chatId:o},s);return}if(t==="presets"){await this.#Ze(i,o,{updateMessageId:e});return}if(t==="models"){await this.#Xe(i,o,{updateMessageId:e});return}if(t==="status"){await this.#eA(i,o,{updateMessageId:e});return}if(t==="help"){await this.#AA(i,o,{updateMessageId:e});return}if(t==="back_to_menu"){await this.#Z(i,o,{updateMessageId:e});return}if(t==="preset_default"){await this.#Te(i,o,{updateMessageId:e});return}if(t.startsWith("preset:select:")){let s=t.slice(14);if(s===qm){await this.#Te(i,o,{updateMessageId:e});return}await this.#iA(i,o,s,{updateMessageId:e});return}if(t.startsWith("model:select:")){let s=t.slice(13);await this.#oA(i,o,s,{updateMessageId:e});return}if(t.startsWith("use:")){await this.#Ve(i,o,t.slice(4),{updateMessageId:e});return}if(t.startsWith("workspace:")){await this.#We(i,o,t.slice(10),{updateMessageId:e});return}if(t.startsWith("unwatch:")){(await this.#ue(i,o,t.slice(8))).ok&&e&&await this.#ce({chatId:o,key:i},a,A,{updateMessageId:e});return}if(t.startsWith("watch:")){let s=t.slice(6);(await this.#Ce(i,o,s,{workspaceHint:a})).ok&&e&&await this.#ce({chatId:o,key:i},a,A,{updateMessageId:e})}}#oe(t,o){if(this.#Y.size>=mRe){let i=this.#Y.keys().next().value;i!==void 0&&this.#Y.delete(i)}this.#Y.delete(t),this.#Y.set(t,{...o,expiresAt:Date.now()+yRe})}#qe(t){let o=this.#Y.get(t);return o?o.expiresAto.archived!==!0):t}async#ce({chatId:t,key:o,replyTo:i=null},e,a=0,{updateMessageId:A=null}={}){try{let r=this.#V(),s=await YM(e??"",this.#t,{signal:r});if(s.error){await this.#O(t,s.error,{replyTo:i});return}let g=await this.#t.listWorkspaceSessions(s.workspace,{signal:r}),c=this.#ne(Array.isArray(g?.sessions)?g.sessions:[]),I=g?.workspace??s.workspace;if(c.length===0){await this.#O(t,w(`\u5DE5\u4F5C\u533A\uFF1A{workspace} +\u8BE5\u5DE5\u4F5C\u533A\u6682\u65E0\u4F1A\u8BDD\u3002`,{workspace:I}),{replyTo:i});return}let d=Math.ceil(c.length/wc),B=Number.isSafeInteger(a)&&a>0?Math.min(a,d-1):0,f=new Set((this.#r.watchEntries?.(o)??[]).map(y=>y.sessionId)),Q=c.slice(B*wc,(B+1)*wc);this.#oe(o,{kind:"sessions",sessions:Q.map(y=>({...y,watched:f.has(y.sessionId)}))}),await this.#W(t,WW(I,c,B,c.length,f),{key:o,updateMessageId:A,replyTo:i,sessionWorkspace:s.workspace,sessionPage:B})}catch(r){await this.#x(t,r,{logLabel:"session list"})}}async#_e({chatId:t,key:o,replyTo:i=null},{updateMessageId:e=null}={}){try{let{current:a,paths:A}=await _E(this.#t,{signal:this.#V()});this.#oe(o,{kind:"workspaces",paths:A}),await this.#W(t,ZW(A,a),{key:o,updateMessageId:e,replyTo:i})}catch(a){await this.#x(t,a,{logLabel:"workspace list"})}}async#Ve(t,o,i,{updateMessageId:e=null}={}){try{let a=await this.#t.bindWorkspaceSession(t,i),A=String(a?.title??"").replace(/\s+/gu," ").trim()||w("\u6682\u65E0\u6807\u9898");await this.#O(o,[w(`\u5DF2\u7ED1\u5B9A\u4F1A\u8BDD\u300C{title}\u300D ID\uFF1A{id}`,{title:A,id:a?.sessionId??i}),w("\u53D1\u9001 /history \u67E5\u770B\u6700\u8FD1\u5BF9\u8BDD\u3002")].join(` -`)),await this.#Z(t,o,{updateMessageId:e})}catch(a){await this.#x(o,a,{logLabel:"session binding",userMessage:w("\u7ED1\u5B9A\u5931\u8D25\uFF1A{message}",{message:Cu(a)})})}}async#We(t,o,i,{updateMessageId:e=null}={}){try{let a=await this.#t.switchWorkspace(i);await this.#O(o,w("\u5DE5\u4F5C\u533A\u5DF2\u5207\u6362\u4E3A\uFF1A{workspace}",{workspace:a})),await this.#Z(t,o,{updateMessageId:e})}catch(a){await this.#x(o,a,{logLabel:"workspace switch",userMessage:w("\u5207\u6362\u5931\u8D25\uFF1A{message}",{message:Cu(a)})})}}#_e(t,o,i){if(!(!i.key||!t)&&(this.#H.delete(t),this.#H.set(t,{key:i.key,chatId:o,sessionWorkspace:typeof i.sessionWorkspace=="string"&&i.sessionWorkspace?i.sessionWorkspace:null,sessionPage:Number.isSafeInteger(i.sessionPage)&&i.sessionPage>=0?i.sessionPage:0}),this.#H.size>200)){let e=this.#H.keys().next().value;e!==void 0&&this.#H.delete(e)}}async#W(t,o,i={}){let e=hA(i.updateMessageId);if(e)try{let r=await this.#e.im.v1.message.patch({path:{message_id:e},data:{content:o}});if(r?.code&&r.code!==0)throw new Error(`Feishu card update failed: ${r.msg||r.code}`);return this.#_e(e,t,i),e}catch(r){this.#D.warn?.("[dsh-feishu] card update failed:",r?.code??r?.message??r,"sending new")}let a=await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"interactive",content:o}});if(a?.code&&a.code!==0)throw new Error(`Feishu card send failed: ${a.msg||a.code}`);let A=hA(a?.data?.message_id);return this.#_e(A,t,i),A}async#Z(t,o,{updateMessageId:i=null}={}){let e=null,a=null;try{let F=this.#r.sessionFor(t);if(typeof F=="string"&&F){e=F;let K=this.#t.workspaceSession?.(F);a=hA(K?.title)??hA(K?.name)??hA(K?.displayName)}}catch{}let A=this.#V(),r=_E(this.#t,{signal:A}).catch(()=>{let F=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;return{current:F,paths:F?[F]:[]}}),s=(async()=>{let F=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;if(!F||typeof this.#t.listWorkspaceSessions!="function")return[];try{let K=await this.#t.listWorkspaceSessions(F,{signal:A});return this.#ne(Array.isArray(K?.sessions)?K.sessions:[])}catch{return[]}})(),g=(async()=>{try{let F=await this.#t.agentPresetSettings({signal:A});return{...F.agentPresetCatalog,_currentId:F.agentPreset}}catch{return null}})(),c=(async()=>{try{if(e){let F=this.#t.workspaceSession?.(e);if(typeof F?.models=="function")return await F.models({signal:A})}return await this.#t.listModels({signal:A})}catch{return null}})(),[I,d,B,f]=await Promise.all([r,s,g,c]),Q=Array.isArray(I.paths)?I.paths:[],y=I.current??null,m=d.find(F=>F.sessionId===e),_=e?hA(m?.title)??hA(m?.name)??a??e:null,T=d.map(F=>({id:F.sessionId,title:F.title??F.name??F.sessionId})).slice(0,20);e&&(T=T.filter(F=>F.id!==e),T.unshift({id:e,title:_??e}),T=T.slice(0,20));let R=this.#r?.includesArchivedSessions?.()??!1;this.#oe(t,{kind:"menu",chatId:o}),await this.#W(o,xW({workspaces:Q,currentWorkspace:y,currentSession:e?{id:e,title:_}:null,sessions:T,archiveVisible:R,presetCatalog:B,modelCatalog:f}),{key:t,updateMessageId:i})}async#uA(t,o){try{if(typeof this.#t.workspaceSession=="function"){let e=this.#t.workspaceSession(o);if(e&&typeof e=="object"){let a=hA(e.title)??hA(e.name)??hA(e.displayName);if(a)return a}}let i=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;if(i&&typeof this.#t.listWorkspaceSessions=="function"){let e=await this.#t.listWorkspaceSessions(i),a=(Array.isArray(e?.sessions)?e.sessions:[]).find(A=>A.sessionId===o);if(a){let A=hA(a.title)??hA(a.name);if(A)return A}}}catch{}return null}async#Ze(t,o,{updateMessageId:i=null}={}){try{let e=await this.#t.agentPresetSettings({signal:this.#V()}),a=e.agentPresetCatalog;a._currentId=e.agentPreset,await this.#W(o,YW(a),{key:t,updateMessageId:i})}catch(e){await this.#x(o,e,{logLabel:"preset card"})}}async#Xe(t,o,{updateMessageId:i=null}={}){try{let e=this.#V();await this.#t.ensureRunning({signal:e});let a=this.#r?.sessionFor?.(t),A;if(typeof a=="string"&&a){let r=this.#t.workspaceSession(a);r?.models&&(A=await r.models({signal:e}))}A||(A=await this.#t.listModels({signal:e})),await this.#W(o,jW(A),{key:t,updateMessageId:i})}catch(e){await this.#x(o,e,{logLabel:"model card"})}}async#$e(t,o){try{await this.#t.ensureRunning({signal:this.#w});let i=[w("\u8FDE\u63A5\u6B63\u5E38")],e=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;e&&i.push(w("\u5DE5\u4F5C\u533A\uFF1A{workspace}",{workspace:e}));let a=typeof this.#t.agentPresetSettings=="function"?await this.#t.agentPresetSettings({signal:this.#w}).catch(()=>null):null;if(a){let A=a.agentPresetCatalog?.items?.find(r=>r.id===a.agentPreset);i.push(w("\u9884\u8BBE\uFF1A{preset}",{preset:A?`${A.label}\uFF08${A.id}\uFF09`:a.agentPreset||w("\u8DDF\u968F\u9ED8\u8BA4")}))}await this.#O(o,i.join(` -`))}catch(i){await this.#x(o,i,{logLabel:"status text"})}}async#eA(t,o,{updateMessageId:i=null}={}){try{let e=this.#V();await this.#t.ensureRunning({signal:e});let a={connected:!0,workspace:null,preset:null,model:null,sessionCount:0};try{let A=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;a.workspace=A||w("\u672A\u77E5")}catch{}try{let A=await this.#t.agentPresetSettings({signal:e}),r=A.agentPresetCatalog.items.find(s=>s.id===A.agentPreset);a.preset=r?`${r.label}\uFF08${r.id}\uFF09`:A.agentPreset||w("\u8DDF\u968F\u9ED8\u8BA4")}catch{}try{let A=this.#r?.sessionFor?.(t);if(typeof A=="string"&&A){let r=this.#t.workspaceSession(A);if(r?.models){let s=await r.models({signal:e});s.current&&(a.model=`${s.current.provider}/${s.current.model}`)}}}catch{}try{let A=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;if(A){let r=await this.#t.listWorkspaceSessions(A,{signal:e});Array.isArray(r?.sessions)&&(a.sessionCount=r.sessions.length)}}catch{}await this.#W(o,JW(a),{key:t,updateMessageId:i})}catch(e){await this.#x(o,e,{logLabel:"status card"})}}async#AA(t,o,{updateMessageId:i=null}={}){await this.#W(o,zW(GRe.map(e=>w(e))),{key:t,updateMessageId:i})}async#tA(t,o){try{let i=await Bi("/compact",this.#t,this.#r,t,{signal:this.#w});await this.#O(o,i?.message||w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\u3002"))}catch(i){await this.#x(o,i,{logLabel:"compact"})}}async#rA(t,o){try{let i=await Qi("/stop",this.#t,this.#r,t,{signal:this.#w,control:{owner:this,key:t}});i?.stopped&&await Promise.allSettled([this.#Se(t),this.#m.closeRoute(t)]),await this.#O(o,i?.message||w("/stop \u6267\u884C\u5B8C\u6210\u3002"))}catch(i){await this.#x(o,i,{logLabel:"stop"})}}async#aA(t,o,{updateMessageId:i=null}={}){let e=!!this.#r.sessionFor?.(t);this.#oe(t,{kind:"steer"}),await this.#W(o,A6({hasSession:e}),{key:t,updateMessageId:i})}async#de(t,o){let{key:i,chatId:e}=t,a=await Qi(`/steer ${o}`,this.#t,this.#r,i,{signal:this.#w,pendingInteraction:this.#ae(i),control:{owner:this,key:i}});await this.#O(e,a?.message||w("\u5DF2\u63D0\u4EA4\u8865\u5145\u6307\u4EE4\u3002"))}async#Te(t,o,{updateMessageId:i=null}={}){try{let e=await yi("/preset --default",this.#t,this.#r,t,{signal:this.#w});for(let a of e?.messages??[e?.message])a&&await this.#O(o,a)}catch(e){await this.#x(o,e,{logLabel:"preset reset"});return}try{await this.#Z(t,o,{updateMessageId:i})}catch(e){this.#D.warn?.("[dsh-feishu] menu refresh failed after preset reset:",e.message)}}async#iA(t,o,i,{updateMessageId:e=null}={}){try{let a=/^\d+$/u.test(i)?`id:${i}`:i,A=await yi(`/preset ${a}`,this.#t,this.#r,t,{signal:this.#w});for(let r of A?.messages??[A?.message])r&&await this.#O(o,r)}catch(a){await this.#x(o,a,{logLabel:"preset selection"});return}try{await this.#Z(t,o,{updateMessageId:e})}catch(a){this.#D.warn?.("[dsh-feishu] menu refresh failed after preset select:",a.message)}}async#oA(t,o,i,{updateMessageId:e=null}={}){try{let a=await Wi(`/model ${i}`,this.#t,this.#r,t,{signal:this.#w,pendingInteraction:this.#ae(t),control:{owner:this,key:t}});for(let A of a?.messages??[a?.message])A&&await this.#O(o,A)}catch(a){await this.#x(o,a,{logLabel:"model selection"});return}try{await this.#Z(t,o,{updateMessageId:e})}catch(a){this.#D.warn?.("[dsh-feishu] menu refresh failed after model select:",a.message)}}#Ne(){if(this.#q||typeof this.#t?.watchHarnessEvents!="function"||this.#w?.aborted)return;let t=this.#w??new AbortController().signal;try{this.#q=this.#t.watchHarnessEvents({signal:t,onSessionEvent:o=>this.#cA(o),onReconnect:()=>{this.#IA()}}),Promise.resolve(this.#q).catch(o=>{t.aborted||this.#D.warn?.("[dsh-feishu] event watcher stopped:",o.message)})}catch(o){this.#q=null,this.#D.warn?.("[dsh-feishu] event watcher failed to start:",o.message)}}#Re(t,o){let i=this.#z.get(t)??Promise.resolve(),e;return e=i.then(o,o).catch(a=>{this.#w?.aborted||this.#D.warn?.("[dsh-feishu] completion event failed:",a.message)}).finally(()=>{this.#z.get(t)===e&&this.#z.delete(t)}),this.#z.set(t,e),e}#he(t=Date.now()){let o=0;for(let[i,e]of this.#K){for(let[a,A]of e)(!Number.isSafeInteger(A?.arrivalAt)||A.arrivalAt<0||A.arrivalAt+ORe<=t)&&e.delete(a);for(;e.size>MRe;){let a=e.keys().next().value;if(a===void 0)break;e.delete(a)}e.size===0?this.#K.delete(i):o+=e.size}for(;this.#K.size>bRe;){let i=this.#K.keys().next().value;if(i===void 0)break;o-=this.#K.get(i)?.size??0,this.#K.delete(i)}for(;o>_Re;){let i=this.#K.keys().next().value;if(i===void 0)break;let e=this.#K.get(i),a=e?.keys().next().value;if(a===void 0){this.#K.delete(i);continue}e.delete(a),o-=1,e.size===0&&this.#K.delete(i)}}#nA(t,o,i=Date.now()){this.#he(i);let e=this.#K.get(t);e||(e=new Map);let a=o?.data?.reason,A=typeof a=="string"?a:typeof a?.kind=="string"?{kind:a.kind}:null;e.delete(o.seq),e.set(o.seq,{arrivalAt:i,event:{type:"turn/end",seq:o.seq,...Number.isSafeInteger(o.time)&&o.time>=0?{time:o.time}:{},data:{reason:A}}}),this.#K.delete(t),this.#K.set(t,e),this.#he(i)}async#sA(t,{workspaceHint:o=null,signal:i=this.#w}={}){if(typeof t!="string"||t==="")return{error:w("\u7528\u6CD5\uFF1A/watch ")};let e=/^\d{1,4}$/.test(t)?Number(t):null,a=typeof this.#t?.currentWorkspace=="function"?this.#t.currentWorkspace():null,A=async s=>{let g=await this.#t.listWorkspaceSessions(s,{signal:i});return Array.isArray(g?.sessions)?g.sessions:[]};if(e!==null){if(!a)return{error:w("\u5F53\u524D\u673A\u5668\u4EBA\u6CA1\u6709\u53EF\u7528\u7684\u5DE5\u4F5C\u533A\uFF0C\u65E0\u6CD5\u6309\u5E8F\u53F7\u89E3\u6790\u4F1A\u8BDD\u3002")};let s=this.#ne(await A(a)),g=s[e-1];return g?.sessionId?{sessionId:g.sessionId,title:g.title??w("\u6682\u65E0\u6807\u9898"),workspace:a,...Qn(g.lastSeq)?{lastSeq:g.lastSeq}:{}}:{error:w("\u5F53\u524D\u5DE5\u4F5C\u533A\u53EA\u6709 {count} \u4E2A\u4F1A\u8BDD\u3002",{count:s.length})}}let r;if(hA(o))r=[o];else{let s=typeof this.#t?.listWorkspaces=="function"?(await this.#t.listWorkspaces({signal:i})).filter(g=>g!==a):[];r=[a,...s].filter(Boolean)}for(let s of r){let c=(await A(s)).find(I=>I.sessionId===t);if(c)return{sessionId:t,title:c.title??w("\u6682\u65E0\u6807\u9898"),workspace:s,...Qn(c.lastSeq)?{lastSeq:c.lastSeq}:{}}}return{error:w("\u6CA1\u6709\u627E\u5230\u8FD9\u4E2A\u4F1A\u8BDD\uFF0C\u8BF7\u7528 /sessionlist \u67E5\u770B\u53EF\u7528\u4F1A\u8BDD\u3002")}}async#gA(t){let o=hA(t)??(typeof this.#t?.currentWorkspace=="function"?hA(this.#t.currentWorkspace()):null);if(!o||typeof this.#t?.listWorkspaceSessions!="function")return new Map;let i=await this.#t.listWorkspaceSessions(o,{signal:this.#V()});return new Map(this.#ne(Array.isArray(i?.sessions)?i.sessions:[]).filter(e=>hA(e?.sessionId)).map(e=>[e.sessionId,{sessionId:e.sessionId,title:e.title??e.name??w("\u6682\u65E0\u6807\u9898"),workspace:o,...Qn(e.lastSeq)?{lastSeq:e.lastSeq}:{}}]))}#ke(t){let o=this.#F.get(t);if(o)return o.requested=!0,o.promise;let i={requested:!0,promise:null};return this.#F.set(t,i),i.promise=Promise.resolve().then(async()=>{try{do i.requested=!1,await this.#Re(t,()=>this.#Pe(t));while(i.requested&&!this.#w?.aborted)}finally{this.#F.get(t)===i&&this.#F.delete(t)}}),i.promise}async#Ee(t,o,i,{notify:e=!0,validatedTarget:a=null,workspaceHint:A=null}={}){let r=Date.now(),s=async Q=>{e&&await this.#O(o,Q).catch(y=>{this.#D.warn?.("[dsh-feishu] watch notification failed:",y.message)})};if(this.#Ne(),typeof this.#r?.setWatch!="function")return await s(w("\u5F53\u524D\u72B6\u6001\u5B58\u50A8\u4E0D\u652F\u6301\u5173\u6CE8\u3002")),{ok:!1,changed:!1,reason:"unsupported"};let g;try{g=a?.sessionId===i?a:await this.#sA(i,{workspaceHint:A,signal:A?this.#V():this.#w})}catch(Q){return await s(w("\u65E0\u6CD5\u89E3\u6790\u4F1A\u8BDD\uFF1A{message}",{message:Cu(Q)})),{ok:!1,changed:!1,reason:"resolve"}}if(g.error)return await s(g.error),{ok:!1,changed:!1,reason:"not-found"};let c=this.#r.watchEntries?.(t)??[],I=c.find(Q=>Q.sessionId===g.sessionId);if(!I&&c.length>=Zm)return await s(w("\u6BCF\u4E2A\u804A\u5929\u6700\u591A\u5173\u6CE8 {count} \u4E2A\u4F1A\u8BDD\u3002",{count:Zm})),{ok:!1,changed:!1,reason:"limit"};let d=Qn(I?.lastSeq)?I.lastSeq:Qn(g.lastSeq)?g.lastSeq:null,f=rS(I)??(I?null:r);try{await this.#r.setWatch(t,{sessionId:g.sessionId,title:g.title,chatId:o,lastSeq:d,...f!==null?{watchStartedAt:f}:{}})}catch(Q){return await s(w("\u5173\u6CE8\u5931\u8D25\uFF1A{message}",{message:Cu(Q)})),{ok:!1,changed:!1,reason:"persist"}}return(!I||f!==null||!Qn(d))&&this.#ke(g.sessionId),await s(w("\u5DF2\u5173\u6CE8\u4F1A\u8BDD\u300C{title}\u300D\uFF0C\u4EFB\u52A1\u5B8C\u6210\u4F1A\u63A8\u9001\u7ED3\u679C\u3002",{title:String(g.title).replace(/\s+/gu," ")})),{ok:!0,changed:!I,entry:this.#r.watchEntry?.(t,g.sessionId)}}async#Ce(t,o,i,{notify:e=!0}={}){let a=async s=>{e&&await this.#O(o,s).catch(g=>{this.#D.warn?.("[dsh-feishu] unwatch notification failed:",g.message)})};if(typeof this.#r?.removeWatch!="function")return{ok:!1,changed:!1,reason:"unsupported"};let A=this.#r.watchEntries?.(t)??[],r=typeof i=="string"&&/^\d{1,4}$/.test(i)?A[Number(i)-1]:A.find(s=>s.sessionId===i);if(!r)return await a(w("\u5173\u6CE8\u5217\u8868\u91CC\u6CA1\u6709\u8FD9\u4E2A\u4F1A\u8BDD\uFF0C\u56DE\u590D /watchlist \u67E5\u770B\u3002")),{ok:!0,changed:!1,reason:"absent"};try{await this.#r.removeWatch(t,r.sessionId),this.#G.delete(`${t}\0${r.sessionId}`)}catch(s){return await a(w("\u53D6\u6D88\u5931\u8D25\uFF1A{message}",{message:Cu(s)})),{ok:!1,changed:!1,reason:"persist"}}return await a(w("\u5DF2\u53D6\u6D88\u5173\u6CE8\u300C{title}\u300D\u3002",{title:String(r.title??"").replace(/\s+/gu," ")})),{ok:!0,changed:!0,entry:r}}async#ue(t,o,{updateMessageId:i=null}={}){let e=this.#r.watchEntries?.(t)??[],a=[],A=null;try{if(A=typeof this.#t?.currentWorkspace=="function"?this.#t.currentWorkspace():null,A&&typeof this.#t?.listWorkspaceSessions=="function"){let r=await this.#t.listWorkspaceSessions(A,{signal:this.#V()});a=this.#ne(Array.isArray(r?.sessions)?r.sessions:[]).map(s=>({sessionId:s.sessionId,title:s.title??s.name??s.sessionId}))}}catch{}this.#oe(t,{kind:"watches",entries:e}),await this.#W(o,XW(e,a),{key:t,updateMessageId:i,sessionWorkspace:A})}#cA({sessionId:t,event:o}){this.#w?.aborted||!t||!o||typeof o!="object"||o.type!=="turn/end"||!fu(o.seq)||(this.#nA(t,o),this.#Re(t,async()=>{let i=this.#r.keysWatching?.(t)??[],e=i.some(A=>tS(this.#r.watchEntry?.(A,t))),a=i.some(A=>this.#G.has(`${A}\0${t}`));(e||a)&&await this.#Pe(t),await this.#ve(t,o)}))}async#ve(t,o,{keys:i=null}={}){if(this.#w?.aborted||typeof this.#r?.keysWatching!="function")return;let e=o?.data?.reason?.kind??o?.data?.reason??null,a=i??this.#r.keysWatching(t);for(let A of a){if(this.#w?.aborted)return;let r=this.#r.watchEntry?.(A,t),s=`${A}\0${t}`,g=this.#G.get(s);if(fu(g)&&Qn(r?.lastSeq)&&r.lastSeq>=g&&(this.#G.delete(s),g=void 0),!(!r?.chatId||tS(r)||Qn(r.lastSeq)&&r.lastSeq>=o.seq||fu(g)&&o.seq>g))try{await this.#W(r.chatId,$W(t,r.title,e),{key:A});let c=this.#r.watchEntry?.(A,t);if(!c||c.chatId!==r.chatId||tS(c)||Qn(c.lastSeq)&&c.lastSeq>=o.seq)continue;await this.#r.setWatch(A,{...c,lastSeq:o.seq}),g===o.seq&&this.#G.delete(s)}catch(c){this.#G.set(s,fu(g)?Math.min(g,o.seq):o.seq),this.#D.warn?.("[dsh-feishu] completion push failed:",c.message)}}}async#Pe(t){if(!(this.#w?.aborted||typeof this.#t?.rpc!="function"))try{let o=await this.#t.rpc("session.history",{sessionId:t,maxMessages:20},3e4,{signal:this.#w}),i=LRe(o);this.#he();let e=this.#K.get(t)??new Map,a=new Map(i.map(g=>[g.seq,g]));for(let[g,c]of e)a.has(g)||a.set(g,c.event);let A=[...a.values()].sort((g,c)=>g.seq-c.seq),r=A.at(-1)?.seq??-1,s=typeof this.#r?.keysWatching=="function"?this.#r.keysWatching(t):[];for(let g of s){let c=this.#r.watchEntry?.(g,t);if(!tS(c))continue;let I=rS(c),d=Qn(c.lastSeq)?c.lastSeq:-1,B=I===null?null:A.find(_=>{if(_.seq<=d)return!1;let T=Number.isSafeInteger(_.time)&&_.time>=0?_.time:e.get(_.seq)?.arrivalAt;return Number.isSafeInteger(T)&&T>=I}),f=B?Math.max(d,B.seq-1):Math.max(d,r),Q=this.#r.watchEntry?.(g,t);if(!Q||Q.chatId!==c.chatId||Q.lastSeq!==c.lastSeq||rS(Q)!==I)continue;let{watchStartedAt:y,...m}=Q;await this.#r.setWatch(g,{...m,lastSeq:f})}for(let g of A)g.type==="turn/end"&&await this.#ve(t,g,{keys:s})}catch(o){this.#w?.aborted||this.#D.warn?.(`[dsh-feishu] watch compensation failed for ${t}:`,o.message)}}async#IA(){let t=typeof this.#r?.watchedSessionIds=="function"?this.#r.watchedSessionIds():[];this.#w?.aborted||await Promise.allSettled(t.map(o=>this.#ke(o)))}#Be(t,o,i){return{timeoutMs:this.#R,signal:this.#w,control:{owner:this,key:o},onInteraction:e=>this.#dA(e,{key:o,actor:Qu(t),chatId:t.message.chat_id,requiresMention:t.message.chat_type!=="p2p",replyToMessageId:t.message.message_id}),onInteractionResolved:e=>this.#hA(e),files:i}}async#fe(t,o,{deliveryId:i,presentation:e}){let a=[];for(let A of UW(o)){this.#w?.throwIfAborted();let r=await this.#O(t,A);r&&a.push(r)}return Zt({deliveryId:i,presentation:e,providerMessageIds:a})}async#Ie(t,o,i=[],e){let a=await bo({artifacts:i,baseReceipt:e,deliveryId:e?.deliveryId??i[0]?.deliveryKey??o,aggregatePresentation:e?"feishu-text-and-files":"feishu-files",channelKey:"feishu",signal:this.#w,sendImage:typeof this.#A?.sendImage=="function"?A=>this.#A.sendImage(t,A,{replyTo:o,signal:this.#w}):void 0,sendFile:typeof this.#A?.sendFile=="function"?A=>this.#A.sendFile(t,A,{replyTo:o,signal:this.#w}):void 0,onFailure:(A,r)=>tt(this.#u,r,{userMessage:FRe(A?.fileName,r),reason:r?.code}),sendFailureNotice:async(A,r,s)=>({messageId:await this.#O(t,dt(s))}),logger:this.#D});return this.#u.artifactsSent=(this.#u.artifactsSent??0)+a.artifactsSent,this.#u.artifactSendErrors=(this.#u.artifactSendErrors??0)+a.artifactSendErrors,a.receipt?{receipt:a.receipt,failureNoticeVisible:a.failureNoticeVisible,artifactSendErrors:a.artifactSendErrors}:{receipt:Zt({deliveryId:o,presentation:"feishu-files"}),failureNoticeVisible:a.failureNoticeVisible,artifactSendErrors:a.artifactSendErrors}}async#lA(t,o,i,{onAskComplete:e}={}){let a=t.message.chat_id,A=t.message.message_id,r=i.content,s=!1,g=()=>{s||(s=!0,e?.())},c=Wt(i)?await Bo(i,{signal:this.#w}):void 0,I=this.#o.get(A);if(I&&(c=mo(c??r,I,()=>({channel:"feishu",senderId:Qu(t)}))),!this.#A?.stream){let{answer:m,artifacts:_=[]}=await ui({harness:this.#t,state:this.#r,key:o,text:r,content:c,createOptions:{signal:this.#w},existsOptions:{signal:this.#w},askOptions:this.#Be(t,o,i.files)});g();let T,R=null;try{T=await this.#fe(a,AS(m,_),{deliveryId:A,presentation:"feishu-text"})}catch(L){R=Ma(L),this.#D.warn?.("[dsh-feishu] final text delivery failed; continuing with result files:",L)}let F=await this.#Ie(a,A,_,T),K=F.receipt.artifacts.some(({outcome:L})=>L==="sent"||L==="unknown");if(R&&!K&&!F.failureNoticeVisible)throw R;return R&&F.artifactSendErrors===0&&tt(this.#u,R),this.#u.streamFallbacks=(this.#u.streamFallbacks??0)+1,{...F,textDeliveryErrors:R?1:0}}let d=!1,B="",f=[],Q;try{Q=await this.#A.stream(a,{markdown:async m=>{d=!0;let _={...this.#Be(t,o,i.files),onUpdate:async R=>{await m.setContent(this.#EA(R)),this.#u.streamUpdates=(this.#u.streamUpdates??0)+1}},T=await ui({harness:this.#t,state:this.#r,key:o,text:r,content:c,createOptions:{signal:this.#w},existsOptions:{signal:this.#w},askOptions:_});g(),B=T.answer,f=T.artifacts??[],await m.setContent(AS(B,f))}},{replyTo:A})}catch(m){if(this.#u.streamErrors=(this.#u.streamErrors??0)+1,B||f.length>0){this.#D.warn?.("[dsh-feishu] native stream failed after generation; sending final text:",m.message);let q,z=null;try{q=await this.#fe(a,AS(B,f),{deliveryId:A,presentation:"feishu-text-fallback"})}catch(J){z=Ma(J),this.#D.warn?.("[dsh-feishu] fallback text delivery failed; continuing with result files:",J)}let j=await this.#Ie(a,A,f,q),P=j.receipt.artifacts.some(({outcome:J})=>J==="sent"||J==="unknown");if(z&&!P&&!j.failureNoticeVisible)throw z;return z&&j.artifactSendErrors===0&&tt(this.#u,z),this.#u.streamFallbacks=(this.#u.streamFallbacks??0)+1,{...j,textDeliveryErrors:z?1:0}}if(d)throw m;this.#D.warn?.("[dsh-feishu] native stream unavailable; using text fallback:",m.message);let{answer:_,artifacts:T=[]}=await ui({harness:this.#t,state:this.#r,key:o,text:r,content:c,createOptions:{signal:this.#w},existsOptions:{signal:this.#w},askOptions:this.#Be(t,o,i.files)});g();let R,F=null;try{R=await this.#fe(a,AS(_,T),{deliveryId:A,presentation:"feishu-text-fallback"})}catch(q){F=Ma(q),this.#D.warn?.("[dsh-feishu] fallback text delivery failed; continuing with result files:",q)}let K=await this.#Ie(a,A,T,R),L=K.receipt.artifacts.some(({outcome:q})=>q==="sent"||q==="unknown");if(F&&!L&&!K.failureNoticeVisible)throw F;return F&&K.artifactSendErrors===0&&tt(this.#u,F),this.#u.streamFallbacks=(this.#u.streamFallbacks??0)+1,{...K,textDeliveryErrors:F?1:0}}let y=await this.#Ie(a,A,f,Zt({deliveryId:A,presentation:"feishu-cardkit",providerMessageIds:ka(Q)}));return this.#u.streamResponses=(this.#u.streamResponses??0)+1,y}async#pA(t,o,i,e,a){this.#w?.throwIfAborted();let A=this.#i.get(i),r=e.claimedReplyMessageId===o;if(!A||A!==e||A.submitting)return this.#Qe(t,i)?this.#ye(t,o):r&&(!A||A!==e)?this.#ye(t,o):this.#j(t,o,i,a,{releaseMessageId:!1,finalize:!1});if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1;let s=_d(t);if(!s){await this.#O(t.message.chat_id,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002"));return}let g=this.#i.get(i);if(!g||g!==e||g.submitting){if(this.#Qe(t,i)){await this.#O(t.message.chat_id,$m(),{replyTo:t.message.message_id}).catch(()=>{});return}if(r&&(!g||g!==e)){await this.#O(t.message.chat_id,$m(),{replyTo:t.message.message_id});return}return this.#j(t,o,i,a,{releaseMessageId:!1,alreadyRecorded:!0,finalize:!1})}if(g.chatId=t.message.chat_id,g.needsPresentation){try{await this.#le(g)}catch{this.#u.lastError="\u98DE\u4E66\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#D.error?.("[dsh-feishu] failed to retry an interaction question"),g.interaction.reconnect?.()}return}let c=g.questions[g.index];if(c){if(g.answers.push(Ei(c,s)),g.index+=1,g.index{});return}g.submitting=!1,g.answers.pop(),g.index-=1,this.#u.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#D.error?.("[dsh-feishu] failed to answer a Harness interaction"),await this.#O(t.message.chat_id,w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002")).catch(()=>{})}}}async#dA(t,{key:o,actor:i,chatId:e,requiresMention:a,replyToMessageId:A}){if(await this.#m.handleRequested(t,{key:o,actor:i,requiresMention:a,send:I=>this.#O(e,I)})||t?.kind!=="question")return;let r=t?.payload?.questions,s=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t.rpcId!="string"||typeof s!="string"||typeof t.sessionId!="string"||!Array.isArray(r)||r.length===0||r.some(I=>!di(I))){this.#D.warn?.("[dsh-feishu] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"Feishu safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#O(e,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002"),{replyTo:A}).catch(()=>{});return}let g=this.#i.get(o);if(g?.interactionId===s){g.interaction=t,g.needsPresentation&&await this.#le(g);return}if(this.#I.has(s))return;if(g){await t.respond({ok:!1,error:{code:"cancelled",message:"Feishu is already handling another user interaction.",details:{}}});return}let c={kind:"question",interactionId:s,sessionId:t.sessionId,interaction:t,key:o,actor:i,requiresMention:a,questions:r,answers:[],index:0,chatId:e,replyToMessageId:A,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,questionMessageIds:new Set,inactive:!1};this.#i.set(o,c),this.#I.set(c.interactionId,o),await this.#le(c)}async#hA(t){if(await this.#m.handleResolved(t))return;let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#I.get(o);if(!i)return;let e=this.#i.get(i);e&&this.#se(i,e),this.#me(i,o)}async#le(t){let o=t.questions[t.index];if(!o)return;let i=await this.#O(t.chatId,hi(o,t.index,t.questions.length,{requiresMention:t.requiresMention}),{replyTo:t.replyToMessageId});i&&(t.questionMessageIds.add(i),t.inactive&&this.#se(t.key,t)),t.needsPresentation=!1}#se(t,o){let i=Date.now()+dRe;for(let e of o.questionMessageIds??[])this.#l.set(e,{key:t,expiresAt:i})}#Qe(t,o){let i=Date.now();for(let[e,a]of this.#l)a.expiresAt<=i&&this.#l.delete(e);for(let e of[t?.message?.parent_id,t?.message?.root_id]){let a=this.#l.get(e);if(a?.key===o&&a.expiresAt>i)return!0}return!1}async#ye(t,o){this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1,await this.#O(t.message.chat_id,$m(),{replyTo:t.message.message_id}).catch(()=>{}))}#Ge(t,o){let i=this.#i.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#i.delete(t),this.#I.delete(i.interactionId),i.inactive=!0,i)}#me(t,o){return this.#Ge(t,o)!==null}async#Se(t){let o=this.#Ge(t);if(!(!o||o.kind!=="question")){this.#se(t,o);try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Feishu interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#D.warn?.("[dsh-feishu] failed to cancel a pending Harness interaction")}}}#EA(t){return t.type==="text"&&t.text?t.text:t.type==="tool"?t.name==="web_search"?w("_\u6B63\u5728\u641C\u7D22\u7F51\u7EDC\u5E76\u6574\u7406\u4FE1\u606F\u2026_"):w("_\u6B63\u5728\u4F7F\u7528 {name}\u2026_",{name:t.name||w("\u5DE5\u5177")}):w("_{text}_",{text:t.text||w("\u6B63\u5728\u5904\u7406\u2026")})}#CA(t){return PQ({adapter:this.#A,target:t,reactions:{processing:"OnIt",success:"DONE",error:"ERROR"},status:this.#u,logger:this.#D,label:"feishu"})}#Fe(t,o){o.clear()}#ee(t,o,i){i==="ERROR"?o.error():o.success()}async#O(t,o,{replyTo:i}={}){let e=JSON.stringify({text:o});if(i)try{let A=await this.#e.im.v1.message.reply({path:{message_id:i},data:{msg_type:"text",content:e}});if(A?.code&&A.code!==0)throw new Error(`Feishu reply failed: ${A.msg||A.code}`);return hA(A?.data?.message_id)}catch(A){this.#D.warn?.("[dsh-feishu] threaded reply failed; falling back to a plain message:",A?.message??String(A))}let a=await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"text",content:e}});if(a?.code&&a.code!==0)throw new Error(`Feishu send failed: ${a.msg||a.code}`);return hA(a?.data?.message_id)}};import{createHash as xRe}from"node:crypto";var p6="stream_md",YRe="\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026",mu=28e3,iS=12e4,d6=new Map([[99991672,["artifact-permission-required","Feishu file delivery requires the im:resource permission."]],[234006,["artifact-too-large","The result file exceeds Feishu's size limit."]],[234010,["artifact-empty","Feishu does not accept empty files."]],[230017,["artifact-provider-rejected","Feishu rejected the uploaded file ownership."]],[230020,["artifact-rate-limited","Feishu temporarily rate-limited file delivery."]],[230049,["artifact-delivery-uncertain","Feishu could not confirm the file message result."]],[230055,["artifact-provider-rejected","Feishu rejected the file message type."]]]);function nl(n,t){if(t?.code&&t.code!==0)throw new Error(`${n} failed: ${t.msg||t.code}`);return t}function h6(n){let t=[n],o=new Set,i;for(;t.length>0;){let e=t.shift();if(!e||o.has(e))continue;if(typeof e=="object"&&o.add(e),Array.isArray(e)){t.push(...e);continue}let a=Number(e?.code);if(Number.isFinite(a)&&a!==0){if(d6.has(a))return a;i??=a}t.push(e?.response?.data,e?.data,e?.error,e?.cause)}return i}function yu(n,t,o,{uncertain:i=!1}={}){let e=o==null?void 0:Number(o),a=Number.isFinite(e)&&e!==0?e:h6(t),A=Number.isFinite(a)?["artifact-provider-rejected",`Feishu rejected file ${n}.`]:i?["artifact-delivery-uncertain","Feishu could not confirm the file message result."]:["artifact-provider-failed",`Feishu file ${n} failed.`],[r,s]=d6.get(a)??A,g=new Error(s,{cause:t});return g.code=r,Number.isFinite(a)&&(g.providerCode=a),g}function c6(n,t){if(!Number.isInteger(n)||n<1||n>iS)throw new TypeError(`${t} must be an integer between 1 and ${iS}`);return n}function Vv(n){return n?.reason??new DOMException("The operation was aborted","AbortError")}function jRe(n){let t=new Error(`Feishu file ${n} timed out.`);return t.code="provider-timeout",t}function I6(n,{signal:t,timeoutMs:o,stage:i}){t?.throwIfAborted();let e=new AbortController,a=t?AbortSignal.any([t,e.signal]):e.signal;return new Promise((A,r)=>{let s=!1,g=(d,B)=>{s||(s=!0,clearTimeout(I),a.removeEventListener("abort",c),d(B))},c=()=>g(r,t?.aborted?Vv(t):jRe(i)),I=setTimeout(()=>e.abort(),o);a.addEventListener("abort",c,{once:!0}),Promise.resolve().then(()=>n(a)).then(d=>g(A,d),d=>g(r,d)),a.aborted&&c()})}function JRe(n,t,o){let i=`${n.deliveryKey}\0${t}`;return`dshim_${xRe("sha256").update(o==="file"?i:`${i}\0${o}`).digest("hex").slice(0,40)}`}function qRe(n){let t=String(n??"").replace(/\s+/g," ").trim();return t.length<=50?t:`${Wv(t,49)}\u2026`}function Wv(n,t){let o=Math.min(n.length,t),i=n.charCodeAt(o-1),e=n.charCodeAt(o);return i>=55296&&i<=56319&&e>=56320&&e<=57343&&(o-=1),n.slice(0,o)}function l6(n){if(n.length<=mu)return n;let t=` +`)),await this.#Z(t,o,{updateMessageId:e})}catch(a){await this.#x(o,a,{logLabel:"session binding",userMessage:w("\u7ED1\u5B9A\u5931\u8D25\uFF1A{message}",{message:Cu(a)})})}}async#We(t,o,i,{updateMessageId:e=null}={}){try{let a=await this.#t.switchWorkspace(i);await this.#O(o,w("\u5DE5\u4F5C\u533A\u5DF2\u5207\u6362\u4E3A\uFF1A{workspace}",{workspace:a})),await this.#Z(t,o,{updateMessageId:e})}catch(a){await this.#x(o,a,{logLabel:"workspace switch",userMessage:w("\u5207\u6362\u5931\u8D25\uFF1A{message}",{message:Cu(a)})})}}#de(t,o,i){if(!(!i.key||!t)&&(this.#H.delete(t),this.#H.set(t,{key:i.key,chatId:o,sessionWorkspace:typeof i.sessionWorkspace=="string"&&i.sessionWorkspace?i.sessionWorkspace:null,sessionPage:Number.isSafeInteger(i.sessionPage)&&i.sessionPage>=0?i.sessionPage:0}),this.#H.size>200)){let e=this.#H.keys().next().value;e!==void 0&&this.#H.delete(e)}}async#W(t,o,i={}){let e=pA(i.updateMessageId),a=pA(i.replyTo);if(e)try{let g=await this.#e.im.v1.message.patch({path:{message_id:e},data:{content:o}});if(g?.code&&g.code!==0)throw new Error(`Feishu card update failed: ${g.msg||g.code}`);return this.#de(e,t,i),e}catch(g){this.#D.warn?.("[dsh-feishu] card update failed:",g?.code??g?.message??g,"sending new")}let A=o;if(a)try{let g=await this.#e.im.v1.message.reply({path:{message_id:a},data:{msg_type:"interactive",content:A}});if(g?.code&&g.code!==0)throw new Error(`Feishu card reply failed: ${g.msg||g.code}`);let c=pA(g?.data?.message_id);if(c)return this.#de(c,t,i),c}catch(g){this.#D.warn?.("[dsh-feishu] threaded card reply failed; sending a plain card:",g?.message??String(g))}let r=await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"interactive",content:o}});if(r?.code&&r.code!==0)throw new Error(`Feishu card send failed: ${r.msg||r.code}`);let s=pA(r?.data?.message_id);return this.#de(s,t,i),s}async#Z(t,o,{updateMessageId:i=null,replyTo:e=null}={}){let a=null,A=null;try{let U=this.#r.sessionFor(t);if(typeof U=="string"&&U){a=U;let F=this.#t.workspaceSession?.(U);A=pA(F?.title)??pA(F?.name)??pA(F?.displayName)}}catch{}let r=this.#V(),s=_E(this.#t,{signal:r}).catch(()=>{let U=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;return{current:U,paths:U?[U]:[]}}),g=(async()=>{let U=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;if(!U||typeof this.#t.listWorkspaceSessions!="function")return[];try{let F=await this.#t.listWorkspaceSessions(U,{signal:r});return this.#ne(Array.isArray(F?.sessions)?F.sessions:[])}catch{return[]}})(),c=(async()=>{try{let U=await this.#t.agentPresetSettings({signal:r});return{...U.agentPresetCatalog,_currentId:U.agentPreset}}catch{return null}})(),I=(async()=>{try{if(a){let U=this.#t.workspaceSession?.(a);if(typeof U?.models=="function")return await U.models({signal:r})}return await this.#t.listModels({signal:r})}catch{return null}})(),[d,B,f,Q]=await Promise.all([s,g,c,I]),y=Array.isArray(d.paths)?d.paths:[],m=d.current??null,_=B.find(U=>U.sessionId===a),T=a?pA(_?.title)??pA(_?.name)??A??a:null,R=B.map(U=>({id:U.sessionId,title:U.title??U.name??U.sessionId})).slice(0,20);a&&(R=R.filter(U=>U.id!==a),R.unshift({id:a,title:T??a}),R=R.slice(0,20));let L=this.#r?.includesArchivedSessions?.()??!1;this.#oe(t,{kind:"menu",chatId:o}),await this.#W(o,xW({workspaces:y,currentWorkspace:m,currentSession:a?{id:a,title:T}:null,sessions:R,archiveVisible:L,presetCatalog:f,modelCatalog:Q}),{key:t,updateMessageId:i,replyTo:e})}async#uA(t,o){try{if(typeof this.#t.workspaceSession=="function"){let e=this.#t.workspaceSession(o);if(e&&typeof e=="object"){let a=pA(e.title)??pA(e.name)??pA(e.displayName);if(a)return a}}let i=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;if(i&&typeof this.#t.listWorkspaceSessions=="function"){let e=await this.#t.listWorkspaceSessions(i),a=(Array.isArray(e?.sessions)?e.sessions:[]).find(A=>A.sessionId===o);if(a){let A=pA(a.title)??pA(a.name);if(A)return A}}}catch{}return null}async#Ze(t,o,{updateMessageId:i=null}={}){try{let e=await this.#t.agentPresetSettings({signal:this.#V()}),a=e.agentPresetCatalog;a._currentId=e.agentPreset,await this.#W(o,YW(a),{key:t,updateMessageId:i})}catch(e){await this.#x(o,e,{logLabel:"preset card"})}}async#Xe(t,o,{updateMessageId:i=null}={}){try{let e=this.#V();await this.#t.ensureRunning({signal:e});let a=this.#r?.sessionFor?.(t),A;if(typeof a=="string"&&a){let r=this.#t.workspaceSession(a);r?.models&&(A=await r.models({signal:e}))}A||(A=await this.#t.listModels({signal:e})),await this.#W(o,jW(A),{key:t,updateMessageId:i})}catch(e){await this.#x(o,e,{logLabel:"model card"})}}async#$e(t,o,i=null){try{await this.#t.ensureRunning({signal:this.#w});let e=[w("\u8FDE\u63A5\u6B63\u5E38")],a=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;a&&e.push(w("\u5DE5\u4F5C\u533A\uFF1A{workspace}",{workspace:a}));let A=typeof this.#t.agentPresetSettings=="function"?await this.#t.agentPresetSettings({signal:this.#w}).catch(()=>null):null;if(A){let r=A.agentPresetCatalog?.items?.find(s=>s.id===A.agentPreset);e.push(w("\u9884\u8BBE\uFF1A{preset}",{preset:r?`${r.label}\uFF08${r.id}\uFF09`:A.agentPreset||w("\u8DDF\u968F\u9ED8\u8BA4")}))}await this.#O(o,e.join(` +`),{replyTo:i})}catch(e){await this.#x(o,e,{logLabel:"status text"})}}async#eA(t,o,{updateMessageId:i=null}={}){try{let e=this.#V();await this.#t.ensureRunning({signal:e});let a={connected:!0,workspace:null,preset:null,model:null,sessionCount:0};try{let A=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;a.workspace=A||w("\u672A\u77E5")}catch{}try{let A=await this.#t.agentPresetSettings({signal:e}),r=A.agentPresetCatalog.items.find(s=>s.id===A.agentPreset);a.preset=r?`${r.label}\uFF08${r.id}\uFF09`:A.agentPreset||w("\u8DDF\u968F\u9ED8\u8BA4")}catch{}try{let A=this.#r?.sessionFor?.(t);if(typeof A=="string"&&A){let r=this.#t.workspaceSession(A);if(r?.models){let s=await r.models({signal:e});s.current&&(a.model=`${s.current.provider}/${s.current.model}`)}}}catch{}try{let A=typeof this.#t.currentWorkspace=="function"?this.#t.currentWorkspace():null;if(A){let r=await this.#t.listWorkspaceSessions(A,{signal:e});Array.isArray(r?.sessions)&&(a.sessionCount=r.sessions.length)}}catch{}await this.#W(o,JW(a),{key:t,updateMessageId:i})}catch(e){await this.#x(o,e,{logLabel:"status card"})}}async#AA(t,o,{updateMessageId:i=null}={}){await this.#W(o,zW(GRe.map(e=>w(e))),{key:t,updateMessageId:i})}async#tA(t,o){try{let i=await Bi("/compact",this.#t,this.#r,t,{signal:this.#w});await this.#O(o,i?.message||w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\u3002"))}catch(i){await this.#x(o,i,{logLabel:"compact"})}}async#rA(t,o){try{let i=await Qi("/stop",this.#t,this.#r,t,{signal:this.#w,control:{owner:this,key:t}});i?.stopped&&await Promise.allSettled([this.#we(t),this.#m.closeRoute(t)]),await this.#O(o,i?.message||w("/stop \u6267\u884C\u5B8C\u6210\u3002"))}catch(i){await this.#x(o,i,{logLabel:"stop"})}}async#aA(t,o,{updateMessageId:i=null}={}){let e=!!this.#r.sessionFor?.(t);this.#oe(t,{kind:"steer"}),await this.#W(o,A6({hasSession:e}),{key:t,updateMessageId:i})}async#he(t,o){let{key:i,chatId:e}=t,a=await Qi(`/steer ${o}`,this.#t,this.#r,i,{signal:this.#w,pendingInteraction:this.#ae(i),control:{owner:this,key:i}});await this.#O(e,a?.message||w("\u5DF2\u63D0\u4EA4\u8865\u5145\u6307\u4EE4\u3002"))}async#Te(t,o,{updateMessageId:i=null}={}){try{let e=await yi("/preset --default",this.#t,this.#r,t,{signal:this.#w});for(let a of e?.messages??[e?.message])a&&await this.#O(o,a)}catch(e){await this.#x(o,e,{logLabel:"preset reset"});return}try{await this.#Z(t,o,{updateMessageId:i})}catch(e){this.#D.warn?.("[dsh-feishu] menu refresh failed after preset reset:",e.message)}}async#iA(t,o,i,{updateMessageId:e=null}={}){try{let a=/^\d+$/u.test(i)?`id:${i}`:i,A=await yi(`/preset ${a}`,this.#t,this.#r,t,{signal:this.#w});for(let r of A?.messages??[A?.message])r&&await this.#O(o,r)}catch(a){await this.#x(o,a,{logLabel:"preset selection"});return}try{await this.#Z(t,o,{updateMessageId:e})}catch(a){this.#D.warn?.("[dsh-feishu] menu refresh failed after preset select:",a.message)}}async#oA(t,o,i,{updateMessageId:e=null}={}){try{let a=await Wi(`/model ${i}`,this.#t,this.#r,t,{signal:this.#w,pendingInteraction:this.#ae(t),control:{owner:this,key:t}});for(let A of a?.messages??[a?.message])A&&await this.#O(o,A)}catch(a){await this.#x(o,a,{logLabel:"model selection"});return}try{await this.#Z(t,o,{updateMessageId:e})}catch(a){this.#D.warn?.("[dsh-feishu] menu refresh failed after model select:",a.message)}}#Ne(){if(this.#q||typeof this.#t?.watchHarnessEvents!="function"||this.#w?.aborted)return;let t=this.#w??new AbortController().signal;try{this.#q=this.#t.watchHarnessEvents({signal:t,onSessionEvent:o=>this.#cA(o),onReconnect:()=>{this.#IA()}}),Promise.resolve(this.#q).catch(o=>{t.aborted||this.#D.warn?.("[dsh-feishu] event watcher stopped:",o.message)})}catch(o){this.#q=null,this.#D.warn?.("[dsh-feishu] event watcher failed to start:",o.message)}}#Re(t,o){let i=this.#z.get(t)??Promise.resolve(),e;return e=i.then(o,o).catch(a=>{this.#w?.aborted||this.#D.warn?.("[dsh-feishu] completion event failed:",a.message)}).finally(()=>{this.#z.get(t)===e&&this.#z.delete(t)}),this.#z.set(t,e),e}#Ee(t=Date.now()){let o=0;for(let[i,e]of this.#K){for(let[a,A]of e)(!Number.isSafeInteger(A?.arrivalAt)||A.arrivalAt<0||A.arrivalAt+ORe<=t)&&e.delete(a);for(;e.size>MRe;){let a=e.keys().next().value;if(a===void 0)break;e.delete(a)}e.size===0?this.#K.delete(i):o+=e.size}for(;this.#K.size>bRe;){let i=this.#K.keys().next().value;if(i===void 0)break;o-=this.#K.get(i)?.size??0,this.#K.delete(i)}for(;o>_Re;){let i=this.#K.keys().next().value;if(i===void 0)break;let e=this.#K.get(i),a=e?.keys().next().value;if(a===void 0){this.#K.delete(i);continue}e.delete(a),o-=1,e.size===0&&this.#K.delete(i)}}#nA(t,o,i=Date.now()){this.#Ee(i);let e=this.#K.get(t);e||(e=new Map);let a=o?.data?.reason,A=typeof a=="string"?a:typeof a?.kind=="string"?{kind:a.kind}:null;e.delete(o.seq),e.set(o.seq,{arrivalAt:i,event:{type:"turn/end",seq:o.seq,...Number.isSafeInteger(o.time)&&o.time>=0?{time:o.time}:{},data:{reason:A}}}),this.#K.delete(t),this.#K.set(t,e),this.#Ee(i)}async#sA(t,{workspaceHint:o=null,signal:i=this.#w}={}){if(typeof t!="string"||t==="")return{error:w("\u7528\u6CD5\uFF1A/watch ")};let e=/^\d{1,4}$/.test(t)?Number(t):null,a=typeof this.#t?.currentWorkspace=="function"?this.#t.currentWorkspace():null,A=async s=>{let g=await this.#t.listWorkspaceSessions(s,{signal:i});return Array.isArray(g?.sessions)?g.sessions:[]};if(e!==null){if(!a)return{error:w("\u5F53\u524D\u673A\u5668\u4EBA\u6CA1\u6709\u53EF\u7528\u7684\u5DE5\u4F5C\u533A\uFF0C\u65E0\u6CD5\u6309\u5E8F\u53F7\u89E3\u6790\u4F1A\u8BDD\u3002")};let s=this.#ne(await A(a)),g=s[e-1];return g?.sessionId?{sessionId:g.sessionId,title:g.title??w("\u6682\u65E0\u6807\u9898"),workspace:a,...Qn(g.lastSeq)?{lastSeq:g.lastSeq}:{}}:{error:w("\u5F53\u524D\u5DE5\u4F5C\u533A\u53EA\u6709 {count} \u4E2A\u4F1A\u8BDD\u3002",{count:s.length})}}let r;if(pA(o))r=[o];else{let s=typeof this.#t?.listWorkspaces=="function"?(await this.#t.listWorkspaces({signal:i})).filter(g=>g!==a):[];r=[a,...s].filter(Boolean)}for(let s of r){let c=(await A(s)).find(I=>I.sessionId===t);if(c)return{sessionId:t,title:c.title??w("\u6682\u65E0\u6807\u9898"),workspace:s,...Qn(c.lastSeq)?{lastSeq:c.lastSeq}:{}}}return{error:w("\u6CA1\u6709\u627E\u5230\u8FD9\u4E2A\u4F1A\u8BDD\uFF0C\u8BF7\u7528 /sessionlist \u67E5\u770B\u53EF\u7528\u4F1A\u8BDD\u3002")}}async#gA(t){let o=pA(t)??(typeof this.#t?.currentWorkspace=="function"?pA(this.#t.currentWorkspace()):null);if(!o||typeof this.#t?.listWorkspaceSessions!="function")return new Map;let i=await this.#t.listWorkspaceSessions(o,{signal:this.#V()});return new Map(this.#ne(Array.isArray(i?.sessions)?i.sessions:[]).filter(e=>pA(e?.sessionId)).map(e=>[e.sessionId,{sessionId:e.sessionId,title:e.title??e.name??w("\u6682\u65E0\u6807\u9898"),workspace:o,...Qn(e.lastSeq)?{lastSeq:e.lastSeq}:{}}]))}#ke(t){let o=this.#F.get(t);if(o)return o.requested=!0,o.promise;let i={requested:!0,promise:null};return this.#F.set(t,i),i.promise=Promise.resolve().then(async()=>{try{do i.requested=!1,await this.#Re(t,()=>this.#Pe(t));while(i.requested&&!this.#w?.aborted)}finally{this.#F.get(t)===i&&this.#F.delete(t)}}),i.promise}async#Ce(t,o,i,{notify:e=!0,validatedTarget:a=null,workspaceHint:A=null,replyTo:r=null}={}){let s=Date.now(),g=async y=>{e&&await this.#O(o,y,{replyTo:r}).catch(m=>{this.#D.warn?.("[dsh-feishu] watch notification failed:",m.message)})};if(this.#Ne(),typeof this.#r?.setWatch!="function")return await g(w("\u5F53\u524D\u72B6\u6001\u5B58\u50A8\u4E0D\u652F\u6301\u5173\u6CE8\u3002")),{ok:!1,changed:!1,reason:"unsupported"};let c;try{c=a?.sessionId===i?a:await this.#sA(i,{workspaceHint:A,signal:A?this.#V():this.#w})}catch(y){return await g(w("\u65E0\u6CD5\u89E3\u6790\u4F1A\u8BDD\uFF1A{message}",{message:Cu(y)})),{ok:!1,changed:!1,reason:"resolve"}}if(c.error)return await g(c.error),{ok:!1,changed:!1,reason:"not-found"};let I=this.#r.watchEntries?.(t)??[],d=I.find(y=>y.sessionId===c.sessionId);if(!d&&I.length>=Zm)return await g(w("\u6BCF\u4E2A\u804A\u5929\u6700\u591A\u5173\u6CE8 {count} \u4E2A\u4F1A\u8BDD\u3002",{count:Zm})),{ok:!1,changed:!1,reason:"limit"};let B=Qn(d?.lastSeq)?d.lastSeq:Qn(c.lastSeq)?c.lastSeq:null,Q=rS(d)??(d?null:s);try{await this.#r.setWatch(t,{sessionId:c.sessionId,title:c.title,chatId:o,lastSeq:B,...Q!==null?{watchStartedAt:Q}:{}})}catch(y){return await g(w("\u5173\u6CE8\u5931\u8D25\uFF1A{message}",{message:Cu(y)})),{ok:!1,changed:!1,reason:"persist"}}return(!d||Q!==null||!Qn(B))&&this.#ke(c.sessionId),await g(w("\u5DF2\u5173\u6CE8\u4F1A\u8BDD\u300C{title}\u300D\uFF0C\u4EFB\u52A1\u5B8C\u6210\u4F1A\u63A8\u9001\u7ED3\u679C\u3002",{title:String(c.title).replace(/\s+/gu," ")})),{ok:!0,changed:!d,entry:this.#r.watchEntry?.(t,c.sessionId)}}async#ue(t,o,i,{notify:e=!0,replyTo:a=null}={}){let A=async g=>{e&&await this.#O(o,g,{replyTo:a}).catch(c=>{this.#D.warn?.("[dsh-feishu] unwatch notification failed:",c.message)})};if(typeof this.#r?.removeWatch!="function")return{ok:!1,changed:!1,reason:"unsupported"};let r=this.#r.watchEntries?.(t)??[],s=typeof i=="string"&&/^\d{1,4}$/.test(i)?r[Number(i)-1]:r.find(g=>g.sessionId===i);if(!s)return await A(w("\u5173\u6CE8\u5217\u8868\u91CC\u6CA1\u6709\u8FD9\u4E2A\u4F1A\u8BDD\uFF0C\u56DE\u590D /watchlist \u67E5\u770B\u3002")),{ok:!0,changed:!1,reason:"absent"};try{await this.#r.removeWatch(t,s.sessionId),this.#G.delete(`${t}\0${s.sessionId}`)}catch(g){return await A(w("\u53D6\u6D88\u5931\u8D25\uFF1A{message}",{message:Cu(g)})),{ok:!1,changed:!1,reason:"persist"}}return await A(w("\u5DF2\u53D6\u6D88\u5173\u6CE8\u300C{title}\u300D\u3002",{title:String(s.title??"").replace(/\s+/gu," ")})),{ok:!0,changed:!0,entry:s}}async#Be(t,o,{updateMessageId:i=null,replyTo:e=null}={}){let a=this.#r.watchEntries?.(t)??[],A=[],r=null;try{if(r=typeof this.#t?.currentWorkspace=="function"?this.#t.currentWorkspace():null,r&&typeof this.#t?.listWorkspaceSessions=="function"){let s=await this.#t.listWorkspaceSessions(r,{signal:this.#V()});A=this.#ne(Array.isArray(s?.sessions)?s.sessions:[]).map(g=>({sessionId:g.sessionId,title:g.title??g.name??g.sessionId}))}}catch{}this.#oe(t,{kind:"watches",entries:a}),await this.#W(o,XW(a,A),{key:t,updateMessageId:i,replyTo:e,sessionWorkspace:r})}#cA({sessionId:t,event:o}){this.#w?.aborted||!t||!o||typeof o!="object"||o.type!=="turn/end"||!fu(o.seq)||(this.#nA(t,o),this.#Re(t,async()=>{let i=this.#r.keysWatching?.(t)??[],e=i.some(A=>tS(this.#r.watchEntry?.(A,t))),a=i.some(A=>this.#G.has(`${A}\0${t}`));(e||a)&&await this.#Pe(t),await this.#ve(t,o)}))}async#ve(t,o,{keys:i=null}={}){if(this.#w?.aborted||typeof this.#r?.keysWatching!="function")return;let e=o?.data?.reason?.kind??o?.data?.reason??null,a=i??this.#r.keysWatching(t);for(let A of a){if(this.#w?.aborted)return;let r=this.#r.watchEntry?.(A,t),s=`${A}\0${t}`,g=this.#G.get(s);if(fu(g)&&Qn(r?.lastSeq)&&r.lastSeq>=g&&(this.#G.delete(s),g=void 0),!(!r?.chatId||tS(r)||Qn(r.lastSeq)&&r.lastSeq>=o.seq||fu(g)&&o.seq>g))try{await this.#W(r.chatId,$W(t,r.title,e),{key:A});let c=this.#r.watchEntry?.(A,t);if(!c||c.chatId!==r.chatId||tS(c)||Qn(c.lastSeq)&&c.lastSeq>=o.seq)continue;await this.#r.setWatch(A,{...c,lastSeq:o.seq}),g===o.seq&&this.#G.delete(s)}catch(c){this.#G.set(s,fu(g)?Math.min(g,o.seq):o.seq),this.#D.warn?.("[dsh-feishu] completion push failed:",c.message)}}}async#Pe(t){if(!(this.#w?.aborted||typeof this.#t?.rpc!="function"))try{let o=await this.#t.rpc("session.history",{sessionId:t,maxMessages:20},3e4,{signal:this.#w}),i=LRe(o);this.#Ee();let e=this.#K.get(t)??new Map,a=new Map(i.map(g=>[g.seq,g]));for(let[g,c]of e)a.has(g)||a.set(g,c.event);let A=[...a.values()].sort((g,c)=>g.seq-c.seq),r=A.at(-1)?.seq??-1,s=typeof this.#r?.keysWatching=="function"?this.#r.keysWatching(t):[];for(let g of s){let c=this.#r.watchEntry?.(g,t);if(!tS(c))continue;let I=rS(c),d=Qn(c.lastSeq)?c.lastSeq:-1,B=I===null?null:A.find(_=>{if(_.seq<=d)return!1;let T=Number.isSafeInteger(_.time)&&_.time>=0?_.time:e.get(_.seq)?.arrivalAt;return Number.isSafeInteger(T)&&T>=I}),f=B?Math.max(d,B.seq-1):Math.max(d,r),Q=this.#r.watchEntry?.(g,t);if(!Q||Q.chatId!==c.chatId||Q.lastSeq!==c.lastSeq||rS(Q)!==I)continue;let{watchStartedAt:y,...m}=Q;await this.#r.setWatch(g,{...m,lastSeq:f})}for(let g of A)g.type==="turn/end"&&await this.#ve(t,g,{keys:s})}catch(o){this.#w?.aborted||this.#D.warn?.(`[dsh-feishu] watch compensation failed for ${t}:`,o.message)}}async#IA(){let t=typeof this.#r?.watchedSessionIds=="function"?this.#r.watchedSessionIds():[];this.#w?.aborted||await Promise.allSettled(t.map(o=>this.#ke(o)))}#fe(t,o,i){return{timeoutMs:this.#R,signal:this.#w,control:{owner:this,key:o},onInteraction:e=>this.#dA(e,{key:o,actor:Qu(t),chatId:t.message.chat_id,requiresMention:t.message.chat_type!=="p2p",replyToMessageId:t.message.message_id}),onInteractionResolved:e=>this.#hA(e),files:i}}async#Qe(t,o,{deliveryId:i,presentation:e,replyTo:a=null}){let A=[];for(let r of UW(o)){this.#w?.throwIfAborted();let s=await this.#O(t,r,{replyTo:a});s&&A.push(s)}return Zt({deliveryId:i,presentation:e,providerMessageIds:A})}async#Ie(t,o,i=[],e){let a=await bo({artifacts:i,baseReceipt:e,deliveryId:e?.deliveryId??i[0]?.deliveryKey??o,aggregatePresentation:e?"feishu-text-and-files":"feishu-files",channelKey:"feishu",signal:this.#w,sendImage:typeof this.#A?.sendImage=="function"?A=>this.#A.sendImage(t,A,{replyTo:o,signal:this.#w}):void 0,sendFile:typeof this.#A?.sendFile=="function"?A=>this.#A.sendFile(t,A,{replyTo:o,signal:this.#w}):void 0,onFailure:(A,r)=>tt(this.#u,r,{userMessage:FRe(A?.fileName,r),reason:r?.code}),sendFailureNotice:async(A,r,s)=>({messageId:await this.#O(t,dt(s))}),logger:this.#D});return this.#u.artifactsSent=(this.#u.artifactsSent??0)+a.artifactsSent,this.#u.artifactSendErrors=(this.#u.artifactSendErrors??0)+a.artifactSendErrors,a.receipt?{receipt:a.receipt,failureNoticeVisible:a.failureNoticeVisible,artifactSendErrors:a.artifactSendErrors}:{receipt:Zt({deliveryId:o,presentation:"feishu-files"}),failureNoticeVisible:a.failureNoticeVisible,artifactSendErrors:a.artifactSendErrors}}async#lA(t,o,i,{onAskComplete:e}={}){let a=t.message.chat_id,A=t.message.message_id,r=i.content,s=!1,g=()=>{s||(s=!0,e?.())},c=Wt(i)?await Bo(i,{signal:this.#w}):void 0,I=this.#o.get(A);if(I&&(c=mo(c??r,I,()=>({channel:"feishu",senderId:Qu(t)}))),!this.#A?.stream){let{answer:m,artifacts:_=[]}=await ui({harness:this.#t,state:this.#r,key:o,text:r,content:c,createOptions:{signal:this.#w},existsOptions:{signal:this.#w},askOptions:this.#fe(t,o,i.files)});g();let T,R=null;try{T=await this.#Qe(a,AS(m,_),{deliveryId:A,presentation:"feishu-text",replyTo:A})}catch(F){R=Ma(F),this.#D.warn?.("[dsh-feishu] final text delivery failed; continuing with result files:",F)}let L=await this.#Ie(a,A,_,T),U=L.receipt.artifacts.some(({outcome:F})=>F==="sent"||F==="unknown");if(R&&!U&&!L.failureNoticeVisible)throw R;return R&&L.artifactSendErrors===0&&tt(this.#u,R),this.#u.streamFallbacks=(this.#u.streamFallbacks??0)+1,{...L,textDeliveryErrors:R?1:0}}let d=!1,B="",f=[],Q;try{Q=await this.#A.stream(a,{markdown:async m=>{d=!0;let _={...this.#fe(t,o,i.files),onUpdate:async R=>{await m.setContent(this.#EA(R)),this.#u.streamUpdates=(this.#u.streamUpdates??0)+1}},T=await ui({harness:this.#t,state:this.#r,key:o,text:r,content:c,createOptions:{signal:this.#w},existsOptions:{signal:this.#w},askOptions:_});g(),B=T.answer,f=T.artifacts??[],await m.setContent(AS(B,f))}},{replyTo:A})}catch(m){if(this.#u.streamErrors=(this.#u.streamErrors??0)+1,B||f.length>0){this.#D.warn?.("[dsh-feishu] native stream failed after generation; sending final text:",m.message);let q,z=null;try{q=await this.#Qe(a,AS(B,f),{deliveryId:A,presentation:"feishu-text-fallback",replyTo:A})}catch(J){z=Ma(J),this.#D.warn?.("[dsh-feishu] fallback text delivery failed; continuing with result files:",J)}let j=await this.#Ie(a,A,f,q),P=j.receipt.artifacts.some(({outcome:J})=>J==="sent"||J==="unknown");if(z&&!P&&!j.failureNoticeVisible)throw z;return z&&j.artifactSendErrors===0&&tt(this.#u,z),this.#u.streamFallbacks=(this.#u.streamFallbacks??0)+1,{...j,textDeliveryErrors:z?1:0}}if(d)throw m;this.#D.warn?.("[dsh-feishu] native stream unavailable; using text fallback:",m.message);let{answer:_,artifacts:T=[]}=await ui({harness:this.#t,state:this.#r,key:o,text:r,content:c,createOptions:{signal:this.#w},existsOptions:{signal:this.#w},askOptions:this.#fe(t,o,i.files)});g();let R,L=null;try{R=await this.#Qe(a,AS(_,T),{deliveryId:A,presentation:"feishu-text-fallback",replyTo:A})}catch(q){L=Ma(q),this.#D.warn?.("[dsh-feishu] fallback text delivery failed; continuing with result files:",q)}let U=await this.#Ie(a,A,T,R),F=U.receipt.artifacts.some(({outcome:q})=>q==="sent"||q==="unknown");if(L&&!F&&!U.failureNoticeVisible)throw L;return L&&U.artifactSendErrors===0&&tt(this.#u,L),this.#u.streamFallbacks=(this.#u.streamFallbacks??0)+1,{...U,textDeliveryErrors:L?1:0}}let y=await this.#Ie(a,A,f,Zt({deliveryId:A,presentation:"feishu-cardkit",providerMessageIds:ka(Q)}));return this.#u.streamResponses=(this.#u.streamResponses??0)+1,y}async#pA(t,o,i,e,a){this.#w?.throwIfAborted();let A=this.#i.get(i),r=e.claimedReplyMessageId===o;if(!A||A!==e||A.submitting)return this.#ye(t,i)?this.#me(t,o):r&&(!A||A!==e)?this.#me(t,o):this.#j(t,o,i,a,{releaseMessageId:!1,finalize:!1});if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1;let s=_d(t);if(!s){await this.#O(t.message.chat_id,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002"));return}let g=this.#i.get(i);if(!g||g!==e||g.submitting){if(this.#ye(t,i)){await this.#O(t.message.chat_id,$m(),{replyTo:t.message.message_id}).catch(()=>{});return}if(r&&(!g||g!==e)){await this.#O(t.message.chat_id,$m(),{replyTo:t.message.message_id});return}return this.#j(t,o,i,a,{releaseMessageId:!1,alreadyRecorded:!0,finalize:!1})}if(g.chatId=t.message.chat_id,g.needsPresentation){try{await this.#le(g)}catch{this.#u.lastError="\u98DE\u4E66\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#D.error?.("[dsh-feishu] failed to retry an interaction question"),g.interaction.reconnect?.()}return}let c=g.questions[g.index];if(c){if(g.answers.push(Ei(c,s)),g.index+=1,g.index{});return}g.submitting=!1,g.answers.pop(),g.index-=1,this.#u.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#D.error?.("[dsh-feishu] failed to answer a Harness interaction"),await this.#O(t.message.chat_id,w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002")).catch(()=>{})}}}async#dA(t,{key:o,actor:i,chatId:e,requiresMention:a,replyToMessageId:A}){if(await this.#m.handleRequested(t,{key:o,actor:i,requiresMention:a,send:I=>this.#O(e,I,{replyTo:A})})||t?.kind!=="question")return;let r=t?.payload?.questions,s=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t.rpcId!="string"||typeof s!="string"||typeof t.sessionId!="string"||!Array.isArray(r)||r.length===0||r.some(I=>!di(I))){this.#D.warn?.("[dsh-feishu] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"Feishu safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#O(e,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002"),{replyTo:A}).catch(()=>{});return}let g=this.#i.get(o);if(g?.interactionId===s){g.interaction=t,g.needsPresentation&&await this.#le(g);return}if(this.#I.has(s))return;if(g){await t.respond({ok:!1,error:{code:"cancelled",message:"Feishu is already handling another user interaction.",details:{}}});return}let c={kind:"question",interactionId:s,sessionId:t.sessionId,interaction:t,key:o,actor:i,requiresMention:a,questions:r,answers:[],index:0,chatId:e,replyToMessageId:A,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,questionMessageIds:new Set,inactive:!1};this.#i.set(o,c),this.#I.set(c.interactionId,o),await this.#le(c)}async#hA(t){if(await this.#m.handleResolved(t))return;let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#I.get(o);if(!i)return;let e=this.#i.get(i);e&&this.#se(i,e),this.#Se(i,o)}async#le(t){let o=t.questions[t.index];if(!o)return;let i=await this.#O(t.chatId,hi(o,t.index,t.questions.length,{requiresMention:t.requiresMention}),{replyTo:t.replyToMessageId});i&&(t.questionMessageIds.add(i),t.inactive&&this.#se(t.key,t)),t.needsPresentation=!1}#se(t,o){let i=Date.now()+dRe;for(let e of o.questionMessageIds??[])this.#l.set(e,{key:t,expiresAt:i})}#ye(t,o){let i=Date.now();for(let[e,a]of this.#l)a.expiresAt<=i&&this.#l.delete(e);for(let e of[t?.message?.parent_id,t?.message?.root_id]){let a=this.#l.get(e);if(a?.key===o&&a.expiresAt>i)return!0}return!1}async#me(t,o){this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#u.lastMessageAt=new Date().toISOString(),this.#u.messagesReceived+=1,await this.#O(t.message.chat_id,$m(),{replyTo:t.message.message_id}).catch(()=>{}))}#Ge(t,o){let i=this.#i.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#i.delete(t),this.#I.delete(i.interactionId),i.inactive=!0,i)}#Se(t,o){return this.#Ge(t,o)!==null}async#we(t){let o=this.#Ge(t);if(!(!o||o.kind!=="question")){this.#se(t,o);try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Feishu interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#D.warn?.("[dsh-feishu] failed to cancel a pending Harness interaction")}}}#EA(t){return t.type==="text"&&t.text?t.text:t.type==="tool"?t.name==="web_search"?w("_\u6B63\u5728\u641C\u7D22\u7F51\u7EDC\u5E76\u6574\u7406\u4FE1\u606F\u2026_"):w("_\u6B63\u5728\u4F7F\u7528 {name}\u2026_",{name:t.name||w("\u5DE5\u5177")}):w("_{text}_",{text:t.text||w("\u6B63\u5728\u5904\u7406\u2026")})}#CA(t){return PQ({adapter:this.#A,target:t,reactions:{processing:"OnIt",success:"DONE",error:"ERROR"},status:this.#u,logger:this.#D,label:"feishu"})}#Fe(t,o){o.clear()}#ee(t,o,i){i==="ERROR"?o.error():o.success()}async#O(t,o,{replyTo:i}={}){let e=JSON.stringify({text:o});if(i)try{let A=await this.#e.im.v1.message.reply({path:{message_id:i},data:{msg_type:"text",content:e}});if(A?.code&&A.code!==0)throw new Error(`Feishu reply failed: ${A.msg||A.code}`);return pA(A?.data?.message_id)}catch(A){this.#D.warn?.("[dsh-feishu] threaded reply failed; falling back to a plain message:",A?.message??String(A))}let a=await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"text",content:e}});if(a?.code&&a.code!==0)throw new Error(`Feishu send failed: ${a.msg||a.code}`);return pA(a?.data?.message_id)}};import{createHash as xRe}from"node:crypto";var p6="stream_md",YRe="\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026",mu=28e3,iS=12e4,d6=new Map([[99991672,["artifact-permission-required","Feishu file delivery requires the im:resource permission."]],[234006,["artifact-too-large","The result file exceeds Feishu's size limit."]],[234010,["artifact-empty","Feishu does not accept empty files."]],[230017,["artifact-provider-rejected","Feishu rejected the uploaded file ownership."]],[230020,["artifact-rate-limited","Feishu temporarily rate-limited file delivery."]],[230049,["artifact-delivery-uncertain","Feishu could not confirm the file message result."]],[230055,["artifact-provider-rejected","Feishu rejected the file message type."]]]);function nl(n,t){if(t?.code&&t.code!==0)throw new Error(`${n} failed: ${t.msg||t.code}`);return t}function h6(n){let t=[n],o=new Set,i;for(;t.length>0;){let e=t.shift();if(!e||o.has(e))continue;if(typeof e=="object"&&o.add(e),Array.isArray(e)){t.push(...e);continue}let a=Number(e?.code);if(Number.isFinite(a)&&a!==0){if(d6.has(a))return a;i??=a}t.push(e?.response?.data,e?.data,e?.error,e?.cause)}return i}function yu(n,t,o,{uncertain:i=!1}={}){let e=o==null?void 0:Number(o),a=Number.isFinite(e)&&e!==0?e:h6(t),A=Number.isFinite(a)?["artifact-provider-rejected",`Feishu rejected file ${n}.`]:i?["artifact-delivery-uncertain","Feishu could not confirm the file message result."]:["artifact-provider-failed",`Feishu file ${n} failed.`],[r,s]=d6.get(a)??A,g=new Error(s,{cause:t});return g.code=r,Number.isFinite(a)&&(g.providerCode=a),g}function c6(n,t){if(!Number.isInteger(n)||n<1||n>iS)throw new TypeError(`${t} must be an integer between 1 and ${iS}`);return n}function Vv(n){return n?.reason??new DOMException("The operation was aborted","AbortError")}function jRe(n){let t=new Error(`Feishu file ${n} timed out.`);return t.code="provider-timeout",t}function I6(n,{signal:t,timeoutMs:o,stage:i}){t?.throwIfAborted();let e=new AbortController,a=t?AbortSignal.any([t,e.signal]):e.signal;return new Promise((A,r)=>{let s=!1,g=(d,B)=>{s||(s=!0,clearTimeout(I),a.removeEventListener("abort",c),d(B))},c=()=>g(r,t?.aborted?Vv(t):jRe(i)),I=setTimeout(()=>e.abort(),o);a.addEventListener("abort",c,{once:!0}),Promise.resolve().then(()=>n(a)).then(d=>g(A,d),d=>g(r,d)),a.aborted&&c()})}function JRe(n,t,o){let i=`${n.deliveryKey}\0${t}`;return`dshim_${xRe("sha256").update(o==="file"?i:`${i}\0${o}`).digest("hex").slice(0,40)}`}function qRe(n){let t=String(n??"").replace(/\s+/g," ").trim();return t.length<=50?t:`${Wv(t,49)}\u2026`}function Wv(n,t){let o=Math.min(n.length,t),i=n.charCodeAt(o-1),e=n.charCodeAt(o);return i>=55296&&i<=56319&&e>=56320&&e<=57343&&(o-=1),n.slice(0,o)}function l6(n){if(n.length<=mu)return n;let t=` ${w("\u5185\u5BB9\u8F83\u957F\uFF0C\u751F\u6210\u5B8C\u6210\u540E\u5C06\u5206\u6BB5\u53D1\u9001\u5B8C\u6574\u56DE\u7B54\u3002")}`;return Wv(n,mu-t.length)+t}function zRe(n){let t=[],o=n;for(;o.length>mu;){let i=Wv(o,mu),e=i.lastIndexOf(` -`)+1;e{let c=String(g??"")||"\u2026";await this.#n(a,l6(c)),A=c}};await o.markdown(r);let s=zRe(A);for(let[g,c]of s.entries()){let I=g===0?a:await this.#a(t,i.replyTo);g>0&&e.push(I),await this.#n(I,c),await this.#i(I)}return{messageId:a.messageId,providerMessageIds:e.map(g=>g.messageId)}}catch(a){for(let A of e)await this.#l(A.messageId);throw a}}async sendFile(t,o,{replyTo:i,signal:e}={}){return this.#g(t,o,{replyTo:i,signal:e,messageType:"file",presentation:"feishu-file"})}async sendImage(t,o,{replyTo:i,signal:e}={}){return this.#g(t,o,{replyTo:i,signal:e,messageType:"image",presentation:"feishu-image"})}async#g(t,o,{replyTo:i,signal:e,messageType:a,presentation:A}){if(e?.throwIfAborted(),typeof t!="string"||!t)throw new TypeError("chatId is required");if(!o||typeof o!="object"||typeof o.artifactId!="string"||!o.artifactId||typeof o.deliveryKey!="string"||!o.deliveryKey||typeof o.fileName!="string"||!o.fileName||!Buffer.isBuffer(o.bytes))throw new TypeError("A materialized result file is required");let r;try{r=await I6(Q=>{Q.throwIfAborted();let y=a==="image"?this.#e.im.v1.image.create({data:{image_type:"message",image:o.bytes}}):this.#e.im.v1.file.create({data:{file_type:"stream",file_name:o.fileName,file:o.bytes}});return ln(o,y),y},{signal:e,timeoutMs:this.#t,stage:"upload"})}catch(Q){throw e?.aborted?Vv(e):yu("upload",Q)}e?.throwIfAborted();let s=a==="image"?r?.image_key??r?.data?.image_key:r?.file_key??r?.data?.file_key;if(typeof s!="string"||!s)throw yu("upload",void 0,r?.code);let g=JRe(o,t,a),c=JSON.stringify(a==="image"?{image_key:s}:{file_key:s}),I=i?{path:{message_id:i},data:{msg_type:a,content:c,uuid:g}}:{params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:a,content:c,uuid:g}},d=()=>{let Q=i?this.#e.im.v1.message.reply(I):this.#e.im.v1.message.create(I);return ln(o,Q),Q},B;try{B=await I6(async Q=>{Q.throwIfAborted();let y;try{y=await d()}catch(m){if(h6(m)!==230049)throw m;y={code:230049}}return Q.throwIfAborted(),Number(y?.code)===230049&&(y=await d(),Q.throwIfAborted()),y},{signal:e,timeoutMs:this.#r,stage:"message send"})}catch(Q){throw e?.aborted?Vv(e):yu("message send",Q,void 0,{uncertain:!0})}if(Number.isFinite(Number(B?.code))&&Number(B.code)!==0)throw yu("message send",void 0,B.code,{uncertain:!0});let f=B?.data?.message_id;if(typeof f!="string"||!f)throw yu("message send",void 0,void 0,{uncertain:!0});return Zt({deliveryId:o.deliveryKey,presentation:A,providerMessageIds:[f],artifacts:[{artifactId:o.artifactId,outcome:"sent"}]})}async#a(t,o){let i=l6(this.#A),a=nl("Feishu card.create",await this.#e.cardkit.v1.card.create({data:{type:"card_json",data:JSON.stringify(VRe(i))}}))?.data?.card_id;if(!a)throw new Error("Feishu card.create returned no card_id");let A=await this.#I(t,a,o);return{cardId:a,messageId:A,content:i,sequence:0}}async#n(t,o){if(o===t.content)return;let i=await this.#e.cardkit.v1.cardElement.content({path:{card_id:t.cardId,element_id:p6},data:{content:o,sequence:++t.sequence,uuid:`content_${t.cardId}_${t.sequence}`}});nl("Feishu cardElement.content",i),t.content=o}async#i(t){let o=await this.#e.cardkit.v1.card.settings({path:{card_id:t.cardId},data:{settings:JSON.stringify({config:{streaming_mode:!1,summary:{content:qRe(t.content)||w("\u56DE\u7B54\u5B8C\u6210")}}}),sequence:++t.sequence,uuid:`settings_${t.cardId}_${t.sequence}`}});nl("Feishu card.settings",o)}async#I(t,o,i){let e=JSON.stringify({type:"card",data:{card_id:o}}),a=i?await this.#e.im.v1.message.reply({path:{message_id:i},data:{msg_type:"interactive",content:e}}):await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"interactive",content:e}});nl("Feishu message send",a);let A=a?.data?.message_id;if(!A)throw new Error("Feishu message send returned no message_id");return A}async#l(t){try{let o=await this.#e.im.v1.message.delete({path:{message_id:t}});nl("Feishu message delete",o)}catch(o){console.warn("[bridge] unable to recall a failed streaming card:",o.message)}}async addReaction(t,o){let e=nl("Feishu reaction.create",await this.#e.im.v1.messageReaction.create({path:{message_id:t},data:{reaction_type:{emoji_type:o}}}))?.data?.reaction_id;if(!e)throw new Error("Feishu reaction.create returned no reaction_id");return e}async removeReaction(t,o){nl("Feishu reaction.delete",await this.#e.im.v1.messageReaction.delete({path:{message_id:t,reaction_id:o}}))}};var C6="/open-apis/application/v7/app_slash_commands",WRe=new Set(["99991640","99991672"]),nS=Object.freeze(["application:app_slash_command:read","application:app_slash_command:write"]),u6="ai-agent_outlined",Zv=Object.freeze([{command:"menu",icon:"skill_outlined",default:"\u6253\u5F00\u529F\u80FD\u83DC\u5355",en_us:"Open the feature menu"},{command:"new",icon:"ai-deepthink_outlined",default:"\u5F00\u542F\u5168\u65B0\u4F1A\u8BDD",en_us:"Start a fresh session"},{command:"help",icon:"promptword_outlined",default:"\u67E5\u770B\u5E2E\u52A9",en_us:"Show help"},{command:"status",icon:"ai-functions_outlined",default:"\u67E5\u770B\u673A\u5668\u4EBA\u72B6\u6001",en_us:"Show bot status"},{command:"compact",icon:"ai-block_outlined",default:"\u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u4E0A\u4E0B\u6587",en_us:"Compact the current session"},{command:"sessionlist",icon:"chat-ai_outlined",default:"\u5217\u51FA\u4F1A\u8BDD",en_us:"List sessions"},{command:"workspacelist",icon:"folder_outlined",default:"\u5217\u51FA\u5DE5\u4F5C\u533A",en_us:"List workspaces"},{command:"watch",icon:"flag_outlined",default:"\u5173\u6CE8\u4E00\u4E2A\u4F1A\u8BDD",en_us:"Watch a session"},{command:"unwatch",icon:"clear_outlined",default:"\u53D6\u6D88\u5173\u6CE8\u4F1A\u8BDD",en_us:"Unwatch a session"},{command:"watchlist",icon:"flag_outlined",default:"\u67E5\u770B\u5173\u6CE8\u5217\u8868",en_us:"List watched sessions"},{command:"archived",icon:"folder_outlined",default:"\u8BBE\u7F6E\u5F52\u6863\u4F1A\u8BDD\u663E\u9690\uFF08on/off\uFF09",en_us:"Show or hide archived sessions (on/off)"}]);function Xv(n,t){let o=n==="lark"?"https://open.larksuite.com":"https://open.feishu.cn";return new URL(t,o)}function E6(n,t){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} returned a non-JSON response`);if(n.code!==0){let o=new Error(`${t} failed: ${n.msg||`code ${n.code}`}`);throw o.code=String(n.code),o.msg=n.msg,o}return n}function $v(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}async function eP(n,t,o){try{return E6(await n.request(t),o)}catch(i){let e=i?.response?.data;if(e&&typeof e=="object"&&!Array.isArray(e)&&Object.hasOwn(e,"code"))return E6(e,o);throw i}}async function ZRe({appId:n,appSecret:t,domain:o,httpInstance:i,timeoutMs:e,signal:a}){if(!n||!t)throw new Error("Feishu slash registration requires app credentials");if(!i||typeof i.request!="function")throw new TypeError("Feishu slash registration requires an HTTP instance");let A=await eP(i,{method:"POST",url:Xv(o,"/open-apis/auth/v3/tenant_access_token/internal").href,headers:{"content-type":"application/json; charset=utf-8"},data:{app_id:n,app_secret:t},signal:$v(a,e),timeout:e},"Feishu authentication");if(!A.tenant_access_token)throw new Error("Feishu authentication returned no tenant access token");return A.tenant_access_token}async function XRe({tenantAccessToken:n,domain:t,httpInstance:o,timeoutMs:i,signal:e}){let a=await eP(o,{method:"GET",url:Xv(t,C6).href,headers:{authorization:`Bearer ${n}`,"content-type":"application/json; charset=utf-8"},signal:$v(e,i),timeout:i},"Feishu slash command list");return Array.isArray(a.data?.items)?a.data.items:[]}async function $Re({tenantAccessToken:n,domain:t,httpInstance:o,timeoutMs:i,signal:e,command:a,description:A,icon:r=u6}){let s={command:a};return A&&(A.default_value||A.i18n)?s.description=A:typeof A=="string"&&A.trim()&&(s.description={default_value:A.trim()}),r&&(s.description={...s.description??{},icon:{icon_key:r}}),(await eP(o,{method:"POST",url:Xv(t,C6).href,headers:{authorization:`Bearer ${n}`,"content-type":"application/json; charset=utf-8"},data:s,signal:$v(e,i),timeout:i},`Feishu slash command create (/${a})`)).data?.command_id??null}async function B6({appId:n,appSecret:t,domain:o="feishu",httpInstance:i,timeoutMs:e=15e3,signal:a,manifest:A=Zv}){let r=await ZRe({appId:n,appSecret:t,domain:o,httpInstance:i,timeoutMs:e,signal:a}),s=new Set((await XRe({tenantAccessToken:r,domain:o,httpInstance:i,timeoutMs:e,signal:a})).map(I=>I.command)),g=[],c=[];for(let I of A){let d=String(I.command??"").replace(/^\//,"");if(d&&!s.has(d))try{let B={default_value:I.default??I.en_us??d,i18n:{zh_cn:I.default??d,en_us:I.en_us??I.default??d}},f=await $Re({tenantAccessToken:r,domain:o,httpInstance:i,timeoutMs:e,signal:a,command:d,description:B,icon:I.icon??u6});g.push({command:d,command_id:f})}catch(B){if(B?.code==="40000000"&&/already exists/i.test(B?.msg??"")){s.add(d);continue}if(WRe.has(B?.code)||/(?:lacks permission|access denied)/i.test(B?.msg??"")){c.push({command:d,error:B});break}c.push({command:d,error:B?.message??String(B)})}}return{created:g,existing:[...s].filter(I=>I!=null),failed:c}}var Ake=15e3,tke="\u2705 \u4FEE\u590D\u5B8C\u6210\uFF1A\u5DF2\u5B9E\u6D4B\u6536\u5230 card.action.trigger\uFF0C\u83DC\u5355\u6309\u94AE\u73B0\u5728\u53EF\u7528\u3002",rke="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u8D85\u65F6\uFF1A\u672A\u6536\u5230\u6D4B\u8BD5\u5361\u6309\u94AE\u7684 card.action.trigger\uFF0C\u4E0D\u80FD\u786E\u8BA4\u6309\u94AE\u5DF2\u4FEE\u590D\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u68C0\u67E5\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u7684\u5361\u7247\u56DE\u8C03\u914D\u7F6E\uFF0C\u786E\u8BA4\u540E\u518D\u53D1\u9001 /repair\u3002",AP="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u5931\u8D25\uFF1A\u65E0\u6CD5\u53D1\u9001\u4E13\u7528\u6D4B\u8BD5\u5361\uFF0C\u4E0D\u80FD\u786E\u8BA4 card.action.trigger \u5DF2\u6062\u590D\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u68C0\u67E5\u673A\u5668\u4EBA\u6D88\u606F\u6743\u9650\u548C\u8FDE\u63A5\u72B6\u6001\u3002",ake="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u4E2D\u65AD\uFF1ARuntime \u5DF2\u505C\u6B62\uFF0C\u672A\u5B8C\u6210 card.action.trigger \u5B9E\u6D4B\uFF0C\u4E0D\u80FD\u786E\u8BA4\u4FEE\u590D\u6210\u529F\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u7B49\u5F85\u673A\u5668\u4EBA\u6062\u590D\u8FDE\u63A5\u3002",ike=new Set(["connected","connecting","reconnecting"]);function yn(n){return typeof n=="string"&&n.trim()?n.trim():null}function oke(n){return yn(n?.operator?.open_id)??yn(n?.operator?.operator_id?.open_id)}function nke(n,t){try{let o=n?.getConnectionStatus?.()?.state;return typeof o=="string"&&o?o:t}catch{return t}}function Nd(n,t){let o=new Error(t);return o.code=n,o}function ske(n,t){if(!n||typeof n.request!="function")return;let o=i=>({...i??{},timeout:i?.timeout??t});return{request:i=>n.request(o(i)),get:(i,e)=>n.get(i,o(e)),delete:(i,e)=>n.delete(i,o(e)),head:(i,e)=>n.head(i,o(e)),options:(i,e)=>n.options(i,o(e)),post:(i,e,a)=>n.post(i,e,o(a)),put:(i,e,a)=>n.put(i,e,o(a)),patch:(i,e,a)=>n.patch(i,e,o(a))}}function gke({allowedSenderCount:n=1}={}){return{startedAt:null,ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1,messagesReceived:0,messagesReplied:0,messagesRejected:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0,streamResponses:0,streamUpdates:0,streamFallbacks:0,streamErrors:0,cardActionsReceived:0,cardActionProbesVerified:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastCardActionAt:null,lastError:null,agentPreset:"standard",authorizationMode:"sender-open-id-allowlist",allowedSenderCount:n,slashCommandRegistration:"idle",slashCommandsRegistered:0,slashCommandsExisting:0,slashCommandsFailed:0,slashCommandsError:null}}var sS=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c;#p;#d;#h;#E;#C=null;#f=null;#B=null;#y=null;#S=null;#Q=null;#m=new Map;#u;#b=!0;constructor({lark:t,botId:o,appId:i,appSecret:e,domain:a="feishu",botOpenId:A,groupResponseMode:r,ownerOpenId:s,ownerOpenIds:g,harness:c,state:I,contextEnhancement:d,repair:B,replyTimeoutMs:f=6e5,connectTimeoutMs:Q=15e3,requestTimeoutMs:y=Ake,slashCommands:m=!0,wsAgent:_,logger:T=console}){if(!t)throw new Error("FeishuRuntime requires the Feishu SDK");if(!i||!e)throw new Error("FeishuRuntime requires app credentials");let R=Array.isArray(g)?g:[s],F=[...new Set(R.filter(K=>typeof K=="string"&&K))];if(F.length===0)throw new Error("FeishuRuntime requires at least one owner open_id");if(!c)throw new Error("FeishuRuntime requires a Harness client");if(!I)throw new Error("FeishuRuntime requires a state store");if(B!=null&&!yn(o))throw new TypeError("FeishuRuntime repair capability requires a botId");if(!Number.isFinite(y)||y<=0)throw new TypeError("FeishuRuntime requestTimeoutMs must be a positive number");this.#e=t,this.#A=yn(o),this.#t=i,this.#r=e,this.#g=a,this.#a=yn(A),this.#n=ao(r),this.#i=F,this.#I=c,this.#l=I,this.#o=d,this.#E=B??null,this.#s=f,this.#c=Q,this.#p=y,this.#b=!!m,this.#d=_,this.#h=T,this.#u=gke({allowedSenderCount:F.length})}get status(){return structuredClone(this.#u)}setGroupResponseMode(t){this.#n=ao(t),this.#f?.setGroupResponseMode(this.#n)}async start(){for(;;){for(;this.#S;)await this.#S;if(this.#y)return this.#y;let o=this.#B;if(o){let i=nke(o,this.#u.feishuLongConnectionState);if(ike.has(i))return this.status;await this.stop({preserveError:i==="failed"});continue}if(this.#C||this.#f||this.#Q){await this.stop({preserveError:this.#u.feishuLongConnectionState==="failed"});continue}break}let t;return t=this.#R().finally(()=>{this.#y===t&&(this.#y=null)}),this.#y=t,t}async#R(){let t=new AbortController;this.#Q=t;let{signal:o}=t,i=()=>o.reason??new DOMException("Feishu runtime stopped","AbortError"),e=()=>!o.aborted&&this.#Q===t,a=()=>{if(!e())throw i()};this.#u.startedAt=new Date().toISOString(),this.#u.feishuLongConnectionState="connecting",this.#u.lastError=null;try{await this.#I.ensureRunning({signal:o}),a(),this.#u.harnessReachable=!0;let A=this.#g==="lark"?this.#e.Domain.Lark:this.#e.Domain.Feishu,r={appId:this.#t,appSecret:this.#r,domain:A},s=ske(this.#e.defaultHttpInstance,this.#p);s&&(r.httpInstance=s);let g=new this.#e.Client(r);this.#C=g;let c=new oS({client:g,initialText:w("\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026")}),I=new aS({client:g,channel:c,harness:this.#I,state:this.#l,contextEnhancement:this.#o,status:this.#u,allowedSenderOpenIds:new Set(this.#i),botId:this.#A,appId:this.#t,botOpenId:this.#a,groupResponseMode:this.#n,repair:this.#E,replyTimeoutMs:this.#s,signal:o,logger:this.#h});this.#f=I;let d=new this.#e.EventDispatcher({}).register({"im.message.receive_v1":_=>{e()&&I.accept(_)},"im.message.reaction.created_v1":()=>{},"im.message.reaction.deleted_v1":()=>{},"card.action.trigger":_=>{e()&&(this.#u.cardActionsReceived+=1,this.#u.lastCardActionAt=new Date().toISOString(),this.#D(_)||I.onCardAction(_))}}),B,f,Q=new Promise((_,T)=>{let R=!1,F=()=>{f(i())},K=(q,z)=>{R||(R=!0,clearTimeout(L),o.removeEventListener("abort",F),q(z))},L=setTimeout(()=>{K(T,new Error(`Feishu WebSocket handshake timed out after ${this.#c}ms`))},this.#c);B=()=>{K(_)},f=q=>{K(T,q)},o.addEventListener("abort",F,{once:!0}),o.aborted&&F()});Q.catch(()=>{});let y=new this.#e.WSClient({...r,...this.#d?{agent:this.#d}:{},loggerLevel:this.#e.LoggerLevel.info,handshakeTimeoutMs:this.#c,onReady:()=>{e()&&(this.#u.feishuLongConnectionState="connected",this.#u.ready=!0,this.#u.lastError=null,B())},onError:_=>{e()&&(this.#u.feishuLongConnectionState="failed",this.#u.ready=!1,this.#u.lastError=_?.message??String(_),this.#h.error("[dsh-feishu] Feishu long connection failed:",this.#u.lastError),f(_))},onReconnecting:()=>{e()&&(this.#u.feishuLongConnectionState="reconnecting",this.#u.ready=!1)},onReconnected:()=>{e()&&(this.#u.feishuLongConnectionState="connected",this.#u.ready=!0,this.#u.lastError=null)}});this.#B=y;let m=Promise.resolve().then(()=>y.start({eventDispatcher:d})).catch(_=>{throw f(_),_});return await Promise.all([m,Q]),a(),this.#b&&s&&this.#T(s,e,o),this.status}catch(A){throw o.aborted||(this.#u.ready=!1,this.#u.feishuLongConnectionState="failed",this.#u.lastError=A?.message??String(A),await this.#M({preserveError:!0,abortController:t})),A}}async beginCardActionProbe({expectedOperatorOpenId:t,timeoutMs:o=9e4}={}){if(!this.#u.ready||!this.#C)throw Nd("card_action_probe_unavailable","\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");let i=yn(t);if(!i||i==="*")throw new TypeError("A precise Feishu operator open_id is required");if(!Number.isFinite(o)||o<=0||o>10*6e4)throw new TypeError("Card-action probe timeout must be between 1 and 600000ms");let e=eke().replaceAll("-",""),a;try{a=await this.#C.im.v1.message.create({params:{receive_id_type:"open_id"},data:{receive_id:i,msg_type:"interactive",content:VW(e)}})}catch{throw this.#w(i,w(AP),"failure"),Nd("card_action_probe_send_failed","\u65E0\u6CD5\u53D1\u9001\u98DE\u4E66\u5361\u7247\u56DE\u8C03\u6D4B\u8BD5")}if(a?.code&&a.code!==0)throw this.#w(i,w(AP),"failure"),Nd("card_action_probe_send_failed","\u65E0\u6CD5\u53D1\u9001\u98DE\u4E66\u5361\u7247\u56DE\u8C03\u6D4B\u8BD5");let A=yn(a?.data?.message_id)??yn(a?.message_id);if(!A)throw this.#w(i,w(AP),"failure"),Nd("card_action_probe_send_failed","\u98DE\u4E66\u672A\u8FD4\u56DE\u6D4B\u8BD5\u5361\u7247\u7684\u6D88\u606F ID");return new Promise((r,s)=>{let g=setTimeout(()=>{let c=this.#m.get(A);!c||c.nonce!==e||(this.#m.delete(A),this.#w(i,w(rke),"timeout"),s(Nd("card_action_probe_timeout","\u5728\u89C4\u5B9A\u65F6\u95F4\u5185\u672A\u6536\u5230\u98DE\u4E66\u5361\u7247\u6309\u94AE\u56DE\u8C03")))},o);g.unref?.(),this.#m.set(A,{messageId:A,nonce:e,expectedOperatorOpenId:i,timeout:g,resolve:r,reject:s})})}#D(t){let o=yn(t?.context?.open_message_id);if(!o)return!1;let i=this.#m.get(o);if(!i)return!1;let e=t?.action?.value,a=oke(t);return e?.action!=="repair_verify"||e?.nonce!==i.nonce||a!==i.expectedOperatorOpenId?!1:(clearTimeout(i.timeout),this.#m.delete(o),this.#u.cardActionProbesVerified+=1,this.#w(a,w(tke),"success").finally(()=>{i.resolve({verified:!0,messageId:o,operatorOpenId:a})}),!0)}#w(t,o,i){let e=this.#C;return e?Promise.resolve().then(async()=>{let a=await e.im.v1.message.create({params:{receive_id_type:"open_id"},data:{receive_id:t,msg_type:"text",content:JSON.stringify({text:o})}});if(a?.code&&a.code!==0)throw new Error("Feishu callback repair notice failed");return!0}).catch(()=>(this.#h.warn?.(`[dsh-feishu] unable to send the callback repair ${i} notice`),!1)):(this.#h.warn?.(`[dsh-feishu] unable to send the callback repair ${i} notice`),Promise.resolve(!1))}async sendConnectionTest(t){if(!this.#u.ready||!this.#C){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}if(typeof t!="string"||!t.trim())throw new TypeError("Feishu connection test text is required");let o=async(e,a,A)=>{let r=await this.#C.im.v1.message.create({params:{receive_id_type:e},data:{receive_id:a,msg_type:"text",content:JSON.stringify({text:A})}});if(r?.code&&r.code!==0)throw new Error(`Feishu connection test failed: ${r.msg||r.code}`)},i=this.#i.find(e=>e!=="*");return i?(await o("open_id",i,t),{sent:!0}):ec({state:this.#l,text:t,channelLabel:w("\u98DE\u4E66\u673A\u5668\u4EBA"),send:async(e,a)=>{let A=typeof e?.chatId=="string"?e.chatId.trim():"";if(!A)throw Ir(w("\u98DE\u4E66\u673A\u5668\u4EBA"));await o("chat_id",A,a)}})}async sendProactiveText(t,o,{signal:i}={}){if(!this.#u.ready||!this.#C){let r=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw r.code="bot-not-connected",r}let e=t?.kind==="user"?"open_id":t?.kind==="group"?"chat_id":null,a=t?.kind==="user"?yn(t?.route?.openId):t?.kind==="group"?yn(t?.route?.chatId):null;if(!e||!a){let r=new TypeError("Invalid Feishu proactive delivery target");throw r.code="invalid-target",r}i?.throwIfAborted();let A=await this.#C.im.v1.message.create({params:{receive_id_type:e},data:{receive_id:a,msg_type:"text",content:JSON.stringify({text:o})}});if(A?.code&&A.code!==0){let r=new Error(`Feishu proactive delivery failed: ${A.msg||A.code}`);throw r.code="target-rejected",r}return{sent:!0}}async#T(t,o,i){this.#u.slashCommandRegistration="registering",this.#u.slashCommandsError=null;try{let e=await B6({appId:this.#t,appSecret:this.#r,domain:this.#g,httpInstance:t,signal:i,manifest:Zv});if(!o())return;this.#u.slashCommandRegistration="done",this.#u.slashCommandsRegistered=e.created.length,this.#u.slashCommandsExisting=e.existing.length,this.#u.slashCommandsFailed=e.failed.length,this.#u.slashCommandsError=e.failed.length>0?e.failed.map(a=>`/${a.command}: ${a.error?.message??String(a.error)}`).join("; "):null,e.created.length>0&&this.#h.info?.(`[dsh-feishu] registered ${e.created.length} slash command(s)`),e.failed.length>0&&this.#h.warn?.(`[dsh-feishu] ${e.failed.length} slash command(s) failed to register: ${this.#u.slashCommandsError}`)}catch(e){if(!o())return;this.#u.slashCommandRegistration="failed",this.#u.slashCommandsError=e?.message??String(e),this.#h.warn?.(`[dsh-feishu] slash command registration skipped: ${this.#u.slashCommandsError}`)}}stop(t={}){if(this.#S)return this.#S;let o;return o=this.#k(t).finally(()=>{this.#S===o&&(this.#S=null)}),this.#S=o,o}async#k({preserveError:t=!1}={}){let o=this.#Q;this.#Q===o&&(this.#Q=null),o?.abort(new DOMException("Feishu runtime stopped","AbortError"));let i=this.#y;return i&&await i.catch(()=>{}),this.#M({preserveError:t,abortController:o})}async#M({preserveError:t=!1,abortController:o}={}){let i=t?this.#u.lastError:null;this.#Q===o&&(this.#Q=null),o?.abort(new DOMException("Feishu runtime stopped","AbortError"));for(let A of this.#m.values())clearTimeout(A.timeout),this.#w(A.expectedOperatorOpenId,w(ake),"abort"),A.reject(Nd("abort","\u98DE\u4E66\u8FD0\u884C\u65F6\u5DF2\u505C\u6B62"));this.#m.clear(),this.#u.ready=!1;let e=this.#B;this.#B=null,e?.close({force:!0});let a=this.#f;return this.#f=null,a&&await a.waitForIdle(),this.#C=null,this.#u.feishuLongConnectionState=t?"failed":"idle",this.#u.slashCommandRegistration="idle",this.#u.lastError=i,this.status}};var gS=class extends lr{constructor(t){super({...t,rpcIdPrefix:"feishu",logPrefix:"dsh-feishu"})}};import{createHash as cke}from"node:crypto";import{mkdir as Ike,readFile as lke,rename as pke,unlink as dke,writeFile as hke}from"node:fs/promises";import{dirname as Eke}from"node:path";var lS="DSH_FEISHU_APP_SECRET";function ps(n){return typeof n=="string"&&n.trim()?n.trim():null}function f6(n){let t=ps(n);return t&&/^[A-Za-z0-9_-]{1,128}$/.test(t)?t:null}function Q6(n){return`bot_${cke("sha256").update(n).digest("hex").slice(0,24)}`}function Cke(n){let t=Array.isArray(n.ownerOpenIds)?n.ownerOpenIds:[n.ownerOpenId];return[...new Set(t.map(ps).filter(Boolean))]}function cS(n,{legacy:t=!1}={}){if(!n||typeof n!="object")return null;let o=ps(n.appId),i=Cke(n);if(!o||i.length===0)return null;let e=f6(n.id)??(t?Q6(o):null),a=ps(n.secretRef)??(t?lS:null);if(!e||!a||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))return null;let A=n.domain==="lark"?"lark":"feishu";return Object.freeze({id:e,appId:o,secretRef:a,ownerOpenIds:Object.freeze(i),domain:A,botName:ps(n.botName),botOpenId:ps(n.botOpenId),activated:n.activated??null,groupResponseMode:ao(n.groupResponseMode),groupMessagePermissionGranted:n.groupMessagePermissionGranted===!0,deletionPending:n.deletionPending===!0,connectedAt:ps(n.connectedAt),createdAt:ps(n.createdAt)??ps(n.connectedAt)})}function uke(n){if(!n||typeof n!="object")return null;if(n.version===2&&Array.isArray(n.bots)){let o=n.bots.map(A=>cS(A));if(o.some(A=>A===null))throw new Error("dsh-feishu config contains an invalid bot entry");let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.id)||e.has(A.secretRef)||a.has(A.appId))throw new Error("dsh-feishu config contains duplicate bot identities");i.add(A.id),e.add(A.secretRef),a.add(A.appId)}return{value:Object.freeze({version:2,bots:Object.freeze(o)}),migrated:!1}}let t=cS(n,{legacy:!0});return t?{value:Object.freeze({version:2,bots:Object.freeze([t])}),migrated:!0}:null}var IS=class{#e;#A=Object.freeze({version:2,bots:Object.freeze([])});#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=JSON.parse(await lke(this.#e,"utf8")),o=uke(t);if(!o)throw new Error("dsh-feishu config is incomplete or invalid");this.#A=o.value,o.migrated&&await this.#a(this.#A)}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=Object.freeze({version:2,bots:Object.freeze([])})}return this}get(){let t=this.#A.bots[0];if(!t)return null;let o=structuredClone(t);return o.ownerOpenId=o.ownerOpenIds[0],o}list(){return structuredClone(this.#A.bots)}getBot(t){let o=this.#A.bots.find(i=>i.id===t);return o?structuredClone(o):null}async save(t){let o={...t};o.id||(o.id=Q6(ps(o.appId)??"invalid")),o.secretRef||(o.secretRef=lS);let i=cS(o);if(!i)throw new Error("Refusing to persist incomplete dsh-feishu configuration");return await this.#r([i]),this.get()}async saveBot(t){let o=cS(t);if(!o)throw new Error("Refusing to persist incomplete dsh-feishu bot configuration");return this.#g(i=>{if(i.find(r=>r.secretRef===o.secretRef&&r.id!==o.id))throw new Error("Refusing to share a credential reference between Feishu bots");if(i.find(r=>r.appId===o.appId&&r.id!==o.id))throw new Error("Refusing to persist the same Feishu app twice");let A=i.findIndex(r=>r.id===o.id);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async removeBot(t){if(!f6(t))throw new TypeError("Invalid Feishu bot id");return this.#g(o=>{let i=o.findIndex(a=>a.id===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await dke(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=Object.freeze({version:2,bots:Object.freeze([])})});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o=Object.freeze({version:2,bots:Object.freeze([...t])}),i=this.#t.then(async()=>{await this.#a(o),this.#A=o});this.#t=i.then(()=>{},()=>{}),await i}async#g(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:2,bots:Object.freeze(e)});await this.#a(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#a(t){await Ike(Eke(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await hke(o,`${JSON.stringify(t,null,2)} -`,{encoding:"utf8",mode:384}),await pke(o,this.#e)}};import{randomUUID as O6}from"node:crypto";var tP=new Set(["starting","qr_ready","polling","slow_down","domain_switched","saving"]),Bke=new Set(["polling","slow_down","domain_switched"]),vi=Object.freeze({IDLE:"idle",STARTING:"starting",QR_READY:"qr_ready",POLLING:"polling",SLOW_DOWN:"slow_down",DOMAIN_SWITCHED:"domain_switched",SAVING:"saving",SUCCEEDED:"succeeded",EXPIRED:"expired",CANCELLED:"cancelled",ERROR:"error"});function y6(n){return["access_denied","expired_token","abort"].includes(n?.code)?n.code:"registration_failed"}function rP(n){let t=y6(n);return{code:t,message:{access_denied:"Registration was denied.",abort:"Registration was cancelled.",expired_token:"The registration QR code expired."}[t]??"Unable to register the Feishu app."}}function fke(n){let t=Number(n);if(!Number.isFinite(t)||t<=0)throw new TypeError("registerApp onQRCodeReady returned an invalid expireIn");return t}function Qke(n){if(n!==void 0){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError("registerApp returned invalid user_info");return{...n}}}var yg=class{#e;#A;#t;#r;#g;#a=0;#n=null;#i;constructor({registerApp:t,onCredentials:o,now:i=Date.now,setTimeout:e=globalThis.setTimeout,clearTimeout:a=globalThis.clearTimeout}={}){if(typeof t!="function")throw new TypeError("RegistrationManager requires a registerApp function");if(typeof o!="function")throw new TypeError("RegistrationManager requires an onCredentials function");if(typeof i!="function"||typeof e!="function"||typeof a!="function")throw new TypeError("RegistrationManager clock dependencies must be functions");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#i=this.#l(null,vi.IDLE)}start(t={}){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("Registration options must be an object");this.#B();let o={id:++this.#a,controller:new AbortController,qrCodeUrl:null,expiresAt:null,pollIntervalSeconds:null,expiryTimer:null};this.#n=o,this.#i=this.#l(o,vi.STARTING);let i={...t,signal:o.controller.signal,onQRCodeReady:a=>this.#s(o,a),onStatusChange:a=>this.#c(o,a)};return Promise.resolve().then(()=>this.#e(i)).then(a=>this.#p(o,a),a=>this.#d(o,a)),this.status()}status(){this.#h();let t={...this.#i};t.error&&(t.error={...t.error});let o=this.#n;return o&&o.expiresAt!==null&&tP.has(t.state)&&(t.remainingSeconds=Math.max(0,Math.ceil((o.expiresAt-this.#t())/1e3))),t}cancel(){let t=this.#n;return t?(this.#C(t,vi.CANCELLED,{error:{code:"abort",message:"Registration was cancelled."}}),t.controller.abort(),this.status()):this.status()}#I(t){return this.#n===t}#l(t,o,i={}){let e={state:o,attempt:t?.id??this.#a,updatedAt:this.#t(),...i};return t?.qrCodeUrl&&tP.has(o)&&(e.qrCodeUrl=t.qrCodeUrl,e.expiresAt=t.expiresAt),t?.pollIntervalSeconds!==null&&tP.has(o)&&(e.pollIntervalSeconds=t.pollIntervalSeconds),e}#o(t,o,i={}){this.#I(t)&&(this.#i=this.#l(t,o,i))}#s(t,o){if(!this.#I(t))return;if(typeof o?.url!="string"||!o.url)throw new TypeError("registerApp onQRCodeReady returned an invalid URL");let i=fke(o.expireIn);t.qrCodeUrl=o.url,t.expiresAt=this.#t()+i*1e3,this.#f(t),t.expiryTimer=this.#r(()=>this.#E(t),i*1e3),t.expiryTimer?.unref?.(),this.#o(t,vi.QR_READY)}#c(t,o){!this.#I(t)||!Bke.has(o?.status)||(o.status===vi.SLOW_DOWN&&Number.isFinite(Number(o.interval))&&(t.pollIntervalSeconds=Number(o.interval)),this.#o(t,o.status))}async#p(t,o){if(!this.#I(t))return;let i=o?.client_id,e=o?.client_secret;if(typeof i!="string"||!i||typeof e!="string"||!e){this.#C(t,vi.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}let a;try{a=Qke(o.user_info)}catch{this.#C(t,vi.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}this.#f(t),t.qrCodeUrl=null,t.expiresAt=null,t.pollIntervalSeconds=null,this.#o(t,vi.SAVING);try{await this.#A({client_id:i,client_secret:e,user_info:a})}catch{this.#I(t)&&this.#C(t,vi.ERROR,{error:{code:"credentials_callback_failed",message:"Unable to store the Feishu credentials."}});return}this.#I(t)&&this.#C(t,vi.SUCCEEDED)}#d(t,o){if(!this.#I(t))return;let i=y6(o);if(i==="expired_token"){this.#C(t,vi.EXPIRED,{error:rP(o)});return}if(i==="abort"){this.#C(t,vi.CANCELLED,{error:rP(o)});return}this.#C(t,vi.ERROR,{error:rP(o)})}#h(){let t=this.#n;t&&t.expiresAt!==null&&this.#t()>=t.expiresAt&&this.#E(t)}#E(t){this.#I(t)&&(this.#C(t,vi.EXPIRED,{error:{code:"expired_token",message:"The registration QR code expired."}}),t.controller.abort())}#C(t,o,i={}){this.#I(t)&&(this.#f(t),this.#i=this.#l(t,o,i),this.#n=null)}#f(t){t.expiryTimer!==null&&(this.#g(t.expiryTimer),t.expiryTimer=null)}#B(){let t=this.#n;t&&(this.#f(t),this.#n=null,t.controller.abort())}};var yke="card.action.trigger",mke="im:message:readonly",Ske="im:resource",Su="callback_repair";function wke(n){return n==="lark"?"accounts.larksuite.com":"accounts.feishu.cn"}function Dke(n){return n==="lark"?"open.larksuite.com":"open.feishu.cn"}function aP(n,t,o="feishu",i="Feishu app update"){let e;try{e=new URL(n)}catch{throw new Error(`${i} returned an invalid verification URL`)}let a=o==="feishu"||o==="lark",A=e.searchParams.getAll("clientID"),r=e.searchParams.getAll("tp"),s=e.searchParams.getAll("addons"),g=String(t).includes("{{")||String(t).includes("}}")||[...e.searchParams.values()].some(c=>c.includes("{{")||c.includes("}}"));if(!a||e.protocol!=="https:"||e.hostname!==Dke(o)||e.port!==""||e.username!==""||e.password!==""||r.length!==1||r[0]!=="sdk"||A.length!==1||A[0]!==t||e.searchParams.has("createOnly")||s.length!==1||!s[0]?.trim()||g)throw new Error(`${i} returned an unsafe verification URL`);return e.toString()}function Oke(n,t,o="feishu"){return aP(n,t,o,"Feishu callback repair")}var pS=class{#e;#A;#t;constructor({registerApp:t,onCredentials:o,appId:i,domain:e="feishu"}={}){if(typeof t!="function")throw new TypeError("registerApp is required");if(typeof o!="function")throw new TypeError("onCredentials is required");if(typeof i!="string"||!i.trim())throw new TypeError("appId is required");if(e!=="feishu"&&e!=="lark")throw new TypeError("domain is invalid");this.#A=i.trim(),this.#t=e,this.#e=new yg({registerApp:a=>t({...a,onQRCodeReady:A=>{Oke(A?.url,this.#A,this.#t),a.onQRCodeReady(A)}}),onCredentials:o})}start(){return this.#e.start({source:"deepseek-harness-card-action-repair",domain:wke(this.#t),appId:this.#A,addons:{preset:!1,scopes:{tenant:[mke,Ske,...nS]},callbacks:{items:[yke]}}})}status(){return this.#e.status()}cancel(){return this.#e.cancel()}};var bke="im:message.group_msg",hS="group_message_permission";function Mke(n){return n==="lark"?"accounts.larksuite.com":"accounts.feishu.cn"}function _ke(n,t,o="feishu"){return aP(n,t,o,"Feishu group message permission update")}var dS=class{#e;#A;#t;constructor({registerApp:t,onCredentials:o,appId:i,domain:e="feishu"}={}){if(typeof t!="function")throw new TypeError("registerApp is required");if(typeof o!="function")throw new TypeError("onCredentials is required");if(typeof i!="string"||!i.trim())throw new TypeError("appId is required");if(e!=="feishu"&&e!=="lark")throw new TypeError("domain is invalid");this.#A=i.trim(),this.#t=e,this.#e=new yg({registerApp:a=>t({...a,onQRCodeReady:A=>{_ke(A?.url,this.#A,this.#t),a.onQRCodeReady(A)}}),onCredentials:o})}start(){return this.#e.start({source:"deepseek-harness-group-message-permission",domain:Mke(this.#t),appId:this.#A,addons:{preset:!1,scopes:{tenant:[bke]}}})}status(){return this.#e.status()}cancel(){return this.#e.cancel()}};var m6=Object.freeze(["im:message.p2p_msg:readonly","im:message.group_at_msg:readonly","im:message:readonly","im:message:send_as_bot","im:message.reactions:write_only","im:message:recall","im:resource","cardkit:card:write",...nS]);var iP=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]),ES=new Set([...iP,"saving"]),S6=new Set([Su,hS]),w6="*",Tke=12e4,Nke=6e5;function b6(){return{ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1}}function wu(n){return n?n.status:b6()}function Du(n){return n.ready===!0&&n.feishuLongConnectionState==="connected"&&n.harnessReachable===!0}function M6(n){return n.length>12?`${n.slice(0,8)}\u2022\u2022\u2022\u2022${n.slice(-4)}`:"cli_\u2022\u2022\u2022\u2022"}function Rke(n){return{name:n.botName,appIdMasked:M6(n.appId),activated:n.activated,domain:n.domain}}function kke({connected:n,error:t,connection:o}){return n?"connected":t||o.feishuLongConnectionState==="failed"?"error":"disconnected"}function vke(){return`bot_${O6().replaceAll("-","")}`}function Pke(){return`reg_${O6().replaceAll("-","")}`}function D6(n){return`DSH_FEISHU_APP_SECRET_${n.slice(4).toUpperCase()}`}function CS(n){return JSON.stringify({id:n.id,appId:n.appId,secretRef:n.secretRef,ownerOpenIds:n.ownerOpenIds,domain:n.domain,botName:n.botName,botOpenId:n.botOpenId,activated:n.activated,groupResponseMode:ao(n.groupResponseMode),groupMessagePermissionGranted:n.groupMessagePermissionGranted===!0,deletionPending:n.deletionPending===!0,connectedAt:n.connectedAt??null,createdAt:n.createdAt??null})}function uS(n){return typeof n=="string"&&n.trim()?n.trim():null}var Ou=class{#e;#A;#t;#r;#g;#a;#n;#i;#I=new Map;#l=new Map;#o=new Map;#s=new Map;#c=new Map;#p=null;#d=Promise.resolve();#h=new Map;#E=1;#C;#f=!1;constructor({registerApp:t,verifyApp:o,credentials:i,configStore:e,createRuntime:a,deleteState:A=async()=>{},createBotId:r=vke,createRegistrationId:s=Pke,callbackProbeTimeoutMs:g=Tke}){if(typeof t!="function")throw new Error("registerApp is required");if(typeof o!="function")throw new Error("verifyApp is required");if(!i)throw new Error("credentials service is required");if(!e||typeof e.list!="function")throw new Error("multi-bot config store is required");if(typeof a!="function")throw new Error("createRuntime is required");if(typeof A!="function")throw new Error("deleteState must be a function");if(!Number.isFinite(g)||g<=0||g>Nke)throw new TypeError("callbackProbeTimeoutMs must be between 1 and 600000ms");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#C=g}async initialize(){if(this.#f)return this.status();let t=this.#r.list(),o=!1;return await Promise.allSettled(t.map(i=>this.#_(i.id,async()=>{let e=wu(this.#I.get(i.id));if(Du(e)||e.feishuLongConnectionState==="connecting"||e.feishuLongConnectionState==="reconnecting")return;if(o=!0,i.deletionPending){this.#l.set(i.id,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"});return}let a;try{a=await this.#t.resolve(i.secretRef)}catch{this.#l.set(i.id,{code:"missing_credentials",message:"\u65E0\u6CD5\u8BFB\u53D6\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u3002"});return}if(!a?.value){this.#l.set(i.id,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"});return}try{await this.#b(i,a.value),this.#l.delete(i.id)}catch{this.#l.set(i.id,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}}))),o&&this.#v(),this.status()}startRegistration(){this.#M();let t=this.#i();if(typeof t!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(t)||this.#o.has(t))throw new Error("Registration id generator returned an invalid or duplicate id");let o={id:t,manager:null,botId:null,createdNew:!1,cancelled:!1};return o.manager=new yg({registerApp:this.#e,onCredentials:i=>this.#L(()=>this.#u(o,i))}),this.#o.set(t,o),this.#p=t,this.#U(),o.manager.start({source:"deepseek-harness",createOnly:!0,appPreset:{name:"{user} \u7684\u5317\u6C47\u661F\u6CB3 AI \u52A9\u624B",desc:"\u8FDE\u63A5\u98DE\u4E66\u4E0E DeepSeek Harness\uFF0C\u5728\u804A\u5929\u4E2D\u4F7F\u7528\u4F01\u4E1A AI \u52A9\u624B\u3002"},addons:{preset:!1,scopes:{tenant:[...m6]},events:{items:{tenant:["im.message.receive_v1"]}},callbacks:{items:["card.action.trigger"]}}}),this.#v(),this.registrationStatus(t)}startCallbackRepair(t,{actorOpenId:o,chatId:i}={}){this.#M();let e=this.#k(t);if(e.deletionPending)throw new Error("Cannot repair a Feishu bot pending deletion");let a=this.#s.get(t),A=a?this.#o.get(a):null;if(A&&ES.has(A.manager.status().state)){if(A.operation!==Su)throw new Error("Another Feishu app update is already active for this bot");return this.registrationStatus(A.id)}this.#s.delete(t);let r=this.#i();if(typeof r!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(r)||this.#o.has(r))throw new Error("Registration id generator returned an invalid or duplicate id");let s={id:r,operation:Su,manager:null,botId:t,createdNew:!1,cancelled:!1,remoteCommitted:!1,processing:null,publicError:null,stage:"authorizing",target:structuredClone(e),targetFingerprint:CS(e),initiator:{actorOpenId:uS(o),chatId:uS(i)}};return s.manager=new pS({registerApp:this.#e,appId:e.appId,domain:e.domain,onCredentials:g=>{s.remoteCommitted=!0;let I=this.#Q(s,g).finally(()=>{s.processing===I&&(s.processing=null)});return s.processing=I,I}}),this.#o.set(r,s),this.#s.set(t,r),this.#p=r,this.#U(),s.manager.start(),this.#v(),this.registrationStatus(r)}startGroupMessagePermission(t){this.#M();let o=this.#k(t);if(o.deletionPending)throw new Error("Cannot update permissions for a Feishu bot pending deletion");let i=this.#s.get(t),e=i?this.#o.get(i):null;if(e&&ES.has(e.manager.status().state)){if(e.operation!==hS)throw new Error("Another Feishu app update is already active for this bot");return this.registrationStatus(e.id)}this.#s.delete(t);let a=this.#i();if(typeof a!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(a)||this.#o.has(a))throw new Error("Registration id generator returned an invalid or duplicate id");let A={id:a,operation:hS,manager:null,botId:t,createdNew:!1,cancelled:!1,remoteCommitted:!1,processing:null,publicError:null,stage:"authorizing",target:structuredClone(o),targetFingerprint:CS(o),initiator:{actorOpenId:null,chatId:null}};return A.manager=new dS({registerApp:this.#e,appId:o.appId,domain:o.domain,onCredentials:r=>{A.remoteCommitted=!0;let g=this.#S(A,r).finally(()=>{A.processing===g&&(A.processing=null)});return A.processing=g,g}}),this.#o.set(a,A),this.#s.set(t,a),this.#p=a,this.#U(),A.manager.start(),this.#v(),this.registrationStatus(a)}hasRegistration(t){return this.#o.has(t)}registrationStatus(t){let o=this.#o.get(t);return o?this.#B({registration:o,selectedBotId:o.botId}):null}async cancelRegistration(t=this.#p){let o=this.#o.get(t);if(!o)return this.status();let i=o.manager.status().state;return S6.has(o.operation)&&i==="saving"?this.registrationStatus(t):ES.has(i)?(o.cancelled=!0,o.manager.cancel(),await this.#L(async()=>{o.createdNew&&o.botId&&this.#c.get(o.botId)===o.id&&this.#r.getBot(o.botId)&&await this.#_(o.botId,()=>this.#w(o.botId))}),this.#v(),this.registrationStatus(t)??this.status()):this.registrationStatus(t)}status(t){return this.#B({registration:this.#o.get(this.#p)??null,selectedBotId:t})}async bindCredentials({appId:t,appSecret:o,domain:i="feishu"}={}){this.#M();let e=typeof t=="string"?t.trim():"",a=typeof o=="string"?o.trim():"",A=i==="lark"?"lark":"feishu";if(!e||!a)throw new TypeError("Feishu App ID and App Secret are required");return this.#L(async()=>{this.#M();let r=await this.#A({appId:e,appSecret:a,domain:A});this.#M();let s=this.#r.list().find(f=>f.appId===e),g=s?.id??this.#n();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??D6(g),I=await this.#t.resolve(c).catch(()=>{}),d={...s,id:g,appId:e,secretRef:c,ownerOpenIds:s?.ownerOpenIds?.length?s.ownerOpenIds:[w6],domain:A,botName:r.name,botOpenId:r.openId,activated:r.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()};await this.#t.set(c,a);let B;try{B=await this.#r.saveBot(d)}catch(f){throw await this.#T(c,I),f}return await this.#_(g,async()=>{try{await this.#b(B,a),this.#l.delete(g)}catch{this.#l.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u7ED1\u5B9A\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"})}}),this.#v(),this.status(g)})}async reconnectBot(t){return this.#M(),this.#_(t,async()=>{let o=this.#k(t);if(o.deletionPending)return this.#l.set(t,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"}),this.status(t);if(Du(wu(this.#I.get(t))))return this.status(t);let i;try{i=await this.#t.resolve(o.secretRef)}catch{i=null}if(!i?.value)return this.#l.set(t,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"}),this.#v(),this.status(t);try{await this.#b(o,i.value),this.#l.delete(t)}catch{this.#l.set(t,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}return this.#v(),this.status(t)})}async sendConnectionTest(t){return this.#M(),this.#_(t,async()=>{let o=this.#k(t),i=this.#I.get(t);if(!Du(wu(i))||typeof i.sendConnectionTest!="function"){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}return i.sendConnectionTest(ba(`${o.botName}\uFF08${M6(o.appId)}\uFF09`,"\u98DE\u4E66\u673A\u5668\u4EBA"))})}async sendProactiveText(t,o,i,e={}){return this.#M(),this.#_(t,async()=>{this.#k(t);let a=this.#I.get(t);if(!Du(wu(a))||typeof a.sendProactiveText!="function"){let A=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw A.code="bot-not-connected",A}return a.sendProactiveText(o,i,e)})}async disconnectBot(t){return this.#M(),this.#_(t,async()=>(this.#k(t),await this.#D(t),this.#l.delete(t),this.#v(),this.status(t)))}async updateGroupResponseMode(t,o){if(this.#M(),!Xm(o))throw new TypeError("Invalid Feishu group response mode");return this.#L(()=>this.#_(t,async()=>{let i=this.#k(t);if(o==="all"&&i.groupMessagePermissionGranted!==!0){let a=new Error("Authorize im:message.group_msg before enabling all group messages");throw a.code="group_message_permission_required",a}let e=await this.#r.saveBot({...i,groupResponseMode:o});return this.#I.get(t)?.setGroupResponseMode?.(e.groupResponseMode),this.#v(),this.status(t)}))}async deleteBot(t){return this.#M(),this.#L(()=>this.#_(t,async()=>(this.#k(t),await this.#w(t),this.#v(),this.status())))}async reconnect(){let t=this.#r.list()[0];return t?this.reconnectBot(t.id):this.status()}async disconnect(){let t=this.#r.list()[0];return t?this.deleteBot(t.id):this.status()}async close(){if(this.#f)return;this.#f=!0;let t=[];for(let o of this.#o.values()){let i=o.manager.status().state;S6.has(o.operation)&&i==="saving"?(o.manager.cancel(),o.processing&&t.push(o.processing)):ES.has(i)&&(o.cancelled=!0,o.manager.cancel())}await this.#d,await Promise.allSettled([...this.#h.values()]),await Promise.allSettled([...this.#I.keys()].map(o=>this.#D(o))),await Promise.allSettled(t),await this.#d,await Promise.allSettled([...this.#h.values()]),await Promise.allSettled([...this.#I.keys()].map(o=>this.#D(o)))}#B({registration:t,selectedBotId:o}={}){let i=this.#r.list().map(I=>{let d=wu(this.#I.get(I.id)),B=Du(d),f=this.#l.get(I.id)??null;return{botId:I.id,phase:kke({connected:B,error:f,connection:d}),connected:B,configured:!0,groupResponseMode:ao(I.groupResponseMode),groupMessagePermissionGranted:I.groupMessagePermissionGranted===!0,bot:Rke(I),connection:d,lastMessageError:Vr(d.lastMessageError),error:f}}),e=t?this.#y(t):{state:"idle",attempt:0,updatedAt:Date.now()},a=iP.has(e.state),A=e.state==="saving",r=!!t&&(a||A),s=i.find(I=>I.botId===o)??(r?null:i[0]??null),g=i.some(I=>I.connected),c=s?.phase??"unconfigured";return a?c="registering":A?c="connecting":e.state==="error"&&!s&&(c="error"),{schemaVersion:2,revision:this.#E,phase:c,connected:s?.connected??!1,configured:i.length>0,bot:s?.bot??null,connection:s?.connection??b6(),error:s?.error??e.error??null,registration:e,bots:i,totals:{configured:i.length,connected:i.filter(I=>I.connected).length},anyConnected:g}}#y(t){let o=t.manager.status();return{...o,attempt:t.id,...t.botId?{botId:t.botId}:{},...t.operation?{operation:t.operation}:{},...t.stage?{stage:t.stage}:{},...o.state==="error"&&t.publicError?{error:{...t.publicError}}:{}}}async#S(t,o){let i=o.client_id,e=o.client_secret,a=uS(o.user_info?.open_id),A=o.user_info?.tenant_brand,r=t.target;if(t.cancelled)throw this.#m(t,"abort","Group message permission update was cancelled before local activation.");if(i!==r.appId)throw this.#m(t,"repair_app_mismatch","Feishu returned credentials for a different app.");if(!a)throw this.#m(t,"repair_owner_missing","Feishu returned no permission operator identity.");if(A!==void 0&&A!==r.domain)throw this.#m(t,"repair_domain_mismatch","Feishu returned credentials for a different account domain.");if(!r.ownerOpenIds.includes(w6)&&!r.ownerOpenIds.includes(a))throw this.#m(t,"repair_owner_mismatch","The Feishu permission operator is not an owner of this configured bot.");t.stage="verifying_identity";let s;try{s=await this.#A({appId:i,appSecret:e,domain:r.domain})}catch(g){throw this.#m(t,"repair_credentials_invalid","Feishu could not verify the updated app credentials.",g)}if(r.botOpenId&&s?.openId!==r.botOpenId)throw this.#m(t,"repair_bot_mismatch","The updated Feishu app belongs to a different bot identity.");await this.#L(()=>this.#_(t.botId,async()=>{let g=this.#r.getBot(t.botId);if(!g||g.deletionPending||CS(g)!==t.targetFingerprint)throw this.#m(t,"repair_target_changed","The Feishu bot changed while its permission update was in progress.");let c;try{c=await this.#t.resolve(g.secretRef)}catch(d){throw this.#m(t,"credential_update_failed","Unable to read the current Feishu credential.",d)}if(c?.value!==e){t.stage="persisting_secret";try{await this.#t.set(g.secretRef,e)}catch(B){if((await this.#t.resolve(g.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_update_failed","Unable to store the updated Feishu credential.",B)}if((await this.#t.resolve(g.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_state_unknown","The updated Feishu credential could not be confirmed after writing.")}t.stage="enabling_all_messages";let I;try{I=await this.#r.saveBot({...g,groupMessagePermissionGranted:!0,groupResponseMode:"all"})}catch(d){throw this.#m(t,"group_message_permission_save_failed","The permission was accepted, but all-message mode could not be saved.",d)}t.stage="restarting";try{await this.#b(I,e)}catch(d){throw this.#l.set(t.botId,{code:"connection_failed",message:"\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u5F00\u901A\uFF0C\u4F46\u673A\u5668\u4EBA\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#v(),this.#m(t,"group_message_permission_connection_failed","The permission was accepted, but the Feishu runtime could not restart.",d)}this.#l.delete(t.botId),t.stage="verified",t.publicError=null,this.#v()}))}async#Q(t,o){let i=o.client_id,e=o.client_secret,a=uS(o.user_info?.open_id),A=o.user_info?.tenant_brand,r=t.target;if(t.cancelled)throw this.#m(t,"abort","Callback repair was cancelled before local activation.");if(i!==r.appId)throw this.#m(t,"repair_app_mismatch","Feishu returned credentials for a different app.");if(!a)throw this.#m(t,"repair_owner_missing","Feishu returned no repair operator identity.");if(A!==void 0&&A!==r.domain)throw this.#m(t,"repair_domain_mismatch","Feishu returned credentials for a different account domain.");t.stage="verifying_identity";let s;try{s=await this.#A({appId:i,appSecret:e,domain:r.domain})}catch(c){throw this.#m(t,"repair_credentials_invalid","Feishu could not verify the repaired app credentials.",c)}if(r.botOpenId&&s?.openId!==r.botOpenId)throw this.#m(t,"repair_bot_mismatch","The repaired Feishu app belongs to a different bot identity.");let g=await this.#L(()=>this.#_(t.botId,async()=>{let c=this.#r.getBot(t.botId);if(!c||c.deletionPending||CS(c)!==t.targetFingerprint)throw this.#m(t,"repair_target_changed","The Feishu bot changed while its callback repair was in progress.");let I;try{I=await this.#t.resolve(c.secretRef)}catch(f){throw this.#m(t,"credential_update_failed","Unable to read the current Feishu credential.",f)}if(I?.value!==e){t.stage="persisting_secret";try{await this.#t.set(c.secretRef,e)}catch(Q){if((await this.#t.resolve(c.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_update_failed","Unable to store the repaired Feishu credential.",Q)}if((await this.#t.resolve(c.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_state_unknown","The repaired Feishu credential could not be confirmed after writing.")}let B;t.stage="restarting";try{await this.#b(c,e),B=this.#I.get(t.botId)}catch(f){throw this.#l.set(t.botId,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u56DE\u8C03\u4FEE\u590D\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#v(),this.#m(t,"repair_connection_failed","The repaired Feishu runtime could not be started.",f)}if(!B)throw this.#m(t,"repair_connection_failed","The repaired Feishu runtime is unavailable.");return this.#l.delete(t.botId),this.#v(),B}));if(typeof g.beginCardActionProbe!="function")throw this.#m(t,"card_action_probe_unavailable","The Feishu runtime cannot verify card callbacks.");t.stage="awaiting_callback";try{if((await g.beginCardActionProbe({expectedOperatorOpenId:t.initiator.actorOpenId??a,timeoutMs:this.#C,...t.initiator.chatId?{chatId:t.initiator.chatId}:{}}))?.verified!==!0){let I=new Error("Feishu runtime returned no callback proof");throw I.code="card_action_probe_failed",I}}catch(c){let I=c?.code==="card_action_probe_timeout"?"card_action_probe_timeout":c?.code==="card_action_probe_unavailable"?"card_action_probe_unavailable":c?.code==="card_action_probe_send_failed"?"card_action_probe_send_failed":"card_action_probe_failed";throw this.#m(t,I,I==="card_action_probe_timeout"?"Timed out waiting for the Feishu callback verification button.":"The Feishu card callback probe failed.",c)}t.stage="verified",t.publicError=null,this.#v()}#m(t,o,i,e){t.publicError={code:o,message:i};let a=new Error(i,e?{cause:e}:void 0);return a.code=o,a}async#u(t,o){if(t.cancelled)throw new Error("Registration was cancelled");let i=o.client_id,e=o.client_secret,a=o.user_info?.open_id,A=o.user_info?.tenant_brand==="lark"?"lark":"feishu";if(!a)throw new Error("Feishu registration returned no owner open_id");let r=await this.#A({appId:i,appSecret:e,domain:A});if(t.cancelled)throw new Error("Registration was cancelled");let s=this.#r.list().find(Q=>Q.appId===i),g=s?.id??this.#n();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??D6(g),I=this.#c.get(g),d=await this.#t.resolve(c).catch(()=>{});await this.#t.set(c,e);let B;try{B=await this.#r.saveBot({...s,id:g,appId:i,secretRef:c,ownerOpenIds:[...new Set([...s?.ownerOpenIds??[],a])],domain:A,botName:r.name,botOpenId:r.openId,activated:r.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()}),t.botId=g,t.createdNew=!s,this.#c.set(g,t.id)}catch(Q){try{await this.#T(c,d)}catch(y){throw new Error("Unable to restore the Feishu credential after a config failure.",{cause:y})}throw Q}if(t.cancelled)throw t.createdNew?await this.#_(g,()=>this.#w(g)):(await this.#r.saveBot(s),await this.#T(c,d),I?this.#c.set(g,I):this.#c.delete(g)),new Error("Registration was cancelled");let f=!1;try{if(await this.#_(g,()=>this.#b(B,e)),t.cancelled)throw t.createdNew?await this.#_(g,()=>this.#w(g)):(await this.#r.saveBot(s),await this.#T(c,d),I?this.#c.set(g,I):this.#c.delete(g),d?.value&&!s.deletionPending?await this.#_(g,()=>this.#b(s,d.value)):await this.#_(g,()=>this.#D(g))),f=!0,new Error("Registration was cancelled");this.#l.delete(g),this.#v()}catch(Q){if(t.cancelled)throw!f&&t.createdNew&&this.#r.getBot(g)?await this.#_(g,()=>this.#w(g)):!f&&s&&(await this.#r.saveBot(s),await this.#T(c,d),I?this.#c.set(g,I):this.#c.delete(g),!this.#f&&d?.value&&!s.deletionPending?await this.#_(g,()=>this.#b(s,d.value)):await this.#_(g,()=>this.#D(g))),this.#v(),Q;if(s&&d?.value)try{throw await this.#r.saveBot(s),await this.#T(c,d),I?this.#c.set(g,I):this.#c.delete(g),s.deletionPending?(await this.#_(g,()=>this.#D(g)),this.#l.set(g,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"})):(await this.#_(g,()=>this.#b(s,d.value)),this.#l.delete(g)),this.#v(),Q}catch(y){throw y===Q?Q:(this.#l.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u8FDE\u63A5\u66F4\u65B0\u5931\u8D25\uFF0C\u4E14\u539F\u8FDE\u63A5\u65E0\u6CD5\u6062\u590D\uFF0C\u8BF7\u91CD\u8BD5\u3002"}),this.#v(),new Error("Unable to restore the previous Feishu bot connection.",{cause:y}))}throw this.#l.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u521B\u5EFA\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#v(),Q}}async#b(t,o){await this.#D(t.id);let i=await this.#g({botId:t.id,config:t,appSecret:o,repair:this.#R(t.id)});this.#I.set(t.id,i);try{await i.start()}catch(e){throw this.#I.get(t.id)===i&&this.#I.delete(t.id),await i.stop({preserveError:!0}).catch(()=>{}),e}}#R(t){let o=i=>{let e=this.#o.get(i);return e?.operation===Su&&e.botId===t?e:null};return Object.freeze({start:({actorOpenId:i,chatId:e}={})=>this.startCallbackRepair(t,{actorOpenId:i,chatId:e}),status:({attemptId:i}={})=>o(i)?this.registrationStatus(i):null,cancel:async({attemptId:i}={})=>o(i)?this.cancelRegistration(i):this.status(t)})}async#D(t){let o=this.#I.get(t);this.#I.delete(t),o&&await o.stop()}async#w(t){let o=this.#r.getBot(t);if(o){o.deletionPending||(o=await this.#r.saveBot({...o,deletionPending:!0})),await this.#D(t);try{await this.#t.unset(o.secretRef)}catch(i){throw this.#l.set(t,{code:"credential_removal_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu credential.",{cause:i})}try{await this.#a({botId:t,config:o})}catch(i){throw this.#l.set(t,{code:"state_cleanup_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u7684\u672C\u5730\u4F1A\u8BDD\u6570\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu bot session state.",{cause:i})}await this.#r.removeBot(t),this.#l.delete(t),this.#c.delete(t)}}async#T(t,o){o?.value?await this.#t.set(t,o.value):await this.#t.unset(t)}#k(t){let o=this.#r.getBot(t);if(!o)throw new Error("Unknown Feishu bot");return o}#M(){if(this.#f)throw new Error("The Feishu controller is closed")}#L(t){let o=this.#d.then(t,t);return this.#d=o.then(()=>{},()=>{}),o}#_(t,o){let e=(this.#h.get(t)??Promise.resolve()).then(o,o),a=e.then(()=>{},()=>{});return this.#h.set(t,a),a.finally(()=>{this.#h.get(t)===a&&this.#h.delete(t)}),e}#U(){if(!(this.#o.size<=32))for(let[t,o]of this.#o){if(t===this.#p)continue;let i=o.manager.status().state;if(!iP.has(i)&&i!=="saving"&&this.#o.delete(t),this.#o.size<=32)break}}#v(){this.#E+=1}};function Lke(n){for(let t of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY"]){let o=n?.[t];if(typeof o=="string"&&o.trim())return o.trim()}}function Uke(n,t=o=>new _6.default(o)){let o=Lke(n);return o?t(o):void 0}function Hke(n){let t=Oc(n.dshHome??process.env.DSH_HOME??Rd(Gke(),".dsh")),o=Oc(n.dataDir??Rd(t,"integrations","dsh-feishu"));return{root:o,config:Oc(n.configPath??Rd(o,"config.json")),legacyState:Oc(n.statePath??Rd(o,"state.json")),bots:Oc(n.botsDir??Rd(o,"bots")),workspaces:Oc(n.workspacesPath??Rd(o,"workspaces.json"))}}async function oP(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-feishu requires ctx.credentials");let i=Aa(n,t),e=o.lark??Uv,a=o.Controller??Ou,A=o.ConfigStore??IS,r=o.StateStore??Wm,s=o.HarnessClient??gS,g=o.FeishuRuntime??sS,c=o.verifyFeishuApp??FW,I=Ee=>c({...Ee,httpInstance:e.defaultHttpInstance}),d=o.createConnectionSupervisor??Hv,B=typeof n.logger=="function"?n.logger("dsh-feishu"):n.logger??console,f=()=>Ra(n),Q=Hke(t),y=await new A(Q.config).load(),m=Oc(t.workspace??process.cwd()),_=o.WorkspaceStore??ea,T=o.workspaces??await new _(Q.workspaces,{defaultWorkspace:m}).load(),R=typeof y.list=="function",F=()=>R?y.list():[],K=F();R&&await T.reconcile(K.map(Ee=>Ee.id)),await Promise.all(K.map(Ee=>T.ensure(Ee.id,{defaultAgentPreset:t.agentPreset})));let L=typeof y.removeBot=="function"?Pa(y,{workspaces:T,method:"removeBot",botIdFromRemoved:Ee=>Ee.id,saveMethod:"saveBot",botIdFromSave:Ee=>Ee?.id}):y,q=new Map,z=Ee=>!Ee.id||!Ee.secretRef||Ee.secretRef===lS?Q.legacyState:Oc(Q.bots,Ee.id,"state.json"),j=async Ee=>{let Qe=Ee.id??"__legacy__",Le=q.get(Qe);return Le||(Le=await new r(z(Ee)).load(),q.set(Qe,Le)),Le},P=async Ee=>{let Qe=F().find(Le=>Le.id===Ee);if(!Qe)throw new Error("Unknown Feishu bot");return j(Qe)},J=Ua(n,o.commandExecutor),{controlExecutor:U,sessionMaintenanceExecutor:N,fileIngressExecutor:k}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),V=new s({...i,workspace:m,autostart:!1,dshBin:t.dshBin??"dsh",...J?{commandExecutor:J}:{},...U?{controlExecutor:U}:{},...N?{sessionMaintenanceExecutor:N}:{},...k?{fileIngressExecutor:k}:{}}),Ae=o.proxyEnv??process.env,ie=Uke(Ae,o.createProxyAgent),De=new a({registerApp:Ee=>e.registerApp(Ee),verifyApp:I,credentials:n.credentials,configStore:L,createRuntime:async({botId:Ee,config:Qe,appSecret:Le,repair:AA})=>{let aA=await j(Qe),He=Ee??Qe.id??Qe.appId;await T.ensure(He,{defaultAgentPreset:t.agentPreset});let ce=Ga(V,{botId:He,workspaces:T,state:aA,agentPresetCatalog:f});return new g({lark:e,botId:He,repair:AA,appId:Qe.appId,appSecret:Le,domain:Qe.domain,botOpenId:Qe.botOpenId,groupResponseMode:Qe.groupResponseMode,ownerOpenIds:Qe.ownerOpenIds??[Qe.ownerOpenId],harness:ce.harness,state:ce.state,contextEnhancement:{botId:He,getSettings:()=>T.contextEnhancementFor(He)},replyTimeoutMs:t.replyTimeoutMs??6e5,slashCommands:t.slashCommands!==!1,...ie?{wsAgent:ie}:{},logger:{error:(...Be)=>B.error?.(`[${Ee??Qe.id}]`,...Be),warn:(...Be)=>B.warn?.(`[${Ee??Qe.id}]`,...Be),info:(...Be)=>B.info?.(`[${Ee??Qe.id}]`,...Be),debug:(...Be)=>B.debug?.(`[${Ee??Qe.id}]`,...Be)}})},deleteState:async({botId:Ee,config:Qe})=>{q.delete(Ee);try{await Fke(z(Qe))}catch(Le){if(Le?.code!=="ENOENT")throw Le}}}),fe=Fa(De,{workspaces:T,stateFor:P,agentPresetCatalog:f}),_e=d({controller:fe,harness:V,logger:B,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:fe,deliveryAdapter:La({channel:"feishu",workspaces:T,coreController:De,stateFor:P}),ready:_e.ready,async close(){await _e.close(),await fe.close(),V.stopManagedProcess(),ie?.destroy?.()}}}import ove from"qrcode";var vd=Je(pP(),1);var rve=Je(pP(),1);var ave=Object.freeze({$locale:"en",IM\u673A\u5668\u4EBA:"IM bots",IM\u673A\u5668\u4EBA\u8BBE\u7F6E:"IM bot settings",\u66F4\u591A\u673A\u5668\u4EBA\u8BBE\u7F6E:"More bot settings","IM \u6E20\u9053":"IM channels","\u8BA9 DeepSeek Harness \u89E6\u624B\u53EF\u53CA":"Connecting DeepSeek Harness",\u5F53\u524D\u7248\u672C:"Current version","DSH-IM \u66F4\u65B0":"DSH-IM update",\u68C0\u67E5\u66F4\u65B0:"Check for updates",\u91CD\u65B0\u68C0\u67E5:"Check again",\u5237\u65B0\u72B6\u6001:"Refresh status",\u624B\u5DE5\u66F4\u65B0:"Manual update",\u624B\u5DE5\u66F4\u65B0\u547D\u4EE4:"Manual update command",\u590D\u5236\u547D\u4EE4:"Copy command","\u590D\u5236\u4E2D\u2026":"Copying\u2026",\u5DF2\u590D\u5236:"Copied","\u547D\u4EE4\u5DF2\u590D\u5236\u3002":"Command copied.","\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u9009\u4E2D\u547D\u4EE4\u540E\u6309 Ctrl+C \u6216 \u2318C \u590D\u5236\u3002":"Copy failed. Select the command and press Ctrl+C or \u2318C to copy it.","\u81EA\u52A8\u66F4\u65B0\u5931\u8D25\u53EF\u4EE5\u4F7F\u7528\u547D\u4EE4\u66F4\u65B0\uFF1A":"If the automatic update fails, update with this command:","\u5C1A\u672A\u786E\u8BA4\u76EE\u6807\u7248\u672C\uFF0C\u6B64\u547D\u4EE4\u5B89\u88C5\u6267\u884C\u65F6 npm \u7684 latest \u7248\u672C\u3002":"No target version has been confirmed. This command installs the npm latest version available when you run it.","\u8BF7\u5728\u5F53\u524D Desktop \u7684\u5185\u7F6E\u7EC8\u7AEF\u6267\u884C\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002":"Run this in the current Desktop\u2019s built-in terminal, then restart manually.","\u8BF7\u5728\u8FD0\u884C\u5F53\u524D Harness \u7684\u540C\u4E00\u73AF\u5883\u6267\u884C\uFF0C\u4FDD\u6301 DSH_HOME \u4E00\u81F4\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002":"Run this in the same environment as the current Harness, with the same DSH_HOME, then restart manually.","\u8BF7\u7B49\u5F85\u5F53\u524D\u64CD\u4F5C\u7ED3\u675F\uFF0C\u786E\u8BA4\u6CA1\u6709\u5B89\u88C5\u8FDB\u7A0B\u8FD0\u884C\u540E\u518D\u6267\u884C\u547D\u4EE4\u3002":"Wait for the current operation to finish and confirm no installer is running before using this command.","\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\u8BF7\u6309\u539F\u5B89\u88C5\u65B9\u5F0F\u66F4\u65B0\uFF0C\u4E0D\u63D0\u4F9B\u8986\u76D6\u6E90\u7801\u7684 npm \u547D\u4EE4\u3002":"Update source or linked installations using their original method. No npm command is provided to overwrite the source.","\u65E0\u6CD5\u5B89\u5168\u751F\u6210\u5F53\u524D profile \u7684\u547D\u4EE4\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u624B\u52A8\u786E\u8BA4 profile \u540E\u66F4\u65B0\u3002":"A safe command cannot be generated for this profile. Confirm the profile in your terminal before updating manually.",\u66F4\u65B0\u81F3:"Update to",\u5B89\u88C5\u66F4\u65B0:"Install update","\u6B63\u5728\u66F4\u65B0\u2026":"Updating\u2026",\u5F85\u624B\u52A8\u91CD\u542F:"Restart needed",\u8FD0\u884C\u7248\u672C:"Running version",\u5DF2\u5B89\u88C5\u7248\u672C:"Installed version","\u76EE\u6807 profile":"Target profile",\u76EE\u6807\u7248\u672C:"Target version",\u65E0\u6CD5\u786E\u8BA4:"Unknown",\u53D1\u73B0\u65B0\u7248\u672C:"Update available",\u5DF2\u662F\u6700\u65B0\u7248\u672C:"Up to date",\u5F53\u524D\u7248\u672C\u65E0\u9700\u66F4\u65B0:"No newer version available","\u5DF2\u83B7\u53D6 npm \u6700\u65B0\u7248\u672C":"Latest npm version retrieved","\u68C0\u67E5 npm \u6700\u65B0\u7248\u672C\uFF0C\u4E0D\u4F1A\u81EA\u52A8\u5B89\u88C5\u3002":"Check the latest npm version. Nothing is installed automatically.","\u6B63\u5728\u4ECE npm \u68C0\u67E5\u6700\u65B0\u7248\u672C\u2026":"Checking npm for the latest version\u2026","\u6B63\u5728\u5B89\u88C5\uFF0C\u8BF7\u7A0D\u5019\u2026":"Installing, please wait\u2026","\u6B63\u5728\u6821\u9A8C\u5B89\u88C5\u7ED3\u679C\u2026":"Verifying the installation\u2026","\u5DF2\u5B89\u88C5\uFF0C\u5F85\u624B\u52A8\u91CD\u542F":"Installed \u2014 manual restart needed",\u66F4\u65B0\u5DF2\u751F\u6548:"Updated version is active",\u66F4\u65B0\u5931\u8D25:"Update failed",\u66F4\u65B0\u8BF7\u6C42\u5931\u8D25:"Update request failed","\u4EC5\u66F4\u65B0 DSH-IM\u3002\u5B89\u88C5\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u540E\u53F0\uFF1B\u672C\u529F\u80FD\u4E0D\u4F1A\u81EA\u52A8\u91CD\u542F\u6216\u4E3B\u52A8\u5237\u65B0\u9875\u9762\u3002":"Only DSH-IM will be updated. Restart the backend manually after installation. This feature does not automatically restart it or initiate a page refresh.","\u5F53\u524D\u662F\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\uFF0C\u53EA\u80FD\u68C0\u67E5\u7248\u672C\uFF1B\u8BF7\u624B\u52A8\u66F4\u65B0\u6E90\u7801\uFF0C\u6216\u8FC1\u79FB\u5230 npm \u5B89\u88C5\u3002":"This is a source or linked installation. You can check versions, but must update the source manually or migrate to an npm installation.","\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D profile\uFF0C\u8BF7\u5728\u5BF9\u5E94\u7684 Harness \u73AF\u5883\u4E2D\u624B\u52A8\u66F4\u65B0\u3002":"The current profile could not be identified. Update manually in the corresponding Harness environment.","\u5F53\u524D\u8FD0\u884C\u73AF\u5883\u4E0D\u652F\u6301\u6309\u94AE\u5B89\u88C5\uFF0C\u8BF7\u624B\u52A8\u66F4\u65B0\u63D2\u4EF6\u3002":"This runtime cannot install through this button. Update the plugin manually.","\u5F53\u524D npm \u6E90\u914D\u7F6E\u4E0E\u5B98\u65B9\u6E90\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u5148\u68C0\u67E5 registry \u914D\u7F6E\u3002":"The npm registry configuration differs from the official registry. Check your registry settings first.","\u5F53\u524D Host \u7684 Node.js \u7248\u672C\u4E0D\u6EE1\u8DB3\u65B0\u7248\u8981\u6C42\uFF0C\u8BF7\u5148\u66F4\u65B0\u8FD0\u884C\u73AF\u5883\u3002":"The Host Node.js version does not meet the new version\u2019s requirements. Update the runtime first.","\u65B0\u7248\u672C\u5DF2\u5B89\u88C5\uFF0C\u8BF7\u5728\u65B9\u4FBF\u65F6\u624B\u52A8\u91CD\u542F\u5F53\u524D Harness \u6216 Desktop\u3002":"The new version is installed. Manually restart this Harness or Desktop when convenient.","\u4E0A\u6B21\u5B89\u88C5\u7ED3\u679C\u65E0\u6CD5\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u6B64 profile \u7684\u63D2\u4EF6\u5B89\u88C5\u72B6\u6001\u3002":"The previous installation result is uncertain. Check this profile\u2019s plugin installation first.","\u65E0\u6CD5\u8BBF\u95EE npm \u6216\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u68C0\u67E5\u3002":"npm is unreachable or the request timed out. Check again later.","npm \u8FD4\u56DE\u7684\u7248\u672C\u4FE1\u606F\u65E0\u6548\uFF0C\u6682\u65F6\u65E0\u6CD5\u66F4\u65B0\u3002":"npm returned invalid release information. Updating is unavailable.","\u7248\u672C\u786E\u8BA4\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u540E\u518D\u5B89\u88C5\u3002":"The version confirmation expired. Check again before installing.","\u63D2\u4EF6\u5B89\u88C5\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u3002":"The plugin installation changed. Check again.","\u6B64 profile \u6B63\u5728\u66F4\u65B0\uFF0C\u8BF7\u7A0D\u540E\u67E5\u770B\u72B6\u6001\u3002":"This profile is already updating. Check its status shortly.","\u5B89\u88C5\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u5F53\u524D\u5B89\u88C5\u72B6\u6001\u540E\u91CD\u8BD5\u3002":"Installation failed. Check the current installation before retrying.","\u5B89\u88C5\u7ED3\u679C\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u63D2\u4EF6\u7248\u672C\u3002":"Installation verification failed. Check the plugin version manually.","\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u66F4\u65B0\u72B6\u6001\uFF0C\u8BF7\u5148\u68C0\u67E5\u5F53\u524D\u5B89\u88C5\u7ED3\u679C\u3002":"Update state could not be saved safely. Check the current installation result before retrying.","\u4E0A\u6B21\u66F4\u65B0\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u68C0\u67E5\u5B89\u88C5\u72B6\u6001\u540E\u91CD\u8BD5\u3002":"The previous update was interrupted. Check the installation before retrying.","\u66F4\u65B0\u670D\u52A1\u5DF2\u5173\u95ED\uFF0C\u8BF7\u624B\u52A8\u91CD\u65B0\u6253\u5F00\u8BBE\u7F6E\u9875\u3002":"The update service has closed. Reopen settings manually.","\u66F4\u65B0\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u7248\u672C\u3002":"The update request is invalid. Check the version again.","\u5F53\u524D\u63D2\u4EF6\u5B89\u88C5\u4E0D\u5B8C\u6574\u6216\u4E0E profile \u4E0D\u7B26\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u5B89\u88C5\u914D\u7F6E\u3002":"The plugin installation is incomplete or does not match this profile. Check the installation configuration manually.","\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D npm \u6E90\u914D\u7F6E\uFF0C\u6682\u65F6\u4E0D\u80FD\u5B89\u88C5\u66F4\u65B0\u3002":"The npm registry configuration could not be verified. Installation is unavailable.","\u5B89\u88C5\u8D85\u65F6\uFF0C\u8BF7\u5148\u786E\u8BA4\u5F53\u524D\u5B89\u88C5\u72B6\u6001\uFF0C\u518D\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5\u3002":"Installation timed out. Check the current installation before retrying.","\u66F4\u65B0\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"The update request failed. Try again.","\u66F4\u65B0\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u54CD\u5E94\u3002":"The update service returned an unrecognized response.","\u5F53\u524D Host \u4E0D\u652F\u6301\u66F4\u65B0\u63A5\u53E3\uFF0C\u8BF7\u5148\u624B\u52A8\u66F4\u65B0\u63D2\u4EF6\u5E76\u91CD\u542F\u3002":"This Host does not support the update API. Update the plugin manually and restart first.","\u5173\u95ED\u7A97\u53E3\u4E0D\u4F1A\u53D6\u6D88\u5B89\u88C5\u3002\u8BF7\u52FF\u540C\u65F6\u5728\u5176\u4ED6\u7A97\u53E3\u7BA1\u7406\u6B64 profile \u7684\u63D2\u4EF6\u3002":"Closing this window does not cancel installation. Do not manage this profile\u2019s plugins in another window at the same time.","\u9875\u9762\u7248\u672C\u4E0E\u8FD0\u884C\u7248\u672C\u4E0D\u540C\uFF0C\u8BF7\u624B\u52A8\u5237\u65B0\u9875\u9762\uFF1B\u82E5\u4ECD\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u624B\u52A8\u91CD\u542F Harness \u6216 Desktop\u3002":"The page and running versions differ. Refresh the page manually; if they still differ, manually restart Harness or Desktop.","\u8BF7\u5728\u673A\u5668\u4EBA\u7A7A\u95F2\u65F6\u5B89\u88C5\uFF1B\u5B89\u88C5\u4F1A\u4FEE\u6539\u5F53\u524D profile \u7684\u4F9D\u8D56\uFF0C\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u3002":"Install while bots are idle. This changes the current profile\u2019s dependencies and requires a manual restart afterward.","AI Office":"AI Office","\uFF08\u5B9E\u9A8C\u529F\u80FD\uFF09":"(Experimental)","AI Office \u8BBE\u7F6E":"AI Office settings","AI Office \u8BBE\u7F6E\u9875\u7F3A\u5C11 RPC \u8FDE\u63A5":"AI Office settings are missing an RPC connection","\u6B63\u5728\u8BFB\u53D6 AI Office Connector\u2026":"Loading AI Office Connector\u2026","\u672C\u673A\u4E3B\u52A8\u8FDE\u63A5\u516C\u7F51 Office\uFF1BHarness \u4E0D\u5F00\u653E\u7AEF\u53E3\u3002\u534F\u8BAE Hook \u56FA\u5B9A\u4E3A ":"This machine connects outward to the public Office; Harness exposes no port. Protocol hooks: ",\u5C1A\u672A\u914D\u7F6E:"Not configured","\u5DF2\u8FDE\u63A5 Office":"Connected to Office",\u5DF2\u914D\u7F6E:"Configured",\u7B49\u5F85\u91CD\u8FDE:"Waiting to reconnect",\u51ED\u636E\u7F3A\u5931:"Credential missing",\u6700\u8FD1\u5FC3\u8DF3:"Last heartbeat",\u6700\u8FD1\u4E8B\u4EF6:"Last event",\u91CD\u8FDE\u6B21\u6570:"Reconnects","\u8FD0\u884C Job":"Running Jobs","\u5B8C\u6210 Job":"Completed Jobs",\u5C1A\u65E0:"None yet",\u8BBE\u5907\u8FDE\u63A5:"Device connection","Token \u53EA\u5199\u5165\u672C\u673A\u51ED\u636E\u5B58\u50A8":"Token is written only to the local credential store","\u7C98\u8D34 Office \u4E00\u6B21\u6027\u51ED\u636E":"Paste the one-time Office credential","\u5DF2\u5B89\u5168\u4FDD\u5B58\uFF1B\u7559\u7A7A\u4FDD\u6301\u4E0D\u53D8":"Stored securely; leave blank to keep it",\u6700\u5927\u5E76\u53D1:"Max concurrency","Heartbeat \u79D2\u6570":"Heartbeat seconds","Workspace \u6620\u5C04":"Workspace mappings","\u6BCF\u884C alias=/\u672C\u673A/\u7EDD\u5BF9\u8DEF\u5F84\uFF1BOffice \u53EA\u80FD\u770B\u5230 alias\u3002":"One alias=/local/absolute/path per line; Office sees only aliases.","Instruction Preset \u6620\u5C04":"Instruction preset mappings","\u6BCF\u884C alias=\u6307\u4EE4\uFF1B\u65B0\u589E preset \u4E0D\u9700\u8981\u6539 Office \u4EE3\u7801\u3002":"One alias=instruction per line; new presets require no Office code change.",\u4FDD\u5B58\u5E76\u8FDE\u63A5:"Save and connect",\u6D4B\u8BD5\u8FDE\u63A5:"Test connection","\u6D4B\u8BD5\u4E2D\u2026":"Testing\u2026",\u91CD\u65B0\u8FDE\u63A5:"Reconnect",\u79FB\u9664\u8FDE\u63A5:"Remove connection","\u8FDE\u63A5\u6D4B\u8BD5\u901A\u8FC7\u3002":"Connection test passed.","\u914D\u7F6E\u5DF2\u4FDD\u5B58\u3002":"Configuration saved.","\u534F\u8BAE Hook \u9884\u89C8":"Protocol hook preview","\u7531 Base URL \u81EA\u52A8\u6D3E\u751F\uFF0C\u4E0D\u5355\u72EC\u586B\u5199":"Derived from Base URL; no separate input","Base URL \u65E0\u6548":"Invalid Base URL","Office Hook \u5C1A\u672A\u90E8\u7F72\u65F6\uFF0C\u914D\u7F6E\u4F1A\u5B89\u5168\u4FDD\u5B58\u5E76\u81EA\u52A8\u91CD\u8BD5\uFF1B\u51FA\u73B0 HTTP 404 \u4EE3\u8868\u534F\u8BAE\u7AEF\u70B9\u5F85\u4E0A\u7EBF\uFF0C\u4E0D\u4EE3\u8868 Harness \u6545\u969C\u3002":"Configuration is saved and retried while Office hooks are unavailable; HTTP 404 means the protocol endpoint is pending, not a Harness failure.","Workspace \u6620\u5C04\u6BCF\u884C\u5FC5\u987B\u4F7F\u7528 alias=value":"Each workspace mapping must use alias=value","Instruction Preset \u6620\u5C04\u6BCF\u884C\u5FC5\u987B\u4F7F\u7528 alias=value":"Each instruction preset mapping must use alias=value","action-items=\u8F6C\u6362\u4E3A\u8D1F\u8D23\u4EBA\u3001\u622A\u6B62\u548C\u9A8C\u6536\u660E\u786E\u7684\u5DE5\u5355":"action-items=Turn this into accountable tasks with deadlines and acceptance criteria","AI Office \u62D2\u7EDD\u4E86 Device Token\u3002":"AI Office rejected the Device Token.","AI Office Connector Hook \u5C1A\u672A\u5C31\u7EEA\u3002":"AI Office Connector hooks are not available yet.","AI Office Connector \u534F\u8BAE\u7248\u672C\u4E0D\u517C\u5BB9\u3002":"The AI Office Connector protocol is incompatible.","\u672C\u673A\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE AI Office\u3002":"AI Office cannot currently be reached from this machine.","AI Office \u8FDE\u63A5\u5DF2\u4E2D\u65AD\u3002":"The AI Office connection was interrupted.","\u5E2E\u52A9\u4E0E\u53CD\u9988 \xB7 \u524D\u5F80 GitHub":"Help & feedback \xB7 Open GitHub","\u8BF7\u6539\u7528 localhost \u91CD\u65B0\u6253\u5F00":"Reopen with localhost","\u9875\u9762\u4F1A\u5728\u5F53\u524D\u7AEF\u53E3\u91CD\u65B0\u6253\u5F00\uFF0C\u673A\u5668\u4EBA\u914D\u7F6E\u4E0D\u4F1A\u6539\u53D8\u3002":"The page will reopen on the current port. Your bot configuration will not change.","\u4F7F\u7528 localhost \u91CD\u65B0\u6253\u5F00":"Reopen with localhost","\u5F53\u524D\u5730\u5740\u4E0E\u6D4F\u89C8\u5668\u7684\u672C\u673A\u8BF7\u6C42\u6821\u9A8C\u4E0D\u517C\u5BB9\u3002\u8BF7\u4F7F\u7528\u4E0A\u65B9\u6309\u94AE\u6539\u7528 localhost \u91CD\u65B0\u6253\u5F00\u3002":"This address is incompatible with the browser\u2019s local-request checks. Use the button above to reopen with localhost.",\u5FAE\u4FE1:"WeChat",\u98DE\u4E66:"Feishu",\u9489\u9489:"DingTalk",\u4F01\u4E1A\u5FAE\u4FE1:"WeCom",\u5FAE\u4FE1\u673A\u5668\u4EBA:"WeChat bot",\u98DE\u4E66\u673A\u5668\u4EBA:"Feishu bot",\u9489\u9489\u673A\u5668\u4EBA:"DingTalk bot",\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"WeCom bot",QQ\u673A\u5668\u4EBA:"QQ bot",WhatsApp\u673A\u5668\u4EBA:"WhatsApp bot",WhatsApp\u8D26\u53F7:"WhatsApp account",\u5FAE\u4FE1\u8BBE\u7F6E:"WeChat settings",\u98DE\u4E66\u673A\u5668\u4EBA\u8BBE\u7F6E:"Feishu bot settings",\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F:"Group response mode","\u4EC5\u5728 @\u673A\u5668\u4EBA\u65F6\u54CD\u5E94\uFF08\u63A8\u8350\uFF09":"Only respond when @mentioned (recommended)",\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F:"Respond to all group messages","\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\uFF08\u9700\u98DE\u4E66\u654F\u611F\u6743\u9650\uFF09":"Respond to all group messages (requires a sensitive Feishu scope)",\u91CD\u65B0\u6388\u6743:"Reauthorize",\u53BB\u6388\u6743:"Authorize",\u91CD\u65B0\u6388\u6743\u7FA4\u6D88\u606F\u6743\u9650:"Reauthorize group-message permission",\u6388\u6743\u7FA4\u6D88\u606F\u6743\u9650:"Authorize group-message permission","\u6B63\u5728\u51C6\u5907\u6388\u6743\u2026":"Preparing authorization\u2026","\u6B63\u5728\u51C6\u5907\u2026":"Preparing\u2026","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u5F00\u901A\uFF0C\u518D\u6B21\u5207\u6362\u65E0\u9700\u6388\u6743\u3002":"Direct messages always work; group chats require an explicit @mention of this bot. The group-message permission is already granted, so switching again needs no authorization.","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002\u9009\u62E9\u5168\u90E8\u6D88\u606F\u540E\u4F1A\u6253\u5F00\u98DE\u4E66\u5B98\u65B9\u6388\u6743\u6D41\u7A0B\u3002":"Direct messages always work; group chats require an explicit @mention of this bot. Selecting all messages opens the official Feishu authorization flow.","\u5DF2\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF08im:message.group_msg\uFF09\uFF1B\u673A\u5668\u4EBA\u4F1A\u5904\u7406\u7FA4\u804A\u4E2D\u7684\u6240\u6709\u53EF\u89C1\u6D88\u606F\u3002":"The \u201CRead all messages in associated group chat\u201D scope (im:message.group_msg) is granted; the bot processes every visible group message.","\u5C1A\u672A\u786E\u8BA4\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF0C\u8BF7\u5B8C\u6210\u98DE\u4E66\u6388\u6743\u3002":"The \u201CRead all messages in associated group chat\u201D scope has not been confirmed. Complete Feishu authorization.","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002":"Direct messages always work; group chats require an explicit @mention of this bot.","\u9700\u5728\u98DE\u4E66\u4E3A\u8BE5\u673A\u5668\u4EBA\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF08im:message.group_msg\uFF09\uFF1B\u5F00\u901A\u540E\uFF0C\u673A\u5668\u4EBA\u4F1A\u5904\u7406\u7FA4\u804A\u4E2D\u7684\u6240\u6709\u53EF\u89C1\u6D88\u606F\u3002":"Grant this bot the \u201CRead all messages in associated group chat\u201D Feishu scope (im:message.group_msg); once granted, it will process every visible group message.","\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F\u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the group response mode. Try again.","\u7FA4\u6D88\u606F\u6743\u9650\u6388\u6743\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not authorize group-message permission. Try again.",\u9489\u9489\u8BBE\u7F6E:"DingTalk settings",\u4F01\u4E1A\u5FAE\u4FE1\u8BBE\u7F6E:"WeCom settings",\u626B\u7801\u63A5\u5165\u673A\u5668\u4EBA:"Scan QR code",\u6B63\u5728\u63A5\u5165:"Connecting",\u624B\u52A8\u63A5\u5165:"Manual setup",\u6536\u8D77\u51ED\u636E:"Hide credentials",\u6536\u8D77\u63A5\u5165:"Hide setup",\u63A5\u5165\u673A\u5668\u4EBA:"Connect bot",\u5F00\u59CB\u63A5\u5165:"Start setup",\u5728\u7EBF:"online",\u8FD0\u884C\u6B63\u5E38:"Connected",\u6B63\u5728\u8FDE\u63A5:"Connecting","\u6B63\u5728\u8FDE\u63A5\u2026":"Connecting\u2026",\u8FDE\u63A5\u672A\u5C31\u7EEA:"Not connected",\u8FDE\u63A5\u4E2D:"Connecting",\u8FDE\u63A5\u4E2D\u65AD:"Disconnected",\u9700\u8981\u5904\u7406:"Needs attention",\u72B6\u6001\u672A\u77E5:"Unknown status",\u79BB\u7EBF:"Offline",\u5DF2\u65AD\u5F00:"Disconnected",\u6D88\u606F\u901A\u9053:"Message channel",\u67E5\u770B\u6D88\u606F\u901A\u9053\u8BF4\u660E:"View message channel details",\u6700\u8FD1\u68C0\u67E5:"Last checked",\u6700\u8FD1\u4E00\u6761\u6D88\u606F\u5904\u7406\u5931\u8D25:"Latest message failed",\u9519\u8BEF\u7801:"Code",\u53C2\u8003\u53F7:"Reference",\u5F53\u524D\u5DE5\u4F5C\u533A:"Current workspace",\u9009\u62E9\u76EE\u5F55:"Choose folder",\u9009\u62E9\u673A\u5668\u4EBA\u5DE5\u4F5C\u533A\u76EE\u5F55:"Select bot workspace folder",\u5F53\u524D\u76EE\u5F55:"Current folder",\u4E3B\u76EE\u5F55:"Home",\u76F4\u63A5\u8F93\u5165\u8DEF\u5F84:"Enter a path directly","\u652F\u6301 Windows \u76D8\u7B26\u3001UNC \u4E0E POSIX \u7EDD\u5BF9\u8DEF\u5F84\u3002":"Supports Windows drives, UNC paths, and POSIX absolute paths.","\u8F93\u5165 Host \u4E0A\u7684\u5B8C\u6574\u7EDD\u5BF9\u8DEF\u5F84":"Enter a full absolute path on the Host",\u524D\u5F80:"Go","\u8BFB\u53D6\u4E2D\u2026":"Loading\u2026","\u6B63\u5728\u51C6\u5907\u76EE\u5F55\u9009\u62E9\u5668\u2026":"Preparing folder picker\u2026","\u6B63\u5728\u8BFB\u53D6\u76EE\u5F55\u2026":"Loading folders\u2026","\u8FD9\u4E2A\u76EE\u5F55\u4E2D\u6CA1\u6709\u5B50\u6587\u4EF6\u5939\u3002":"This folder has no subfolders.","\u6B64\u76EE\u5F55\u7684\u5B50\u6587\u4EF6\u5939\u8FC7\u591A\uFF0C\u4EC5\u663E\u793A\u524D\u4E00\u90E8\u5206\u3002":"This folder has too many subfolders; only the first group is shown.","\u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not load the folder. Try again.",\u91CD\u8BD5:"Retry",\u663E\u793A\u9690\u85CF\u6587\u4EF6\u5939:"Show hidden folders","\u5207\u6362\u540E\u4F1A\u6E05\u9664\u8FD9\u4E2A\u673A\u5668\u4EBA\u7684\u65E7\u4F1A\u8BDD\u6620\u5C04\u3002":"Switching clears this bot\u2019s previous session mappings.","\u5207\u6362\u4E2D\u2026":"Switching\u2026",\u9009\u62E9\u6B64\u76EE\u5F55:"Select this folder",\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84:"Absolute workspace path","/\u7EDD\u5BF9\u8DEF\u5F84/\u5230/\u5DE5\u4F5C\u533A":"/absolute/path/to/workspace",\u4FEE\u6539:"Change",\u4FDD\u5B58:"Save",\u4E0A\u4E0B\u6587\u589E\u5F3A:"Context enhancement",\u672A\u5F00\u542F:"Not enabled",\u4EC5\u7FA4\u804A:"Groups only",\u4EC5\u79C1\u804A:"Direct only",\u7FA4\u804A\u548C\u79C1\u804A:"Groups and direct",\u5173\u95ED\u5F39\u7A97:"Close dialog",\u67E5\u770B\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BF4\u660E:"View context enhancement details",\u542F\u7528\u8303\u56F4:"Enable in",\u7FA4\u804A\u4E2D\u542F\u7528:"Enable in group chats",\u79C1\u804A\u4E2D\u542F\u7528:"Enable in direct chats","\uFF08\u5F53\u524D\u6E20\u9053\u4E0D\u652F\u6301\u7FA4\u804A\uFF09":"(This channel does not support group chats)",\u6765\u6E90\u5B57\u6BB5:"Source fields",\u67E5\u770B\u6765\u6E90\u5B57\u6BB5\u8BF4\u660E:"View source field details",\u6E20\u9053:"Channel",\u4F1A\u8BDD\u7C7B\u578B:"Conversation type",\u53D1\u9001\u8005\u6807\u8BC6:"Sender ID",\u53D1\u9001\u8005\u6635\u79F0:"Sender name",\u67E5\u770B\u53D1\u9001\u8005\u6635\u79F0\u5B57\u6BB5\u8BF4\u660E:"View sender name field details","\u8BE5\u5B57\u6BB5\u4E0D\u662F\u6BCF\u4E2A\u6E20\u9053\u90FD\u80FD\u63D0\u4F9B\u3002\u5F53\u524D\u6D88\u606F\u6CA1\u6709\u53D1\u9001\u8005\u6635\u79F0\u65F6\uFF0C\u5373\u4F7F\u5DF2\u9009\u62E9\u8BE5\u5B57\u6BB5\uFF0C \u4E2D\u4E5F\u4F1A\u7701\u7565 senderName\u3002":"This field is not available on every channel. If the current message has no sender name, omits senderName even when the field is selected.",\u673A\u5668\u4EBA\u6807\u8BC6:"Bot ID",\u589E\u5F3A\u63D0\u793A\u8BCD:"Guidance",\u67E5\u770B\u589E\u5F3A\u63D0\u793A\u8BCD\u4F7F\u7528\u8BF4\u660E:"View guidance instructions",\u4F7F\u7528\u8BF4\u660E:"How to use","\u7528\u4E8E\u544A\u8BC9\u6A21\u578B\u5982\u4F55\u4F7F\u7528 \u4E2D\u5DF2\u9009\u62E9\u7684\u6765\u6E90\u5B57\u6BB5\u3002\u53EA\u586B\u5199\u6B63\u6587\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u6DFB\u52A0 \u6210\u5BF9\u6807\u7B7E\u3002":"Tell the model how to use the selected fields in . Enter only the body; the plugin adds paired tags.",\u751F\u6548\u89C4\u5219:"Behavior",\u9690\u79C1\u63D0\u793A:"Privacy",\u4F7F\u7528\u793A\u4F8B:"Example","\u4EC5\u4F9D\u636E\u5F53\u524D\u6D88\u606F\u7684 \u4E2D\u5B9E\u9645\u63D0\u4F9B\u7684\u5B57\u6BB5\u7406\u89E3\u6765\u6E90\uFF1B\u6CA1\u6709\u63D0\u4F9B\u7684\u5B57\u6BB5\u4E0D\u8981\u731C\u6D4B\u6216\u8865\u5168\u3002\nconversationType\u662F\u7FA4\u804A\u65F6\u56DE\u590D\u4E25\u8083\u4E00\u70B9\uFF0CconversationType\u662F\u79C1\u804A\u65F6\u56DE\u590D\u4E00\u5B9A\u8981\u5E7D\u9ED8\u641E\u7B11\uFF0C\u50CF\u5468\u661F\u9A70\u7684\u7535\u5F71\u4E00\u6837\u641E\u7B11":`Understand the source only from fields actually present in for the current message; do not guess or fill in missing fields. +`)+1;e{let c=String(g??"")||"\u2026";await this.#n(a,l6(c)),A=c}};await o.markdown(r);let s=zRe(A);for(let[g,c]of s.entries()){let I=g===0?a:await this.#a(t,i.replyTo);g>0&&e.push(I),await this.#n(I,c),await this.#i(I)}return{messageId:a.messageId,providerMessageIds:e.map(g=>g.messageId)}}catch(a){for(let A of e)await this.#l(A.messageId);throw a}}async sendFile(t,o,{replyTo:i,signal:e}={}){return this.#g(t,o,{replyTo:i,signal:e,messageType:"file",presentation:"feishu-file"})}async sendImage(t,o,{replyTo:i,signal:e}={}){return this.#g(t,o,{replyTo:i,signal:e,messageType:"image",presentation:"feishu-image"})}async#g(t,o,{replyTo:i,signal:e,messageType:a,presentation:A}){if(e?.throwIfAborted(),typeof t!="string"||!t)throw new TypeError("chatId is required");if(!o||typeof o!="object"||typeof o.artifactId!="string"||!o.artifactId||typeof o.deliveryKey!="string"||!o.deliveryKey||typeof o.fileName!="string"||!o.fileName||!Buffer.isBuffer(o.bytes))throw new TypeError("A materialized result file is required");let r;try{r=await I6(Q=>{Q.throwIfAborted();let y=a==="image"?this.#e.im.v1.image.create({data:{image_type:"message",image:o.bytes}}):this.#e.im.v1.file.create({data:{file_type:"stream",file_name:o.fileName,file:o.bytes}});return ln(o,y),y},{signal:e,timeoutMs:this.#t,stage:"upload"})}catch(Q){throw e?.aborted?Vv(e):yu("upload",Q)}e?.throwIfAborted();let s=a==="image"?r?.image_key??r?.data?.image_key:r?.file_key??r?.data?.file_key;if(typeof s!="string"||!s)throw yu("upload",void 0,r?.code);let g=JRe(o,t,a),c=JSON.stringify(a==="image"?{image_key:s}:{file_key:s}),I=i?{path:{message_id:i},data:{msg_type:a,content:c,uuid:g}}:{params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:a,content:c,uuid:g}},d=()=>{let Q=i?this.#e.im.v1.message.reply(I):this.#e.im.v1.message.create(I);return ln(o,Q),Q},B;try{B=await I6(async Q=>{Q.throwIfAborted();let y;try{y=await d()}catch(m){if(h6(m)!==230049)throw m;y={code:230049}}return Q.throwIfAborted(),Number(y?.code)===230049&&(y=await d(),Q.throwIfAborted()),y},{signal:e,timeoutMs:this.#r,stage:"message send"})}catch(Q){throw e?.aborted?Vv(e):yu("message send",Q,void 0,{uncertain:!0})}if(Number.isFinite(Number(B?.code))&&Number(B.code)!==0)throw yu("message send",void 0,B.code,{uncertain:!0});let f=B?.data?.message_id;if(typeof f!="string"||!f)throw yu("message send",void 0,void 0,{uncertain:!0});return Zt({deliveryId:o.deliveryKey,presentation:A,providerMessageIds:[f],artifacts:[{artifactId:o.artifactId,outcome:"sent"}]})}async#a(t,o){let i=l6(this.#A),a=nl("Feishu card.create",await this.#e.cardkit.v1.card.create({data:{type:"card_json",data:JSON.stringify(VRe(i))}}))?.data?.card_id;if(!a)throw new Error("Feishu card.create returned no card_id");let A=await this.#I(t,a,o);return{cardId:a,messageId:A,content:i,sequence:0}}async#n(t,o){if(o===t.content)return;let i=await this.#e.cardkit.v1.cardElement.content({path:{card_id:t.cardId,element_id:p6},data:{content:o,sequence:++t.sequence,uuid:`content_${t.cardId}_${t.sequence}`}});nl("Feishu cardElement.content",i),t.content=o}async#i(t){let o=await this.#e.cardkit.v1.card.settings({path:{card_id:t.cardId},data:{settings:JSON.stringify({config:{streaming_mode:!1,summary:{content:qRe(t.content)||w("\u56DE\u7B54\u5B8C\u6210")}}}),sequence:++t.sequence,uuid:`settings_${t.cardId}_${t.sequence}`}});nl("Feishu card.settings",o)}async#I(t,o,i){let e=JSON.stringify({type:"card",data:{card_id:o}}),a=i?await this.#e.im.v1.message.reply({path:{message_id:i},data:{msg_type:"interactive",content:e}}):await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"interactive",content:e}});nl("Feishu message send",a);let A=a?.data?.message_id;if(!A)throw new Error("Feishu message send returned no message_id");return A}async#l(t){try{let o=await this.#e.im.v1.message.delete({path:{message_id:t}});nl("Feishu message delete",o)}catch(o){console.warn("[bridge] unable to recall a failed streaming card:",o.message)}}async addReaction(t,o){let e=nl("Feishu reaction.create",await this.#e.im.v1.messageReaction.create({path:{message_id:t},data:{reaction_type:{emoji_type:o}}}))?.data?.reaction_id;if(!e)throw new Error("Feishu reaction.create returned no reaction_id");return e}async removeReaction(t,o){nl("Feishu reaction.delete",await this.#e.im.v1.messageReaction.delete({path:{message_id:t,reaction_id:o}}))}};var C6="/open-apis/application/v7/app_slash_commands",WRe=new Set(["99991640","99991672"]),nS=Object.freeze(["application:app_slash_command:read","application:app_slash_command:write"]),u6="ai-agent_outlined",Zv=Object.freeze([{command:"menu",icon:"skill_outlined",default:"\u6253\u5F00\u529F\u80FD\u83DC\u5355",en_us:"Open the feature menu"},{command:"new",icon:"ai-deepthink_outlined",default:"\u5F00\u542F\u5168\u65B0\u4F1A\u8BDD",en_us:"Start a fresh session"},{command:"help",icon:"promptword_outlined",default:"\u67E5\u770B\u5E2E\u52A9",en_us:"Show help"},{command:"status",icon:"ai-functions_outlined",default:"\u67E5\u770B\u673A\u5668\u4EBA\u72B6\u6001",en_us:"Show bot status"},{command:"compact",icon:"ai-block_outlined",default:"\u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u4E0A\u4E0B\u6587",en_us:"Compact the current session"},{command:"sessionlist",icon:"chat-ai_outlined",default:"\u5217\u51FA\u4F1A\u8BDD",en_us:"List sessions"},{command:"workspacelist",icon:"folder_outlined",default:"\u5217\u51FA\u5DE5\u4F5C\u533A",en_us:"List workspaces"},{command:"watch",icon:"flag_outlined",default:"\u5173\u6CE8\u4E00\u4E2A\u4F1A\u8BDD",en_us:"Watch a session"},{command:"unwatch",icon:"clear_outlined",default:"\u53D6\u6D88\u5173\u6CE8\u4F1A\u8BDD",en_us:"Unwatch a session"},{command:"watchlist",icon:"flag_outlined",default:"\u67E5\u770B\u5173\u6CE8\u5217\u8868",en_us:"List watched sessions"},{command:"archived",icon:"folder_outlined",default:"\u8BBE\u7F6E\u5F52\u6863\u4F1A\u8BDD\u663E\u9690\uFF08on/off\uFF09",en_us:"Show or hide archived sessions (on/off)"}]);function Xv(n,t){let o=n==="lark"?"https://open.larksuite.com":"https://open.feishu.cn";return new URL(t,o)}function E6(n,t){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} returned a non-JSON response`);if(n.code!==0){let o=new Error(`${t} failed: ${n.msg||`code ${n.code}`}`);throw o.code=String(n.code),o.msg=n.msg,o}return n}function $v(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}async function eP(n,t,o){try{return E6(await n.request(t),o)}catch(i){let e=i?.response?.data;if(e&&typeof e=="object"&&!Array.isArray(e)&&Object.hasOwn(e,"code"))return E6(e,o);throw i}}async function ZRe({appId:n,appSecret:t,domain:o,httpInstance:i,timeoutMs:e,signal:a}){if(!n||!t)throw new Error("Feishu slash registration requires app credentials");if(!i||typeof i.request!="function")throw new TypeError("Feishu slash registration requires an HTTP instance");let A=await eP(i,{method:"POST",url:Xv(o,"/open-apis/auth/v3/tenant_access_token/internal").href,headers:{"content-type":"application/json; charset=utf-8"},data:{app_id:n,app_secret:t},signal:$v(a,e),timeout:e},"Feishu authentication");if(!A.tenant_access_token)throw new Error("Feishu authentication returned no tenant access token");return A.tenant_access_token}async function XRe({tenantAccessToken:n,domain:t,httpInstance:o,timeoutMs:i,signal:e}){let a=await eP(o,{method:"GET",url:Xv(t,C6).href,headers:{authorization:`Bearer ${n}`,"content-type":"application/json; charset=utf-8"},signal:$v(e,i),timeout:i},"Feishu slash command list");return Array.isArray(a.data?.items)?a.data.items:[]}async function $Re({tenantAccessToken:n,domain:t,httpInstance:o,timeoutMs:i,signal:e,command:a,description:A,icon:r=u6}){let s={command:a};return A&&(A.default_value||A.i18n)?s.description=A:typeof A=="string"&&A.trim()&&(s.description={default_value:A.trim()}),r&&(s.description={...s.description??{},icon:{icon_key:r}}),(await eP(o,{method:"POST",url:Xv(t,C6).href,headers:{authorization:`Bearer ${n}`,"content-type":"application/json; charset=utf-8"},data:s,signal:$v(e,i),timeout:i},`Feishu slash command create (/${a})`)).data?.command_id??null}async function B6({appId:n,appSecret:t,domain:o="feishu",httpInstance:i,timeoutMs:e=15e3,signal:a,manifest:A=Zv}){let r=await ZRe({appId:n,appSecret:t,domain:o,httpInstance:i,timeoutMs:e,signal:a}),s=new Set((await XRe({tenantAccessToken:r,domain:o,httpInstance:i,timeoutMs:e,signal:a})).map(I=>I.command)),g=[],c=[];for(let I of A){let d=String(I.command??"").replace(/^\//,"");if(d&&!s.has(d))try{let B={default_value:I.default??I.en_us??d,i18n:{zh_cn:I.default??d,en_us:I.en_us??I.default??d}},f=await $Re({tenantAccessToken:r,domain:o,httpInstance:i,timeoutMs:e,signal:a,command:d,description:B,icon:I.icon??u6});g.push({command:d,command_id:f})}catch(B){if(B?.code==="40000000"&&/already exists/i.test(B?.msg??"")){s.add(d);continue}if(WRe.has(B?.code)||/(?:lacks permission|access denied)/i.test(B?.msg??"")){c.push({command:d,error:B});break}c.push({command:d,error:B?.message??String(B)})}}return{created:g,existing:[...s].filter(I=>I!=null),failed:c}}var Ake=15e3,tke="\u2705 \u4FEE\u590D\u5B8C\u6210\uFF1A\u5DF2\u5B9E\u6D4B\u6536\u5230 card.action.trigger\uFF0C\u83DC\u5355\u6309\u94AE\u73B0\u5728\u53EF\u7528\u3002",rke="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u8D85\u65F6\uFF1A\u672A\u6536\u5230\u6D4B\u8BD5\u5361\u6309\u94AE\u7684 card.action.trigger\uFF0C\u4E0D\u80FD\u786E\u8BA4\u6309\u94AE\u5DF2\u4FEE\u590D\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u68C0\u67E5\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u7684\u5361\u7247\u56DE\u8C03\u914D\u7F6E\uFF0C\u786E\u8BA4\u540E\u518D\u53D1\u9001 /repair\u3002",AP="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u5931\u8D25\uFF1A\u65E0\u6CD5\u53D1\u9001\u4E13\u7528\u6D4B\u8BD5\u5361\uFF0C\u4E0D\u80FD\u786E\u8BA4 card.action.trigger \u5DF2\u6062\u590D\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u68C0\u67E5\u673A\u5668\u4EBA\u6D88\u606F\u6743\u9650\u548C\u8FDE\u63A5\u72B6\u6001\u3002",ake="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u4E2D\u65AD\uFF1ARuntime \u5DF2\u505C\u6B62\uFF0C\u672A\u5B8C\u6210 card.action.trigger \u5B9E\u6D4B\uFF0C\u4E0D\u80FD\u786E\u8BA4\u4FEE\u590D\u6210\u529F\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u7B49\u5F85\u673A\u5668\u4EBA\u6062\u590D\u8FDE\u63A5\u3002",ike=new Set(["connected","connecting","reconnecting"]);function yn(n){return typeof n=="string"&&n.trim()?n.trim():null}function oke(n){return yn(n?.operator?.open_id)??yn(n?.operator?.operator_id?.open_id)}function nke(n,t){try{let o=n?.getConnectionStatus?.()?.state;return typeof o=="string"&&o?o:t}catch{return t}}function Nd(n,t){let o=new Error(t);return o.code=n,o}function ske(n,t){if(!n||typeof n.request!="function")return;let o=i=>({...i??{},timeout:i?.timeout??t});return{request:i=>n.request(o(i)),get:(i,e)=>n.get(i,o(e)),delete:(i,e)=>n.delete(i,o(e)),head:(i,e)=>n.head(i,o(e)),options:(i,e)=>n.options(i,o(e)),post:(i,e,a)=>n.post(i,e,o(a)),put:(i,e,a)=>n.put(i,e,o(a)),patch:(i,e,a)=>n.patch(i,e,o(a))}}function gke({allowedSenderCount:n=1}={}){return{startedAt:null,ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1,messagesReceived:0,messagesReplied:0,messagesRejected:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0,streamResponses:0,streamUpdates:0,streamFallbacks:0,streamErrors:0,cardActionsReceived:0,cardActionProbesVerified:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastCardActionAt:null,lastError:null,agentPreset:"standard",authorizationMode:"sender-open-id-allowlist",allowedSenderCount:n,slashCommandRegistration:"idle",slashCommandsRegistered:0,slashCommandsExisting:0,slashCommandsFailed:0,slashCommandsError:null}}var sS=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c;#p;#d;#h;#E;#C=null;#f=null;#B=null;#y=null;#S=null;#Q=null;#m=new Map;#u;#b=!0;constructor({lark:t,botId:o,appId:i,appSecret:e,domain:a="feishu",botOpenId:A,groupResponseMode:r,ownerOpenId:s,ownerOpenIds:g,harness:c,state:I,contextEnhancement:d,repair:B,replyTimeoutMs:f=6e5,connectTimeoutMs:Q=15e3,requestTimeoutMs:y=Ake,slashCommands:m=!0,wsAgent:_,logger:T=console}){if(!t)throw new Error("FeishuRuntime requires the Feishu SDK");if(!i||!e)throw new Error("FeishuRuntime requires app credentials");let R=Array.isArray(g)?g:[s],L=[...new Set(R.filter(U=>typeof U=="string"&&U))];if(L.length===0)throw new Error("FeishuRuntime requires at least one owner open_id");if(!c)throw new Error("FeishuRuntime requires a Harness client");if(!I)throw new Error("FeishuRuntime requires a state store");if(B!=null&&!yn(o))throw new TypeError("FeishuRuntime repair capability requires a botId");if(!Number.isFinite(y)||y<=0)throw new TypeError("FeishuRuntime requestTimeoutMs must be a positive number");this.#e=t,this.#A=yn(o),this.#t=i,this.#r=e,this.#g=a,this.#a=yn(A),this.#n=ao(r),this.#i=L,this.#I=c,this.#l=I,this.#o=d,this.#E=B??null,this.#s=f,this.#c=Q,this.#p=y,this.#b=!!m,this.#d=_,this.#h=T,this.#u=gke({allowedSenderCount:L.length})}get status(){return structuredClone(this.#u)}setGroupResponseMode(t){this.#n=ao(t),this.#f?.setGroupResponseMode(this.#n)}async start(){for(;;){for(;this.#S;)await this.#S;if(this.#y)return this.#y;let o=this.#B;if(o){let i=nke(o,this.#u.feishuLongConnectionState);if(ike.has(i))return this.status;await this.stop({preserveError:i==="failed"});continue}if(this.#C||this.#f||this.#Q){await this.stop({preserveError:this.#u.feishuLongConnectionState==="failed"});continue}break}let t;return t=this.#R().finally(()=>{this.#y===t&&(this.#y=null)}),this.#y=t,t}async#R(){let t=new AbortController;this.#Q=t;let{signal:o}=t,i=()=>o.reason??new DOMException("Feishu runtime stopped","AbortError"),e=()=>!o.aborted&&this.#Q===t,a=()=>{if(!e())throw i()};this.#u.startedAt=new Date().toISOString(),this.#u.feishuLongConnectionState="connecting",this.#u.lastError=null;try{await this.#I.ensureRunning({signal:o}),a(),this.#u.harnessReachable=!0;let A=this.#g==="lark"?this.#e.Domain.Lark:this.#e.Domain.Feishu,r={appId:this.#t,appSecret:this.#r,domain:A},s=ske(this.#e.defaultHttpInstance,this.#p);s&&(r.httpInstance=s);let g=new this.#e.Client(r);this.#C=g;let c=new oS({client:g,initialText:w("\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026")}),I=new aS({client:g,channel:c,harness:this.#I,state:this.#l,contextEnhancement:this.#o,status:this.#u,allowedSenderOpenIds:new Set(this.#i),botId:this.#A,appId:this.#t,botOpenId:this.#a,groupResponseMode:this.#n,repair:this.#E,replyTimeoutMs:this.#s,signal:o,logger:this.#h});this.#f=I;let d=new this.#e.EventDispatcher({}).register({"im.message.receive_v1":_=>{e()&&I.accept(_)},"im.message.reaction.created_v1":()=>{},"im.message.reaction.deleted_v1":()=>{},"card.action.trigger":_=>{e()&&(this.#u.cardActionsReceived+=1,this.#u.lastCardActionAt=new Date().toISOString(),this.#D(_)||I.onCardAction(_))}}),B,f,Q=new Promise((_,T)=>{let R=!1,L=()=>{f(i())},U=(q,z)=>{R||(R=!0,clearTimeout(F),o.removeEventListener("abort",L),q(z))},F=setTimeout(()=>{U(T,new Error(`Feishu WebSocket handshake timed out after ${this.#c}ms`))},this.#c);B=()=>{U(_)},f=q=>{U(T,q)},o.addEventListener("abort",L,{once:!0}),o.aborted&&L()});Q.catch(()=>{});let y=new this.#e.WSClient({...r,...this.#d?{agent:this.#d}:{},loggerLevel:this.#e.LoggerLevel.info,handshakeTimeoutMs:this.#c,onReady:()=>{e()&&(this.#u.feishuLongConnectionState="connected",this.#u.ready=!0,this.#u.lastError=null,B())},onError:_=>{e()&&(this.#u.feishuLongConnectionState="failed",this.#u.ready=!1,this.#u.lastError=_?.message??String(_),this.#h.error("[dsh-feishu] Feishu long connection failed:",this.#u.lastError),f(_))},onReconnecting:()=>{e()&&(this.#u.feishuLongConnectionState="reconnecting",this.#u.ready=!1)},onReconnected:()=>{e()&&(this.#u.feishuLongConnectionState="connected",this.#u.ready=!0,this.#u.lastError=null)}});this.#B=y;let m=Promise.resolve().then(()=>y.start({eventDispatcher:d})).catch(_=>{throw f(_),_});return await Promise.all([m,Q]),a(),this.#b&&s&&this.#T(s,e,o),this.status}catch(A){throw o.aborted||(this.#u.ready=!1,this.#u.feishuLongConnectionState="failed",this.#u.lastError=A?.message??String(A),await this.#M({preserveError:!0,abortController:t})),A}}async beginCardActionProbe({expectedOperatorOpenId:t,timeoutMs:o=9e4}={}){if(!this.#u.ready||!this.#C)throw Nd("card_action_probe_unavailable","\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");let i=yn(t);if(!i||i==="*")throw new TypeError("A precise Feishu operator open_id is required");if(!Number.isFinite(o)||o<=0||o>10*6e4)throw new TypeError("Card-action probe timeout must be between 1 and 600000ms");let e=eke().replaceAll("-",""),a;try{a=await this.#C.im.v1.message.create({params:{receive_id_type:"open_id"},data:{receive_id:i,msg_type:"interactive",content:VW(e)}})}catch{throw this.#w(i,w(AP),"failure"),Nd("card_action_probe_send_failed","\u65E0\u6CD5\u53D1\u9001\u98DE\u4E66\u5361\u7247\u56DE\u8C03\u6D4B\u8BD5")}if(a?.code&&a.code!==0)throw this.#w(i,w(AP),"failure"),Nd("card_action_probe_send_failed","\u65E0\u6CD5\u53D1\u9001\u98DE\u4E66\u5361\u7247\u56DE\u8C03\u6D4B\u8BD5");let A=yn(a?.data?.message_id)??yn(a?.message_id);if(!A)throw this.#w(i,w(AP),"failure"),Nd("card_action_probe_send_failed","\u98DE\u4E66\u672A\u8FD4\u56DE\u6D4B\u8BD5\u5361\u7247\u7684\u6D88\u606F ID");return new Promise((r,s)=>{let g=setTimeout(()=>{let c=this.#m.get(A);!c||c.nonce!==e||(this.#m.delete(A),this.#w(i,w(rke),"timeout"),s(Nd("card_action_probe_timeout","\u5728\u89C4\u5B9A\u65F6\u95F4\u5185\u672A\u6536\u5230\u98DE\u4E66\u5361\u7247\u6309\u94AE\u56DE\u8C03")))},o);g.unref?.(),this.#m.set(A,{messageId:A,nonce:e,expectedOperatorOpenId:i,timeout:g,resolve:r,reject:s})})}#D(t){let o=yn(t?.context?.open_message_id);if(!o)return!1;let i=this.#m.get(o);if(!i)return!1;let e=t?.action?.value,a=oke(t);return e?.action!=="repair_verify"||e?.nonce!==i.nonce||a!==i.expectedOperatorOpenId?!1:(clearTimeout(i.timeout),this.#m.delete(o),this.#u.cardActionProbesVerified+=1,this.#w(a,w(tke),"success").finally(()=>{i.resolve({verified:!0,messageId:o,operatorOpenId:a})}),!0)}#w(t,o,i){let e=this.#C;return e?Promise.resolve().then(async()=>{let a=await e.im.v1.message.create({params:{receive_id_type:"open_id"},data:{receive_id:t,msg_type:"text",content:JSON.stringify({text:o})}});if(a?.code&&a.code!==0)throw new Error("Feishu callback repair notice failed");return!0}).catch(()=>(this.#h.warn?.(`[dsh-feishu] unable to send the callback repair ${i} notice`),!1)):(this.#h.warn?.(`[dsh-feishu] unable to send the callback repair ${i} notice`),Promise.resolve(!1))}async sendConnectionTest(t){if(!this.#u.ready||!this.#C){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}if(typeof t!="string"||!t.trim())throw new TypeError("Feishu connection test text is required");let o=async(e,a,A)=>{let r=await this.#C.im.v1.message.create({params:{receive_id_type:e},data:{receive_id:a,msg_type:"text",content:JSON.stringify({text:A})}});if(r?.code&&r.code!==0)throw new Error(`Feishu connection test failed: ${r.msg||r.code}`)},i=this.#i.find(e=>e!=="*");return i?(await o("open_id",i,t),{sent:!0}):ec({state:this.#l,text:t,channelLabel:w("\u98DE\u4E66\u673A\u5668\u4EBA"),send:async(e,a)=>{let A=typeof e?.chatId=="string"?e.chatId.trim():"";if(!A)throw Ir(w("\u98DE\u4E66\u673A\u5668\u4EBA"));await o("chat_id",A,a)}})}async sendProactiveText(t,o,{signal:i}={}){if(!this.#u.ready||!this.#C){let r=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw r.code="bot-not-connected",r}let e=t?.kind==="user"?"open_id":t?.kind==="group"?"chat_id":null,a=t?.kind==="user"?yn(t?.route?.openId):t?.kind==="group"?yn(t?.route?.chatId):null;if(!e||!a){let r=new TypeError("Invalid Feishu proactive delivery target");throw r.code="invalid-target",r}i?.throwIfAborted();let A=await this.#C.im.v1.message.create({params:{receive_id_type:e},data:{receive_id:a,msg_type:"text",content:JSON.stringify({text:o})}});if(A?.code&&A.code!==0){let r=new Error(`Feishu proactive delivery failed: ${A.msg||A.code}`);throw r.code="target-rejected",r}return{sent:!0}}async#T(t,o,i){this.#u.slashCommandRegistration="registering",this.#u.slashCommandsError=null;try{let e=await B6({appId:this.#t,appSecret:this.#r,domain:this.#g,httpInstance:t,signal:i,manifest:Zv});if(!o())return;this.#u.slashCommandRegistration="done",this.#u.slashCommandsRegistered=e.created.length,this.#u.slashCommandsExisting=e.existing.length,this.#u.slashCommandsFailed=e.failed.length,this.#u.slashCommandsError=e.failed.length>0?e.failed.map(a=>`/${a.command}: ${a.error?.message??String(a.error)}`).join("; "):null,e.created.length>0&&this.#h.info?.(`[dsh-feishu] registered ${e.created.length} slash command(s)`),e.failed.length>0&&this.#h.warn?.(`[dsh-feishu] ${e.failed.length} slash command(s) failed to register: ${this.#u.slashCommandsError}`)}catch(e){if(!o())return;this.#u.slashCommandRegistration="failed",this.#u.slashCommandsError=e?.message??String(e),this.#h.warn?.(`[dsh-feishu] slash command registration skipped: ${this.#u.slashCommandsError}`)}}stop(t={}){if(this.#S)return this.#S;let o;return o=this.#k(t).finally(()=>{this.#S===o&&(this.#S=null)}),this.#S=o,o}async#k({preserveError:t=!1}={}){let o=this.#Q;this.#Q===o&&(this.#Q=null),o?.abort(new DOMException("Feishu runtime stopped","AbortError"));let i=this.#y;return i&&await i.catch(()=>{}),this.#M({preserveError:t,abortController:o})}async#M({preserveError:t=!1,abortController:o}={}){let i=t?this.#u.lastError:null;this.#Q===o&&(this.#Q=null),o?.abort(new DOMException("Feishu runtime stopped","AbortError"));for(let A of this.#m.values())clearTimeout(A.timeout),this.#w(A.expectedOperatorOpenId,w(ake),"abort"),A.reject(Nd("abort","\u98DE\u4E66\u8FD0\u884C\u65F6\u5DF2\u505C\u6B62"));this.#m.clear(),this.#u.ready=!1;let e=this.#B;this.#B=null,e?.close({force:!0});let a=this.#f;return this.#f=null,a&&await a.waitForIdle(),this.#C=null,this.#u.feishuLongConnectionState=t?"failed":"idle",this.#u.slashCommandRegistration="idle",this.#u.lastError=i,this.status}};var gS=class extends lr{constructor(t){super({...t,rpcIdPrefix:"feishu",logPrefix:"dsh-feishu"})}};import{createHash as cke}from"node:crypto";import{mkdir as Ike,readFile as lke,rename as pke,unlink as dke,writeFile as hke}from"node:fs/promises";import{dirname as Eke}from"node:path";var lS="DSH_FEISHU_APP_SECRET";function ps(n){return typeof n=="string"&&n.trim()?n.trim():null}function f6(n){let t=ps(n);return t&&/^[A-Za-z0-9_-]{1,128}$/.test(t)?t:null}function Q6(n){return`bot_${cke("sha256").update(n).digest("hex").slice(0,24)}`}function Cke(n){let t=Array.isArray(n.ownerOpenIds)?n.ownerOpenIds:[n.ownerOpenId];return[...new Set(t.map(ps).filter(Boolean))]}function cS(n,{legacy:t=!1}={}){if(!n||typeof n!="object")return null;let o=ps(n.appId),i=Cke(n);if(!o||i.length===0)return null;let e=f6(n.id)??(t?Q6(o):null),a=ps(n.secretRef)??(t?lS:null);if(!e||!a||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))return null;let A=n.domain==="lark"?"lark":"feishu";return Object.freeze({id:e,appId:o,secretRef:a,ownerOpenIds:Object.freeze(i),domain:A,botName:ps(n.botName),botOpenId:ps(n.botOpenId),activated:n.activated??null,groupResponseMode:ao(n.groupResponseMode),groupMessagePermissionGranted:n.groupMessagePermissionGranted===!0,deletionPending:n.deletionPending===!0,connectedAt:ps(n.connectedAt),createdAt:ps(n.createdAt)??ps(n.connectedAt)})}function uke(n){if(!n||typeof n!="object")return null;if(n.version===2&&Array.isArray(n.bots)){let o=n.bots.map(A=>cS(A));if(o.some(A=>A===null))throw new Error("dsh-feishu config contains an invalid bot entry");let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.id)||e.has(A.secretRef)||a.has(A.appId))throw new Error("dsh-feishu config contains duplicate bot identities");i.add(A.id),e.add(A.secretRef),a.add(A.appId)}return{value:Object.freeze({version:2,bots:Object.freeze(o)}),migrated:!1}}let t=cS(n,{legacy:!0});return t?{value:Object.freeze({version:2,bots:Object.freeze([t])}),migrated:!0}:null}var IS=class{#e;#A=Object.freeze({version:2,bots:Object.freeze([])});#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=JSON.parse(await lke(this.#e,"utf8")),o=uke(t);if(!o)throw new Error("dsh-feishu config is incomplete or invalid");this.#A=o.value,o.migrated&&await this.#a(this.#A)}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=Object.freeze({version:2,bots:Object.freeze([])})}return this}get(){let t=this.#A.bots[0];if(!t)return null;let o=structuredClone(t);return o.ownerOpenId=o.ownerOpenIds[0],o}list(){return structuredClone(this.#A.bots)}getBot(t){let o=this.#A.bots.find(i=>i.id===t);return o?structuredClone(o):null}async save(t){let o={...t};o.id||(o.id=Q6(ps(o.appId)??"invalid")),o.secretRef||(o.secretRef=lS);let i=cS(o);if(!i)throw new Error("Refusing to persist incomplete dsh-feishu configuration");return await this.#r([i]),this.get()}async saveBot(t){let o=cS(t);if(!o)throw new Error("Refusing to persist incomplete dsh-feishu bot configuration");return this.#g(i=>{if(i.find(r=>r.secretRef===o.secretRef&&r.id!==o.id))throw new Error("Refusing to share a credential reference between Feishu bots");if(i.find(r=>r.appId===o.appId&&r.id!==o.id))throw new Error("Refusing to persist the same Feishu app twice");let A=i.findIndex(r=>r.id===o.id);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async removeBot(t){if(!f6(t))throw new TypeError("Invalid Feishu bot id");return this.#g(o=>{let i=o.findIndex(a=>a.id===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await dke(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=Object.freeze({version:2,bots:Object.freeze([])})});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o=Object.freeze({version:2,bots:Object.freeze([...t])}),i=this.#t.then(async()=>{await this.#a(o),this.#A=o});this.#t=i.then(()=>{},()=>{}),await i}async#g(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:2,bots:Object.freeze(e)});await this.#a(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#a(t){await Ike(Eke(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await hke(o,`${JSON.stringify(t,null,2)} +`,{encoding:"utf8",mode:384}),await pke(o,this.#e)}};import{randomUUID as O6}from"node:crypto";var tP=new Set(["starting","qr_ready","polling","slow_down","domain_switched","saving"]),Bke=new Set(["polling","slow_down","domain_switched"]),vi=Object.freeze({IDLE:"idle",STARTING:"starting",QR_READY:"qr_ready",POLLING:"polling",SLOW_DOWN:"slow_down",DOMAIN_SWITCHED:"domain_switched",SAVING:"saving",SUCCEEDED:"succeeded",EXPIRED:"expired",CANCELLED:"cancelled",ERROR:"error"});function y6(n){return["access_denied","expired_token","abort"].includes(n?.code)?n.code:"registration_failed"}function rP(n){let t=y6(n);return{code:t,message:{access_denied:"Registration was denied.",abort:"Registration was cancelled.",expired_token:"The registration QR code expired."}[t]??"Unable to register the Feishu app."}}function fke(n){let t=Number(n);if(!Number.isFinite(t)||t<=0)throw new TypeError("registerApp onQRCodeReady returned an invalid expireIn");return t}function Qke(n){if(n!==void 0){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError("registerApp returned invalid user_info");return{...n}}}var yg=class{#e;#A;#t;#r;#g;#a=0;#n=null;#i;constructor({registerApp:t,onCredentials:o,now:i=Date.now,setTimeout:e=globalThis.setTimeout,clearTimeout:a=globalThis.clearTimeout}={}){if(typeof t!="function")throw new TypeError("RegistrationManager requires a registerApp function");if(typeof o!="function")throw new TypeError("RegistrationManager requires an onCredentials function");if(typeof i!="function"||typeof e!="function"||typeof a!="function")throw new TypeError("RegistrationManager clock dependencies must be functions");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#i=this.#l(null,vi.IDLE)}start(t={}){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("Registration options must be an object");this.#B();let o={id:++this.#a,controller:new AbortController,qrCodeUrl:null,expiresAt:null,pollIntervalSeconds:null,expiryTimer:null};this.#n=o,this.#i=this.#l(o,vi.STARTING);let i={...t,signal:o.controller.signal,onQRCodeReady:a=>this.#s(o,a),onStatusChange:a=>this.#c(o,a)};return Promise.resolve().then(()=>this.#e(i)).then(a=>this.#p(o,a),a=>this.#d(o,a)),this.status()}status(){this.#h();let t={...this.#i};t.error&&(t.error={...t.error});let o=this.#n;return o&&o.expiresAt!==null&&tP.has(t.state)&&(t.remainingSeconds=Math.max(0,Math.ceil((o.expiresAt-this.#t())/1e3))),t}cancel(){let t=this.#n;return t?(this.#C(t,vi.CANCELLED,{error:{code:"abort",message:"Registration was cancelled."}}),t.controller.abort(),this.status()):this.status()}#I(t){return this.#n===t}#l(t,o,i={}){let e={state:o,attempt:t?.id??this.#a,updatedAt:this.#t(),...i};return t?.qrCodeUrl&&tP.has(o)&&(e.qrCodeUrl=t.qrCodeUrl,e.expiresAt=t.expiresAt),t?.pollIntervalSeconds!==null&&tP.has(o)&&(e.pollIntervalSeconds=t.pollIntervalSeconds),e}#o(t,o,i={}){this.#I(t)&&(this.#i=this.#l(t,o,i))}#s(t,o){if(!this.#I(t))return;if(typeof o?.url!="string"||!o.url)throw new TypeError("registerApp onQRCodeReady returned an invalid URL");let i=fke(o.expireIn);t.qrCodeUrl=o.url,t.expiresAt=this.#t()+i*1e3,this.#f(t),t.expiryTimer=this.#r(()=>this.#E(t),i*1e3),t.expiryTimer?.unref?.(),this.#o(t,vi.QR_READY)}#c(t,o){!this.#I(t)||!Bke.has(o?.status)||(o.status===vi.SLOW_DOWN&&Number.isFinite(Number(o.interval))&&(t.pollIntervalSeconds=Number(o.interval)),this.#o(t,o.status))}async#p(t,o){if(!this.#I(t))return;let i=o?.client_id,e=o?.client_secret;if(typeof i!="string"||!i||typeof e!="string"||!e){this.#C(t,vi.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}let a;try{a=Qke(o.user_info)}catch{this.#C(t,vi.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}this.#f(t),t.qrCodeUrl=null,t.expiresAt=null,t.pollIntervalSeconds=null,this.#o(t,vi.SAVING);try{await this.#A({client_id:i,client_secret:e,user_info:a})}catch{this.#I(t)&&this.#C(t,vi.ERROR,{error:{code:"credentials_callback_failed",message:"Unable to store the Feishu credentials."}});return}this.#I(t)&&this.#C(t,vi.SUCCEEDED)}#d(t,o){if(!this.#I(t))return;let i=y6(o);if(i==="expired_token"){this.#C(t,vi.EXPIRED,{error:rP(o)});return}if(i==="abort"){this.#C(t,vi.CANCELLED,{error:rP(o)});return}this.#C(t,vi.ERROR,{error:rP(o)})}#h(){let t=this.#n;t&&t.expiresAt!==null&&this.#t()>=t.expiresAt&&this.#E(t)}#E(t){this.#I(t)&&(this.#C(t,vi.EXPIRED,{error:{code:"expired_token",message:"The registration QR code expired."}}),t.controller.abort())}#C(t,o,i={}){this.#I(t)&&(this.#f(t),this.#i=this.#l(t,o,i),this.#n=null)}#f(t){t.expiryTimer!==null&&(this.#g(t.expiryTimer),t.expiryTimer=null)}#B(){let t=this.#n;t&&(this.#f(t),this.#n=null,t.controller.abort())}};var yke="card.action.trigger",mke="im:message:readonly",Ske="im:resource",Su="callback_repair";function wke(n){return n==="lark"?"accounts.larksuite.com":"accounts.feishu.cn"}function Dke(n){return n==="lark"?"open.larksuite.com":"open.feishu.cn"}function aP(n,t,o="feishu",i="Feishu app update"){let e;try{e=new URL(n)}catch{throw new Error(`${i} returned an invalid verification URL`)}let a=o==="feishu"||o==="lark",A=e.searchParams.getAll("clientID"),r=e.searchParams.getAll("tp"),s=e.searchParams.getAll("addons"),g=String(t).includes("{{")||String(t).includes("}}")||[...e.searchParams.values()].some(c=>c.includes("{{")||c.includes("}}"));if(!a||e.protocol!=="https:"||e.hostname!==Dke(o)||e.port!==""||e.username!==""||e.password!==""||r.length!==1||r[0]!=="sdk"||A.length!==1||A[0]!==t||e.searchParams.has("createOnly")||s.length!==1||!s[0]?.trim()||g)throw new Error(`${i} returned an unsafe verification URL`);return e.toString()}function Oke(n,t,o="feishu"){return aP(n,t,o,"Feishu callback repair")}var pS=class{#e;#A;#t;constructor({registerApp:t,onCredentials:o,appId:i,domain:e="feishu"}={}){if(typeof t!="function")throw new TypeError("registerApp is required");if(typeof o!="function")throw new TypeError("onCredentials is required");if(typeof i!="string"||!i.trim())throw new TypeError("appId is required");if(e!=="feishu"&&e!=="lark")throw new TypeError("domain is invalid");this.#A=i.trim(),this.#t=e,this.#e=new yg({registerApp:a=>t({...a,onQRCodeReady:A=>{Oke(A?.url,this.#A,this.#t),a.onQRCodeReady(A)}}),onCredentials:o})}start(){return this.#e.start({source:"deepseek-harness-card-action-repair",domain:wke(this.#t),appId:this.#A,addons:{preset:!1,scopes:{tenant:[mke,Ske,...nS]},callbacks:{items:[yke]}}})}status(){return this.#e.status()}cancel(){return this.#e.cancel()}};var bke="im:message.group_msg",hS="group_message_permission";function Mke(n){return n==="lark"?"accounts.larksuite.com":"accounts.feishu.cn"}function _ke(n,t,o="feishu"){return aP(n,t,o,"Feishu group message permission update")}var dS=class{#e;#A;#t;constructor({registerApp:t,onCredentials:o,appId:i,domain:e="feishu"}={}){if(typeof t!="function")throw new TypeError("registerApp is required");if(typeof o!="function")throw new TypeError("onCredentials is required");if(typeof i!="string"||!i.trim())throw new TypeError("appId is required");if(e!=="feishu"&&e!=="lark")throw new TypeError("domain is invalid");this.#A=i.trim(),this.#t=e,this.#e=new yg({registerApp:a=>t({...a,onQRCodeReady:A=>{_ke(A?.url,this.#A,this.#t),a.onQRCodeReady(A)}}),onCredentials:o})}start(){return this.#e.start({source:"deepseek-harness-group-message-permission",domain:Mke(this.#t),appId:this.#A,addons:{preset:!1,scopes:{tenant:[bke]}}})}status(){return this.#e.status()}cancel(){return this.#e.cancel()}};var m6=Object.freeze(["im:message.p2p_msg:readonly","im:message.group_at_msg:readonly","im:message:readonly","im:message:send_as_bot","im:message.reactions:write_only","im:message:recall","im:resource","cardkit:card:write",...nS]);var iP=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]),ES=new Set([...iP,"saving"]),S6=new Set([Su,hS]),w6="*",Tke=12e4,Nke=6e5;function b6(){return{ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1}}function wu(n){return n?n.status:b6()}function Du(n){return n.ready===!0&&n.feishuLongConnectionState==="connected"&&n.harnessReachable===!0}function M6(n){return n.length>12?`${n.slice(0,8)}\u2022\u2022\u2022\u2022${n.slice(-4)}`:"cli_\u2022\u2022\u2022\u2022"}function Rke(n){return{name:n.botName,appIdMasked:M6(n.appId),activated:n.activated,domain:n.domain}}function kke({connected:n,error:t,connection:o}){return n?"connected":t||o.feishuLongConnectionState==="failed"?"error":"disconnected"}function vke(){return`bot_${O6().replaceAll("-","")}`}function Pke(){return`reg_${O6().replaceAll("-","")}`}function D6(n){return`DSH_FEISHU_APP_SECRET_${n.slice(4).toUpperCase()}`}function CS(n){return JSON.stringify({id:n.id,appId:n.appId,secretRef:n.secretRef,ownerOpenIds:n.ownerOpenIds,domain:n.domain,botName:n.botName,botOpenId:n.botOpenId,activated:n.activated,groupResponseMode:ao(n.groupResponseMode),groupMessagePermissionGranted:n.groupMessagePermissionGranted===!0,deletionPending:n.deletionPending===!0,connectedAt:n.connectedAt??null,createdAt:n.createdAt??null})}function uS(n){return typeof n=="string"&&n.trim()?n.trim():null}var Ou=class{#e;#A;#t;#r;#g;#a;#n;#i;#I=new Map;#l=new Map;#o=new Map;#s=new Map;#c=new Map;#p=null;#d=Promise.resolve();#h=new Map;#E=1;#C;#f=!1;constructor({registerApp:t,verifyApp:o,credentials:i,configStore:e,createRuntime:a,deleteState:A=async()=>{},createBotId:r=vke,createRegistrationId:s=Pke,callbackProbeTimeoutMs:g=Tke}){if(typeof t!="function")throw new Error("registerApp is required");if(typeof o!="function")throw new Error("verifyApp is required");if(!i)throw new Error("credentials service is required");if(!e||typeof e.list!="function")throw new Error("multi-bot config store is required");if(typeof a!="function")throw new Error("createRuntime is required");if(typeof A!="function")throw new Error("deleteState must be a function");if(!Number.isFinite(g)||g<=0||g>Nke)throw new TypeError("callbackProbeTimeoutMs must be between 1 and 600000ms");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#C=g}async initialize(){if(this.#f)return this.status();let t=this.#r.list(),o=!1;return await Promise.allSettled(t.map(i=>this.#_(i.id,async()=>{let e=wu(this.#I.get(i.id));if(Du(e)||e.feishuLongConnectionState==="connecting"||e.feishuLongConnectionState==="reconnecting")return;if(o=!0,i.deletionPending){this.#l.set(i.id,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"});return}let a;try{a=await this.#t.resolve(i.secretRef)}catch{this.#l.set(i.id,{code:"missing_credentials",message:"\u65E0\u6CD5\u8BFB\u53D6\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u3002"});return}if(!a?.value){this.#l.set(i.id,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"});return}try{await this.#b(i,a.value),this.#l.delete(i.id)}catch{this.#l.set(i.id,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}}))),o&&this.#v(),this.status()}startRegistration(){this.#M();let t=this.#i();if(typeof t!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(t)||this.#o.has(t))throw new Error("Registration id generator returned an invalid or duplicate id");let o={id:t,manager:null,botId:null,createdNew:!1,cancelled:!1};return o.manager=new yg({registerApp:this.#e,onCredentials:i=>this.#L(()=>this.#u(o,i))}),this.#o.set(t,o),this.#p=t,this.#U(),o.manager.start({source:"deepseek-harness",createOnly:!0,appPreset:{name:"{user} \u7684\u5317\u6C47\u661F\u6CB3 AI \u52A9\u624B",desc:"\u8FDE\u63A5\u98DE\u4E66\u4E0E DeepSeek Harness\uFF0C\u5728\u804A\u5929\u4E2D\u4F7F\u7528\u4F01\u4E1A AI \u52A9\u624B\u3002"},addons:{preset:!1,scopes:{tenant:[...m6]},events:{items:{tenant:["im.message.receive_v1"]}},callbacks:{items:["card.action.trigger"]}}}),this.#v(),this.registrationStatus(t)}startCallbackRepair(t,{actorOpenId:o,chatId:i}={}){this.#M();let e=this.#k(t);if(e.deletionPending)throw new Error("Cannot repair a Feishu bot pending deletion");let a=this.#s.get(t),A=a?this.#o.get(a):null;if(A&&ES.has(A.manager.status().state)){if(A.operation!==Su)throw new Error("Another Feishu app update is already active for this bot");return this.registrationStatus(A.id)}this.#s.delete(t);let r=this.#i();if(typeof r!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(r)||this.#o.has(r))throw new Error("Registration id generator returned an invalid or duplicate id");let s={id:r,operation:Su,manager:null,botId:t,createdNew:!1,cancelled:!1,remoteCommitted:!1,processing:null,publicError:null,stage:"authorizing",target:structuredClone(e),targetFingerprint:CS(e),initiator:{actorOpenId:uS(o),chatId:uS(i)}};return s.manager=new pS({registerApp:this.#e,appId:e.appId,domain:e.domain,onCredentials:g=>{s.remoteCommitted=!0;let I=this.#Q(s,g).finally(()=>{s.processing===I&&(s.processing=null)});return s.processing=I,I}}),this.#o.set(r,s),this.#s.set(t,r),this.#p=r,this.#U(),s.manager.start(),this.#v(),this.registrationStatus(r)}startGroupMessagePermission(t){this.#M();let o=this.#k(t);if(o.deletionPending)throw new Error("Cannot update permissions for a Feishu bot pending deletion");let i=this.#s.get(t),e=i?this.#o.get(i):null;if(e&&ES.has(e.manager.status().state)){if(e.operation!==hS)throw new Error("Another Feishu app update is already active for this bot");return this.registrationStatus(e.id)}this.#s.delete(t);let a=this.#i();if(typeof a!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(a)||this.#o.has(a))throw new Error("Registration id generator returned an invalid or duplicate id");let A={id:a,operation:hS,manager:null,botId:t,createdNew:!1,cancelled:!1,remoteCommitted:!1,processing:null,publicError:null,stage:"authorizing",target:structuredClone(o),targetFingerprint:CS(o),initiator:{actorOpenId:null,chatId:null}};return A.manager=new dS({registerApp:this.#e,appId:o.appId,domain:o.domain,onCredentials:r=>{A.remoteCommitted=!0;let g=this.#S(A,r).finally(()=>{A.processing===g&&(A.processing=null)});return A.processing=g,g}}),this.#o.set(a,A),this.#s.set(t,a),this.#p=a,this.#U(),A.manager.start(),this.#v(),this.registrationStatus(a)}hasRegistration(t){return this.#o.has(t)}registrationStatus(t){let o=this.#o.get(t);return o?this.#B({registration:o,selectedBotId:o.botId}):null}async cancelRegistration(t=this.#p){let o=this.#o.get(t);if(!o)return this.status();let i=o.manager.status().state;return S6.has(o.operation)&&i==="saving"?this.registrationStatus(t):ES.has(i)?(o.cancelled=!0,o.manager.cancel(),await this.#L(async()=>{o.createdNew&&o.botId&&this.#c.get(o.botId)===o.id&&this.#r.getBot(o.botId)&&await this.#_(o.botId,()=>this.#w(o.botId))}),this.#v(),this.registrationStatus(t)??this.status()):this.registrationStatus(t)}status(t){return this.#B({registration:this.#o.get(this.#p)??null,selectedBotId:t})}async bindCredentials({appId:t,appSecret:o,domain:i="feishu"}={}){this.#M();let e=typeof t=="string"?t.trim():"",a=typeof o=="string"?o.trim():"",A=i==="lark"?"lark":"feishu";if(!e||!a)throw new TypeError("Feishu App ID and App Secret are required");return this.#L(async()=>{this.#M();let r=await this.#A({appId:e,appSecret:a,domain:A});this.#M();let s=this.#r.list().find(f=>f.appId===e),g=s?.id??this.#n();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??D6(g),I=await this.#t.resolve(c).catch(()=>{}),d={...s,id:g,appId:e,secretRef:c,ownerOpenIds:s?.ownerOpenIds?.length?s.ownerOpenIds:[w6],domain:A,botName:r.name,botOpenId:r.openId,activated:r.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()};await this.#t.set(c,a);let B;try{B=await this.#r.saveBot(d)}catch(f){throw await this.#T(c,I),f}return await this.#_(g,async()=>{try{await this.#b(B,a),this.#l.delete(g)}catch{this.#l.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u7ED1\u5B9A\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"})}}),this.#v(),this.status(g)})}async reconnectBot(t){return this.#M(),this.#_(t,async()=>{let o=this.#k(t);if(o.deletionPending)return this.#l.set(t,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"}),this.status(t);if(Du(wu(this.#I.get(t))))return this.status(t);let i;try{i=await this.#t.resolve(o.secretRef)}catch{i=null}if(!i?.value)return this.#l.set(t,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"}),this.#v(),this.status(t);try{await this.#b(o,i.value),this.#l.delete(t)}catch{this.#l.set(t,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}return this.#v(),this.status(t)})}async sendConnectionTest(t){return this.#M(),this.#_(t,async()=>{let o=this.#k(t),i=this.#I.get(t);if(!Du(wu(i))||typeof i.sendConnectionTest!="function"){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}return i.sendConnectionTest(ba(`${o.botName}\uFF08${M6(o.appId)}\uFF09`,"\u98DE\u4E66\u673A\u5668\u4EBA"))})}async sendProactiveText(t,o,i,e={}){return this.#M(),this.#_(t,async()=>{this.#k(t);let a=this.#I.get(t);if(!Du(wu(a))||typeof a.sendProactiveText!="function"){let A=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw A.code="bot-not-connected",A}return a.sendProactiveText(o,i,e)})}async disconnectBot(t){return this.#M(),this.#_(t,async()=>(this.#k(t),await this.#D(t),this.#l.delete(t),this.#v(),this.status(t)))}async updateGroupResponseMode(t,o){if(this.#M(),!Xm(o))throw new TypeError("Invalid Feishu group response mode");return this.#L(()=>this.#_(t,async()=>{let i=this.#k(t);if(o==="all"&&i.groupMessagePermissionGranted!==!0){let a=new Error("Authorize im:message.group_msg before enabling all group messages");throw a.code="group_message_permission_required",a}let e=await this.#r.saveBot({...i,groupResponseMode:o});return this.#I.get(t)?.setGroupResponseMode?.(e.groupResponseMode),this.#v(),this.status(t)}))}async deleteBot(t){return this.#M(),this.#L(()=>this.#_(t,async()=>(this.#k(t),await this.#w(t),this.#v(),this.status())))}async reconnect(){let t=this.#r.list()[0];return t?this.reconnectBot(t.id):this.status()}async disconnect(){let t=this.#r.list()[0];return t?this.deleteBot(t.id):this.status()}async close(){if(this.#f)return;this.#f=!0;let t=[];for(let o of this.#o.values()){let i=o.manager.status().state;S6.has(o.operation)&&i==="saving"?(o.manager.cancel(),o.processing&&t.push(o.processing)):ES.has(i)&&(o.cancelled=!0,o.manager.cancel())}await this.#d,await Promise.allSettled([...this.#h.values()]),await Promise.allSettled([...this.#I.keys()].map(o=>this.#D(o))),await Promise.allSettled(t),await this.#d,await Promise.allSettled([...this.#h.values()]),await Promise.allSettled([...this.#I.keys()].map(o=>this.#D(o)))}#B({registration:t,selectedBotId:o}={}){let i=this.#r.list().map(I=>{let d=wu(this.#I.get(I.id)),B=Du(d),f=this.#l.get(I.id)??null;return{botId:I.id,phase:kke({connected:B,error:f,connection:d}),connected:B,configured:!0,groupResponseMode:ao(I.groupResponseMode),groupMessagePermissionGranted:I.groupMessagePermissionGranted===!0,bot:Rke(I),connection:d,lastMessageError:Vr(d.lastMessageError),error:f}}),e=t?this.#y(t):{state:"idle",attempt:0,updatedAt:Date.now()},a=iP.has(e.state),A=e.state==="saving",r=!!t&&(a||A),s=i.find(I=>I.botId===o)??(r?null:i[0]??null),g=i.some(I=>I.connected),c=s?.phase??"unconfigured";return a?c="registering":A?c="connecting":e.state==="error"&&!s&&(c="error"),{schemaVersion:2,revision:this.#E,phase:c,connected:s?.connected??!1,configured:i.length>0,bot:s?.bot??null,connection:s?.connection??b6(),error:s?.error??e.error??null,registration:e,bots:i,totals:{configured:i.length,connected:i.filter(I=>I.connected).length},anyConnected:g}}#y(t){let o=t.manager.status();return{...o,attempt:t.id,...t.botId?{botId:t.botId}:{},...t.operation?{operation:t.operation}:{},...t.stage?{stage:t.stage}:{},...o.state==="error"&&t.publicError?{error:{...t.publicError}}:{}}}async#S(t,o){let i=o.client_id,e=o.client_secret,a=uS(o.user_info?.open_id),A=o.user_info?.tenant_brand,r=t.target;if(t.cancelled)throw this.#m(t,"abort","Group message permission update was cancelled before local activation.");if(i!==r.appId)throw this.#m(t,"repair_app_mismatch","Feishu returned credentials for a different app.");if(!a)throw this.#m(t,"repair_owner_missing","Feishu returned no permission operator identity.");if(A!==void 0&&A!==r.domain)throw this.#m(t,"repair_domain_mismatch","Feishu returned credentials for a different account domain.");if(!r.ownerOpenIds.includes(w6)&&!r.ownerOpenIds.includes(a))throw this.#m(t,"repair_owner_mismatch","The Feishu permission operator is not an owner of this configured bot.");t.stage="verifying_identity";let s;try{s=await this.#A({appId:i,appSecret:e,domain:r.domain})}catch(g){throw this.#m(t,"repair_credentials_invalid","Feishu could not verify the updated app credentials.",g)}if(r.botOpenId&&s?.openId!==r.botOpenId)throw this.#m(t,"repair_bot_mismatch","The updated Feishu app belongs to a different bot identity.");await this.#L(()=>this.#_(t.botId,async()=>{let g=this.#r.getBot(t.botId);if(!g||g.deletionPending||CS(g)!==t.targetFingerprint)throw this.#m(t,"repair_target_changed","The Feishu bot changed while its permission update was in progress.");let c;try{c=await this.#t.resolve(g.secretRef)}catch(d){throw this.#m(t,"credential_update_failed","Unable to read the current Feishu credential.",d)}if(c?.value!==e){t.stage="persisting_secret";try{await this.#t.set(g.secretRef,e)}catch(B){if((await this.#t.resolve(g.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_update_failed","Unable to store the updated Feishu credential.",B)}if((await this.#t.resolve(g.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_state_unknown","The updated Feishu credential could not be confirmed after writing.")}t.stage="enabling_all_messages";let I;try{I=await this.#r.saveBot({...g,groupMessagePermissionGranted:!0,groupResponseMode:"all"})}catch(d){throw this.#m(t,"group_message_permission_save_failed","The permission was accepted, but all-message mode could not be saved.",d)}t.stage="restarting";try{await this.#b(I,e)}catch(d){throw this.#l.set(t.botId,{code:"connection_failed",message:"\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u5F00\u901A\uFF0C\u4F46\u673A\u5668\u4EBA\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#v(),this.#m(t,"group_message_permission_connection_failed","The permission was accepted, but the Feishu runtime could not restart.",d)}this.#l.delete(t.botId),t.stage="verified",t.publicError=null,this.#v()}))}async#Q(t,o){let i=o.client_id,e=o.client_secret,a=uS(o.user_info?.open_id),A=o.user_info?.tenant_brand,r=t.target;if(t.cancelled)throw this.#m(t,"abort","Callback repair was cancelled before local activation.");if(i!==r.appId)throw this.#m(t,"repair_app_mismatch","Feishu returned credentials for a different app.");if(!a)throw this.#m(t,"repair_owner_missing","Feishu returned no repair operator identity.");if(A!==void 0&&A!==r.domain)throw this.#m(t,"repair_domain_mismatch","Feishu returned credentials for a different account domain.");t.stage="verifying_identity";let s;try{s=await this.#A({appId:i,appSecret:e,domain:r.domain})}catch(c){throw this.#m(t,"repair_credentials_invalid","Feishu could not verify the repaired app credentials.",c)}if(r.botOpenId&&s?.openId!==r.botOpenId)throw this.#m(t,"repair_bot_mismatch","The repaired Feishu app belongs to a different bot identity.");let g=await this.#L(()=>this.#_(t.botId,async()=>{let c=this.#r.getBot(t.botId);if(!c||c.deletionPending||CS(c)!==t.targetFingerprint)throw this.#m(t,"repair_target_changed","The Feishu bot changed while its callback repair was in progress.");let I;try{I=await this.#t.resolve(c.secretRef)}catch(f){throw this.#m(t,"credential_update_failed","Unable to read the current Feishu credential.",f)}if(I?.value!==e){t.stage="persisting_secret";try{await this.#t.set(c.secretRef,e)}catch(Q){if((await this.#t.resolve(c.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_update_failed","Unable to store the repaired Feishu credential.",Q)}if((await this.#t.resolve(c.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_state_unknown","The repaired Feishu credential could not be confirmed after writing.")}let B;t.stage="restarting";try{await this.#b(c,e),B=this.#I.get(t.botId)}catch(f){throw this.#l.set(t.botId,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u56DE\u8C03\u4FEE\u590D\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#v(),this.#m(t,"repair_connection_failed","The repaired Feishu runtime could not be started.",f)}if(!B)throw this.#m(t,"repair_connection_failed","The repaired Feishu runtime is unavailable.");return this.#l.delete(t.botId),this.#v(),B}));if(typeof g.beginCardActionProbe!="function")throw this.#m(t,"card_action_probe_unavailable","The Feishu runtime cannot verify card callbacks.");t.stage="awaiting_callback";try{if((await g.beginCardActionProbe({expectedOperatorOpenId:t.initiator.actorOpenId??a,timeoutMs:this.#C,...t.initiator.chatId?{chatId:t.initiator.chatId}:{}}))?.verified!==!0){let I=new Error("Feishu runtime returned no callback proof");throw I.code="card_action_probe_failed",I}}catch(c){let I=c?.code==="card_action_probe_timeout"?"card_action_probe_timeout":c?.code==="card_action_probe_unavailable"?"card_action_probe_unavailable":c?.code==="card_action_probe_send_failed"?"card_action_probe_send_failed":"card_action_probe_failed";throw this.#m(t,I,I==="card_action_probe_timeout"?"Timed out waiting for the Feishu callback verification button.":"The Feishu card callback probe failed.",c)}t.stage="verified",t.publicError=null,this.#v()}#m(t,o,i,e){t.publicError={code:o,message:i};let a=new Error(i,e?{cause:e}:void 0);return a.code=o,a}async#u(t,o){if(t.cancelled)throw new Error("Registration was cancelled");let i=o.client_id,e=o.client_secret,a=o.user_info?.open_id,A=o.user_info?.tenant_brand==="lark"?"lark":"feishu";if(!a)throw new Error("Feishu registration returned no owner open_id");let r=await this.#A({appId:i,appSecret:e,domain:A});if(t.cancelled)throw new Error("Registration was cancelled");let s=this.#r.list().find(Q=>Q.appId===i),g=s?.id??this.#n();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??D6(g),I=this.#c.get(g),d=await this.#t.resolve(c).catch(()=>{});await this.#t.set(c,e);let B;try{B=await this.#r.saveBot({...s,id:g,appId:i,secretRef:c,ownerOpenIds:[...new Set([...s?.ownerOpenIds??[],a])],domain:A,botName:r.name,botOpenId:r.openId,activated:r.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()}),t.botId=g,t.createdNew=!s,this.#c.set(g,t.id)}catch(Q){try{await this.#T(c,d)}catch(y){throw new Error("Unable to restore the Feishu credential after a config failure.",{cause:y})}throw Q}if(t.cancelled)throw t.createdNew?await this.#_(g,()=>this.#w(g)):(await this.#r.saveBot(s),await this.#T(c,d),I?this.#c.set(g,I):this.#c.delete(g)),new Error("Registration was cancelled");let f=!1;try{if(await this.#_(g,()=>this.#b(B,e)),t.cancelled)throw t.createdNew?await this.#_(g,()=>this.#w(g)):(await this.#r.saveBot(s),await this.#T(c,d),I?this.#c.set(g,I):this.#c.delete(g),d?.value&&!s.deletionPending?await this.#_(g,()=>this.#b(s,d.value)):await this.#_(g,()=>this.#D(g))),f=!0,new Error("Registration was cancelled");this.#l.delete(g),this.#v()}catch(Q){if(t.cancelled)throw!f&&t.createdNew&&this.#r.getBot(g)?await this.#_(g,()=>this.#w(g)):!f&&s&&(await this.#r.saveBot(s),await this.#T(c,d),I?this.#c.set(g,I):this.#c.delete(g),!this.#f&&d?.value&&!s.deletionPending?await this.#_(g,()=>this.#b(s,d.value)):await this.#_(g,()=>this.#D(g))),this.#v(),Q;if(s&&d?.value)try{throw await this.#r.saveBot(s),await this.#T(c,d),I?this.#c.set(g,I):this.#c.delete(g),s.deletionPending?(await this.#_(g,()=>this.#D(g)),this.#l.set(g,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"})):(await this.#_(g,()=>this.#b(s,d.value)),this.#l.delete(g)),this.#v(),Q}catch(y){throw y===Q?Q:(this.#l.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u8FDE\u63A5\u66F4\u65B0\u5931\u8D25\uFF0C\u4E14\u539F\u8FDE\u63A5\u65E0\u6CD5\u6062\u590D\uFF0C\u8BF7\u91CD\u8BD5\u3002"}),this.#v(),new Error("Unable to restore the previous Feishu bot connection.",{cause:y}))}throw this.#l.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u521B\u5EFA\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#v(),Q}}async#b(t,o){await this.#D(t.id);let i=await this.#g({botId:t.id,config:t,appSecret:o,repair:this.#R(t.id)});this.#I.set(t.id,i);try{await i.start()}catch(e){throw this.#I.get(t.id)===i&&this.#I.delete(t.id),await i.stop({preserveError:!0}).catch(()=>{}),e}}#R(t){let o=i=>{let e=this.#o.get(i);return e?.operation===Su&&e.botId===t?e:null};return Object.freeze({start:({actorOpenId:i,chatId:e}={})=>this.startCallbackRepair(t,{actorOpenId:i,chatId:e}),status:({attemptId:i}={})=>o(i)?this.registrationStatus(i):null,cancel:async({attemptId:i}={})=>o(i)?this.cancelRegistration(i):this.status(t)})}async#D(t){let o=this.#I.get(t);this.#I.delete(t),o&&await o.stop()}async#w(t){let o=this.#r.getBot(t);if(o){o.deletionPending||(o=await this.#r.saveBot({...o,deletionPending:!0})),await this.#D(t);try{await this.#t.unset(o.secretRef)}catch(i){throw this.#l.set(t,{code:"credential_removal_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu credential.",{cause:i})}try{await this.#a({botId:t,config:o})}catch(i){throw this.#l.set(t,{code:"state_cleanup_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u7684\u672C\u5730\u4F1A\u8BDD\u6570\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu bot session state.",{cause:i})}await this.#r.removeBot(t),this.#l.delete(t),this.#c.delete(t)}}async#T(t,o){o?.value?await this.#t.set(t,o.value):await this.#t.unset(t)}#k(t){let o=this.#r.getBot(t);if(!o)throw new Error("Unknown Feishu bot");return o}#M(){if(this.#f)throw new Error("The Feishu controller is closed")}#L(t){let o=this.#d.then(t,t);return this.#d=o.then(()=>{},()=>{}),o}#_(t,o){let e=(this.#h.get(t)??Promise.resolve()).then(o,o),a=e.then(()=>{},()=>{});return this.#h.set(t,a),a.finally(()=>{this.#h.get(t)===a&&this.#h.delete(t)}),e}#U(){if(!(this.#o.size<=32))for(let[t,o]of this.#o){if(t===this.#p)continue;let i=o.manager.status().state;if(!iP.has(i)&&i!=="saving"&&this.#o.delete(t),this.#o.size<=32)break}}#v(){this.#E+=1}};function Lke(n){for(let t of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY"]){let o=n?.[t];if(typeof o=="string"&&o.trim())return o.trim()}}function Uke(n,t=o=>new _6.default(o)){let o=Lke(n);return o?t(o):void 0}function Hke(n){let t=Oc(n.dshHome??process.env.DSH_HOME??Rd(Gke(),".dsh")),o=Oc(n.dataDir??Rd(t,"integrations","dsh-feishu"));return{root:o,config:Oc(n.configPath??Rd(o,"config.json")),legacyState:Oc(n.statePath??Rd(o,"state.json")),bots:Oc(n.botsDir??Rd(o,"bots")),workspaces:Oc(n.workspacesPath??Rd(o,"workspaces.json"))}}async function oP(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-feishu requires ctx.credentials");let i=Aa(n,t),e=o.lark??Uv,a=o.Controller??Ou,A=o.ConfigStore??IS,r=o.StateStore??Wm,s=o.HarnessClient??gS,g=o.FeishuRuntime??sS,c=o.verifyFeishuApp??FW,I=Ee=>c({...Ee,httpInstance:e.defaultHttpInstance}),d=o.createConnectionSupervisor??Hv,B=typeof n.logger=="function"?n.logger("dsh-feishu"):n.logger??console,f=()=>Ra(n),Q=Hke(t),y=await new A(Q.config).load(),m=Oc(t.workspace??process.cwd()),_=o.WorkspaceStore??ea,T=o.workspaces??await new _(Q.workspaces,{defaultWorkspace:m}).load(),R=typeof y.list=="function",L=()=>R?y.list():[],U=L();R&&await T.reconcile(U.map(Ee=>Ee.id)),await Promise.all(U.map(Ee=>T.ensure(Ee.id,{defaultAgentPreset:t.agentPreset})));let F=typeof y.removeBot=="function"?Pa(y,{workspaces:T,method:"removeBot",botIdFromRemoved:Ee=>Ee.id,saveMethod:"saveBot",botIdFromSave:Ee=>Ee?.id}):y,q=new Map,z=Ee=>!Ee.id||!Ee.secretRef||Ee.secretRef===lS?Q.legacyState:Oc(Q.bots,Ee.id,"state.json"),j=async Ee=>{let Qe=Ee.id??"__legacy__",Le=q.get(Qe);return Le||(Le=await new r(z(Ee)).load(),q.set(Qe,Le)),Le},P=async Ee=>{let Qe=L().find(Le=>Le.id===Ee);if(!Qe)throw new Error("Unknown Feishu bot");return j(Qe)},J=Ua(n,o.commandExecutor),{controlExecutor:H,sessionMaintenanceExecutor:N,fileIngressExecutor:k}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),V=new s({...i,workspace:m,autostart:!1,dshBin:t.dshBin??"dsh",...J?{commandExecutor:J}:{},...H?{controlExecutor:H}:{},...N?{sessionMaintenanceExecutor:N}:{},...k?{fileIngressExecutor:k}:{}}),Ae=o.proxyEnv??process.env,ie=Uke(Ae,o.createProxyAgent),De=new a({registerApp:Ee=>e.registerApp(Ee),verifyApp:I,credentials:n.credentials,configStore:F,createRuntime:async({botId:Ee,config:Qe,appSecret:Le,repair:AA})=>{let aA=await j(Qe),He=Ee??Qe.id??Qe.appId;await T.ensure(He,{defaultAgentPreset:t.agentPreset});let ce=Ga(V,{botId:He,workspaces:T,state:aA,agentPresetCatalog:f});return new g({lark:e,botId:He,repair:AA,appId:Qe.appId,appSecret:Le,domain:Qe.domain,botOpenId:Qe.botOpenId,groupResponseMode:Qe.groupResponseMode,ownerOpenIds:Qe.ownerOpenIds??[Qe.ownerOpenId],harness:ce.harness,state:ce.state,contextEnhancement:{botId:He,getSettings:()=>T.contextEnhancementFor(He)},replyTimeoutMs:t.replyTimeoutMs??6e5,slashCommands:t.slashCommands!==!1,...ie?{wsAgent:ie}:{},logger:{error:(...Be)=>B.error?.(`[${Ee??Qe.id}]`,...Be),warn:(...Be)=>B.warn?.(`[${Ee??Qe.id}]`,...Be),info:(...Be)=>B.info?.(`[${Ee??Qe.id}]`,...Be),debug:(...Be)=>B.debug?.(`[${Ee??Qe.id}]`,...Be)}})},deleteState:async({botId:Ee,config:Qe})=>{q.delete(Ee);try{await Fke(z(Qe))}catch(Le){if(Le?.code!=="ENOENT")throw Le}}}),fe=Fa(De,{workspaces:T,stateFor:P,agentPresetCatalog:f}),_e=d({controller:fe,harness:V,logger:B,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:fe,deliveryAdapter:La({channel:"feishu",workspaces:T,coreController:De,stateFor:P}),ready:_e.ready,async close(){await _e.close(),await fe.close(),V.stopManagedProcess(),ie?.destroy?.()}}}import ove from"qrcode";var vd=Je(pP(),1);var rve=Je(pP(),1);var ave=Object.freeze({$locale:"en",IM\u673A\u5668\u4EBA:"IM bots",IM\u673A\u5668\u4EBA\u8BBE\u7F6E:"IM bot settings",\u66F4\u591A\u673A\u5668\u4EBA\u8BBE\u7F6E:"More bot settings","IM \u6E20\u9053":"IM channels","\u8BA9 DeepSeek Harness \u89E6\u624B\u53EF\u53CA":"Connecting DeepSeek Harness",\u5F53\u524D\u7248\u672C:"Current version","DSH-IM \u66F4\u65B0":"DSH-IM update",\u68C0\u67E5\u66F4\u65B0:"Check for updates",\u91CD\u65B0\u68C0\u67E5:"Check again",\u5237\u65B0\u72B6\u6001:"Refresh status",\u624B\u5DE5\u66F4\u65B0:"Manual update",\u624B\u5DE5\u66F4\u65B0\u547D\u4EE4:"Manual update command",\u590D\u5236\u547D\u4EE4:"Copy command","\u590D\u5236\u4E2D\u2026":"Copying\u2026",\u5DF2\u590D\u5236:"Copied","\u547D\u4EE4\u5DF2\u590D\u5236\u3002":"Command copied.","\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u9009\u4E2D\u547D\u4EE4\u540E\u6309 Ctrl+C \u6216 \u2318C \u590D\u5236\u3002":"Copy failed. Select the command and press Ctrl+C or \u2318C to copy it.","\u81EA\u52A8\u66F4\u65B0\u5931\u8D25\u53EF\u4EE5\u4F7F\u7528\u547D\u4EE4\u66F4\u65B0\uFF1A":"If the automatic update fails, update with this command:","\u5C1A\u672A\u786E\u8BA4\u76EE\u6807\u7248\u672C\uFF0C\u6B64\u547D\u4EE4\u5B89\u88C5\u6267\u884C\u65F6 npm \u7684 latest \u7248\u672C\u3002":"No target version has been confirmed. This command installs the npm latest version available when you run it.","\u8BF7\u5728\u5F53\u524D Desktop \u7684\u5185\u7F6E\u7EC8\u7AEF\u6267\u884C\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002":"Run this in the current Desktop\u2019s built-in terminal, then restart manually.","\u8BF7\u5728\u8FD0\u884C\u5F53\u524D Harness \u7684\u540C\u4E00\u73AF\u5883\u6267\u884C\uFF0C\u4FDD\u6301 DSH_HOME \u4E00\u81F4\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002":"Run this in the same environment as the current Harness, with the same DSH_HOME, then restart manually.","\u8BF7\u7B49\u5F85\u5F53\u524D\u64CD\u4F5C\u7ED3\u675F\uFF0C\u786E\u8BA4\u6CA1\u6709\u5B89\u88C5\u8FDB\u7A0B\u8FD0\u884C\u540E\u518D\u6267\u884C\u547D\u4EE4\u3002":"Wait for the current operation to finish and confirm no installer is running before using this command.","\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\u8BF7\u6309\u539F\u5B89\u88C5\u65B9\u5F0F\u66F4\u65B0\uFF0C\u4E0D\u63D0\u4F9B\u8986\u76D6\u6E90\u7801\u7684 npm \u547D\u4EE4\u3002":"Update source or linked installations using their original method. No npm command is provided to overwrite the source.","\u65E0\u6CD5\u5B89\u5168\u751F\u6210\u5F53\u524D profile \u7684\u547D\u4EE4\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u624B\u52A8\u786E\u8BA4 profile \u540E\u66F4\u65B0\u3002":"A safe command cannot be generated for this profile. Confirm the profile in your terminal before updating manually.",\u66F4\u65B0\u81F3:"Update to",\u5B89\u88C5\u66F4\u65B0:"Install update","\u6B63\u5728\u66F4\u65B0\u2026":"Updating\u2026",\u5F85\u624B\u52A8\u91CD\u542F:"Restart needed",\u8FD0\u884C\u7248\u672C:"Running version",\u5DF2\u5B89\u88C5\u7248\u672C:"Installed version","\u76EE\u6807 profile":"Target profile",\u76EE\u6807\u7248\u672C:"Target version",\u65E0\u6CD5\u786E\u8BA4:"Unknown",\u53D1\u73B0\u65B0\u7248\u672C:"Update available",\u5DF2\u662F\u6700\u65B0\u7248\u672C:"Up to date",\u5F53\u524D\u7248\u672C\u65E0\u9700\u66F4\u65B0:"No newer version available","\u5DF2\u83B7\u53D6 npm \u6700\u65B0\u7248\u672C":"Latest npm version retrieved","\u68C0\u67E5 npm \u6700\u65B0\u7248\u672C\uFF0C\u4E0D\u4F1A\u81EA\u52A8\u5B89\u88C5\u3002":"Check the latest npm version. Nothing is installed automatically.","\u6B63\u5728\u4ECE npm \u68C0\u67E5\u6700\u65B0\u7248\u672C\u2026":"Checking npm for the latest version\u2026","\u6B63\u5728\u5B89\u88C5\uFF0C\u8BF7\u7A0D\u5019\u2026":"Installing, please wait\u2026","\u6B63\u5728\u6821\u9A8C\u5B89\u88C5\u7ED3\u679C\u2026":"Verifying the installation\u2026","\u5DF2\u5B89\u88C5\uFF0C\u5F85\u624B\u52A8\u91CD\u542F":"Installed \u2014 manual restart needed",\u66F4\u65B0\u5DF2\u751F\u6548:"Updated version is active",\u66F4\u65B0\u5931\u8D25:"Update failed",\u66F4\u65B0\u8BF7\u6C42\u5931\u8D25:"Update request failed","\u4EC5\u66F4\u65B0 DSH-IM\u3002\u5B89\u88C5\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u540E\u53F0\uFF1B\u672C\u529F\u80FD\u4E0D\u4F1A\u81EA\u52A8\u91CD\u542F\u6216\u4E3B\u52A8\u5237\u65B0\u9875\u9762\u3002":"Only DSH-IM will be updated. Restart the backend manually after installation. This feature does not automatically restart it or initiate a page refresh.","\u5F53\u524D\u662F\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\uFF0C\u53EA\u80FD\u68C0\u67E5\u7248\u672C\uFF1B\u8BF7\u624B\u52A8\u66F4\u65B0\u6E90\u7801\uFF0C\u6216\u8FC1\u79FB\u5230 npm \u5B89\u88C5\u3002":"This is a source or linked installation. You can check versions, but must update the source manually or migrate to an npm installation.","\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D profile\uFF0C\u8BF7\u5728\u5BF9\u5E94\u7684 Harness \u73AF\u5883\u4E2D\u624B\u52A8\u66F4\u65B0\u3002":"The current profile could not be identified. Update manually in the corresponding Harness environment.","\u5F53\u524D\u8FD0\u884C\u73AF\u5883\u4E0D\u652F\u6301\u6309\u94AE\u5B89\u88C5\uFF0C\u8BF7\u624B\u52A8\u66F4\u65B0\u63D2\u4EF6\u3002":"This runtime cannot install through this button. Update the plugin manually.","\u5F53\u524D npm \u6E90\u914D\u7F6E\u4E0E\u5B98\u65B9\u6E90\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u5148\u68C0\u67E5 registry \u914D\u7F6E\u3002":"The npm registry configuration differs from the official registry. Check your registry settings first.","\u5F53\u524D Host \u7684 Node.js \u7248\u672C\u4E0D\u6EE1\u8DB3\u65B0\u7248\u8981\u6C42\uFF0C\u8BF7\u5148\u66F4\u65B0\u8FD0\u884C\u73AF\u5883\u3002":"The Host Node.js version does not meet the new version\u2019s requirements. Update the runtime first.","\u65B0\u7248\u672C\u5DF2\u5B89\u88C5\uFF0C\u8BF7\u5728\u65B9\u4FBF\u65F6\u624B\u52A8\u91CD\u542F\u5F53\u524D Harness \u6216 Desktop\u3002":"The new version is installed. Manually restart this Harness or Desktop when convenient.","\u4E0A\u6B21\u5B89\u88C5\u7ED3\u679C\u65E0\u6CD5\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u6B64 profile \u7684\u63D2\u4EF6\u5B89\u88C5\u72B6\u6001\u3002":"The previous installation result is uncertain. Check this profile\u2019s plugin installation first.","\u65E0\u6CD5\u8BBF\u95EE npm \u6216\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u68C0\u67E5\u3002":"npm is unreachable or the request timed out. Check again later.","npm \u8FD4\u56DE\u7684\u7248\u672C\u4FE1\u606F\u65E0\u6548\uFF0C\u6682\u65F6\u65E0\u6CD5\u66F4\u65B0\u3002":"npm returned invalid release information. Updating is unavailable.","\u7248\u672C\u786E\u8BA4\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u540E\u518D\u5B89\u88C5\u3002":"The version confirmation expired. Check again before installing.","\u63D2\u4EF6\u5B89\u88C5\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u3002":"The plugin installation changed. Check again.","\u6B64 profile \u6B63\u5728\u66F4\u65B0\uFF0C\u8BF7\u7A0D\u540E\u67E5\u770B\u72B6\u6001\u3002":"This profile is already updating. Check its status shortly.","\u5B89\u88C5\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u5F53\u524D\u5B89\u88C5\u72B6\u6001\u540E\u91CD\u8BD5\u3002":"Installation failed. Check the current installation before retrying.","\u5B89\u88C5\u7ED3\u679C\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u63D2\u4EF6\u7248\u672C\u3002":"Installation verification failed. Check the plugin version manually.","\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u66F4\u65B0\u72B6\u6001\uFF0C\u8BF7\u5148\u68C0\u67E5\u5F53\u524D\u5B89\u88C5\u7ED3\u679C\u3002":"Update state could not be saved safely. Check the current installation result before retrying.","\u4E0A\u6B21\u66F4\u65B0\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u68C0\u67E5\u5B89\u88C5\u72B6\u6001\u540E\u91CD\u8BD5\u3002":"The previous update was interrupted. Check the installation before retrying.","\u66F4\u65B0\u670D\u52A1\u5DF2\u5173\u95ED\uFF0C\u8BF7\u624B\u52A8\u91CD\u65B0\u6253\u5F00\u8BBE\u7F6E\u9875\u3002":"The update service has closed. Reopen settings manually.","\u66F4\u65B0\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u7248\u672C\u3002":"The update request is invalid. Check the version again.","\u5F53\u524D\u63D2\u4EF6\u5B89\u88C5\u4E0D\u5B8C\u6574\u6216\u4E0E profile \u4E0D\u7B26\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u5B89\u88C5\u914D\u7F6E\u3002":"The plugin installation is incomplete or does not match this profile. Check the installation configuration manually.","\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D npm \u6E90\u914D\u7F6E\uFF0C\u6682\u65F6\u4E0D\u80FD\u5B89\u88C5\u66F4\u65B0\u3002":"The npm registry configuration could not be verified. Installation is unavailable.","\u5B89\u88C5\u8D85\u65F6\uFF0C\u8BF7\u5148\u786E\u8BA4\u5F53\u524D\u5B89\u88C5\u72B6\u6001\uFF0C\u518D\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5\u3002":"Installation timed out. Check the current installation before retrying.","\u66F4\u65B0\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"The update request failed. Try again.","\u66F4\u65B0\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u54CD\u5E94\u3002":"The update service returned an unrecognized response.","\u5F53\u524D Host \u4E0D\u652F\u6301\u66F4\u65B0\u63A5\u53E3\uFF0C\u8BF7\u5148\u624B\u52A8\u66F4\u65B0\u63D2\u4EF6\u5E76\u91CD\u542F\u3002":"This Host does not support the update API. Update the plugin manually and restart first.","\u5173\u95ED\u7A97\u53E3\u4E0D\u4F1A\u53D6\u6D88\u5B89\u88C5\u3002\u8BF7\u52FF\u540C\u65F6\u5728\u5176\u4ED6\u7A97\u53E3\u7BA1\u7406\u6B64 profile \u7684\u63D2\u4EF6\u3002":"Closing this window does not cancel installation. Do not manage this profile\u2019s plugins in another window at the same time.","\u9875\u9762\u7248\u672C\u4E0E\u8FD0\u884C\u7248\u672C\u4E0D\u540C\uFF0C\u8BF7\u624B\u52A8\u5237\u65B0\u9875\u9762\uFF1B\u82E5\u4ECD\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u624B\u52A8\u91CD\u542F Harness \u6216 Desktop\u3002":"The page and running versions differ. Refresh the page manually; if they still differ, manually restart Harness or Desktop.","\u8BF7\u5728\u673A\u5668\u4EBA\u7A7A\u95F2\u65F6\u5B89\u88C5\uFF1B\u5B89\u88C5\u4F1A\u4FEE\u6539\u5F53\u524D profile \u7684\u4F9D\u8D56\uFF0C\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u3002":"Install while bots are idle. This changes the current profile\u2019s dependencies and requires a manual restart afterward.","AI Office":"AI Office","\uFF08\u5B9E\u9A8C\u529F\u80FD\uFF09":"(Experimental)","AI Office \u8BBE\u7F6E":"AI Office settings","AI Office \u8BBE\u7F6E\u9875\u7F3A\u5C11 RPC \u8FDE\u63A5":"AI Office settings are missing an RPC connection","\u6B63\u5728\u8BFB\u53D6 AI Office Connector\u2026":"Loading AI Office Connector\u2026","\u672C\u673A\u4E3B\u52A8\u8FDE\u63A5\u516C\u7F51 Office\uFF1BHarness \u4E0D\u5F00\u653E\u7AEF\u53E3\u3002\u534F\u8BAE Hook \u56FA\u5B9A\u4E3A ":"This machine connects outward to the public Office; Harness exposes no port. Protocol hooks: ",\u5C1A\u672A\u914D\u7F6E:"Not configured","\u5DF2\u8FDE\u63A5 Office":"Connected to Office",\u5DF2\u914D\u7F6E:"Configured",\u7B49\u5F85\u91CD\u8FDE:"Waiting to reconnect",\u51ED\u636E\u7F3A\u5931:"Credential missing",\u6700\u8FD1\u5FC3\u8DF3:"Last heartbeat",\u6700\u8FD1\u4E8B\u4EF6:"Last event",\u91CD\u8FDE\u6B21\u6570:"Reconnects","\u8FD0\u884C Job":"Running Jobs","\u5B8C\u6210 Job":"Completed Jobs",\u5C1A\u65E0:"None yet",\u8BBE\u5907\u8FDE\u63A5:"Device connection","Token \u53EA\u5199\u5165\u672C\u673A\u51ED\u636E\u5B58\u50A8":"Token is written only to the local credential store","\u7C98\u8D34 Office \u4E00\u6B21\u6027\u51ED\u636E":"Paste the one-time Office credential","\u5DF2\u5B89\u5168\u4FDD\u5B58\uFF1B\u7559\u7A7A\u4FDD\u6301\u4E0D\u53D8":"Stored securely; leave blank to keep it",\u6700\u5927\u5E76\u53D1:"Max concurrency","Heartbeat \u79D2\u6570":"Heartbeat seconds","Workspace \u6620\u5C04":"Workspace mappings","\u6BCF\u884C alias=/\u672C\u673A/\u7EDD\u5BF9\u8DEF\u5F84\uFF1BOffice \u53EA\u80FD\u770B\u5230 alias\u3002":"One alias=/local/absolute/path per line; Office sees only aliases.","Instruction Preset \u6620\u5C04":"Instruction preset mappings","\u6BCF\u884C alias=\u6307\u4EE4\uFF1B\u65B0\u589E preset \u4E0D\u9700\u8981\u6539 Office \u4EE3\u7801\u3002":"One alias=instruction per line; new presets require no Office code change.",\u4FDD\u5B58\u5E76\u8FDE\u63A5:"Save and connect",\u6D4B\u8BD5\u8FDE\u63A5:"Test connection","\u6D4B\u8BD5\u4E2D\u2026":"Testing\u2026",\u91CD\u65B0\u8FDE\u63A5:"Reconnect",\u79FB\u9664\u8FDE\u63A5:"Remove connection","\u8FDE\u63A5\u6D4B\u8BD5\u901A\u8FC7\u3002":"Connection test passed.","\u914D\u7F6E\u5DF2\u4FDD\u5B58\u3002":"Configuration saved.","\u534F\u8BAE Hook \u9884\u89C8":"Protocol hook preview","\u7531 Base URL \u81EA\u52A8\u6D3E\u751F\uFF0C\u4E0D\u5355\u72EC\u586B\u5199":"Derived from Base URL; no separate input","Base URL \u65E0\u6548":"Invalid Base URL","Office Hook \u5C1A\u672A\u90E8\u7F72\u65F6\uFF0C\u914D\u7F6E\u4F1A\u5B89\u5168\u4FDD\u5B58\u5E76\u81EA\u52A8\u91CD\u8BD5\uFF1B\u51FA\u73B0 HTTP 404 \u4EE3\u8868\u534F\u8BAE\u7AEF\u70B9\u5F85\u4E0A\u7EBF\uFF0C\u4E0D\u4EE3\u8868 Harness \u6545\u969C\u3002":"Configuration is saved and retried while Office hooks are unavailable; HTTP 404 means the protocol endpoint is pending, not a Harness failure.","Workspace \u6620\u5C04\u6BCF\u884C\u5FC5\u987B\u4F7F\u7528 alias=value":"Each workspace mapping must use alias=value","Instruction Preset \u6620\u5C04\u6BCF\u884C\u5FC5\u987B\u4F7F\u7528 alias=value":"Each instruction preset mapping must use alias=value","action-items=\u8F6C\u6362\u4E3A\u8D1F\u8D23\u4EBA\u3001\u622A\u6B62\u548C\u9A8C\u6536\u660E\u786E\u7684\u5DE5\u5355":"action-items=Turn this into accountable tasks with deadlines and acceptance criteria","AI Office \u62D2\u7EDD\u4E86 Device Token\u3002":"AI Office rejected the Device Token.","AI Office Connector Hook \u5C1A\u672A\u5C31\u7EEA\u3002":"AI Office Connector hooks are not available yet.","AI Office Connector \u534F\u8BAE\u7248\u672C\u4E0D\u517C\u5BB9\u3002":"The AI Office Connector protocol is incompatible.","\u672C\u673A\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE AI Office\u3002":"AI Office cannot currently be reached from this machine.","AI Office \u8FDE\u63A5\u5DF2\u4E2D\u65AD\u3002":"The AI Office connection was interrupted.","\u5E2E\u52A9\u4E0E\u53CD\u9988 \xB7 \u524D\u5F80 GitHub":"Help & feedback \xB7 Open GitHub","\u8BF7\u6539\u7528 localhost \u91CD\u65B0\u6253\u5F00":"Reopen with localhost","\u9875\u9762\u4F1A\u5728\u5F53\u524D\u7AEF\u53E3\u91CD\u65B0\u6253\u5F00\uFF0C\u673A\u5668\u4EBA\u914D\u7F6E\u4E0D\u4F1A\u6539\u53D8\u3002":"The page will reopen on the current port. Your bot configuration will not change.","\u4F7F\u7528 localhost \u91CD\u65B0\u6253\u5F00":"Reopen with localhost","\u5F53\u524D\u5730\u5740\u4E0E\u6D4F\u89C8\u5668\u7684\u672C\u673A\u8BF7\u6C42\u6821\u9A8C\u4E0D\u517C\u5BB9\u3002\u8BF7\u4F7F\u7528\u4E0A\u65B9\u6309\u94AE\u6539\u7528 localhost \u91CD\u65B0\u6253\u5F00\u3002":"This address is incompatible with the browser\u2019s local-request checks. Use the button above to reopen with localhost.",\u5FAE\u4FE1:"WeChat",\u98DE\u4E66:"Feishu",\u9489\u9489:"DingTalk",\u4F01\u4E1A\u5FAE\u4FE1:"WeCom",\u5FAE\u4FE1\u673A\u5668\u4EBA:"WeChat bot",\u98DE\u4E66\u673A\u5668\u4EBA:"Feishu bot",\u9489\u9489\u673A\u5668\u4EBA:"DingTalk bot",\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"WeCom bot",QQ\u673A\u5668\u4EBA:"QQ bot",WhatsApp\u673A\u5668\u4EBA:"WhatsApp bot",WhatsApp\u8D26\u53F7:"WhatsApp account",\u5FAE\u4FE1\u8BBE\u7F6E:"WeChat settings",\u98DE\u4E66\u673A\u5668\u4EBA\u8BBE\u7F6E:"Feishu bot settings",\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F:"Group response mode","\u4EC5\u5728 @\u673A\u5668\u4EBA\u65F6\u54CD\u5E94\uFF08\u63A8\u8350\uFF09":"Only respond when @mentioned (recommended)",\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F:"Respond to all group messages","\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\uFF08\u9700\u98DE\u4E66\u654F\u611F\u6743\u9650\uFF09":"Respond to all group messages (requires a sensitive Feishu scope)",\u91CD\u65B0\u6388\u6743:"Reauthorize",\u53BB\u6388\u6743:"Authorize",\u91CD\u65B0\u6388\u6743\u7FA4\u6D88\u606F\u6743\u9650:"Reauthorize group-message permission",\u6388\u6743\u7FA4\u6D88\u606F\u6743\u9650:"Authorize group-message permission","\u6B63\u5728\u51C6\u5907\u6388\u6743\u2026":"Preparing authorization\u2026","\u6B63\u5728\u51C6\u5907\u2026":"Preparing\u2026","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u5F00\u901A\uFF0C\u518D\u6B21\u5207\u6362\u65E0\u9700\u6388\u6743\u3002":"Direct messages always work; group chats require an explicit @mention of this bot. The group-message permission is already granted, so switching again needs no authorization.","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002\u9009\u62E9\u5168\u90E8\u6D88\u606F\u540E\u4F1A\u6253\u5F00\u98DE\u4E66\u5B98\u65B9\u6388\u6743\u6D41\u7A0B\u3002":"Direct messages always work; group chats require an explicit @mention of this bot. Selecting all messages opens the official Feishu authorization flow.","\u5DF2\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF08im:message.group_msg\uFF09\uFF1B\u673A\u5668\u4EBA\u4F1A\u5904\u7406\u7FA4\u804A\u4E2D\u7684\u6240\u6709\u53EF\u89C1\u6D88\u606F\u3002":"The \u201CRead all messages in associated group chat\u201D scope (im:message.group_msg) is granted; the bot processes every visible group message.","\u5C1A\u672A\u786E\u8BA4\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF0C\u8BF7\u5B8C\u6210\u98DE\u4E66\u6388\u6743\u3002":"The \u201CRead all messages in associated group chat\u201D scope has not been confirmed. Complete Feishu authorization.","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002":"Direct messages always work; group chats require an explicit @mention of this bot.","\u9700\u5728\u98DE\u4E66\u4E3A\u8BE5\u673A\u5668\u4EBA\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF08im:message.group_msg\uFF09\uFF1B\u5F00\u901A\u540E\uFF0C\u673A\u5668\u4EBA\u4F1A\u5904\u7406\u7FA4\u804A\u4E2D\u7684\u6240\u6709\u53EF\u89C1\u6D88\u606F\u3002":"Grant this bot the \u201CRead all messages in associated group chat\u201D Feishu scope (im:message.group_msg); once granted, it will process every visible group message.","\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F\u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the group response mode. Try again.","\u7FA4\u6D88\u606F\u6743\u9650\u6388\u6743\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not authorize group-message permission. Try again.",\u9489\u9489\u8BBE\u7F6E:"DingTalk settings",\u4F01\u4E1A\u5FAE\u4FE1\u8BBE\u7F6E:"WeCom settings",\u626B\u7801\u63A5\u5165\u673A\u5668\u4EBA:"Scan QR code",\u6B63\u5728\u63A5\u5165:"Connecting",\u624B\u52A8\u63A5\u5165:"Manual setup",\u6536\u8D77\u51ED\u636E:"Hide credentials",\u6536\u8D77\u63A5\u5165:"Hide setup",\u63A5\u5165\u673A\u5668\u4EBA:"Connect bot",\u5F00\u59CB\u63A5\u5165:"Start setup",\u5728\u7EBF:"online",\u8FD0\u884C\u6B63\u5E38:"Connected",\u6B63\u5728\u8FDE\u63A5:"Connecting","\u6B63\u5728\u8FDE\u63A5\u2026":"Connecting\u2026",\u8FDE\u63A5\u672A\u5C31\u7EEA:"Not connected",\u8FDE\u63A5\u4E2D:"Connecting",\u8FDE\u63A5\u4E2D\u65AD:"Disconnected",\u9700\u8981\u5904\u7406:"Needs attention",\u72B6\u6001\u672A\u77E5:"Unknown status",\u79BB\u7EBF:"Offline",\u5DF2\u65AD\u5F00:"Disconnected",\u6D88\u606F\u901A\u9053:"Message channel",\u67E5\u770B\u6D88\u606F\u901A\u9053\u8BF4\u660E:"View message channel details",\u6700\u8FD1\u68C0\u67E5:"Last checked",\u6700\u8FD1\u4E00\u6761\u6D88\u606F\u5904\u7406\u5931\u8D25:"Latest message failed",\u9519\u8BEF\u7801:"Code",\u53C2\u8003\u53F7:"Reference",\u5F53\u524D\u5DE5\u4F5C\u533A:"Current workspace",\u9009\u62E9\u76EE\u5F55:"Choose folder",\u9009\u62E9\u673A\u5668\u4EBA\u5DE5\u4F5C\u533A\u76EE\u5F55:"Select bot workspace folder",\u5F53\u524D\u76EE\u5F55:"Current folder",\u4E3B\u76EE\u5F55:"Home",\u76F4\u63A5\u8F93\u5165\u8DEF\u5F84:"Enter a path directly","\u652F\u6301 Windows \u76D8\u7B26\u3001UNC \u4E0E POSIX \u7EDD\u5BF9\u8DEF\u5F84\u3002":"Supports Windows drives, UNC paths, and POSIX absolute paths.","\u8F93\u5165 Host \u4E0A\u7684\u5B8C\u6574\u7EDD\u5BF9\u8DEF\u5F84":"Enter a full absolute path on the Host",\u524D\u5F80:"Go","\u8BFB\u53D6\u4E2D\u2026":"Loading\u2026","\u6B63\u5728\u51C6\u5907\u76EE\u5F55\u9009\u62E9\u5668\u2026":"Preparing folder picker\u2026","\u6B63\u5728\u8BFB\u53D6\u76EE\u5F55\u2026":"Loading folders\u2026","\u8FD9\u4E2A\u76EE\u5F55\u4E2D\u6CA1\u6709\u5B50\u6587\u4EF6\u5939\u3002":"This folder has no subfolders.","\u6B64\u76EE\u5F55\u7684\u5B50\u6587\u4EF6\u5939\u8FC7\u591A\uFF0C\u4EC5\u663E\u793A\u524D\u4E00\u90E8\u5206\u3002":"This folder has too many subfolders; only the first group is shown.","\u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not load the folder. Try again.",\u91CD\u8BD5:"Retry",\u663E\u793A\u9690\u85CF\u6587\u4EF6\u5939:"Show hidden folders","\u5207\u6362\u540E\u4F1A\u6E05\u9664\u8FD9\u4E2A\u673A\u5668\u4EBA\u7684\u65E7\u4F1A\u8BDD\u6620\u5C04\u3002":"Switching clears this bot\u2019s previous session mappings.","\u5207\u6362\u4E2D\u2026":"Switching\u2026",\u9009\u62E9\u6B64\u76EE\u5F55:"Select this folder",\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84:"Absolute workspace path","/\u7EDD\u5BF9\u8DEF\u5F84/\u5230/\u5DE5\u4F5C\u533A":"/absolute/path/to/workspace",\u4FEE\u6539:"Change",\u4FDD\u5B58:"Save",\u4E0A\u4E0B\u6587\u589E\u5F3A:"Context enhancement",\u672A\u5F00\u542F:"Not enabled",\u4EC5\u7FA4\u804A:"Groups only",\u4EC5\u79C1\u804A:"Direct only",\u7FA4\u804A\u548C\u79C1\u804A:"Groups and direct",\u5173\u95ED\u5F39\u7A97:"Close dialog",\u67E5\u770B\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BF4\u660E:"View context enhancement details",\u542F\u7528\u8303\u56F4:"Enable in",\u7FA4\u804A\u4E2D\u542F\u7528:"Enable in group chats",\u79C1\u804A\u4E2D\u542F\u7528:"Enable in direct chats","\uFF08\u5F53\u524D\u6E20\u9053\u4E0D\u652F\u6301\u7FA4\u804A\uFF09":"(This channel does not support group chats)",\u6765\u6E90\u5B57\u6BB5:"Source fields",\u67E5\u770B\u6765\u6E90\u5B57\u6BB5\u8BF4\u660E:"View source field details",\u6E20\u9053:"Channel",\u4F1A\u8BDD\u7C7B\u578B:"Conversation type",\u53D1\u9001\u8005\u6807\u8BC6:"Sender ID",\u53D1\u9001\u8005\u6635\u79F0:"Sender name",\u67E5\u770B\u53D1\u9001\u8005\u6635\u79F0\u5B57\u6BB5\u8BF4\u660E:"View sender name field details","\u8BE5\u5B57\u6BB5\u4E0D\u662F\u6BCF\u4E2A\u6E20\u9053\u90FD\u80FD\u63D0\u4F9B\u3002\u5F53\u524D\u6D88\u606F\u6CA1\u6709\u53D1\u9001\u8005\u6635\u79F0\u65F6\uFF0C\u5373\u4F7F\u5DF2\u9009\u62E9\u8BE5\u5B57\u6BB5\uFF0C \u4E2D\u4E5F\u4F1A\u7701\u7565 senderName\u3002":"This field is not available on every channel. If the current message has no sender name, omits senderName even when the field is selected.",\u673A\u5668\u4EBA\u6807\u8BC6:"Bot ID",\u589E\u5F3A\u63D0\u793A\u8BCD:"Guidance",\u67E5\u770B\u589E\u5F3A\u63D0\u793A\u8BCD\u4F7F\u7528\u8BF4\u660E:"View guidance instructions",\u4F7F\u7528\u8BF4\u660E:"How to use","\u7528\u4E8E\u544A\u8BC9\u6A21\u578B\u5982\u4F55\u4F7F\u7528 \u4E2D\u5DF2\u9009\u62E9\u7684\u6765\u6E90\u5B57\u6BB5\u3002\u53EA\u586B\u5199\u6B63\u6587\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u6DFB\u52A0 \u6210\u5BF9\u6807\u7B7E\u3002":"Tell the model how to use the selected fields in . Enter only the body; the plugin adds paired tags.",\u751F\u6548\u89C4\u5219:"Behavior",\u9690\u79C1\u63D0\u793A:"Privacy",\u4F7F\u7528\u793A\u4F8B:"Example","\u4EC5\u4F9D\u636E\u5F53\u524D\u6D88\u606F\u7684 \u4E2D\u5B9E\u9645\u63D0\u4F9B\u7684\u5B57\u6BB5\u7406\u89E3\u6765\u6E90\uFF1B\u6CA1\u6709\u63D0\u4F9B\u7684\u5B57\u6BB5\u4E0D\u8981\u731C\u6D4B\u6216\u8865\u5168\u3002\nconversationType\u662F\u7FA4\u804A\u65F6\u56DE\u590D\u4E25\u8083\u4E00\u70B9\uFF0CconversationType\u662F\u79C1\u804A\u65F6\u56DE\u590D\u4E00\u5B9A\u8981\u5E7D\u9ED8\u641E\u7B11\uFF0C\u50CF\u5468\u661F\u9A70\u7684\u7535\u5F71\u4E00\u6837\u641E\u7B11":`Understand the source only from fields actually present in for the current message; do not guess or fill in missing fields. When conversationType is group, reply more seriously. When conversationType is direct, make the reply humorous and funny.`,\u586B\u5165\u793A\u4F8B:"Use example",\u6E05\u7A7A:"Clear","\u9009\u62E9\u5728\u54EA\u4E9B\u4F1A\u8BDD\u4E2D\u542F\u7528\u3001\u63D0\u4F9B\u54EA\u4E9B\u6765\u6E90\u5B57\u6BB5\uFF0C\u4EE5\u53CA\u5982\u4F55\u4F7F\u7528\u8FD9\u4E9B\u4FE1\u606F\u3002\u4EC5\u4F7F\u7528\u5DF2\u6709\u6D88\u606F\u5143\u6570\u636E\uFF0C\u4E0D\u67E5\u8BE2\u5E73\u53F0 API\u3002":"Choose which conversations to enhance, which source fields to include, and how to use them. Only existing message metadata is used; no platform APIs are queried.","\u589E\u5F3A\u63D0\u793A\u8BCD\u4E2D\u8BF7\u4F7F\u7528\u5B57\u6BB5\u540D\uFF08\u5982 senderId\u3001conversationType\uFF09\u5F15\u7528\u8FD9\u4E9B\u4FE1\u606F\u3002\u53EA\u53D1\u9001\u52FE\u9009\u4E14\u5F53\u524D\u6D88\u606F\u4E2D\u53EF\u7528\u7684\u5B57\u6BB5\uFF0C\u4E0D\u4F1A\u989D\u5916\u67E5\u8BE2\u6216\u8865\u5168\u3002":"Reference these values by field name (such as senderId or conversationType) in the guidance. Only selected fields available in the current message are sent; no extra lookups are made.","\u53EA\u9700\u586B\u5199\u6B63\u6587\uFF0C\u63D2\u4EF6\u81EA\u52A8\u6DFB\u52A0 \u6210\u5BF9\u6807\u7B7E\u3002\u6E05\u7A7A\u5E76\u4FDD\u5B58\u540E\uFF0C\u4E0D\u518D\u9644\u52A0\u589E\u5F3A\u63D0\u793A\u8BCD\uFF0C\u5DF2\u9009\u6765\u6E90\u5B57\u6BB5\u4ECD\u6309\u5F00\u5173\u8BBE\u7F6E\u53D1\u9001\u3002":"Enter only the body; the plugin adds paired tags. Clear and save to omit guidance. Selected source fields still follow the conversation switches.","\u53D1\u9001\u8005\u6807\u8BC6\u53EF\u80FD\u5305\u542B\u5E73\u53F0\u7528\u6237 ID \u6216\u7535\u8BDD\u53F7\u7801\u5F62\u5F0F\u7684\u6807\u8BC6\u3002\u5173\u95ED\u5F00\u5173\u4E0D\u4F1A\u5220\u9664\u5DF2\u7ECF\u5199\u5165\u4F1A\u8BDD\u5386\u53F2\u7684\u4FE1\u606F\u3002":"Sender IDs may contain platform user IDs or phone-number-like identifiers. Turning this off does not remove information already saved in conversation history.","\u4E0A\u4E0B\u6587\u589E\u5F3A\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not save context enhancement. Try again.","\u8BF7\u63D0\u4EA4\u5B8C\u6574\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Submit the complete context enhancement settings.","\u7FA4\u804A\u548C\u79C1\u804A\u5F00\u5173\u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002":"Group and direct switches must be booleans.","\u6765\u6E90\u5B57\u6BB5\u53EA\u80FD\u9009\u62E9\u5DF2\u5B9A\u4E49\u7684\u4E94\u4E2A\u5B57\u6BB5\u3002":"Source fields must be chosen from the five defined fields.","\u4FDD\u5B58\u4E2D\u2026":"Saving\u2026",\u672A\u8BBE\u7F6E:"Not set","\u5DE5\u4F5C\u533A\u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the workspace. Try again.","\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Enter an absolute workspace path.","\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002":"The workspace must be an absolute path.","\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002":"The workspace path does not exist.","\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002":"The workspace path must point to a directory.","\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002":"The bot could not be found.","Agent Preset":"Agent Preset","\u67E5\u770B Agent Preset \u8BF4\u660E":"View Agent Preset help","\u8DDF\u968F Host \u9ED8\u8BA4":"Follow the Host default","\uFF08\u5DF2\u4E0D\u53EF\u7528\uFF09":" (unavailable)","\u53EA\u5F71\u54CD\u65B0\u5EFA\u4F1A\u8BDD\uFF1B\u82E5\u5F53\u524D\u804A\u5929\u5DF2\u6709\u4F1A\u8BDD\uFF0C\u5148\u53D1\u9001 /new\uFF0C\u518D\u53D1\u9001\u666E\u901A\u6D88\u606F\u751F\u6548\u3002":"This affects only new sessions. If the current chat already has a session, send /new, then send a regular message to apply it.","\u5F53\u524D Agent Preset \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u9009\u62E9\u5176\u4ED6 Preset \u6216\u8DDF\u968F Host \u9ED8\u8BA4\u3002":"The current Agent Preset is unavailable. Choose another preset or follow the Host default.","Agent Preset \u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the Agent Preset. Try again.","\u8BF7\u9009\u62E9 Agent Preset\u3002":"Choose an Agent Preset.","Agent Preset \u65E0\u6548\u3002":"The Agent Preset is invalid.","Agent Preset \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\u3002":"The Agent Preset does not exist or is unavailable.",\u5C1A\u672A\u68C0\u67E5:"Not checked yet",\u521A\u521A:"Just now",\u68C0\u67E5\u8FDE\u63A5:"Check connection","\u68C0\u67E5\u4E2D\u2026":"Checking\u2026","\u8FDE\u63A5\u68C0\u67E5\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Connection check failed. Try again later.","\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u8BF7\u5230\u5BF9\u5E94\u673A\u5668\u4EBA\u4F1A\u8BDD\u4E2D\u786E\u8BA4\u3002":"Test message sent. Check the matching bot conversation.","\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\u3002\u673A\u5668\u4EBA\u5C1A\u672A\u6536\u5230\u53EF\u7528\u4E8E\u6D4B\u8BD5\u7684\u79C1\u804A\u6D88\u606F\u3002":"Connection check completed. The bot has not received a direct message it can use for testing.","\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"Connection check completed, but the test message could not be sent.","\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u8BF7\u5230\u98DE\u4E66\u4F1A\u8BDD\u4E2D\u786E\u8BA4\u3002":"Test message sent. Check the Feishu conversation.","\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u8BF7\u5230 WhatsApp \u81EA\u804A\u4F1A\u8BDD\u4E2D\u786E\u8BA4\u3002":"Test message sent. Check the WhatsApp self-chat.","\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u5F53\u524D\u6CA1\u6709\u53EF\u7528\u7684 WhatsApp \u81EA\u804A\u76EE\u6807\u3002":"Connection check completed, but no WhatsApp self-chat target is available.","\u9489\u9489\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\u3002":"DingTalk connection check completed and the test message was sent.","\u9489\u9489\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"DingTalk connection check completed, but the test message could not be sent.","\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\u3002":"WeChat connection check completed and the test message was sent.","\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"WeChat connection check completed, but the test message could not be sent.","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\u3002":"WeCom connection check completed and the test message was sent.","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u68C0\u67E5\u5B8C\u6210\uFF0C\u4F46\u6D4B\u8BD5\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002":"WeCom connection check completed, but the test message could not be sent.",\u91CD\u8BD5\u8FDE\u63A5:"Reconnect","\u91CD\u8BD5\u4E2D\u2026":"Retrying\u2026",\u79FB\u9664\u63A5\u5165:"Remove connection",\u786E\u8BA4\u79FB\u9664\u63A5\u5165:"Remove connection",\u786E\u8BA4\u79FB\u9664:"Remove","\u6B63\u5728\u79FB\u9664\u2026":"Removing\u2026",\u4FDD\u7559\u673A\u5668\u4EBA:"Keep bot",\u4FDD\u7559\u8D26\u53F7:"Keep account",\u53D6\u6D88:"Cancel",\u5173\u95ED:"Close",\u7ACB\u5373\u91CD\u8BD5:"Retry now",\u91CD\u65B0\u8BFB\u53D6:"Reload",\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801:"Generate a new QR code",\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u540E\u7EE7\u7EED:"Generate a new QR code",\u5237\u65B0\u4E8C\u7EF4\u7801:"Refresh QR code","\u5237\u65B0\u4E2D\u2026":"Refreshing\u2026",\u6362\u4E00\u4E2A\u4E8C\u7EF4\u7801:"Get another QR code",\u7EE7\u7EED\u8FDE\u63A5:"Continue connecting",\u7ED1\u5B9A\u5E76\u8FDE\u63A5:"Connect","\u6B63\u5728\u7ED1\u5B9A\u2026":"Connecting\u2026",\u9A8C\u8BC1\u5E76\u8FDE\u63A5:"Verify and connect","\u6B63\u5728\u9A8C\u8BC1\u5E76\u8FDE\u63A5\u2026":"Verifying and connecting\u2026","\u6B63\u5728\u9A8C\u8BC1\u2026":"Verifying\u2026","\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":"The operation failed. Try again later.",\u8BF7\u7A0D\u540E\u91CD\u8BD5:"Try again later.",\u5F53\u524D\u4E8C\u7EF4\u7801\u6709\u6548\u65F6\u95F4:"QR code expires in",\u4E8C\u7EF4\u7801\u6709\u6548\u65F6\u95F4:"QR code expires in",\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F:"QR code expired",\u4E8C\u7EF4\u7801\u5DF2\u5931\u6548:"QR code expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\n\u8BF7\u91CD\u65B0\u751F\u6210":`QR code expired Generate a new one`,"\u4E8C\u7EF4\u7801\u56FE\u7247\u6B63\u5728\u751F\u6210\u2026":"Generating QR code\u2026","\u4E8C\u7EF4\u7801\u6B63\u5728\u751F\u6210\u2026":"Generating QR code\u2026","\u4E8C\u7EF4\u7801\u6B63\u5728\u81EA\u52A8\u5237\u65B0\u2026":"Refreshing QR code\u2026","\u4E8C\u7EF4\u7801\u672A\u5C31\u7EEA\uFF0C\u8BF7\u6253\u5F00\u6388\u6743\u94FE\u63A5":"The QR code is not ready. Open the authorization link.","\u4E8C\u7EF4\u7801\u56FE\u7247\u672A\u5C31\u7EEA\uFF0C\u8BF7\u4F7F\u7528\u5907\u7528\u94FE\u63A5\u3002":"The QR code is not ready. Use the alternate link.","\u4E8C\u7EF4\u7801\u56FE\u7247\u672A\u5C31\u7EEA\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002":"The QR code is not ready. Generate a new one.",\u7B49\u5F85\u5237\u65B0:"Waiting to refresh",\u6B63\u5728\u5237\u65B0\u4E8C\u7EF4\u7801:"Refreshing QR code",\u6253\u5F00\u5907\u7528\u94FE\u63A5:"Open alternate link",\u751F\u6210\u4E8C\u7EF4\u7801:"Generate QR code",\u751F\u6210\u5FAE\u4FE1\u4E8C\u7EF4\u7801:"Generate WeChat QR code",\u751F\u6210\u98DE\u4E66\u4E8C\u7EF4\u7801:"Generate Feishu QR code",\u751F\u6210\u9489\u9489\u4E8C\u7EF4\u7801:"Generate DingTalk QR code",\u751F\u6210\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801:"Generate WeCom QR code","\u751F\u6210 QQ \u4E8C\u7EF4\u7801":"Generate QQ QR code","\u6B63\u5728\u751F\u6210\u4E8C\u7EF4\u7801\u2026":"Generating QR code\u2026",\u6B63\u5728\u51C6\u5907\u6388\u6743\u4E8C\u7EF4\u7801:"Preparing authorization QR code",\u6B63\u5728\u51C6\u5907\u6743\u9650\u6388\u6743\u4E8C\u7EF4\u7801:"Preparing permission authorization QR code",\u6B63\u5728\u51C6\u5907\u5FAE\u4FE1\u4E8C\u7EF4\u7801:"Preparing WeChat QR code",\u6B63\u5728\u6DFB\u52A0\u65B0\u673A\u5668\u4EBA:"Adding a new bot","\u6B63\u5728\u7533\u8BF7\u9489\u9489\u6388\u6743\u4E8C\u7EF4\u7801\u2026":"Requesting DingTalk authorization QR code\u2026","\u6B63\u5728\u7533\u8BF7\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u2026":"Requesting WeCom QR code\u2026","\u6B63\u5728\u7533\u8BF7 QQ \u4E8C\u7EF4\u7801\u2026":"Requesting QQ QR code\u2026","\u6B63\u5728\u751F\u6210 WhatsApp \u4E8C\u7EF4\u7801":"Generating WhatsApp QR code","\u626B\u7801\uFF0C\u521B\u5EFA\u7B2C\u4E00\u4E2A\u98DE\u4E66\u5165\u53E3":"Scan to create your first Feishu bot","\u626B\u7801\u53EA\u4F1A\u65B0\u589E\u4E00\u4E2A\u673A\u5668\u4EBA\uFF0C\u5DF2\u63A5\u5165\u7684\u673A\u5668\u4EBA\u4F1A\u7EE7\u7EED\u6B63\u5E38\u6536\u53D1\u6D88\u606F\u3002":"Scanning adds one bot. Existing bots will continue to send and receive messages.","\u65E0\u9700\u624B\u52A8\u586B\u5199 App ID\u3002\u4EE5\u540E\u8FD8\u53EF\u4EE5\u7EE7\u7EED\u6DFB\u52A0\u673A\u5668\u4EBA\uFF0C\u5206\u522B\u670D\u52A1\u4E0D\u540C\u56E2\u961F\u6216\u98DE\u4E66\u79DF\u6237\u3002":"No App ID is required. You can add more bots later for different teams or Feishu tenants.",\u4F7F\u7528\u98DE\u4E66\u626B\u7801\u521B\u5EFA\u673A\u5668\u4EBA:"Scan with Feishu to create a bot",\u5237\u65B0\u4E8C\u7EF4\u7801\u540E\u7EE7\u7EED:"Refresh the QR code to continue","\u6253\u5F00\u98DE\u4E66\u79FB\u52A8\u7AEF\uFF0C\u4F7F\u7528\u626B\u4E00\u626B\u8BFB\u53D6\u4E8C\u7EF4\u7801":"Open Feishu on your phone and scan the QR code","\u6838\u5BF9\u5E94\u7528\u540D\u79F0\u4E0E\u6743\u9650\u8303\u56F4\uFF0C\u5E76\u786E\u8BA4\u521B\u5EFA":"Review the app name and permissions, then confirm","\u4FDD\u6301\u672C\u9875\u6253\u5F00\uFF0C\u7B49\u5F85\u65B0\u673A\u5668\u4EBA\u7684\u957F\u8FDE\u63A5\u5C31\u7EEA":"Keep this page open until the bot connection is ready",\u5728\u98DE\u4E66\u4E2D\u6253\u5F00:"Open in Feishu",\u53D6\u6D88\u6DFB\u52A0:"Cancel",\u4F7F\u7528\u98DE\u4E66\u626B\u7801\u8865\u5168\u6743\u9650:"Scan with Feishu to complete permissions",\u4F7F\u7528\u98DE\u4E66\u786E\u8BA4\u7FA4\u6D88\u606F\u6743\u9650:"Confirm group-message permission with Feishu","\u626B\u7801\u4F1A\u66F4\u65B0\u73B0\u6709\u98DE\u4E66\u5E94\u7528\uFF0C\u53EA\u589E\u91CF\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF1B\u4E0D\u4F1A\u521B\u5EFA\u65B0\u5E94\u7528\u3002\u786E\u8BA4\u540E\u4F1A\u81EA\u52A8\u542F\u7528\u201C\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\u201D\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u53D7\u5F71\u54CD\u3002":"Scanning updates the existing Feishu app with only the \u201CRead all messages in associated group chat\u201D scope. It does not create a new app. After confirmation, \u201CRespond to all group messages\u201D is enabled automatically; other bots are unaffected.","\u6838\u5BF9\u73B0\u6709\u5E94\u7528\uFF0C\u5E76\u786E\u8BA4\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650":"Review the existing app and confirm the \u201CRead all messages in associated group chat\u201D permission","\u4FDD\u6301\u672C\u9875\u6253\u5F00\uFF0C\u7B49\u5F85\u6743\u9650\u751F\u6548\u5E76\u81EA\u52A8\u5207\u6362\u54CD\u5E94\u65B9\u5F0F":"Keep this page open while the permission takes effect and the response mode switches automatically",\u53D6\u6D88\u6388\u6743:"Cancel authorization","\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u542F\u7528\u5168\u90E8\u6D88\u606F\u6A21\u5F0F":"Confirmed. Enabling all-message mode","\u6743\u9650\u914D\u7F6E\u5DF2\u63D0\u4EA4\uFF0C\u6B63\u5728\u4FDD\u5B58\u8BBE\u7F6E\u5E76\u91CD\u8FDE\u6B64\u673A\u5668\u4EBA\uFF1B\u6B64\u9636\u6BB5\u65E0\u6CD5\u53D6\u6D88\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u4F1A\u4E2D\u65AD\u3002":"The permission update was submitted. Saving the setting and reconnecting this bot. This stage cannot be cancelled; other bots will not be interrupted.","\u6743\u9650\u914D\u7F6E\u5DF2\u63D0\u4EA4\uFF0C\u6B63\u5728\u542F\u7528\u5168\u90E8\u6D88\u606F\u6A21\u5F0F\u5E76\u91CD\u8FDE\u6B64\u673A\u5668\u4EBA\uFF1B\u6B64\u9636\u6BB5\u65E0\u6CD5\u53D6\u6D88\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u4F1A\u4E2D\u65AD\u3002":"The permission update was submitted. Enabling all-message mode and reconnecting this bot. This stage cannot be cancelled; other bots will not be interrupted.","\u6B63\u5728\u4E3A\u73B0\u6709\u98DE\u4E66\u5E94\u7528\u7533\u8BF7\u7FA4\u6D88\u606F\u6743\u9650\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u5019\u3002":"Requesting a group-message permission QR code for the existing Feishu app\u2026",\u7FA4\u6D88\u606F\u6743\u9650\u6CA1\u6709\u5F00\u901A\u5B8C\u6210:"Group-message permission was not granted","\u626B\u7801\u4F1A\u66F4\u65B0\u73B0\u6709\u98DE\u4E66\u5E94\u7528\uFF0C\u589E\u91CF\u8865\u5145\u5F53\u524D\u7F3A\u5C11\u7684\u5361\u7247\u6309\u94AE\u56DE\u8C03\u3001\u8BFB\u53D6\u7528\u6237\u6D88\u606F\u5185\u56FE\u7247\u6216\u6587\u4EF6\u6240\u9700\u7684 im:message:readonly\uFF08\u98DE\u4E66\u663E\u793A\u4E3A\u201C\u83B7\u53D6\u5355\u804A\u3001\u7FA4\u7EC4\u6D88\u606F\u201D\uFF09\u3001\u4E0A\u4F20\u673A\u5668\u4EBA\u56FE\u7247\u6216\u6587\u4EF6\u6240\u9700\u7684 im:resource\uFF0C\u4EE5\u53CA\u539F\u751F\u547D\u4EE4\u9762\u677F\u6240\u9700\u7684 application:app_slash_command:read / write\uFF1B\u4E0D\u4F1A\u521B\u5EFA\u65B0\u5E94\u7528\u3002\u786E\u8BA4\u9875\u53EA\u663E\u793A\u5F53\u524D\u7F3A\u5C11\u9879\uFF0C\u5B8C\u6210\u540E\u6B64\u673A\u5668\u4EBA\u4F1A\u77ED\u6682\u91CD\u8FDE\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u53D7\u5F71\u54CD\u3002":"Scanning updates the existing Feishu app with the missing card-button callback, im:message:readonly for reading images or files in user messages (shown by Feishu as \u201CRead direct and group messages\u201D), im:resource for uploading images or files sent by the bot, and application:app_slash_command:read / write for the native command panel. It does not create a new app. The confirmation page shows only missing items; this bot reconnects briefly afterward, while other bots are unaffected.","\u6838\u5BF9\u73B0\u6709\u5E94\u7528\u540D\u79F0\uFF0C\u5E76\u786E\u8BA4\u53EA\u65B0\u589E\u5F53\u524D\u7F3A\u5C11\u7684\u4E0A\u8FF0\u914D\u7F6E":"Review the existing app name and confirm that only the missing items described above are added","\u4FDD\u6301\u672C\u9875\u6253\u5F00\uFF0C\u7B49\u5F85\u6743\u9650\u4E0E\u56DE\u8C03\u8865\u5168\u5B8C\u6210":"Keep this page open until permissions and the callback are complete",\u53D6\u6D88\u8865\u5168:"Cancel setup","\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u5B8C\u6210\u6743\u9650\u4E0E\u56DE\u8C03\u914D\u7F6E":"Confirmed. Completing permissions and callback setup",\u6B63\u5728\u51C6\u5907\u6743\u9650\u8865\u5168\u4E8C\u7EF4\u7801:"Preparing the permission-completion QR code","\u914D\u7F6E\u5DF2\u63D0\u4EA4\uFF0C\u6B63\u5728\u4FDD\u5B58\u6743\u9650\u3001\u9A8C\u8BC1\u5361\u7247\u56DE\u8C03\u5E76\u91CD\u8FDE\u6B64\u673A\u5668\u4EBA\uFF1B\u6B64\u9636\u6BB5\u65E0\u6CD5\u53D6\u6D88\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u4F1A\u4E2D\u65AD\u3002":"The update was submitted. Saving permissions, verifying the card callback, and reconnecting this bot. This stage cannot be cancelled; other bots will not be interrupted.","\u6B63\u5728\u4E3A\u73B0\u6709\u98DE\u4E66\u5E94\u7528\u7533\u8BF7\u4E00\u6B21\u6027\u66F4\u65B0\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u5019\u3002":"Requesting a one-time update QR code for the existing Feishu app\u2026",\u6743\u9650\u4E0E\u56DE\u8C03\u6CA1\u6709\u8865\u5168\u5B8C\u6210:"Permissions and callback setup did not finish",\u8865\u5168\u6743\u9650:"Complete permissions",\u8865\u5168\u8303\u56F4:"Completion scope","\u589E\u91CF\u6DFB\u52A0\u5F53\u524D\u7F3A\u5C11\u7684\u5361\u7247\u56DE\u8C03 card.action.trigger\u3001\u8BFB\u53D6\u6D88\u606F\u5185\u56FE\u7247\u6216\u6587\u4EF6\u6240\u9700\u7684 im:message:readonly\uFF08\u98DE\u4E66\u663E\u793A\u4E3A\u201C\u83B7\u53D6\u5355\u804A\u3001\u7FA4\u7EC4\u6D88\u606F\u201D\uFF09\u3001\u4E0A\u4F20\u673A\u5668\u4EBA\u56FE\u7247\u6216\u6587\u4EF6\u6240\u9700\u7684 im:resource\uFF0C\u4EE5\u53CA\u539F\u751F\u547D\u4EE4\u9762\u677F\u6240\u9700\u7684 application:app_slash_command:read / write\uFF1B\u786E\u8BA4\u9875\u53EA\u663E\u793A\u5F53\u524D\u7F3A\u5C11\u9879\uFF0C\u4E0D\u4F1A\u521B\u5EFA\u65B0\u5E94\u7528\u3002":"Adds the missing card callback card.action.trigger, im:message:readonly for reading images or files in messages (shown by Feishu as \u201CRead direct and group messages\u201D), im:resource for uploading images or files sent by the bot, and application:app_slash_command:read / write for the native command panel. The confirmation page shows only missing items; no new app is created.","\u7B49\u5F85\u626B\u7801\u2026":"Waiting for scan\u2026",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u5339\u914D\u7684\u6743\u9650\u8865\u5168\u4E8C\u7EF4\u7801:"Feishu returned a permission-completion QR code for a different bot",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u5339\u914D\u7684\u7FA4\u6D88\u606F\u6743\u9650\u4E8C\u7EF4\u7801:"Feishu returned a group-message permission QR code for a different bot","\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u7684\u4FEE\u590D\u4FE1\u606F\u7F3A\u5C11 botId":"Feishu repair status is missing the bot ID","\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u7684\u5E94\u7528\u66F4\u65B0\u4FE1\u606F\u7F3A\u5C11 botId":"Feishu app-update status is missing the bot ID",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u5339\u914D\u7684\u6CE8\u518C\u8FDB\u5EA6:"Feishu returned registration progress for a different operation",\u6B64\u673A\u5668\u4EBA:"this bot","\u7528\u4E8E\u4E3A${botName}\u5F00\u901A\u7FA4\u6D88\u606F\u6743\u9650\u7684\u4E00\u6B21\u6027\u6388\u6743\u4E8C\u7EF4\u7801":"One-time QR code for granting group-message permission to ${botName}","\u6B63\u5728\u4E3A\u300C${botName}\u300D\u5F00\u901A\u7FA4\u6D88\u606F\u6743\u9650":"Granting group-message permission to \u201C${botName}\u201D",'${botName ?? "\u673A\u5668\u4EBA"}\u7684\u6743\u9650\u8865\u5168\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u4F7F\u7528\u98DE\u4E66\u626B\u7801\u3002':'Permission-completion QR code generated for ${botName ?? "bot"}. Scan it with Feishu.','${botName ?? "\u673A\u5668\u4EBA"}\u7684\u7FA4\u6D88\u606F\u6743\u9650\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u4F7F\u7528\u98DE\u4E66\u786E\u8BA4\u3002':'Group-message permission QR code generated for ${botName ?? "bot"}. Confirm it with Feishu.',"${targetBotName}\u5DF2\u5F00\u901A\u7FA4\u6D88\u606F\u6743\u9650\uFF0C\u5E76\u542F\u7528\u201C\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\u201D\u3002":"${targetBotName} now has group-message permission and \u201CRespond to all group messages\u201D is enabled.","${targetBot.bot.name}\u5DF2\u5F00\u901A\u7FA4\u6D88\u606F\u6743\u9650\uFF0C\u5E76\u542F\u7528\u201C\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\u201D\u3002":"${targetBot.bot.name} now has group-message permission and \u201CRespond to all group messages\u201D is enabled.","${targetBot.bot.name}\u5DF2\u8FDE\u63A5\uFF0C\u53EF\u4EE5\u5728\u98DE\u4E66\u4E2D\u5F00\u59CB\u804A\u5929\u3002":"${targetBot.bot.name} is connected and ready to chat in Feishu.","\u5DF2\u53D6\u6D88\u8865\u5168\u6743\u9650\u4E0E\u56DE\u8C03\u3002":"Completing permissions and the callback was cancelled.","\u5DF2\u53D6\u6D88\u7FA4\u6D88\u606F\u6743\u9650\u6388\u6743\u3002":"Group-message permission authorization was cancelled.","\u6743\u9650\u4E0E\u56DE\u8C03\u5DF2\u66F4\u65B0\uFF0C\u4F46\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u673A\u5668\u4EBA\u8FDE\u63A5\u72B6\u6001":"Permissions and the callback were updated, but the bot connection could not be confirmed yet","\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u66F4\u65B0\uFF0C\u4F46\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u673A\u5668\u4EBA\u8FDE\u63A5\u72B6\u6001":"The group-message permission was updated, but the bot connection could not be confirmed yet",\u98DE\u4E66\u6743\u9650\u4E0E\u56DE\u8C03\u8865\u5168\u5931\u8D25:"Could not complete Feishu permissions and callback setup",\u98DE\u4E66\u7FA4\u6D88\u606F\u6743\u9650\u5F00\u901A\u5931\u8D25:"Could not grant the Feishu group-message permission","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u98DE\u4E66\u6388\u6743\u64CD\u4F5C\uFF0C\u518D\u5F00\u901A\u7FA4\u6D88\u606F\u6743\u9650\u3002":"Finish the current Feishu authorization before granting group-message permission.","\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u8FDE\u63A5\u65B0\u673A\u5668\u4EBA":"Confirmed. Connecting the new bot","\u6B63\u5728\u5B89\u5168\u4FDD\u5B58\u51ED\u636E\u5E76\u68C0\u67E5\u65B0\u673A\u5668\u4EBA\u7684\u6D88\u606F\u901A\u9053\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E0D\u4F1A\u4E2D\u65AD\u3002":"Saving credentials and checking the new bot connection. Existing bots will not be interrupted.","\u6B63\u5728\u5411\u98DE\u4E66\u7533\u8BF7\u4E00\u6B21\u6027\u6388\u6743\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u5019\u3002":"Requesting a one-time authorization QR code from Feishu\u2026",\u65B0\u673A\u5668\u4EBA\u6CA1\u6709\u6DFB\u52A0\u5B8C\u6210:"The new bot was not added","\u65B0\u98DE\u4E66\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5\uFF0C\u53EF\u4EE5\u5F00\u59CB\u804A\u5929\u3002":"The new Feishu bot is connected and ready to chat.",\u98DE\u4E66\u5E94\u7528\u521B\u5EFA\u5931\u8D25:"Could not create the Feishu app","\u673A\u5668\u4EBA\u5DF2\u7ECF\u521B\u5EFA\uFF0C\u4F46\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u8FDE\u63A5\u72B6\u6001":"The bot was created, but its connection could not be confirmed yet",\u673A\u5668\u4EBA\u4ECD\u672A\u8FDE\u63A5:"The bot is still offline",\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5:"The bot is not connected yet",\u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38:"Persistent connection is healthy",\u957F\u8FDE\u63A5:"Persistent connection",\u5E94\u7528\u6807\u8BC6\u5DF2\u5B89\u5168\u4FDD\u5B58:"App identifier stored securely",\u673A\u5668\u4EBA\u6807\u8BC6\u5DF2\u5B89\u5168\u4FDD\u5B58:"Bot identifier stored securely",\u5DF2\u5B89\u5168\u4FDD\u5B58:"Stored securely",\u5DF2\u63A5\u5165\u7684\u5FAE\u4FE1\u8D26\u53F7:"Connected WeChat accounts",\u5DF2\u63A5\u5165\u7684\u673A\u5668\u4EBA:"Connected bots",\u5DF2\u63A5\u5165\u7684\u9489\u9489\u673A\u5668\u4EBA:"Connected DingTalk bots",\u5DF2\u7ED1\u5B9A\u7684\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"Connected WeCom bots","\u5DF2\u7ED1\u5B9A\u7684 QQ \u673A\u5668\u4EBA":"Connected QQ bots","\u5DF2\u63A5\u5165\u7684 WhatsApp \u673A\u5668\u4EBA":"Connected WhatsApp accounts",\u4F7F\u7528\u624B\u673A\u5FAE\u4FE1\u626B\u63CF\u4E8C\u7EF4\u7801:"Scan with WeChat on your phone","\u626B\u4E00\u6B21\u7801\uFF0C\u5C31\u80FD\u5728\u5FAE\u4FE1\u91CC\u4F7F\u7528 Harness":"Scan once to use Harness in WeChat",\u6253\u5F00\u624B\u673A\u5FAE\u4FE1\u5E76\u626B\u63CF\u5DE6\u4FA7\u4E8C\u7EF4\u7801:"Open WeChat on your phone and scan the QR code",\u5728\u5FAE\u4FE1\u4E2D\u786E\u8BA4\u8FDE\u63A5\u8BE5\u673A\u5668\u4EBA:"Confirm the bot connection in WeChat","\u4FDD\u6301\u672C\u9875\u6253\u5F00\uFF0C\u7B49\u5F85\u673A\u5668\u4EBA\u81EA\u52A8\u8FDE\u63A5":"Keep this page open while the bot connects",\u7B49\u5F85\u5FAE\u4FE1\u626B\u7801:"Waiting for WeChat scan",\u9700\u8981\u914D\u5BF9\u7801:"Pairing code required",\u8F93\u5165\u624B\u673A\u5FAE\u4FE1\u663E\u793A\u7684\u6570\u5B57:"Enter the number shown in WeChat",\u5FAE\u4FE1\u914D\u5BF9\u7801:"WeChat pairing code","\u5DF2\u626B\u7801\uFF0C\u8BF7\u5728\u624B\u673A\u4E0A\u786E\u8BA4":"Scanned. Confirm on your phone","\u914D\u5BF9\u7801\u5DF2\u63D0\u4EA4\uFF0C\u6B63\u5728\u7B49\u5F85\u5FAE\u4FE1\u786E\u8BA4\u3002":"Pairing code submitted. Waiting for WeChat confirmation.","\u8FD9\u662F\u5FAE\u4FE1\u9644\u52A0\u7684\u5B89\u5168\u786E\u8BA4\u6B65\u9AA4\u3002\u914D\u5BF9\u7801\u53EA\u7528\u4E8E\u672C\u6B21\u626B\u7801\u8F6E\u8BE2\uFF0C\u4E0D\u4F1A\u5199\u5165\u914D\u7F6E\u6216\u65E5\u5FD7\u3002":"This is an additional WeChat confirmation step. The pairing code is used only for this connection and is never stored.","\u6B63\u5728\u4FDD\u5B58\u51ED\u636E\u5E76\u9A8C\u8BC1 Harness \u4E0E\u5FAE\u4FE1\u957F\u8F6E\u8BE2\u3002":"Saving credentials and verifying the WeChat connection.","\u5FAE\u4FE1\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u542F\u52A8\u6D88\u606F\u8FDE\u63A5":"Confirmed in WeChat. Starting the message connection","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u8BFB\u53D6\u73B0\u6709\u767B\u5F55\u51ED\u636E\u3002\u8BF7\u68C0\u67E5 DSH \u51ED\u636E\u5B58\u50A8\u3002":"WeChat was authorized, but the existing login credential could not be read. Check the DSH credential store.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u767B\u5F55\u51ED\u636E\u65E0\u6CD5\u5199\u5165 DSH \u51ED\u636E\u5B58\u50A8\u3002\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u662F\u5426\u53EF\u5199\u3002":"WeChat was authorized, but the login credential could not be written to the DSH credential store. Check that the store is writable.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u8D26\u53F7\u914D\u7F6E\u65E0\u6CD5\u5199\u5165\u672C\u673A\u3002\u8BF7\u68C0\u67E5 DSH_HOME \u76EE\u5F55\u6743\u9650\u3002":"WeChat was authorized, but the account configuration could not be saved locally. Check the DSH_HOME directory permissions.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u521D\u59CB\u5316\u8D26\u53F7\u72B6\u6001\u6216\u5DE5\u4F5C\u533A\u3002\u8BF7\u68C0\u67E5 DSH_HOME \u548C\u5DE5\u4F5C\u533A\u76EE\u5F55\u3002":"WeChat was authorized, but the account state or workspace could not be initialized. Check DSH_HOME and the workspace directory.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u63D2\u4EF6\u65E0\u6CD5\u8FDE\u63A5\u672C\u673A Harness\u3002\u8BF7\u68C0\u67E5 dsh web \u5730\u5740\u548C\u7AEF\u53E3\u3002":"WeChat was authorized, but the plugin could not connect to the local Harness. Check the dsh web address and port.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\u3002\u8BF7\u786E\u8BA4 dsh web \u672A\u963B\u585E\u3002":"WeChat was authorized, but the Harness health check timed out. Confirm that dsh web is not blocked.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u62D2\u7EDD\u4E86\u672C\u673A\u5065\u5EB7\u68C0\u67E5\u3002\u8BF7\u68C0\u67E5 Host \u4FE1\u4EFB\u914D\u7F6E\u3002":"WeChat was authorized, but Harness denied the local health check. Check the Host trust configuration.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u627E\u4E0D\u5230 Harness \u5065\u5EB7\u68C0\u67E5\u63A5\u53E3\u3002\u8BF7\u786E\u8BA4 Harness \u4E0E\u63D2\u4EF6\u7248\u672C\u517C\u5BB9\u3002":"WeChat was authorized, but the Harness health endpoint was not found. Confirm that Harness and the plugin are compatible.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u8FD4\u56DE\u670D\u52A1\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002":"WeChat was authorized, but the Harness health check returned a service error. Check the dsh web logs.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u54CD\u5E94\u3002\u8BF7\u786E\u8BA4 Harness \u4E0E\u63D2\u4EF6\u7248\u672C\u517C\u5BB9\u3002":"WeChat was authorized, but Harness returned an unrecognized response. Confirm that Harness and the plugin are compatible.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u62D2\u7EDD\u4E86\u5065\u5EB7\u68C0\u67E5\u8BF7\u6C42\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002":"WeChat was authorized, but Harness rejected the health-check request. Check the dsh web logs.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u53D1\u751F\u672A\u77E5\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002":"WeChat was authorized, but the Harness health check failed unexpectedly. Check the dsh web logs.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u6D88\u606F\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u540E\u91CD\u8BD5\u3002":"WeChat was authorized, but the message connection could not be initialized. Check the dsh web logs and try again.","\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u6FC0\u6D3B\u8FC7\u7A0B\u4E2D\u53D1\u751F\u672A\u77E5\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002":"WeChat was authorized, but an unknown error occurred during activation. Check the dsh web logs.","\u5FAE\u4FE1\u5DF2\u7ED1\u5B9A\uFF0C\u53EF\u4EE5\u5F00\u59CB\u5411\u5DF2\u7ED1\u5B9A\u7684\u673A\u5668\u4EBA\u53D1\u6D88\u606F\u3002":"WeChat is connected and ready for messages.","\u8FD9\u4E2A\u5FAE\u4FE1\u8D26\u53F7\u5DF2\u7ECF\u7ED1\u5B9A\u5E76\u4FDD\u6301\u5728\u7EBF\u3002":"This WeChat account is connected and online.","\u5FAE\u4FE1\u8D26\u53F7\u53CA\u672C\u673A\u51ED\u636E\u5DF2\u79FB\u9664\u3002":"The WeChat account and local credentials were removed.","\u5DF2\u53D6\u6D88\u5FAE\u4FE1\u7ED1\u5B9A\u3002":"WeChat setup was cancelled.","\u6B63\u5728\u8054\u7CFB\u817E\u8BAF\u5FAE\u4FE1 iLink \u670D\u52A1\u3002":"Contacting the WeChat iLink service.","iLink \u957F\u8F6E\u8BE2":"iLink long polling","\u626B\u4E00\u6B21\u7801\uFF0C\u81EA\u52A8\u521B\u5EFA\u5E76\u8FDE\u63A5\u673A\u5668\u4EBA":"Scan once to create and connect a bot","\u4F7F\u7528\u9489\u9489 App \u5B8C\u6210\u673A\u5668\u4EBA\u6388\u6743":"Authorize the bot with the DingTalk app","\u4F7F\u7528\u5DF2\u52A0\u5165\u4F01\u4E1A/\u7EC4\u7EC7\u7684\u9489\u9489\u8D26\u53F7\u626B\u63CF\u5DE6\u4FA7\u4E8C\u7EF4\u7801":"Scan the QR code with a DingTalk account that belongs to an organization","\u5728\u6388\u6743\u9875\u70B9\u51FB\u201C\u4E00\u952E\u521B\u5EFA\u65B0\u673A\u5668\u4EBA\u201D":"Select \u201CCreate new bot\u201D on the authorization page","\u8BF7\u52FF\u5173\u95ED\u672C\u9875\uFF0C\u9489\u9489\u5B8C\u6210\u6388\u6743\u540E\u5C06\u81EA\u52A8\u7EE7\u7EED\u3002":"Keep this page open. Setup will continue after DingTalk authorization.",\u7B49\u5F85\u9489\u9489\u626B\u7801\u6388\u6743:"Waiting for DingTalk authorization","\u6388\u6743\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u521B\u5EFA\u9489\u9489\u673A\u5668\u4EBA":"Authorized. Creating the DingTalk bot",\u6B63\u5728\u786E\u8BA4\u9489\u9489\u6388\u6743:"Confirming DingTalk authorization","\u6B63\u5728\u68C0\u67E5\u9489\u9489 Stream \u957F\u8FDE\u63A5\uFF0C\u6210\u529F\u540E\u4F1A\u81EA\u52A8\u663E\u793A\u4E3A\u5728\u7EBF\u3002":"Checking the DingTalk Stream connection. It will appear online when ready.","\u9489\u9489\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u53EF\u4EE5\u5F00\u59CB\u53D1\u9001\u6D88\u606F\u3002":"The DingTalk bot is connected and ready for messages.","\u8FD9\u4E2A\u9489\u9489\u673A\u5668\u4EBA\u5DF2\u7ECF\u63A5\u5165\u5E76\u4FDD\u6301\u5728\u7EBF\u3002":"This DingTalk bot is connected and online.","Stream \u957F\u8FDE\u63A5":"Stream persistent connection","\u4F7F\u7528\u4F01\u4E1A\u5FAE\u4FE1 App \u626B\u7801\u521B\u5EFA\u667A\u80FD\u673A\u5668\u4EBA":"Scan with WeCom to create an AI bot","\u4F7F\u7528\u4F01\u4E1A\u5FAE\u4FE1 App \u5B8C\u6210\u667A\u80FD\u673A\u5668\u4EBA\u6388\u6743":"Authorize the AI bot with WeCom","\u6253\u5F00\u4F01\u4E1A\u5FAE\u4FE1 App\uFF0C\u626B\u63CF\u5DE6\u4FA7\u4E8C\u7EF4\u7801":"Open WeCom and scan the QR code",\u5728\u817E\u8BAF\u6388\u6743\u9875\u9762\u786E\u8BA4\u521B\u5EFA\u667A\u80FD\u673A\u5668\u4EBA:"Confirm bot creation on the Tencent authorization page",\u8FD4\u56DE\u8FD9\u91CC\u7B49\u5F85\u8FDE\u63A5\u5B8C\u6210:"Return here and wait for the connection to complete","\u7B49\u5F85\u4F01\u4E1A\u5FAE\u4FE1 App \u626B\u7801":"Waiting for WeCom scan","\u4F01\u4E1A\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u6B63\u5728\u8FDE\u63A5\u673A\u5668\u4EBA":"Authorized in WeCom. Connecting the bot","\u51ED\u636E\u6B63\u5728\u5199\u5165\u672C\u673A\uFF0C\u5E76\u542F\u52A8\u4F01\u4E1A\u5FAE\u4FE1 WebSocket \u6D88\u606F\u8FDE\u63A5\u3002":"Saving credentials locally and starting the WeCom WebSocket connection.","WebSocket \u957F\u8FDE\u63A5":"WebSocket persistent connection","\u4F7F\u7528\u624B\u673A QQ \u626B\u7801\u521B\u5EFA\u5E76\u7ED1\u5B9A\u673A\u5668\u4EBA":"Scan with mobile QQ to create and connect a bot","\u4F7F\u7528\u624B\u673A QQ \u5B8C\u6210\u673A\u5668\u4EBA\u7ED1\u5B9A":"Complete bot setup with mobile QQ","\u6253\u5F00\u624B\u673A QQ\uFF0C\u626B\u63CF\u5DE6\u4FA7\u4E8C\u7EF4\u7801":"Open mobile QQ and scan the QR code",\u5728\u817E\u8BAF\u6388\u6743\u9875\u9762\u786E\u8BA4\u521B\u5EFA\u6216\u7ED1\u5B9A\u673A\u5668\u4EBA:"Confirm bot creation or connection on the Tencent authorization page","\u7B49\u5F85\u624B\u673A QQ \u626B\u7801":"Waiting for mobile QQ scan","QQ \u5DF2\u6388\u6743\uFF0C\u6B63\u5728\u8FDE\u63A5\u673A\u5668\u4EBA":"Authorized in QQ. Connecting the bot","\u51ED\u636E\u6B63\u5728\u5199\u5165\u672C\u673A\uFF0C\u5E76\u542F\u52A8 QQ WebSocket \u6D88\u606F\u8FDE\u63A5\u3002":"Saving credentials locally and starting the QQ WebSocket connection.","\u4F7F\u7528\u624B\u673A WhatsApp \u626B\u63CF\u4E8C\u7EF4\u7801\u5373\u53EF\u63A5\u5165\u3002":"Scan the QR code with WhatsApp to connect.","\u7528\u624B\u673A WhatsApp \u626B\u63CF\u4E8C\u7EF4\u7801":"Scan with WhatsApp on your phone","\u6253\u5F00 WhatsApp \u2192 \u8BBE\u7F6E \u2192 \u5DF2\u5173\u8054\u8BBE\u5907":"Open WhatsApp \u2192 Settings \u2192 Linked devices","\u70B9\u51FB\u201C\u5173\u8054\u8BBE\u5907\u201D\u5E76\u626B\u63CF\u5DE6\u4FA7\u4E8C\u7EF4\u7801":"Select \u201CLink a device\u201D and scan the QR code","\u7B49\u5F85 WhatsApp \u626B\u7801":"Waiting for WhatsApp scan","\u5DF2\u626B\u7801\uFF0C\u6B63\u5728\u8FDE\u63A5 WhatsApp":"Scanned. Connecting WhatsApp","\u6B63\u5728\u5EFA\u7ACB\u5B89\u5168\u7684\u5173\u8054\u8BBE\u5907\u4F1A\u8BDD\u3002":"Creating a secure linked-device session.","\u5173\u8054\u8BBE\u5907\u6B63\u5728\u63A5\u5165 DeepSeek Harness\u3002":"Linking the device to DeepSeek Harness.","WhatsApp Web \u5173\u8054\u8BBE\u5907\u8FD0\u884C\u6B63\u5E38":"WhatsApp linked device is healthy","\u67E5\u770B WhatsApp \u8BBF\u95EE\u6A21\u5F0F\u8BF4\u660E":"View WhatsApp access mode details","WhatsApp \u8BBF\u95EE\u6A21\u5F0F":"WhatsApp access mode",\u4EC5\u81EA\u5DF1\u6A21\u5F0F:"Only me",\u6307\u5B9A\u8054\u7CFB\u4EBA\u6A21\u5F0F:"Selected contacts",\u5F00\u653E\u54CD\u5E94\u6A21\u5F0F:"Open responses","\u4EC5\u81EA\u5DF1\u6A21\u5F0F\uFF08\u9ED8\u8BA4\uFF09":"Only me (default)","\u5DF2\u751F\u6548\uFF1A":"Active: ","\u53EA\u54CD\u5E94\u5DF2\u7ED1\u5B9A WhatsApp \u8D26\u53F7\u7684\u81EA\u804A\u6D88\u606F\u3002":"Only respond to self-chat messages from the linked WhatsApp account.","\u54CD\u5E94\u81EA\u804A\u548C\u767D\u540D\u5355\u8054\u7CFB\u4EBA\u7684\u79C1\u804A\uFF0C\u5FFD\u7565\u7FA4\u804A\u3002":"Respond to self-chat and allowlisted direct messages; ignore group messages.","\u54CD\u5E94\u6240\u6709\u79C1\u804A\u3001\u5DF2\u7ED1\u5B9A\u8D26\u53F7\u81EA\u5DF1\u53D1\u51FA\u7684\u7FA4\u804A\u6D88\u606F\uFF0C\u4EE5\u53CA\u5176\u4ED6\u7FA4\u6210\u5458\u7684\u63D0\u53CA\u6216\u56DE\u590D\u3002":"Respond to all direct messages, group messages sent by the linked account, and mentions or replies from other group members.","\u5141\u8BB8\u79C1\u804A\u7684 WhatsApp \u7535\u8BDD\u53F7\u7801":"WhatsApp phone numbers allowed to send direct messages",\u6BCF\u884C\u4E00\u4E2A\u542B\u56FD\u5BB6\u6216\u5730\u533A\u4EE3\u7801\u7684\u53F7\u7801:"One number with country or region code per line","\u53EF\u4EE5\u5305\u542B\u5F00\u5934\u7684 +\uFF0C\u4FDD\u5B58\u65F6\u4F1A\u81EA\u52A8\u79FB\u9664\u3002":"A leading + is allowed and removed when saved.","\u4EC5\u6307\u5B9A\u8054\u7CFB\u4EBA\u6A21\u5F0F\u4F7F\u7528\u767D\u540D\u5355\uFF0C\u5207\u6362\u6A21\u5F0F\u65F6\u4F1A\u4FDD\u7559\u3002":"Only Selected contacts uses the allowlist; it is retained when modes change.","\u767D\u540D\u5355\u4E3A\u7A7A\uFF1B\u4FDD\u5B58\u540E\u5C06\u53EA\u63A5\u53D7\u81EA\u804A\u6D88\u606F\u3002":"The allowlist is empty; only self-chat messages will be accepted after saving.","\u7535\u8BDD\u53F7\u7801\u5FC5\u987B\u5305\u542B\u56FD\u5BB6\u6216\u5730\u533A\u4EE3\u7801\uFF0C\u6BCF\u884C\u4E00\u4E2A\u3002":"Each phone number must include a country or region code on its own line.","WhatsApp \u8BBF\u95EE\u8BBE\u7F6E\u6682\u4E0D\u53EF\u7528\u3002":"WhatsApp access settings are currently unavailable.","WhatsApp \u8BBF\u95EE\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25\u3002":"Could not save WhatsApp access settings.","Bot API \u957F\u8F6E\u8BE2":"Bot API long polling"," Gateway \u957F\u8FDE\u63A5":" Gateway persistent connection","Gateway \u957F\u8FDE\u63A5":"Gateway persistent connection"," Socket Mode \u957F\u8FDE\u63A5":" Socket Mode persistent connection","Socket Mode \u957F\u8FDE\u63A5":"Socket Mode persistent connection","\u63A5\u5165 Telegram \u673A\u5668\u4EBA":"Connect a Telegram bot","\u5148\u901A\u8FC7 @BotFather \u83B7\u53D6 Bot Token\uFF0C\u518D\u5728\u8FD9\u91CC\u5B8C\u6210\u63A5\u5165\u3002":"Get a Bot Token from @BotFather, then connect it here.","\u586B\u5199 @BotFather \u751F\u6210\u7684 Bot Token":"Enter the Bot Token from @BotFather",\u8BBF\u95EE\u6A21\u5F0F:"Access mode",\u8BBF\u95EE\u8BBE\u7F6E:"Access settings","Telegram \u8BBF\u95EE\u6A21\u5F0F":"Telegram access mode","\u67E5\u770B Telegram \u8BBF\u95EE\u6A21\u5F0F\u8BF4\u660E":"View Telegram access mode details","\u7FA4\u804A\u5168\u90E8\u5FFD\u7565\uFF0C\u79C1\u804A\u4EC5\u5141\u8BB8\u767D\u540D\u5355\u7528\u6237\u3002":"All group messages are ignored; only allowlisted users may send DMs.","\u4FDD\u6301\u539F\u6709\u884C\u4E3A\uFF1A\u79C1\u804A\u76F4\u63A5\u54CD\u5E94\uFF0C\u7FA4\u804A\u5728\u88AB\u63D0\u53CA\u6216\u56DE\u590D\u65F6\u54CD\u5E94\u3002":"Keep the original behavior: respond to DMs and to group mentions or replies.",\u5B89\u5168\u6A21\u5F0F:"Safe mode",\u517C\u5BB9\u6A21\u5F0F:"Compatible mode","\u5DF2\u751F\u6548\uFF1A\u5B89\u5168\u6A21\u5F0F":"Active: Safe mode","\u5DF2\u751F\u6548\uFF1A\u517C\u5BB9\u6A21\u5F0F":"Active: Compatible mode",\u6A21\u5F0F:"Mode","\u517C\u5BB9\u6A21\u5F0F\uFF08\u9ED8\u8BA4\uFF09":"Compatible mode (default)","\u5B89\u5168\u6A21\u5F0F\uFF08\u79C1\u804A\u767D\u540D\u5355\uFF09":"Safe mode (private-chat allowlist)","\u5141\u8BB8\u79C1\u804A\u7684 Telegram User ID":"Telegram User IDs allowed to send DMs","\u6BCF\u884C\u4E00\u4E2A\u6570\u5B57 User ID":"One numeric User ID per line","\u767D\u540D\u5355\u4EC5\u5C5E\u4E8E\u5F53\u524D\u673A\u5668\u4EBA\u3002":"This allowlist belongs only to the current bot.","\u517C\u5BB9\u6A21\u5F0F\u4E0B\u6682\u4E0D\u4F7F\u7528\u767D\u540D\u5355\uFF0C\u5207\u6362\u6A21\u5F0F\u65F6\u4F1A\u4FDD\u7559\u3002":"Compatible mode does not enforce the allowlist; it is retained when modes change.","\u767D\u540D\u5355\u4E3A\u7A7A\uFF1B\u4FDD\u5B58\u540E\u8BE5\u673A\u5668\u4EBA\u4F1A\u62D2\u7EDD\u6240\u6709\u5165\u7AD9\u6D88\u606F\u3002":"The allowlist is empty; this bot will reject all inbound messages after saving.","\u6B63\u5728\u4FDD\u5B58\u2026":"Saving\u2026",\u4FDD\u5B58\u8BBF\u95EE\u8BBE\u7F6E:"Save access settings","User ID \u5FC5\u987B\u662F 1\u201316 \u4F4D\u6B63\u6574\u6570\uFF0C\u6BCF\u884C\u4E00\u4E2A\u3002":"Each User ID must be a 1\u201316 digit positive integer on its own line.","Telegram \u8BBF\u95EE\u8BBE\u7F6E\u6682\u4E0D\u53EF\u7528\u3002":"Telegram access settings are currently unavailable.","Telegram \u8BBF\u95EE\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25\u3002":"Could not save Telegram access settings.","\u63A5\u5165 Discord \u673A\u5668\u4EBA":"Connect a Discord bot","\u5148\u5728 Developer Portal \u521B\u5EFA Bot \u5E76\u9080\u8BF7\u5230\u670D\u52A1\u5668\uFF0C\u518D\u5728\u8FD9\u91CC\u5B8C\u6210\u63A5\u5165\u3002":"Create a bot in the Developer Portal and invite it to your server, then connect it here.","\u586B\u5199 Discord Developer Portal \u7684 Bot Token":"Enter the Bot Token from the Discord Developer Portal","\u63A5\u5165 Slack \u673A\u5668\u4EBA":"Connect a Slack bot","\u5148\u7528 Manifest \u521B\u5EFA\u5E76\u914D\u7F6E Slack App":"Create and configure a Slack app with the manifest","\u590D\u5236\u914D\u7F6E\u540E\uFF0C\u5728 Slack \u9009\u62E9 From a manifest\uFF1B\u521B\u5EFA\u5B8C\u6210\u540E\u751F\u6210 connections:write App Token\uFF0C\u5E76\u5C06\u5E94\u7528\u5B89\u88C5\u5230\u5DE5\u4F5C\u533A\u3002":"Copy the manifest and choose \u201CFrom a manifest\u201D in Slack. Then create a connections:write App Token and install the app to your workspace.","\u590D\u5236 Manifest":"Copy manifest","\u5DF2\u590D\u5236 Manifest":"Manifest copied","\u6253\u5F00 Slack \u521B\u5EFA\u9875":"Open Slack app creation","Bot Token \u6765\u81EA OAuth & Permissions\uFF1BApp Token \u6765\u81EA Basic Information\uFF0C\u5E76\u4E14\u5FC5\u987B\u5305\u542B connections:write\u3002":"Get the Bot Token from OAuth & Permissions and the App Token from Basic Information. The App Token must include connections:write.","\u4F7F\u7528\u5B98\u65B9 App Manifest \u5FEB\u901F\u914D\u7F6E\u673A\u5668\u4EBA\uFF0C\u518D\u586B\u5199 Bot Token \u4E0E App Token \u5EFA\u7ACB\u672C\u5730 Socket Mode \u8FDE\u63A5\u3002":"Configure the bot with the official app manifest, then enter the Bot Token and App Token to start a local Socket Mode connection.","Slack \u5DE5\u4F5C\u533A":"Slack workspace","Bot Token \u4E0E App Token":"Bot Token and App Token","\u586B\u5199 Bot Token":"Enter Bot Token",\u624B\u52A8\u63A5\u5165\u98DE\u4E66\u673A\u5668\u4EBA:"Connect Feishu bot manually",\u624B\u52A8\u63A5\u5165\u9489\u9489\u673A\u5668\u4EBA:"Connect DingTalk bot manually",\u624B\u52A8\u63A5\u5165\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"Connect WeCom bot manually",\u624B\u52A8\u63A5\u5165QQ\u673A\u5668\u4EBA:"Connect QQ bot manually","\u586B\u5199\u98DE\u4E66\u5F00\u653E\u5E73\u53F0 App ID":"Enter the Feishu Open Platform App ID","\u586B\u5199\u98DE\u4E66\u5F00\u653E\u5E73\u53F0 App Secret":"Enter the Feishu Open Platform App Secret","\u586B\u5199\u9489\u9489\u5E94\u7528 Client ID":"Enter the DingTalk Client ID","\u586B\u5199\u9489\u9489\u5E94\u7528 Client Secret":"Enter the DingTalk Client Secret","\u586B\u5199\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA Bot ID":"Enter the WeCom AI Bot ID","\u586B\u5199\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA Secret":"Enter the WeCom AI Bot Secret","\u586B\u5199 QQ \u5F00\u653E\u5E73\u53F0 AppID":"Enter the QQ Open Platform AppID","\u586B\u5199 QQ \u5F00\u653E\u5E73\u53F0 AppSecret":"Enter the QQ Open Platform AppSecret",\u626B\u7801\u63A5\u5165\u5FAE\u4FE1\u673A\u5668\u4EBA:"Connect WeChat bot by QR code",\u626B\u7801\u63A5\u5165\u98DE\u4E66\u673A\u5668\u4EBA:"Connect Feishu bot by QR code",\u626B\u7801\u63A5\u5165\u9489\u9489\u673A\u5668\u4EBA:"Connect DingTalk bot by QR code",\u626B\u7801\u63A5\u5165\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"Connect WeCom bot by QR code","\u626B\u7801\u63A5\u5165 QQ \u673A\u5668\u4EBA":"Connect QQ bot by QR code","\u626B\u7801\u63A5\u5165 WhatsApp \u673A\u5668\u4EBA":"Connect WhatsApp by QR code","\u626B\u7801\u7ED1\u5B9A WhatsApp \u673A\u5668\u4EBA":"Connect WhatsApp by QR code","\u4F7F\u7528 App ID \u548C App Secret \u7ED1\u5B9A\u98DE\u4E66\u673A\u5668\u4EBA":"Connect a Feishu bot with App ID and App Secret","\u4F7F\u7528 Client ID \u548C Client Secret \u7ED1\u5B9A\u9489\u9489\u673A\u5668\u4EBA":"Connect a DingTalk bot with Client ID and Client Secret","\u4F7F\u7528 Bot ID \u548C Secret \u7ED1\u5B9A\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA":"Connect a WeCom bot with Bot ID and Secret","\u4F7F\u7528 AppID \u548C AppSecret \u7ED1\u5B9A QQ \u673A\u5668\u4EBA":"Connect a QQ bot with AppID and AppSecret","\u4F7F\u7528 Manifest \u548C\u53CC Token \u63A5\u5165 Slack \u673A\u5668\u4EBA":"Connect a Slack bot with a manifest and two tokens","\u4F7F\u7528 Bot Token \u63A5\u5165 Telegram \u673A\u5668\u4EBA":"Connect a Telegram bot with a Bot Token","\u4F7F\u7528 Bot Token \u63A5\u5165 Discord \u673A\u5668\u4EBA":"Connect a Discord bot with a Bot Token",\u53D6\u6D88\u7ED1\u5B9A:"Cancel setup",\u53D6\u6D88\u63A5\u5165:"Cancel setup","\u4E8C\u7EF4\u7801\u7531\u817E\u8BAF\u5FAE\u4FE1 iLink \u670D\u52A1\u7B7E\u53D1\u3002\u7528\u624B\u673A\u5FAE\u4FE1\u626B\u63CF\u5E76\u786E\u8BA4\u540E\uFF0C\u8D26\u53F7\u51ED\u636E\u4F1A\u76F4\u63A5\u5199\u5165 Harness Host\uFF0C\u6D4F\u89C8\u5668\u4E0D\u4F1A\u6536\u5230 bot_token\u3002":"The QR code is issued by Tencent WeChat iLink. After you scan and confirm, account credentials are written directly to the Harness Host and are never exposed to the browser.","\u626B\u7801\u8D26\u53F7\u5FC5\u987B\u5DF2\u52A0\u5165\u4F01\u4E1A/\u7EC4\u7EC7\u3002\u5982\u679C\u9489\u9489\u63D0\u793A\u5C1A\u672A\u52A0\u5165\u7EC4\u7EC7\uFF0C\u8BF7\u5728\u63D0\u793A\u9875\u521B\u5EFA\u7EC4\u7EC7\uFF0C\u6216\u6362\u7528\u5DF2\u52A0\u5165\u7EC4\u7EC7\u7684\u8D26\u53F7\u3002":"The DingTalk account must belong to an organization. If prompted, create an organization or use an account that already belongs to one.","\u8BF7\u5728\u624B\u673A\u4E0A\u6838\u5BF9\u5E76\u786E\u8BA4\u6388\u6743\u3002\u90E8\u5206\u8D26\u53F7\u4F1A\u989D\u5916\u663E\u793A\u4E00\u4E2A\u914D\u5BF9\u6570\u5B57\uFF0C\u9875\u9762\u4F1A\u5728\u9700\u8981\u65F6\u63D0\u793A\u8F93\u5165\u3002":"Review and confirm authorization on your phone. Some accounts may also require a pairing number.","\u6388\u6743\u7531\u9489\u9489\u5B98\u65B9\u9875\u9762\u5B8C\u6210\u3002\u626B\u7801\u8D26\u53F7\u5FC5\u987B\u5DF2\u52A0\u5165\u4E00\u4E2A\u4F01\u4E1A/\u7EC4\u7EC7\u5E76\u6709\u6743\u521B\u5EFA\u673A\u5668\u4EBA\uFF1B\u521B\u5EFA\u6210\u529F\u540E\uFF0C\u5E94\u7528\u51ED\u636E\u4F1A\u76F4\u63A5\u5199\u5165 Harness Host\u3002":"Authorization is completed on DingTalk\u2019s official page. The account must belong to an organization and be allowed to create bots. Credentials are written directly to the Harness Host.","\u626B\u7801\u7531\u817E\u8BAF\u5B98\u65B9\u9875\u9762\u5B8C\u6210\uFF0C\u4E0D\u9700\u8981\u624B\u52A8\u586B\u5199 AppID \u6216 AppSecret\u3002\u626B\u7801\u6210\u529F\u540E\uFF0C\u673A\u5668\u4EBA\u4F1A\u81EA\u52A8\u8FDE\u63A5 DeepSeek Harness\u3002":"Scanning is completed on Tencent\u2019s official page. No AppID or AppSecret is required, and the bot connects automatically.","\u626B\u7801\u7531\u817E\u8BAF\u5B98\u65B9\u9875\u9762\u5B8C\u6210\uFF0C\u4E0D\u9700\u8981\u624B\u52A8\u586B\u5199 Bot ID \u6216 Secret\u3002\u521B\u5EFA\u6210\u529F\u540E\uFF0C\u673A\u5668\u4EBA\u4F1A\u81EA\u52A8\u8FDE\u63A5 DeepSeek Harness\u3002":"Scanning is completed on Tencent\u2019s official page. No Bot ID or Secret is required, and the bot connects automatically.","\u817E\u8BAF\u9875\u9762\u4F1A\u521B\u5EFA\u6216\u7ED1\u5B9A\u4E00\u4E2A QQ \u673A\u5668\u4EBA\uFF0C\u5E76\u628A\u8FDE\u63A5\u51ED\u636E\u5B89\u5168\u4EA4\u7ED9\u672C\u673A Harness Host\u3002":"Tencent will create or connect a QQ bot and securely deliver its credentials to the local Harness Host.","\u4F01\u4E1A\u5FAE\u4FE1\u5B98\u65B9\u9875\u9762\u4F1A\u521B\u5EFA\u4E00\u4E2A\u667A\u80FD\u673A\u5668\u4EBA\uFF0C\u5E76\u628A\u8FDE\u63A5\u51ED\u636E\u5B89\u5168\u4EA4\u7ED9\u672C\u673A Harness Host\u3002":"WeCom will create an AI bot and securely deliver its credentials to the local Harness Host.","\u4ECE\u6B64 Harness \u79FB\u9664\u8FD9\u4E2A\u5FAE\u4FE1\u8D26\u53F7\uFF1F":"Remove this WeChat account from Harness?","\u8FD9\u4F1A\u505C\u6B62\u6D88\u606F\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u672C\u673A\u4FDD\u5B58\u7684 bot_token\u3001\u8D26\u53F7\u914D\u7F6E\u548C\u4F1A\u8BDD\u6620\u5C04\u3002\u5176\u4ED6\u5FAE\u4FE1\u8D26\u53F7\u4E0D\u53D7\u5F71\u54CD\u3002":"This stops the message connection and removes the locally stored bot_token, account configuration, and session mappings. Other WeChat accounts are not affected.","\u6B64\u64CD\u4F5C\u4F1A\u505C\u6B62\u8FD9\u4E2A\u673A\u5668\u4EBA\u7684\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u4FDD\u5B58\u5728\u672C\u673A\u7684\u63A5\u5165\u914D\u7F6E\u548C\u51ED\u636E\u3002\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u4E2D\u7684\u5E94\u7528\u4E0D\u4F1A\u88AB\u81EA\u52A8\u5220\u9664\uFF0C\u5176\u4ED6\u673A\u5668\u4EBA\u4E5F\u4E0D\u53D7\u5F71\u54CD\u3002":"This stops the bot connection and removes the locally stored configuration and credentials. The app in Feishu Open Platform is not deleted, and other bots are not affected.","\u8FD9\u4F1A\u505C\u6B62\u6D88\u606F\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u672C\u673A\u4FDD\u5B58\u7684\u5E94\u7528\u51ED\u636E\u3001\u673A\u5668\u4EBA\u914D\u7F6E\u53CA\u4F1A\u8BDD\u6620\u5C04\u3002\u9489\u9489\u5F00\u653E\u5E73\u53F0\u4E2D\u7684\u673A\u5668\u4EBA\u4E0D\u4F1A\u88AB\u81EA\u52A8\u5220\u9664\u3002":"This stops the message connection and removes the locally stored app credentials, bot configuration, and session mappings. The bot in DingTalk Open Platform is not deleted.","\u8FD9\u4F1A\u505C\u6B62\u6D88\u606F\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u672C\u673A\u4FDD\u5B58\u7684\u5E94\u7528\u51ED\u636E\u3001\u673A\u5668\u4EBA\u914D\u7F6E\u53CA\u4F1A\u8BDD\u6620\u5C04\u3002\u4F01\u4E1A\u5FAE\u4FE1\u5E73\u53F0\u4E2D\u7684\u673A\u5668\u4EBA\u4E0D\u4F1A\u88AB\u81EA\u52A8\u5220\u9664\u3002":"This stops the message connection and removes the locally stored app credentials, bot configuration, and session mappings. The bot in WeCom is not deleted.","\u8FD9\u4F1A\u505C\u6B62\u6D88\u606F\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u672C\u673A\u4FDD\u5B58\u7684\u5E94\u7528\u51ED\u636E\u3001\u673A\u5668\u4EBA\u914D\u7F6E\u53CA\u4F1A\u8BDD\u6620\u5C04\u3002\u817E\u8BAF\u5E73\u53F0\u4E2D\u7684\u673A\u5668\u4EBA\u4E0D\u4F1A\u88AB\u81EA\u52A8\u5220\u9664\u3002":"This stops the message connection and removes the locally stored app credentials, bot configuration, and session mappings. The bot on Tencent\u2019s platform is not deleted.","\u8FD9\u4F1A\u505C\u6B62\u6D88\u606F\u8FDE\u63A5\uFF0C\u5E76\u5220\u9664\u672C\u673A\u4FDD\u5B58\u7684 WhatsApp \u5173\u8054\u8BBE\u5907\u548C\u4F1A\u8BDD\u6620\u5C04\u3002":"This stops the message connection and removes the locally stored WhatsApp linked device and session mappings.",\u6B63\u5728\u8BFB\u53D6\u98DE\u4E66\u673A\u5668\u4EBA\u5217\u8868:"Loading Feishu bots","\u6B63\u5728\u8BFB\u53D6\u98DE\u4E66\u8FDE\u63A5\u72B6\u6001\u2026":"Loading Feishu connection status\u2026","\u6B63\u5728\u8BFB\u53D6\u5FAE\u4FE1\u8FDE\u63A5\u72B6\u6001\u2026":"Loading WeChat connection status\u2026","\u6B63\u5728\u8BFB\u53D6\u9489\u9489\u8FDE\u63A5\u72B6\u6001\u2026":"Loading DingTalk connection status\u2026","\u901A\u8FC7\u626B\u7801\u628A\u9489\u9489\u673A\u5668\u4EBA\u63A5\u5165 DeepSeek Harness":"Connect a DingTalk bot to DeepSeek Harness by QR code",\u9489\u9489\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u7ED1\u5B9A\u8FDB\u5EA6:"DingTalk did not return QR setup progress",\u9489\u9489\u626B\u7801\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u7ED1\u5B9A\u4EFB\u52A1:"DingTalk did not return a valid setup attempt","\u9489\u9489 Stream \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38":"DingTalk Stream connection is healthy",\u9489\u9489\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u673A\u5668\u4EBA\u5217\u8868:"DingTalk did not return a valid bot list","${totals.connected} / ${totals.configured} \u5728\u7EBF":"${totals.connected} / ${totals.configured} online","\u7528\u4E8E\u628A\u9489\u9489\u673A\u5668\u4EBA\u63A5\u5165 DeepSeek Harness \u7684\u4E00\u6B21\u6027\u4E8C\u7EF4\u7801":"One-time QR code for connecting a DingTalk bot to DeepSeek Harness","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\\n\u8BF7\u91CD\u65B0\u751F\u6210":"QR code expired\\nGenerate a new one","\u673A\u5668\u4EBA\u5DF2\u521B\u5EFA\uFF0C\u6B63\u5728\u5EFA\u7ACB\u6D88\u606F\u8FDE\u63A5":"Bot created. Starting the message connection",\u9489\u9489\u626B\u7801\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u5B89\u5168\u7684\u4E8C\u7EF4\u7801:"DingTalk did not return a secure QR code","\u9489\u9489\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u4F7F\u7528\u9489\u9489 App \u626B\u63CF\u3002":"DingTalk QR code generated. Scan it with the DingTalk app.","\u9489\u9489\u673A\u5668\u4EBA\u51ED\u636E\u5DF2\u7ED1\u5B9A\u3002":"DingTalk bot credentials connected.","\u5DF2\u53D6\u6D88\u9489\u9489\u673A\u5668\u4EBA\u63A5\u5165\u3002":"DingTalk bot setup cancelled.","\u9489\u9489\u673A\u5668\u4EBA\u53CA\u672C\u673A\u51ED\u636E\u5DF2\u79FB\u9664\u3002":"DingTalk bot and local credentials removed.",\u98DE\u4E66\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4FE1\u606F:"Feishu did not return QR code information",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u7684\u4E8C\u7EF4\u7801\u4FE1\u606F\u4E0D\u5B8C\u6574:"Feishu returned incomplete QR code information",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u673A\u5668\u4EBA\u72B6\u6001:"Feishu returned an invalid bot status","\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u7684\u673A\u5668\u4EBA\u7F3A\u5C11 botId":"The Feishu bot is missing botId",\u98DE\u4E66\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u8FDE\u63A5\u72B6\u6001:"Feishu did not return connection status",\u98DE\u4E66\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u521B\u5EFA\u8FDB\u5EA6:"Feishu did not return creation progress",\u98DE\u4E66\u670D\u52A1\u8FD4\u56DE\u4E86\u672A\u77E5\u7684\u521B\u5EFA\u72B6\u6001:"Feishu returned an unknown creation status","\u5DF2\u63A5\u5165 ${totals.configured} \u4E2A\u673A\u5668\u4EBA\uFF0C\u5176\u4E2D ${totals.connected} \u4E2A\u5728\u7EBF":"${totals.connected} of ${totals.configured} bots online",\u5C1A\u672A\u63A5\u5165\u673A\u5668\u4EBA:"No bot connected yet","\u7528\u4E8E\u65B0\u589E DeepSeek Harness \u98DE\u4E66\u673A\u5668\u4EBA\u7684\u4E00\u6B21\u6027\u6388\u6743\u4E8C\u7EF4\u7801":"One-time authorization QR code for adding a Feishu bot to DeepSeek Harness",\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u626B\u7801:"Refresh and scan again",'${connected ? "\u68C0\u67E5\u8FDE\u63A5" : "\u91CD\u8BD5\u8FDE\u63A5"}${bot.name}':'${connected ? "Check connection" : "Reconnect"} ${bot.name}',\u65E0\u6CD5\u8BFB\u53D6\u98DE\u4E66\u673A\u5668\u4EBA:"Could not load Feishu bots","\u6388\u6743\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u4F7F\u7528\u98DE\u4E66\u626B\u7801\u3002":"Authorization QR code generated. Scan it with Feishu.","\u98DE\u4E66\u673A\u5668\u4EBA\u51ED\u636E\u5DF2\u7ED1\u5B9A\u3002":"Feishu bot credentials connected.","\u5DF2\u53D6\u6D88\u6DFB\u52A0\u673A\u5668\u4EBA\u3002":"Adding the bot was cancelled.","${newBot.bot.name}\u5DF2\u8FDE\u63A5\uFF0C\u53EF\u4EE5\u5728\u98DE\u4E66\u4E2D\u5F00\u59CB\u804A\u5929\u3002":"${newBot.bot.name} is connected and ready to chat in Feishu.","${bot.name}\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u67E5\u770B\u673A\u5668\u4EBA\u72B6\u6001\u3002":"${bot.name} operation failed. Check the bot status.","${bot.name}\u5DF2\u4ECE\u6B64 DeepSeek Harness \u79FB\u9664\uFF1B\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u4E2D\u7684\u5E94\u7528\u672A\u88AB\u5220\u9664\u3002":"${bot.name} was removed from this DeepSeek Harness. The app in Feishu Open Platform was not deleted.",\u65E0\u6CD5\u8BFB\u53D6\u8FDE\u63A5\u72B6\u6001:"Could not load connection status","QQ \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u7ED1\u5B9A\u8FDB\u5EA6":"QQ did not return QR setup progress","QQ \u626B\u7801\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u7ED1\u5B9A\u4EFB\u52A1":"QQ did not return a valid setup attempt","QQ WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38":"QQ WebSocket connection is healthy","QQ \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002":"The QQ connection is not ready; the plugin will retry automatically.","QQ \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"The QQ connection is not ready; the plugin will retry automatically","QQ \u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF":"The QQ connection is currently offline","QQ \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u673A\u5668\u4EBA\u5217\u8868":"QQ did not return a valid bot list","\u5C1A\u672A\u7ED1\u5B9A QQ \u673A\u5668\u4EBA":"No QQ bot connected yet","\u7528\u4E8E\u7ED1\u5B9A QQ \u673A\u5668\u4EBA\u7684\u4E00\u6B21\u6027\u4E8C\u7EF4\u7801":"One-time QR code for connecting a QQ bot","${channel}${connectionSummary}\u8FD0\u884C\u6B63\u5E38":"${channel}${connectionSummary} is healthy","${channel} \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u673A\u5668\u4EBA\u5217\u8868":"${channel} did not return a valid bot list","\u4F7F\u7528 Bot Token \u63A5\u5165 ${channel} \u673A\u5668\u4EBA":"Connect a ${channel} bot with a Bot Token","${model.totals.connected} / ${model.totals.configured} \u5728\u7EBF":"${model.totals.connected}/${model.totals.configured} online"," Bot API \u957F\u8F6E\u8BE2":" Bot API long polling",\u4F01\u4E1A\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u7ED1\u5B9A\u8FDB\u5EA6:"WeCom did not return QR setup progress",\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u7ED1\u5B9A\u4EFB\u52A1:"WeCom did not return a valid setup attempt","\u4F01\u4E1A\u5FAE\u4FE1 WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38":"WeCom WebSocket connection is healthy",\u4F01\u4E1A\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u673A\u5668\u4EBA\u5217\u8868:"WeCom did not return a valid bot list",\u5C1A\u672A\u7ED1\u5B9A\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"No WeCom bot connected yet",\u7528\u4E8E\u7ED1\u5B9A\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u7684\u4E00\u6B21\u6027\u4E8C\u7EF4\u7801:"One-time QR code for connecting a WeCom bot",\u5FAE\u4FE1\u626B\u7801\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u7ED1\u5B9A\u4EFB\u52A1:"WeChat did not return a valid setup attempt",\u5FAE\u4FE1\u7ED1\u5B9A\u6CA1\u6709\u5B8C\u6210:"WeChat setup did not complete",\u5FAE\u4FE1\u8FDE\u63A5\u6B63\u5E38:"WeChat connection is healthy",\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA:"WeChat connection is not ready","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u56FE\u7247\uFF0C\u8BF7\u7528 /models \u67E5\u770B\u53EF\u7528\u6A21\u578B\uFF0C\u518D\u7528 /model <\u5E8F\u53F7> \u5207\u6362\u540E\u91CD\u53D1\u3002":"The current model does not support images. Use /models to list models, then /model to switch and resend.","\u56FE\u7247\u8D85\u8FC7\u5BBF\u4E3B\u5141\u8BB8\u7684\u5927\u5C0F\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002":"The image exceeds the Host size limit. Compress it and try again.","\u56FE\u7247\u5206\u8FA8\u7387\u8FC7\u9AD8\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002":"The image resolution is too high. Compress it and try again.","\u56FE\u7247\u5185\u5BB9\u65E0\u6548\u6216\u683C\u5F0F\u4E0D\u53D7\u652F\u6301\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002":"The image is invalid or unsupported. Send it again.","\u672A\u80FD\u8BFB\u53D6\u56FE\u7247\u5185\u5BB9\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002":"The image could not be read. Send it again.","\u56FE\u7247\u683C\u5F0F\u4E0E\u5B9E\u9645\u5185\u5BB9\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002":"The declared image format does not match its content. Send it again.","\u4E00\u6B21\u53D1\u9001\u7684\u56FE\u7247\u6570\u91CF\u8D85\u8FC7\u5BBF\u4E3B\u9650\u5236\uFF0C\u8BF7\u51CF\u5C11\u540E\u91CD\u8BD5\u3002":"The message exceeds the Host image-count limit. Remove some images and try again.","\u56FE\u7247\u603B\u5927\u5C0F\u8D85\u8FC7\u5BBF\u4E3B\u9650\u5236\uFF0C\u8BF7\u51CF\u5C11\u56FE\u7247\u6216\u538B\u7F29\u540E\u91CD\u8BD5\u3002":"The images exceed the Host total-size limit. Remove or compress some images and try again.","\u56FE\u7247\u4E0B\u8F7D\u5730\u5740\u53D1\u751F\u4E86\u91CD\u5B9A\u5411\uFF0C\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u3002":"The image download redirected and cannot be read.","\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002":"The image exceeds 5 MB. Compress it and try again.","\u4E00\u6B21\u53D1\u9001\u7684\u56FE\u7247\u603B\u5927\u5C0F\u8FC7\u5927\uFF0C\u8BF7\u51CF\u5C11\u56FE\u7247\u6570\u91CF\u6216\u538B\u7F29\u540E\u91CD\u8BD5\u3002":"The images are too large in total. Remove or compress some images and try again.","\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002":"The image download failed. Send it again.","\u6682\u4E0D\u652F\u6301\u8BE5\u56FE\u7247\u683C\u5F0F\uFF0C\u8BF7\u53D1\u9001 JPEG\u3001PNG\u3001WebP \u6216 GIF \u56FE\u7247\u3002":"This image format is unsupported. Send a JPEG, PNG, WebP, or GIF image.","\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Message processing failed. Try again later.",\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u8D26\u53F7\u5217\u8868:"WeChat did not return a valid account list",\u5C1A\u672A\u7ED1\u5B9A\u5FAE\u4FE1:"No WeChat account connected yet","\u7528\u4E8E\u628A\u5FAE\u4FE1\u673A\u5668\u4EBA\u7ED1\u5B9A\u5230 DeepSeek Harness \u7684\u4E00\u6B21\u6027\u4E8C\u7EF4\u7801":"One-time QR code for connecting a WeChat bot to DeepSeek Harness","\u4FDD\u6301\u672C\u9875\u6253\u5F00\uFF0C\u7B49\u5F85\u6D88\u606F\u957F\u8F6E\u8BE2\u53D8\u4E3A\u5728\u7EBF":"Keep this page open until long polling is online","\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u751F\u6210\uFF0C\u8BF7\u4F7F\u7528\u624B\u673A\u5FAE\u4FE1\u626B\u63CF\u3002":"WeChat QR code generated. Scan it with WeChat on your phone.","\u79FB\u9664\u5931\u8D25\uFF1A${presentError(error).message}":"Removal failed: ${presentError(error).message}",\u65E0\u6CD5\u8BFB\u53D6\u5FAE\u4FE1\u72B6\u6001:"Could not load WeChat status","WhatsApp \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u8FDB\u5EA6":"WhatsApp did not return QR setup progress","WhatsApp \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u626B\u7801\u4EFB\u52A1":"WhatsApp did not return a valid setup attempt","WhatsApp \u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u673A\u5668\u4EBA\u5217\u8868":"WhatsApp did not return a valid account list","\u7528\u4E8E\u5173\u8054 WhatsApp \u8BBE\u5907\u7684\u4E00\u6B21\u6027\u4E8C\u7EF4\u7801":"One-time QR code for linking a WhatsApp device",\u7528\u6237:"User","\u5FAE\u4FE1\u7528\u6237 ID":"WeChat user ID","\u586B\u5199\u63A5\u6536\u6D88\u606F\u7684\u7528\u6237 ID":"Enter the recipient user ID",\u79C1\u804A:"Direct message",\u7FA4\u804A:"Group","\u7FA4 Chat ID":"Group Chat ID","\u7528\u6237 ID":"User ID","\u586B\u5199\u9489\u9489\u7528\u6237 ID":"Enter the DingTalk user ID","\u7FA4 Open Conversation ID":"Group Open Conversation ID","\u586B\u5199\u4F01\u4E1A\u5FAE\u4FE1\u7528\u6237 ID":"Enter the WeCom user ID","\u586B\u5199\u7FA4 chatid":"Enter the group chatid",\u5355\u804A:"Direct message","\u7528\u6237 Open ID":"User Open ID","\u586B\u5199 user_openid":"Enter the user_openid","\u7FA4 Open ID":"Group Open ID","\u586B\u5199 group_openid":"Enter the group_openid",\u4F1A\u8BDD:"Conversation",\u7EBF\u7A0B:"Thread","Thread \u65F6\u95F4\u6233":"Thread timestamp",\u804A\u5929:"Chat",\u8BDD\u9898:"Topic",\u9891\u9053\u6216\u79C1\u4FE1:"Channel or DM","\u586B\u5199\u53EF\u53D1\u6D88\u606F\u7684 Channel ID":"Enter a Channel ID the bot can message","\u7528\u6237 JID":"User JID","\u7FA4 JID":"Group JID","\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Request failed. Try again later.","\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236\uFF0C\u8BF7\u624B\u52A8\u9009\u62E9\u590D\u5236\u3002":"Automatic copy is unavailable. Select and copy the value manually.","\u76EE\u6807\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5\u3002":"Could not save the target. Check it and try again.","\u65E0\u6CD5\u751F\u6210\u672A\u5360\u7528\u7684 Target ID\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not generate an unused Target ID. Try again.",\u7F16\u8F91\u6295\u9012\u76EE\u6807:"Edit delivery target",\u65B0\u5EFA\u6295\u9012\u76EE\u6807:"New delivery target","\u5DF2\u4ECE\u4F1A\u8BDD\u81EA\u52A8\u586B\u5165\u76EE\u6807\u4FE1\u606F\uFF1B\u786E\u8BA4\u540E\u518D\u4FDD\u5B58\u3002":"Target details were filled from the conversation. Review them before saving.","\u8BF7\u624B\u52A8\u586B\u5199\u4ECE\u5BF9\u5E94\u5E73\u53F0\u53D6\u5F97\u7684\u539F\u751F\u6807\u8BC6\u3002":"Enter the native identifier from the platform manually.","\u4F8B\u5982 daily-report":"For example, daily-report","\u4F7F\u7528\u5927\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u5192\u53F7\u3001@ \u6216\u8FDE\u5B57\u7B26\u3002":"Use letters, numbers, dots, underscores, colons, @, or hyphens.","\u663E\u793A\u540D\u79F0\uFF08\u53EF\u9009\uFF09":"Display name (optional)","\u4F8B\u5982 \u6BCF\u65E5\u6C47\u62A5\u7FA4":"For example, Daily reports",\u76EE\u6807\u7C7B\u578B:"Target type",\u4FDD\u5B58\u76EE\u6807:"Save target",\u8BF7\u5148\u5B8C\u6210\u6295\u9012\u76EE\u6807\u8BFB\u53D6:"Wait for delivery targets to finish loading",\u4ECE\u5DF2\u804A\u8FC7\u7684\u4F1A\u8BDD\u9009\u62E9:"Choose from conversations",\u5DF2\u804A\u4F1A\u8BDD:"Conversation",\u4ECE\u4F1A\u8BDD\u9009\u62E9targetID:"Select a targetID from conversations","\u9009\u62E9\u540E\u4F1A\u81EA\u52A8\u586B\u5199\u76EE\u6807\u4FE1\u606F\u548C\u8C03\u7528\u522B\u540D\uFF0C\u786E\u8BA4\u540E\u518D\u4FDD\u5B58\u3002":"Selecting a conversation fills the target details and call alias. Review them before saving.","\u6B63\u5728\u5237\u65B0\u2026":"Refreshing\u2026",\u5237\u65B0:"Refresh","\u6B63\u5728\u8BFB\u53D6\u5DF2\u804A\u4F1A\u8BDD\u2026":"Loading known conversations\u2026","\u65E0\u6CD5\u8BFB\u53D6\u5DF2\u804A\u4F1A\u8BDD\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Could not load known conversations. Try again later.",\u8FD8\u6CA1\u6709\u53EF\u9009\u62E9\u7684\u4F1A\u8BDD:"No conversations to choose from","\u5148\u5728\u5BF9\u5E94\u5E73\u53F0\u4E0E\u673A\u5668\u4EBA\u804A\u4E00\u6761\u6D88\u606F\uFF0C\u518D\u5237\u65B0\u3002":"Send the bot a message on the platform, then refresh.",\u5DF2\u6DFB\u52A0:"Added","\u624B\u52A8\u586B\u5199\uFF08\u9AD8\u7EA7\uFF09":"Enter manually (advanced)","\u6D4B\u8BD5\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u8BF7\u5230\u76EE\u6807\u4F1A\u8BDD\u786E\u8BA4\u3002":"Test message sent. Confirm it in the target conversation.","\u6D4B\u8BD5\u53D1\u9001\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Test delivery failed. Try again later.",\u5DF2\u590D\u5236\u8C03\u7528\u53C2\u6570:"Call parameters copied","\u590D\u5236\u5931\u8D25\u3002":"Copy failed.","\u5220\u9664\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Could not delete the target. Try again later.",\u590D\u5236\u8C03\u7528\u53C2\u6570:"Copy call parameters",\u673A\u5668\u4EBA\u79BB\u7EBF\u65F6\u4E0D\u53EF\u53D1\u9001\u6D4B\u8BD5\u6D88\u606F:"Test delivery is unavailable while the bot is offline",\u6D4B\u8BD5\u6295\u9012\u76EE\u6807:"Test delivery target",\u6D4B\u8BD5:"Test",\u7F16\u8F91:"Edit",\u5220\u9664:"Delete","\u5220\u9664 ":"Delete ","\uFF1F\u4F7F\u7528\u8FD9\u4E2A targetId \u7684\u5916\u90E8\u8C03\u7528\u5C06\u8FD4\u56DE unknown-target\u3002":"? External calls using this targetId will return unknown-target.","\u6B63\u5728\u5220\u9664\u2026":"Deleting\u2026",\u786E\u8BA4\u5220\u9664:"Delete target","\u6295\u9012\u76EE\u6807\u8BBE\u7F6E\u6682\u4E0D\u53EF\u7528\u3002":"Delivery target settings are unavailable.","\u65E0\u6CD5\u8BFB\u53D6\u6295\u9012\u76EE\u6807\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Could not load delivery targets. Try again later.","\u2190 \u8FD4\u56DE\u673A\u5668\u4EBA\u5217\u8868":"\u2190 Back to bots",\u4F7F\u7528\u6587\u6863:"User guide",\u6253\u5F00\u4E3B\u52A8\u6295\u9012\u4F7F\u7528\u6587\u6863:"Open the proactive delivery guide","\u5F53\u524D\u6E20\u9053\u6682\u4E0D\u652F\u6301\u6295\u9012\u76EE\u6807\u3002":"Delivery targets are not supported for this channel.","\u5DF2\u590D\u5236 Bot ID":"Bot ID copied",\u590D\u5236:"Copy",\u6295\u9012\u76EE\u6807:"Delivery targets","\u673A\u5668\u4EBA\u5F53\u524D\u79BB\u7EBF\uFF1B\u4ECD\u53EF\u914D\u7F6E\u76EE\u6807\uFF0C\u6062\u590D\u8FDE\u63A5\u540E\u518D\u6D4B\u8BD5\u3002":"The bot is offline. You can still configure targets and test them after reconnection.",\u65B0\u5EFA\u76EE\u6807:"New target","\u6B63\u5728\u8BFB\u53D6\u6295\u9012\u76EE\u6807\u2026":"Loading delivery targets\u2026",\u5C1A\u672A\u914D\u7F6E\u6295\u9012\u76EE\u6807:"No delivery targets yet","\u70B9\u51FB\u201C\u65B0\u5EFA\u76EE\u6807\u201D\u53EF\u4ECE\u5DF2\u804A\u8FC7\u7684\u4F1A\u8BDD\u9009\u62E9\uFF0C\u4E5F\u53EF\u624B\u52A8\u586B\u5199\u3002":"Select New target to choose a conversation or enter the details manually."});var KIA=Object.freeze(Object.fromEntries(Object.keys(ave).map(n=>[n,n==="$locale"?"zh":n])));var xIA=Object.freeze(["aria-label","alt","placeholder","title"]);var ive=Object.freeze({defaultId:"",items:Object.freeze([])}),qIA=vd.createContext(ive);var dP="/feishu",bt=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",beginCallbackRepair:"bot.callback-repair.begin",beginGroupMessagePermission:"bot.group-message-permission.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",disconnectBot:"bot.disconnect",deleteBot:"bot.delete",setWorkspace:"bot.workspace.set",setAgentPreset:"bot.preset.set",setContextEnhancement:"bot.context-enhancement.set",setGroupResponseMode:"bot.group-response-mode.set",testConnection:"connection.test",disconnect:"connection.disconnect"}),tlA=Object.freeze({PROVISION:"provision",CALLBACK_REPAIR:"callback_repair",GROUP_MESSAGE_PERMISSION:"group_message_permission"});var sl=Object.freeze({reconnectBot:"bot.reconnect",disconnectBot:"bot.disconnect",deleteBot:"bot.delete"}),z6=Object.freeze([...new Set([...Object.values(bt),...Object.values(sl)])]),nve=new Set(["idle","starting","qr_ready","polling","slow_down","domain_switched","saving","succeeded","expired","cancelled","error"]),sve=new Set(["provision","callback_repair","group_message_permission"]),V6="callback_repair",EP="group_message_permission",wS=new Set([V6,EP]),gve=new Set(["accounts.feishu.cn","accounts.larksuite.com","open.feishu.cn","open.larksuite.com"]),cve=/^[A-Za-z0-9_-]{1,128}$/,Ive=/^cli_[A-Za-z0-9_-]+$/,Y6=Object.freeze({abort:"Registration was cancelled.",access_denied:"Registration was denied.",expired_token:"The registration QR code expired.",invalid_credentials:"Feishu returned invalid app credentials.",credentials_callback_failed:"Unable to activate the Feishu connection.",registration_failed:"Unable to register the Feishu app.",connection_failed:"The bot was created, but its connection could not be started.",credential_removal_failed:"Unable to remove the Feishu credentials.",state_cleanup_failed:"Unable to remove the bot session data. Please retry.",deletion_pending:"Bot deletion is incomplete. Retry removal to finish cleanup.",missing_credentials:"The bot credentials are missing. Delete it and scan again.",repair_app_mismatch:"The authorized Feishu app does not match the selected bot.",repair_owner_missing:"Feishu did not return the authorizing account identity.",repair_domain_mismatch:"The authorized Feishu tenant does not match the selected bot.",repair_owner_mismatch:"The authorizing Feishu account is not an owner of the selected bot.",repair_credentials_invalid:"Feishu returned credentials that could not be verified for the selected bot.",repair_bot_mismatch:"The verified Feishu bot does not match the selected bot.",repair_target_changed:"The selected bot changed while repair was in progress. Start the repair again.",credential_update_failed:"Unable to store the repaired Feishu credentials.",credential_state_unknown:"The repaired Feishu credentials could not be confirmed after saving.",repair_connection_failed:"The callback update was accepted, but the selected bot could not reconnect.",group_message_permission_required:"Authorize access to all group messages before enabling this mode.",group_message_permission_save_failed:"Feishu granted the permission, but all-message mode could not be saved.",group_message_permission_connection_failed:"Feishu granted the permission, but the selected bot could not reconnect.",card_action_probe_unavailable:"The selected bot is not connected, so its card button cannot be verified.",card_action_probe_send_failed:"The callback update was accepted, but the verification card could not be sent.",card_action_probe_timeout:"Feishu accepted the update, but the card button was not verified in time. Start the repair again and click the test button within two minutes.",card_action_probe_failed:"Feishu accepted the update, but the card button verification failed."}),lve=Object.freeze({idle:"pending",starting:"pending",qr_ready:"pending",polling:"pending",slow_down:"pending",domain_switched:"pending",saving:"connecting",succeeded:"connected",expired:"expired",cancelled:"failed",error:"failed"});function pve(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}function Fo(n,t){return pve(n)&&Reflect.ownKeys(n).every(o=>typeof o=="string"&&t.has(o))}function Mu(n){return Number.isFinite(n)?n:void 0}function mn(n){return typeof n=="string"&&cve.test(n)}function j6(n,t){return typeof n=="string"&&n.trim().length>0&&n.length<=t}function uP(n){if(!n||typeof n!="object")return null;let t=typeof n.code=="string"&&Object.hasOwn(Y6,n.code)?n.code:"registration_failed";return{code:t,message:Y6[t]}}function ds(n){if(!n||typeof n!="object")return{state:"idle",attempt:0};let t=nve.has(n.state)?n.state:"error",o=mn(n.attempt)?n.attempt:Mu(n.attempt)??0,i={state:t,attempt:o};i.operation=sve.has(n.operation)?n.operation:"provision";let e=Mu(n.updatedAt),a=Mu(n.expiresAt),A=Mu(n.remainingSeconds),r=Mu(n.pollIntervalSeconds);e!==void 0&&(i.updatedAt=e),typeof n.qrCodeUrl=="string"&&n.qrCodeUrl.length>0&&(i.qrCodeUrl=n.qrCodeUrl),a!==void 0&&(i.expiresAt=a),A!==void 0&&(i.remainingSeconds=A),r!==void 0&&(i.pollIntervalSeconds=r),mn(n.botId)&&(i.botId=n.botId);let s=uP(n.error);return s&&(i.error=s),i}function dve(n,t,o){if(!(typeof n!="string"||n.length===0))try{let i=new URL(n);if(i.protocol!=="https:"||!gve.has(i.hostname)||i.port||i.username||i.password)return;if(wS.has(t)){let e=i.searchParams.getAll("clientID"),a=i.searchParams.getAll("tp"),A=i.searchParams.getAll("addons"),r=[...i.searchParams.values()].some(s=>s.includes("{{")||s.includes("}}"));if(e.length!==1||a.length!==1||a[0]!=="sdk"||!Ive.test(e[0]??"")||i.hostname!==o||i.searchParams.has("createOnly")||A.length!==1||!A[0]?.trim()||r)return}return i.toString()}catch{return}}function DS(n){let t=n&&typeof n=="object"?n:{};return{connected:t.connected===!0||t.ready===!0&&t.feishuLongConnectionState==="connected"&&t.harnessReachable===!0,ready:t.ready===!0,harnessReachable:t.harnessReachable===!0}}function W6(n){let t=n&&typeof n=="object"?n:{},o={name:typeof t.name=="string"&&t.name.length>0?t.name:"\u98DE\u4E66\u673A\u5668\u4EBA"};return typeof t.avatarUrl=="string"&&(o.avatarUrl=t.avatarUrl),typeof t.appIdMasked=="string"&&(o.appIdMasked=t.appIdMasked),typeof t.tenantName=="string"&&(o.tenantName=t.tenantName),(t.domain==="feishu"||t.domain==="lark")&&(o.domain=t.domain),(typeof t.activated=="boolean"||typeof t.activated=="number")&&(o.activated=t.activated),o}function Z6(n,t){return t?{status:"healthy",summary:"\u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38",lastCheckedAt:Date.now()}:n?.configured===!0?{status:"offline",summary:"\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5",lastCheckedAt:Date.now()}:{status:"offline",summary:"\u5C1A\u672A\u63A5\u5165\u98DE\u4E66\u673A\u5668\u4EBA",lastCheckedAt:Date.now()}}function X6(n,t,o){return o?"connected":n?.phase==="error"||t.state==="error"?"error":n?.phase==="connecting"||t.state==="saving"?"connecting":n?.phase==="registering"||["starting","qr_ready","polling","slow_down","domain_switched"].includes(t.state)?"provisioning":"disconnected"}async function $6(n){return ove.toDataURL(n,{errorCorrectionLevel:"M",margin:1,width:320,type:"image/png"})}async function hve(n,t,o){let i=dve(n.qrCodeUrl,n.operation,o),e={attemptId:String(n.attempt),operation:n.operation,...n.botId?{botId:n.botId}:{},expiresAt:n.expiresAt??Date.now()+5*6e4,pollIntervalMs:Math.max(800,Math.min(1e4,(n.pollIntervalSeconds??1.8)*1e3))};if(i)return{...e,verificationUrl:i,qrCodeDataUrl:await t(i)};if(n.state==="saving"&&wS.has(n.operation)&&n.botId)return{...e,submitted:!0}}function Eve(n){let t=n&&typeof n=="object"?n:{};if(!mn(t.botId))return null;let o=DS(t.connection),i=t.connected===!0||o.connected,e={state:"idle"},a={botId:t.botId,state:X6(t,e,i),connected:i,configured:t.configured===!0,agentPreset:eg(t.agentPreset),contextEnhancement:Sp(t.contextEnhancement),groupResponseMode:ao(t.groupResponseMode),groupMessagePermissionGranted:t.groupMessagePermissionGranted===!0,bot:W6(t.bot),health:Z6(t,i)};typeof t.workspace=="string"&&t.workspace&&(a.workspace=t.workspace);let A=Vr(t.lastMessageError);A&&(a.lastMessageError=A);let r=uP(t.error);return r&&(a.error=r),a}async function Wa(n,{encodeQr:t=$6}={}){let o=n&&typeof n=="object"?n:{},i=ds(o.registration),e=DS(o.connection),a=o.connected===!0||e.connected,r=(wS.has(i.operation)&&i.botId&&Array.isArray(o.bots)?o.bots.find(d=>d?.botId===i.botId):void 0)?.bot?.domain==="lark"?"open.larksuite.com":"open.feishu.cn",s=await hve(i,t,r),g=uP(o.error)??i.error??null,c=Array.isArray(o.bots)?o.bots.map(Eve).filter(Boolean):[],I={schemaVersion:o.schemaVersion===2?2:1,revision:Number.isSafeInteger(o.revision)&&o.revision>=0?o.revision:0,state:X6(o,i,a),connected:a,configured:o.configured===!0,bot:W6(o.bot),health:Z6(o,a),bots:c,agentPresetCatalog:Jn(o.agentPresetCatalog),totals:{configured:c.length||(o.configured===!0?1:0),connected:c.length?c.filter(d=>d.connected).length:a?1:0}};return s&&(I.provisioning=s),g&&(I.error=g),I}function mS(n){return{ok:!1,error:{code:"bad-request",message:n,details:{issues:[]}}}}function SS(){return{ok:!1,error:{code:"cancelled",message:"The Feishu request was cancelled.",details:{}}}}function Cve(){return{ok:!1,error:{code:"internal",message:"The Feishu integration operation failed.",details:{}}}}function uve(n,t){return n===bt.status?Fo(t,new Set)?null:"This endpoint accepts an empty payload only.":n===bt.testConnection?Fo(t,new Set)?null:"This endpoint accepts an empty payload only.":n===bt.beginProvisioning?Fo(t,new Set(["locale","replaceAttemptId"]))?t.locale!==void 0&&t.locale!=="zh-CN"?"The provisioning locale must be zh-CN.":t.replaceAttemptId!==void 0&&!mn(t.replaceAttemptId)?"replaceAttemptId must be a valid opaque id.":null:"Provisioning accepts locale and replaceAttemptId only.":n===bt.beginCallbackRepair?Fo(t,new Set(["botId"]))&&mn(t.botId)?null:"Callback repair requires a single valid botId.":n===bt.beginGroupMessagePermission?Fo(t,new Set(["botId"]))&&mn(t.botId)?null:"Group message permission update requires a single valid botId.":n===bt.bindCredentials?Fo(t,new Set(["appId","appSecret"]))&&j6(t.appId,256)&&j6(t.appSecret,1024)?null:"Credential binding requires App ID and App Secret.":n===bt.pollProvisioning||n===bt.cancelProvisioning?Fo(t,new Set(["attemptId"]))&&mn(t.attemptId)?null:"A single valid attemptId is required.":n===bt.disconnect?Fo(t,new Set(["removeCredentials"]))&&t.removeCredentials===!0?null:"Disconnect requires removeCredentials=true.":n===sl.reconnectBot?Fo(t,new Set(["botId","sendTest"]))&&mn(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"A valid botId and optional sendTest flag are required.":n===sl.disconnectBot?Fo(t,new Set(["botId"]))&&mn(t.botId)?null:"A single valid botId is required.":n===sl.deleteBot?Fo(t,new Set(["botId","confirm"]))&&mn(t.botId)&&t.confirm===!0?null:"Deleting a bot requires a valid botId and confirm=true.":n===bt.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===bt.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===bt.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":n===bt.setGroupResponseMode?Fo(t,new Set(["botId","groupResponseMode"]))&&mn(t.botId)&&Xm(t.groupResponseMode)?null:"\u8BF7\u9009\u62E9\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F\u3002":"Unknown Feishu endpoint."}function Bve(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new Error("aborted"));return}let e=setTimeout(a,n);e.unref?.();function a(){t?.removeEventListener("abort",A),o()}function A(){clearTimeout(e),i(t.reason??new Error("aborted"))}t?.addEventListener("abort",A,{once:!0})})}async function CP(n,t){return typeof n.registrationStatus=="function"?n.registrationStatus(t):n.status()}async function hP(n,t,o,i){let e=t,a=Date.now()+15e3;for(;;){let A=ds(e?.registration);if(A.qrCodeUrl)return e;if(["error","expired","cancelled"].includes(A.state))throw new Error("Provisioning stopped before the QR code was ready.");if(Date.now()>=a)throw new Error("Provisioning QR code timed out.");if(await Bve(50,i),e=await CP(n,o),!e)throw new Error("The provisioning attempt is no longer active.")}}function J6(n,t){return String(ds(n?.registration).attempt)===t}function q6(n){let t=ds(n?.registration);return t.state==="succeeded"?t.botId&&(n?.connected===!0||DS(n?.connection).connected)?"connected":"connecting":lve[t.state]??"failed"}function fve(n){if(!n||typeof n.status!="function"||typeof n.startRegistration!="function"||typeof n.cancelRegistration!="function"||typeof n.disconnect!="function")throw new TypeError("A Feishu controller with status/start/cancel/disconnect is required")}function e5(n,{encodeQr:t=$6}={}){fve(n);let o=new Map,i=new Map,e=a=>{let A=o.get(a);return A||(o.size>=32&&o.delete(o.keys().next().value),A=Promise.resolve().then(()=>t(a)),o.set(a,A)),A};return async(a,A,r)=>{if(r?.aborted)return SS();if(!z6.includes(a))return mS("Unknown Feishu endpoint.");let s=uve(a,A);if(s)return mS(s);try{let g;if(a===bt.status)g=await Wa(await n.status(),{encodeQr:e});else if(a===bt.beginProvisioning){A.replaceAttemptId&&await n.cancelRegistration(A.replaceAttemptId);let c=await n.startRegistration({locale:A.locale}),I=String(ds(c?.registration).attempt),d=await hP(n,c,I,r);if(g=(await Wa(d,{encodeQr:e})).provisioning,!g)throw new Error("Provisioning did not produce a QR code.");i.set(I,g.verificationUrl)}else if(a===bt.beginCallbackRepair){if(typeof n.startCallbackRepair!="function")throw new Error("Feishu callback repair is unavailable.");let c=await n.startCallbackRepair(A.botId),I=String(ds(c?.registration).attempt),d=await hP(n,c,I,r);if(g=(await Wa(d,{encodeQr:e})).provisioning,!g||g.operation!==V6||g.botId!==A.botId)throw new Error("Callback repair did not produce a safe QR code.");i.set(I,g.verificationUrl)}else if(a===bt.beginGroupMessagePermission){if(typeof n.startGroupMessagePermission!="function")throw new Error("Feishu group message permission update is unavailable.");let c=await n.startGroupMessagePermission(A.botId),I=String(ds(c?.registration).attempt),d=await hP(n,c,I,r);if(g=(await Wa(d,{encodeQr:e})).provisioning,!g||g.operation!==EP||g.botId!==A.botId)throw new Error("Group message permission update did not produce a safe QR code.");i.set(I,g.verificationUrl)}else if(a===bt.pollProvisioning){let c=await CP(n,A.attemptId);if(!c||!J6(c,A.attemptId))return mS("The provisioning attempt is no longer active.");let I=ds(c.registration),d=await Wa(c,{encodeQr:e});if(g={status:q6(c),operation:I.operation,...I.botId?{botId:I.botId}:{},...d.provisioning?{provisioning:d.provisioning}:{},...I.botId&&d.connected?{connection:d}:{},...d.error?{message:d.error.message}:{}},["connected","expired","failed"].includes(g.status)){let B=i.get(A.attemptId);B&&o.delete(B),i.delete(A.attemptId)}}else if(a===bt.cancelProvisioning){let c=await CP(n,A.attemptId);if(!c||!J6(c,A.attemptId))return mS("The provisioning attempt is no longer active.");let I=typeof n.registrationStatus=="function",d=ds(c.registration),B;!I&&d.state==="saving"?B=await n.disconnect():B=await n.cancelRegistration(A.attemptId);let f=ds(B?.registration);if(wS.has(d.operation)&&d.state==="saving"&&["saving","succeeded"].includes(f.state)&&(g={status:q6(B),operation:f.operation,...f.botId?{botId:f.botId}:{},message:d.operation===EP?"The permission update was already submitted and is still being applied.":"Callback repair was already submitted and is still being verified."}),g?.status!=="connecting"){let Q=i.get(A.attemptId);Q&&o.delete(Q),i.delete(A.attemptId),g??={status:"failed",operation:d.operation,...d.botId?{botId:d.botId}:{},message:"Registration was cancelled."}}}else if(a===bt.bindCredentials){if(typeof n.bindCredentials!="function")throw new Error("Credential binding is unavailable");g=await Wa(await n.bindCredentials(A),{encodeQr:e})}else if(a===bt.testConnection){let c=await n.status(),d=c?.connected===!0||DS(c?.connection).connected||typeof n.reconnect!="function"?c:await n.reconnect();g=await Wa(d,{encodeQr:e})}else if(a===bt.disconnect)g=await Wa(await n.disconnect(),{encodeQr:e});else if(a===sl.reconnectBot){if(typeof n.reconnectBot!="function")throw new Error("Multi-bot reconnect is unavailable");let c=await n.reconnectBot(A.botId);if(r?.aborted)return SS();if(g=await Wa(c,{encodeQr:e}),A.sendTest===!0){let I=null;if(!(c?.bots?.some(B=>B?.botId===A.botId&&B.connected===!0)===!0))I=new Error("Feishu bot is not connected"),I.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let B=new Error("Connection test is unavailable");throw B.code="test-target-unavailable",B}await n.sendConnectionTest(A.botId)}catch(B){I=B}g={...g,testMessage:ir(I)}}}else if(a===sl.disconnectBot){if(typeof n.disconnectBot!="function")throw new Error("Multi-bot disconnect is unavailable");g=await Wa(await n.disconnectBot(A.botId),{encodeQr:e})}else if(a===bt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");g=await Wa(await n.updateWorkspace(A.botId,A.workspace),{encodeQr:e})}else if(a===bt.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");g=await n.updateContextEnhancement(A.botId,A.config,c=>Wa(c,{encodeQr:e}))}else if(a===bt.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");g=await Wa(await n.updateAgentPreset(A.botId,A.agentPreset),{encodeQr:e})}else if(a===bt.setGroupResponseMode){if(typeof n.updateGroupResponseMode!="function")throw new Error("Group response mode update is unavailable");g=await Wa(await n.updateGroupResponseMode(A.botId,A.groupResponseMode),{encodeQr:e})}else{if(typeof n.deleteBot!="function")throw new Error("Multi-bot delete is unavailable");g=await Wa(await n.deleteBot(A.botId),{encodeQr:e})}return r?.aborted?SS():{ok:!0,value:g}}catch(g){let c=Ya(g);return r?.aborted?SS():c?{ok:!1,error:{...c,details:{}}}:Cve()}}}function OS(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(dP,e5(t,o),{authority:hr(i)})}function Qve(n,t){if(t?.controller)return t.controller;if(typeof t?.createController=="function")return t.createController();if(typeof t?.createProvisioningManager=="function")return j_(t)}async function A5(n,t={}){let o=Qve(n,t);if(o)return OS(n,o,t.rpcOptions,t.rpcAuthority);let i=await oP(n,t),e=t.deliveryService&&i.deliveryAdapter?t.deliveryService.registerAdapter(i.deliveryAdapter):void 0,a=OS(n,i.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await e?.(),await i.close()},"dsh-feishu: close controller and live connection"),a}import{unlink as uPe}from"node:fs/promises";import{homedir as BPe}from"node:os";import{join as ku,resolve as Il}from"node:path";import{createHash as yve}from"node:crypto";import{mkdir as mve,readFile as Sve,rename as wve,unlink as Dve,writeFile as Ove}from"node:fs/promises";import{dirname as bve}from"node:path";var BP=Object.freeze({version:1,bots:Object.freeze([])});function bc(n){return typeof n=="string"&&n.trim()?n.trim():null}function t5(n){let t=bc(n);return t&&/^qq_[a-f0-9]{24}$/.test(t)?t:null}function Mve(n){let t=bc(n);return t&&/^DSH_QQBOT_APP_SECRET_[A-F0-9]{24}$/.test(t)?t:null}function MS(n){let t=bc(n);if(!t)throw new TypeError("appId is required");let o=yve("sha256").update(t).digest("hex").slice(0,24);return{botId:`qq_${o}`,secretRef:`DSH_QQBOT_APP_SECRET_${o.toUpperCase()}`}}function fP(n){let t=bc(n)??"";return t.length<=10?t?`${t.slice(0,3)}\u2022\u2022\u2022`:w("QQ\u673A\u5668\u4EBA"):`${t.slice(0,6)}\u2022\u2022\u2022\u2022${t.slice(-4)}`}function r5(n){if(!n||typeof n!="object")return null;let t=bc(n.appId),o=bc(n.ownerUserOpenid),i=t5(n.botId),e=Mve(n.secretRef);if(!t||!o||!i||!e)return null;let a=MS(t);return a.botId!==i||a.secretRef!==e?null:Object.freeze({botId:i,appId:t,secretRef:e,ownerUserOpenid:o,createdAt:bc(n.createdAt)??new Date().toISOString(),connectedAt:bc(n.connectedAt)})}function _ve(n){if(!n||n.version!==1||!Array.isArray(n.bots))return null;let t=n.bots.map(r5);if(t.some(a=>a===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of t){if(o.has(a.botId)||i.has(a.appId)||e.has(a.secretRef))return null;o.add(a.botId),i.add(a.appId),e.add(a.secretRef)}return Object.freeze({version:1,bots:Object.freeze(t)})}var bS=class{#e;#A=BP;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=_ve(JSON.parse(await Sve(this.#e,"utf8")));if(!t)throw new Error("dsh-im QQ config contains invalid bot data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=BP}return this}list(){return structuredClone(this.#A.bots)}get(t){let o=this.#A.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByAppId(t){let o=this.#A.bots.find(i=>i.appId===t);return o?structuredClone(o):null}async save(t){let o=r5(t);if(!o)throw new Error("Refusing to persist incomplete QQ bot data");return this.#r(i=>{let e=i.find(r=>r.appId===o.appId&&r.botId!==o.botId),a=i.find(r=>r.secretRef===o.secretRef&&r.botId!==o.botId);if(e||a)throw new Error("Duplicate QQ bot identity");let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!t5(t))throw new TypeError("Invalid QQ bot id");return this.#r(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await Dve(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=BP});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#g(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#g(t){await mve(bve(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await Ove(o,`${JSON.stringify(t,null,2)} `,{encoding:"utf8",mode:384}),await wve(o,this.#e)}};var _S=class extends lr{constructor(t){super({...t,rpcIdPrefix:"qq",logPrefix:"dsh-qq"})}};import{randomUUID as Tve}from"node:crypto";var a5=new Set(["starting","pending","refreshing","connecting"]),gl=new Set(["connected","failed","cancelled"]),Nve=5*6e4;function cl(n){return typeof n=="string"&&n.trim()?n.trim():null}function Sn(n,t){return Object.freeze({code:n,message:t})}function TS(n){return n?{attemptId:n.id,status:n.state,qrRevision:n.qrRevision,pollIntervalMs:1e3,...n.verificationUrl?{verificationUrl:n.verificationUrl}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.botId?{botId:n.botId}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}var _u=class{#e;#A;#t;#r;#g;#a;#n=new Map;#i=new Map;#I=new Map;#l=null;#o=new Map;#s=0;#c=!1;constructor({qrAuth:t,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.start!="function")throw new TypeError("QQ QR auth is required");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("QqController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("QqController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A}async initialize(){if(this.#c)return this.status();for(let t of this.#t.list())await this.#B(t.botId,async()=>{if(this.#c||this.#n.get(t.botId)?.status?.ready)return;let o=await this.#C(t.secretRef);if(!o){this.#i.set(t.botId,Sn("missing-secret",w("QQ \u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002")));return}try{await this.#h(t,o),this.#i.delete(t.botId)}catch(i){this.#i.set(t.botId,Sn("connection-failed",w("QQ \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"))),this.#a.warn?.(`[dsh-im:qq] bot ${t.botId} failed to initialize:`,i)}finally{this.#y()}});return this.status()}async startProvisioning(){if(this.#c)throw new Error("QQ controller is closed");this.#l&&await this.cancelProvisioning(this.#l);let t,o,i=new Promise((a,A)=>{t=a,o=A}),e={id:Tve(),state:"starting",createdAt:Date.now(),expiresAt:null,qrRevision:0,verificationUrl:null,controller:new AbortController,dispose:null,task:null,error:null,botId:null};this.#I.set(e.id,e),this.#l=e.id,this.#y();try{return e.dispose=this.#e.start({onQrDisplayed:a=>{if(e.controller.signal.aborted||gl.has(e.state))return;let A=cl(a);A&&(e.verificationUrl=A,e.qrRevision+=1,e.expiresAt=Date.now()+Nve,e.state="pending",this.#y(),t())},onQrExpired:()=>{e.controller.signal.aborted||gl.has(e.state)||(e.state="refreshing",e.verificationUrl=null,e.expiresAt=null,this.#y())},onSuccess:a=>{e.controller.signal.aborted||gl.has(e.state)||(e.task=this.#p(e,a))},onFailure:a=>{e.controller.signal.aborted||gl.has(e.state)||(e.state="failed",e.error=Sn("qr-connect-failed",w("QQ \u626B\u7801\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002")),this.#l===e.id&&(this.#l=null),this.#y(),o(a))}},{signal:e.controller.signal}),await i,TS(e)}catch(a){throw e.controller.signal.aborted?(e.state="cancelled",e.error=Sn("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):gl.has(e.state)||(e.state="failed",e.error=Sn("qr-start-failed",w("\u65E0\u6CD5\u751F\u6210 QQ \u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),this.#l===e.id&&(this.#l=null),this.#y(),a}}registrationStatus(t){return TS(this.#I.get(t))}async bindCredentials({appId:t,appSecret:o}={}){if(this.#c)throw new Error("QQ controller is closed");let i=cl(t),e=cl(o);if(!i||!e)throw new TypeError("QQ AppID and AppSecret are required");if(this.#l&&await this.cancelProvisioning(this.#l),this.#c)throw new Error("QQ controller is closed");let a=MS(i);return await this.#B(a.botId,async()=>{if(this.#c)throw new Error("QQ controller is closed");let A=this.#t.getByAppId(i),r=await this.#A.resolve(a.secretRef).catch(()=>{});if(this.#c)throw new Error("QQ controller is closed");let s={botId:a.botId,appId:i,secretRef:a.secretRef,ownerUserOpenid:A?.ownerUserOpenid??"*",createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(a.secretRef,e);try{await this.#t.save(s)}catch(g){throw await this.#f(a.secretRef,r),g}try{await this.#h(s,e),this.#i.delete(a.botId)}catch(g){this.#i.set(a.botId,Sn("connection-failed",w("QQ \u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#a.warn?.(`[dsh-im:qq] bot ${a.botId} credential connection failed:`,g)}this.#y()}),this.status()}async cancelProvisioning(t){let o=this.#I.get(t);return o?(gl.has(o.state)||(o.controller.abort(),o.dispose?.(),await o.task?.catch(()=>{}),gl.has(o.state)||(o.state="cancelled"),o.error??=Sn("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))),this.#l===o.id&&(this.#l=null),this.#y(),TS(o)):null}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown QQ bot");return await this.#B(t,async()=>{let i=await this.#C(o.secretRef);if(!i)throw new Error("QQ bot secret is missing");try{await this.#h(o,i),this.#i.delete(t)}catch(e){throw this.#i.set(t,Sn("connection-failed",w("QQ \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),e}finally{this.#y()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown QQ bot");return this.#B(t,async()=>{let i=this.#n.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error(w("QQ\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw e.code="test-target-unavailable",e}return await i.sendConnectionTest(ba(w("QQ \u673A\u5668\u4EBA\uFF08{appId}\uFF09",{appId:fP(o.appId)}))),{sent:!0}})}async sendProactiveText(t,o,i,e={}){if(!this.#t.get(t))throw new Error("Unknown QQ bot");return this.#B(t,async()=>{let A=this.#n.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("QQ\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown QQ bot");return await this.#B(t,async()=>{let i=await this.#A.resolve(o.secretRef).catch(()=>{});await this.#E(t);try{await this.#A.unset(o.secretRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.secretRef,i.value).catch(()=>{}),await this.#h(o,i.value).catch(()=>{})),new Error("Unable to remove the QQ bot safely.",{cause:e})}await this.#g({botId:t,config:o}).catch(e=>{this.#a.warn?.(`[dsh-im:qq] bot ${t} state cleanup failed:`,e)}),this.#i.delete(t),this.#y()}),this.status()}status(){let t=this.#t.list().map(e=>{let a=this.#n.get(e.botId)?.status??null,A=a?.ready===!0&&a.qqConnectionState==="connected"&&a.harnessReachable===!0,r=A?"connected":a?.qqConnectionState==="connecting"?"connecting":this.#i.has(e.botId)||a?.qqConnectionState==="failed"?"error":"offline";return{botId:e.botId,state:r,connected:A,configured:!0,bot:{name:w("QQ\u673A\u5668\u4EBA"),appIdMasked:fP(e.appId)},health:{status:A?"healthy":r==="error"?"error":"offline",summary:A?w("QQ WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38"):r==="error"?w("QQ \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):w("QQ \u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},lastMessageError:Vr(a?.lastMessageError),error:structuredClone(this.#i.get(e.botId)??null)}}),o=t.filter(e=>e.connected).length,i=this.#l?this.#I.get(this.#l):null;return{schemaVersion:1,revision:this.#s,state:i&&a5.has(i.state)?"provisioning":t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o},...i&&a5.has(i.state)?{provisioning:TS(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#l&&await this.cancelProvisioning(this.#l),await Promise.allSettled([...this.#o.values()]),await Promise.allSettled([...this.#n.keys()].map(t=>this.#E(t))))}async#p(t,o){try{t.state="connecting",t.verificationUrl=null,t.expiresAt=null,this.#y();let i=Array.isArray(o)?o[0]:null,e=cl(i?.appId),a=cl(i?.appSecret),A=cl(i?.userOpenid);if(!e||!a||!A)throw new Error("QQ authorization returned incomplete credentials");t.botId=await this.#d(t,{appId:e,appSecret:a,ownerUserOpenid:A}),t.state="connected",t.error=null}catch(i){t.controller.signal.aborted?(t.state="cancelled",t.error=Sn("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=Sn("activation-failed",w("QQ \u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u63A5\u5165\u914D\u7F6E\u3002")),this.#a.error?.("[dsh-im:qq] provisioning failed:",i))}finally{t.dispose?.(),this.#l===t.id&&(this.#l=null),this.#y()}}async#d(t,{appId:o,appSecret:i,ownerUserOpenid:e}){let a=MS(o),A=this.#t.getByAppId(o),r=await this.#A.resolve(a.secretRef).catch(()=>{}),s={botId:a.botId,appId:o,secretRef:a.secretRef,ownerUserOpenid:e,createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};return this.#B(a.botId,async()=>{await this.#A.set(a.secretRef,i);try{if(t.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#t.save(s)}catch(g){throw await this.#f(a.secretRef,r),g}try{if(t.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#h(s,i),this.#i.delete(a.botId)}catch(g){if(t.controller.signal.aborted)throw await this.#E(a.botId),A?await this.#t.save(A).catch(()=>{}):await this.#t.remove(a.botId).catch(()=>null)&&await this.#g({botId:a.botId,config:s}).catch(I=>{this.#a.warn?.("[dsh-im:qq] cancelled bot state cleanup failed:",I)}),await this.#f(a.secretRef,r),g;this.#i.set(a.botId,Sn("connection-failed",w("QQ \u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#a.warn?.(`[dsh-im:qq] bot ${a.botId} activation connection failed:`,g)}return this.#y(),a.botId})}async#h(t,o){if(this.#c)throw new Error("QQ controller is closed");if(await this.#E(t.botId),this.#c)throw new Error("QQ controller is closed");let i=await this.#r({botId:t.botId,config:t,appSecret:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid QQ runtime");this.#n.set(t.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#n.delete(t.botId),e}}async#E(t){let o=this.#n.get(t);this.#n.delete(t),await o?.stop().catch(i=>{this.#a.warn?.(`[dsh-im:qq] bot ${t} failed to stop cleanly:`,i)})}async#C(t){let o=await this.#A.resolve(t).catch(()=>{});return cl(o?.value)}async#f(t,o){o?.value?await this.#A.set(t,o.value).catch(()=>{}):await this.#A.unset(t).catch(()=>{})}#B(t,o){let a=(this.#o.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#o.get(t)===a&&this.#o.delete(t)});return this.#o.set(t,a),a}#y(){this.#s+=1}};import{QQBot as aPe,contentSanitizer as iPe,typingIndicator as oPe}from"@tencent-connect/qqbot-nodejs";import{ApiError as Rve}from"@tencent-connect/qqbot-nodejs";var i5=4500,kve=/^( {0,3})(`{3,}|~{3,})(.*)$/,vve=new Set([40034090]),Pve=Object.freeze({c2c:4,group:5}),Gve=()=>w("\u56DE\u7B54\u8F83\u957F\uFF0C\u540E\u7EED\u5185\u5BB9\u672A\u80FD\u901A\u8FC7 QQ \u5B8C\u6574\u53D1\u9001\uFF0C\u8BF7\u56DE\u590D\u201C\u7EE7\u7EED\u201D\u3002");function yP(n,t){let o=Math.min(t,n.length),i=n.charCodeAt(o-1),e=n.charCodeAt(o);return i>=55296&&i<=56319&&e>=56320&&e<=57343&&(o-=1),Math.max(1,o)}function s5(n){let t=n.endsWith("\r")?n.slice(0,-1):n,o=kve.exec(t);return!o||o[2][0]==="`"&&o[3].includes("`")?null:{delimiter:o[2],info:o[3],indent:o[1].length}}function Fve(n,t){let o=/^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(n);return!!(o&&o[1][0]===t.delimiter[0]&&o[1].length>=t.delimiter.length)}function o5(n,t){let o=0;for(let i of n.split(` @@ -462,17 +462,17 @@ ${c}`;d.length>i?(A.length>0&&a.push({markdown:A,plain:A}),A=c):A=d;return}r();l `);if(Q.length<=i)s(Q);else{let y=f.slice(1,B?-1:void 0),m=Hve(y,I.indent).join(` `);a.push(...mP(m,I.info,i))}c=B?d+1:e.length;continue}if(g5(e,c)){let d=c+2;for(;dc.length>0||I.length>0)}function Jve(){let n=Date.now()%1e8,t=Math.floor(Math.random()*65536);return(n^t)%65536}function qve(n){return n instanceof Rve&&n.httpStatus>=400&&n.httpStatus<500&&vve.has(Number(n.bizCode))}function n5(n,t,o,i){return typeof n?.send=="function"?n.send({target:t,msgType:0,content:o,extra:{msg_seq:i}}):n.sendText(t,o)}async function c5(n,t,o,{logger:i}={}){let e=jve(o),a=[],A=Jve(),r=t?.msgId?Pve[t.scope]:null,s=r!==null&&e.length>r,g=s?r-1:e.length,c=t?.msgId?{scope:t.scope,targetId:t.targetId}:t,I=!1,d=async()=>{if(!(I||!t?.msgId)){I=!0;try{a.push(await n5(n,t,Gve(),A+e.length&65535))}catch(B){i?.warn?.("[dsh-im:qq] unable to send partial reply notice:",B)}}};for(let[B,f]of e.entries()){let Q=A+B&65535,y=s&&B>=g?c:t;if(typeof n?.send=="function")try{a.push(await n.send({target:y,msgType:2,markdown:{content:f.markdown},extra:{msg_seq:Q}}));continue}catch(m){if(!qve(m)){if(i?.warn?.("[dsh-im:qq] markdown delivery outcome is uncertain; refusing a duplicate-prone retry:",m),a.length===0)throw m;await d();break}i?.warn?.("[dsh-im:qq] markdown delivery failed; retrying as plain text:",m)}if(f.plain.length!==0)try{a.push(await n5(n,y,f.plain,Q))}catch(m){if(a.length===0)throw m;await d();break}}return a}function NS(){return w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")}var RS=12e4,zve=Object.freeze([".myqcloud.com",".qpic.cn",".qq.com",".qq.com.cn",".tencentcos.com",".ugcimg.cn"]),Vve=/\.(?:gif|jpe?g|png|webp)$/i;function Wve(){return[w("QQ \u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002"),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` -`)}function Zve(n){return`${n.kind}:${n.kind==="group"?n.groupOpenid:n.senderId}`}function wP(n,t){return n?.kind==="group"||t==="*"||n?.senderId===t}function Nu(n){return typeof n?.content=="string"?n.content.trim():""}function l5(n){let t=io(n?.content_type??n?.contentType);return t?t.split(";",1)[0].trim().toLowerCase():null}function DP(n){return l5(n)?.startsWith("image/")===!0||Vve.test(io(n?.filename)??"")}function Tu(n){return Array.isArray(n?.attachments)&&n.attachments.some(DP)}function Pd(n){return Array.isArray(n?.attachments)&&n.attachments.some(t=>!DP(t))}async function Xve(n,{fetchImpl:t,signal:o}){let i=n.startsWith("//")?`https:${n}`:n,e=await t(new URL(i),{method:"GET",signal:o,redirect:"follow"});if(!e?.ok)throw await e?.body?.cancel?.().catch?.(()=>{}),new Error(`QQ file download failed with HTTP ${e?.status??"unknown"}`);return Buffer.from(await e.arrayBuffer())}function I5(n,{fetchImpl:t=fetch}={}){if(typeof t!="function")throw new TypeError("fetchImpl must be a function");let o=[],i=[];for(let e of n?.attachments??[]){let a=io(e?.url),A=io(e?.filename)??void 0,r=l5(e),s=Number(e?.size);if(DP(e)){o.push({...A?{name:A}:{},...r?.startsWith("image/")?{mediaType:r}:{},...Number.isFinite(s)&&s>=0?{size:s}:{},load:({signal:g,maxBytes:c})=>{if(!a)throw new Error("QQ image attachment has no download URL");return uo(a,{fetchImpl:t,signal:g,maxBytes:c,allowedHosts:zve})}});continue}i.push({name:A??(i.length===0?"file":`file-${i.length+1}`),...r?.includes("/")?{mediaType:r}:{},...Number.isFinite(s)&&s>=0?{size:s}:{},load:({signal:g}={})=>{if(!a)throw new Error("QQ file attachment has no download URL");return Xve(a,{fetchImpl:t,signal:g})}})}return{content:Nu(n),images:o,files:i}}function io(n){return typeof n=="string"&&n.trim()?n.trim():null}function $ve(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");if(t?.name==="UploadDailyLimitExceededError")return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 QQ \u4ECA\u65E5\u6587\u4EF6\u4E0A\u4F20\u989D\u5EA6\u5DF2\u7528\u5B8C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u7684\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D QQ \u673A\u5668\u4EBA\u6CA1\u6709\u6587\u4EF6\u6D88\u606F\u6743\u9650\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D QQ \u673A\u5668\u4EBA\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0CQQ \u4E0D\u5141\u8BB8\u53D1\u9001\u7A7A\u6587\u4EF6\u3002",{name:o});case"artifact-changed":case"artifact-invalid":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB QQ \u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 QQ \u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7 QQ \u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function ePe(n,t){return typeof n=="string"&&n.trim()?n:t.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):n}function p5(n,{dispatched:t=!1}={}){if(n?.code?.startsWith?.("artifact-"))return n;if(n?.name==="UploadDailyLimitExceededError"){let e=new Error("QQ daily file upload limit exceeded",{cause:n});return e.name=n.name,e.code="artifact-rate-limited",e}let o=Number(n?.httpStatus),i=new Error("QQ file delivery failed",{cause:n});return o===401||o===403?i.code="artifact-permission-required":o===413?i.code="artifact-too-large":o===429?i.code="artifact-rate-limited":[400,404,405,406,410,415,422].includes(o)?i.code="artifact-provider-rejected":i.code=t?"artifact-delivery-uncertain":"artifact-provider-failed",i}function OP(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function d5(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,OP(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}async function APe(n,t,o,{signal:i,timeoutMs:e=RS}={}){if(i?.throwIfAborted(),typeof n?.sendImage!="function"){let a=new Error("QQ image delivery is unavailable");throw a.code="artifact-provider-unavailable",a}try{let a=AbortSignal.timeout(e),A=i?AbortSignal.any([i,a]):a,r=n.sendImage(t,{buffer:o.bytes},{onProgress:()=>i?.throwIfAborted()});return ln(o,r),await d5(r,A)}catch(a){throw i?.aborted?OP(i):p5(a,{dispatched:!0})}}async function tPe(n,t,o,{signal:i,timeoutMs:e=RS}={}){if(i?.throwIfAborted(),typeof n?.sendFile!="function"){let a=new Error("QQ file delivery is unavailable");throw a.code="artifact-provider-unavailable",a}try{let a=AbortSignal.timeout(e),A=i?AbortSignal.any([i,a]):a,r=n.sendFile(t,{buffer:o.bytes},{fileName:o.fileName,onProgress:()=>i?.throwIfAborted()});return ln(o,r),await d5(r,A)}catch(a){throw i?.aborted?OP(i):p5(a,{dispatched:!0})}}function rPe(n,t){return t.questions[t.index]&&io(n?.senderId)===t.actor&&(n.kind!=="group"||n.rawEventType==="GROUP_AT_MESSAGE_CREATE")&&!Tu(n)&&!Pd(n)&&io(Nu(n))}function bP(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,artifactsSent:0,artifactSendErrors:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null}}var kS=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s=new Map;#c=new Map;#p=new Map;#d=new Map;#h=new Set;#E=new Set;#C;#f=new mi;constructor({bot:t,ownerUserOpenid:o,harness:i,state:e,contextEnhancement:a,status:A=bP(),logger:r=console,replyTimeoutMs:s=6e5,signal:g,fetchImpl:c=fetch,fileUploadTimeoutMs:I=RS}){if(!t||typeof t.sendText!="function")throw new TypeError("QQ bot client is required");if(!o)throw new TypeError("QQ scanner identity is required");if(!i||!e)throw new TypeError("Harness client and state store are required");if(typeof c!="function")throw new TypeError("fetchImpl must be a function");if(!Number.isInteger(I)||I<1)throw new TypeError("fileUploadTimeoutMs must be a positive integer");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c,this.#o=Math.min(I,RS),this.#C=new Ci({label:"qq",logger:r})}get status(){return structuredClone(this.#a)}accept(t){if(this.#I?.aborted)return Promise.resolve();let o=io(t?.messageId),i=io(t?.senderId);if(!o||!i||t?.senderIsBot===!0||!["c2c","group"].includes(t?.kind)||this.#r.hasSeen(o)||this.#d.has(o))return Promise.resolve();let e=Zve(t);this.#d.set(o,Xr(this.#g,t.kind==="c2c"?"direct":"group")),t.kind==="c2c"&&(this.#A==="*"||i===this.#A)&&t.replyTarget?.scope==="c2c"&&io(t.replyTarget.targetId)===i&&Eo(this.#r,t.replyTarget);let a=this.#c.get(e),A=Nu(t),r=wP(t,this.#A),s=t.kind!=="group"||t.rawEventType==="GROUP_AT_MESSAGE_CREATE",g=So(A),c=this.#f.status(e);if(g&&r&&s&&t.kind==="group")return this.#S(t,o,{message:qn()});if(r&&t.kind==="c2c"&&(g||c.phase==="collecting")){let f=/^\/batch$/iu.test(A)&&c.phase==="idle"&&(this.#s.has(e)||a||this.#C.hasPending(e))?{handled:!0,kind:"busy",message:wo()}:this.#f.handle(e,A,{plainText:!!A&&!Tu(t)&&!Pd(t)});if(f.handled)return f.kind==="submit"?this.#B({...t,content:f.prompt,attachments:[]},o,e,{batchSubmission:f}):this.#S(t,o,f)}let I=fi(A)?qi:Pd(t)?null:zi(A)?Qi:Vi(A)?Wi:Zi(A)?yi:null;if(I&&r&&s){let B;return B=this.#y(t,o,e,A,I).catch(f=>{if(f?.code==="turn-stopped"||this.#I?.aborted)return;this.#a.lastError=f?.message??String(f);let Q=tt(this.#a,f);return this.#n.error?.(`[dsh-im:qq] failed to process a command [${Q.referenceId}]:`,f),this.#e.sendText(t.replyTarget,dt(Q)).catch(()=>{})}).finally(()=>{this.#d.delete(o),this.#E.delete(B)}),this.#E.add(B),B}let d=this.#C.claimReply({key:e,actor:i,messageId:o,text:Tu(t)||Pd(t)?"":Nu(t),addressed:t.kind!=="group"||t.rawEventType==="GROUP_AT_MESSAGE_CREATE",hasPendingQuestion:!!a,questionCompletion:a?.submitting||a?.claimedReplyMessageId?a.queue:null,isQuestionPending:()=>this.#c.has(e),send:B=>this.#e.sendText(t.replyTarget,B)});if(d){let B;return B=d.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#d.delete(o),this.#h.delete(B)}),this.#h.add(B),B}if(a&&i!==a.actor)return this.#B(t,o,e);if(a?.submitting||a?.claimedReplyMessageId)return this.#B(t,o,e);if(a){rPe(t,a)&&(a.claimedReplyMessageId=o);let f=(a.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#u(t,o,e,a)).catch(Q=>this.#L(t,o,Q)).finally(()=>{this.#d.delete(o),a.claimedReplyMessageId===o&&(a.claimedReplyMessageId=null),a.queue===f&&(a.queue=null)});return a.queue=f,f}return this.#B(t,o,e)}#B(t,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1,batchSubmission:A=null}={}){let r=wP(t,this.#A),s=t.kind!=="group"||t.rawEventType==="GROUP_AT_MESSAGE_CREATE",g=r&&s?wp(I5(t,{fetchImpl:this.#l}),{signal:this.#I}):void 0,I=(this.#s.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#m(t,i,{alreadyRecorded:a,preparedMessage:g,batchSubmission:A})).finally(()=>{e&&this.#d.delete(o),this.#s.get(i)===I&&this.#s.delete(i)});return this.#s.set(i,I),I}async waitForIdle(){await Promise.allSettled([...this.#s.values(),...[...this.#c.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#h,...this.#E])}async#y(t,o,i,e,a){if(this.#I?.throwIfAborted(),this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString();let A=await a(e,this.#t,this.#r,i,{signal:this.#I,isDirect:t.kind==="c2c",hasImages:Tu(t),hasFiles:Pd(t),pendingInteraction:this.#c.has(i)||this.#C.hasPending(i),control:{owner:this,key:i}});A?.stopped&&await Promise.allSettled([this.#M(i),this.#C.closeRoute(i)]);for(let r of A?.messages??[A?.message])r&&await this.#e.sendText(t.replyTarget,r);this.#a.lastError=null}#S(t,o,i){let e;return e=Promise.resolve().then(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),i.message&&await this.#e.sendText(t.replyTarget,i.message),this.#a.lastError=null)}).catch(async a=>{if(this.#I?.aborted)return;this.#a.lastError=a?.message??String(a);let A=tt(this.#a,a);this.#n.error?.(`[dsh-im:qq] failed to process a batch input message [${A.referenceId}]:`,a),await this.#e.sendText(t.replyTarget,dt(A)).catch(()=>{})}).finally(()=>{this.#d.delete(o),this.#E.delete(e)}),this.#E.add(e),e}async#Q(t,o,i=[],e=null){if(i.length===0)return{receipt:e,failureNoticeVisible:!1,artifactSendErrors:0};let a=await bo({artifacts:i,baseReceipt:e,deliveryId:o,aggregatePresentation:e?"qq-text-and-files":"qq-files",alwaysMerge:!0,channelKey:"qq",signal:this.#I,sendImage:A=>APe(this.#e,t,A,{signal:this.#I,timeoutMs:this.#o}),sendFile:A=>tPe(this.#e,t,A,{signal:this.#I,timeoutMs:this.#o}),onFailure:(A,r)=>tt(this.#a,r,{userMessage:$ve(A?.fileName,r),reason:r?.code}),sendFailureNotice:(A,r,s)=>this.#e.sendText(t,dt(s)),logger:this.#n});return this.#a.artifactsSent=(this.#a.artifactsSent??0)+a.artifactsSent,this.#a.artifactSendErrors=(this.#a.artifactSendErrors??0)+a.artifactSendErrors,{receipt:a.receipt,failureNoticeVisible:a.failureNoticeVisible,artifactSendErrors:a.artifactSendErrors}}async#m(t,o,{alreadyRecorded:i=!1,preparedMessage:e,batchSubmission:a=null}={}){if(this.#I?.aborted)return;let A=io(t?.messageId),r=io(t?.senderId);if(!A||!r||t.senderIsBot===!0||!["c2c","group"].includes(t.kind))return;if(!i){if(this.#r.hasSeen(A))return;this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString()}let s=i,g=async()=>{s||(await this.#r.markSeen(A),s=!0)};if(!wP(t,this.#A)){this.#a.messagesRejected+=1,this.#a.lastRejectedAt=new Date().toISOString();return}if(t.kind==="group"&&t.rawEventType!=="GROUP_AT_MESSAGE_CREATE")return;let c=t.replyTarget,I=e??I5(t,{fetchImpl:this.#l}),d=I.content,B=Wt(I),f=Lt(I),Q=null,y=a===null;try{if(!d&&!B&&!f){await this.#e.sendText(c,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002")),await g();return}let m=d.toLowerCase();if(!B&&!f&&m==="/help"){await this.#e.sendText(c,Wve()),await g();return}if(!B&&!f&&m==="/status"){await this.#t.ensureRunning({signal:this.#I}),await this.#e.sendText(c,w("QQ \u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002")),await g();return}if(!B&&!f&&m==="/new"){await this.#r.clearSession(o),await this.#e.sendText(c,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002")),await g();return}let _=B||f?null:await Qo(d,this.#t,o);if(_){for(let k of _.messages??[_.message])await this.#e.sendText(c,k);await g();return}let T=B||f?null:await Bi(d,this.#t,this.#r,o,{signal:this.#I});if(T){await this.#e.sendText(c,T.message),await g();return}let R=B?await Bo(I,{signal:this.#I}):void 0,F=this.#d.get(A);F&&(R=mo(R??d,F,()=>({channel:"qq",senderId:r,senderName:t.kind==="group"?t.senderName:void 0})));let K=[],L,q=[];try{await g(),{answer:L,artifacts:q=[]}=await ui({harness:this.#t,state:this.#r,key:o,...R!==void 0?{content:R}:{text:d},createOptions:{signal:this.#I},existsOptions:{signal:this.#I},askOptions:{timeoutMs:this.#i,signal:this.#I,control:{owner:this,key:o},progressMode:"all",onUpdate:k=>{if(k.error){let V=(io(k.toolName)??w("\u5DE5\u5177")).replace(/[\r\n]+/gu," ").slice(0,80);K.push(w("\u5DE5\u5177\u8C03\u7528\u300C{name}\u300D\u672A\u6210\u529F\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u5177\u914D\u7F6E\u6216\u7A0D\u540E\u91CD\u8BD5\u3002",{name:V}))}},onInteraction:k=>this.#b(k,{key:o,actor:r,target:c,requiresMention:t.kind==="group"}),onInteractionResolved:k=>this.#R(k),files:I.files}}),a&&(this.#f.complete(o,a.token),y=!0)}finally{await Promise.allSettled([this.#M(o),this.#C.closeRoute(o)])}this.#I?.throwIfAborted();let z=ePe(L,q),j=K.length>0?`${z} +`)}function Zve(n){return`${n.kind}:${n.kind==="group"?n.groupOpenid:n.senderId}`}function wP(n,t){return n?.kind==="group"||t==="*"||n?.senderId===t}function Nu(n){return typeof n?.content=="string"?n.content.trim():""}function l5(n){let t=io(n?.content_type??n?.contentType);return t?t.split(";",1)[0].trim().toLowerCase():null}function DP(n){return l5(n)?.startsWith("image/")===!0||Vve.test(io(n?.filename)??"")}function Tu(n){return Array.isArray(n?.attachments)&&n.attachments.some(DP)}function Pd(n){return Array.isArray(n?.attachments)&&n.attachments.some(t=>!DP(t))}async function Xve(n,{fetchImpl:t,signal:o}){let i=n.startsWith("//")?`https:${n}`:n,e=await t(new URL(i),{method:"GET",signal:o,redirect:"follow"});if(!e?.ok)throw await e?.body?.cancel?.().catch?.(()=>{}),new Error(`QQ file download failed with HTTP ${e?.status??"unknown"}`);return Buffer.from(await e.arrayBuffer())}function I5(n,{fetchImpl:t=fetch}={}){if(typeof t!="function")throw new TypeError("fetchImpl must be a function");let o=[],i=[];for(let e of n?.attachments??[]){let a=io(e?.url),A=io(e?.filename)??void 0,r=l5(e),s=Number(e?.size);if(DP(e)){o.push({...A?{name:A}:{},...r?.startsWith("image/")?{mediaType:r}:{},...Number.isFinite(s)&&s>=0?{size:s}:{},load:({signal:g,maxBytes:c})=>{if(!a)throw new Error("QQ image attachment has no download URL");return uo(a,{fetchImpl:t,signal:g,maxBytes:c,allowedHosts:zve})}});continue}i.push({name:A??(i.length===0?"file":`file-${i.length+1}`),...r?.includes("/")?{mediaType:r}:{},...Number.isFinite(s)&&s>=0?{size:s}:{},load:({signal:g}={})=>{if(!a)throw new Error("QQ file attachment has no download URL");return Xve(a,{fetchImpl:t,signal:g})}})}return{content:Nu(n),images:o,files:i}}function io(n){return typeof n=="string"&&n.trim()?n.trim():null}function $ve(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");if(t?.name==="UploadDailyLimitExceededError")return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 QQ \u4ECA\u65E5\u6587\u4EF6\u4E0A\u4F20\u989D\u5EA6\u5DF2\u7528\u5B8C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u7684\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D QQ \u673A\u5668\u4EBA\u6CA1\u6709\u6587\u4EF6\u6D88\u606F\u6743\u9650\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D QQ \u673A\u5668\u4EBA\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0CQQ \u4E0D\u5141\u8BB8\u53D1\u9001\u7A7A\u6587\u4EF6\u3002",{name:o});case"artifact-changed":case"artifact-invalid":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB QQ \u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 QQ \u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7 QQ \u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function ePe(n,t){return typeof n=="string"&&n.trim()?n:t.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):n}function p5(n,{dispatched:t=!1}={}){if(n?.code?.startsWith?.("artifact-"))return n;if(n?.name==="UploadDailyLimitExceededError"){let e=new Error("QQ daily file upload limit exceeded",{cause:n});return e.name=n.name,e.code="artifact-rate-limited",e}let o=Number(n?.httpStatus),i=new Error("QQ file delivery failed",{cause:n});return o===401||o===403?i.code="artifact-permission-required":o===413?i.code="artifact-too-large":o===429?i.code="artifact-rate-limited":[400,404,405,406,410,415,422].includes(o)?i.code="artifact-provider-rejected":i.code=t?"artifact-delivery-uncertain":"artifact-provider-failed",i}function OP(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function d5(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,OP(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}async function APe(n,t,o,{signal:i,timeoutMs:e=RS}={}){if(i?.throwIfAborted(),typeof n?.sendImage!="function"){let a=new Error("QQ image delivery is unavailable");throw a.code="artifact-provider-unavailable",a}try{let a=AbortSignal.timeout(e),A=i?AbortSignal.any([i,a]):a,r=n.sendImage(t,{buffer:o.bytes},{onProgress:()=>i?.throwIfAborted()});return ln(o,r),await d5(r,A)}catch(a){throw i?.aborted?OP(i):p5(a,{dispatched:!0})}}async function tPe(n,t,o,{signal:i,timeoutMs:e=RS}={}){if(i?.throwIfAborted(),typeof n?.sendFile!="function"){let a=new Error("QQ file delivery is unavailable");throw a.code="artifact-provider-unavailable",a}try{let a=AbortSignal.timeout(e),A=i?AbortSignal.any([i,a]):a,r=n.sendFile(t,{buffer:o.bytes},{fileName:o.fileName,onProgress:()=>i?.throwIfAborted()});return ln(o,r),await d5(r,A)}catch(a){throw i?.aborted?OP(i):p5(a,{dispatched:!0})}}function rPe(n,t){return t.questions[t.index]&&io(n?.senderId)===t.actor&&(n.kind!=="group"||n.rawEventType==="GROUP_AT_MESSAGE_CREATE")&&!Tu(n)&&!Pd(n)&&io(Nu(n))}function bP(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,artifactsSent:0,artifactSendErrors:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null}}var kS=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s=new Map;#c=new Map;#p=new Map;#d=new Map;#h=new Set;#E=new Set;#C;#f=new mi;constructor({bot:t,ownerUserOpenid:o,harness:i,state:e,contextEnhancement:a,status:A=bP(),logger:r=console,replyTimeoutMs:s=6e5,signal:g,fetchImpl:c=fetch,fileUploadTimeoutMs:I=RS}){if(!t||typeof t.sendText!="function")throw new TypeError("QQ bot client is required");if(!o)throw new TypeError("QQ scanner identity is required");if(!i||!e)throw new TypeError("Harness client and state store are required");if(typeof c!="function")throw new TypeError("fetchImpl must be a function");if(!Number.isInteger(I)||I<1)throw new TypeError("fileUploadTimeoutMs must be a positive integer");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c,this.#o=Math.min(I,RS),this.#C=new Ci({label:"qq",logger:r})}get status(){return structuredClone(this.#a)}accept(t){if(this.#I?.aborted)return Promise.resolve();let o=io(t?.messageId),i=io(t?.senderId);if(!o||!i||t?.senderIsBot===!0||!["c2c","group"].includes(t?.kind)||this.#r.hasSeen(o)||this.#d.has(o))return Promise.resolve();let e=Zve(t);this.#d.set(o,Xr(this.#g,t.kind==="c2c"?"direct":"group")),t.kind==="c2c"&&(this.#A==="*"||i===this.#A)&&t.replyTarget?.scope==="c2c"&&io(t.replyTarget.targetId)===i&&Eo(this.#r,t.replyTarget);let a=this.#c.get(e),A=Nu(t),r=wP(t,this.#A),s=t.kind!=="group"||t.rawEventType==="GROUP_AT_MESSAGE_CREATE",g=So(A),c=this.#f.status(e);if(g&&r&&s&&t.kind==="group")return this.#S(t,o,{message:qn()});if(r&&t.kind==="c2c"&&(g||c.phase==="collecting")){let f=/^\/batch$/iu.test(A)&&c.phase==="idle"&&(this.#s.has(e)||a||this.#C.hasPending(e))?{handled:!0,kind:"busy",message:wo()}:this.#f.handle(e,A,{plainText:!!A&&!Tu(t)&&!Pd(t)});if(f.handled)return f.kind==="submit"?this.#B({...t,content:f.prompt,attachments:[]},o,e,{batchSubmission:f}):this.#S(t,o,f)}let I=fi(A)?qi:Pd(t)?null:zi(A)?Qi:Vi(A)?Wi:Zi(A)?yi:null;if(I&&r&&s){let B;return B=this.#y(t,o,e,A,I).catch(f=>{if(f?.code==="turn-stopped"||this.#I?.aborted)return;this.#a.lastError=f?.message??String(f);let Q=tt(this.#a,f);return this.#n.error?.(`[dsh-im:qq] failed to process a command [${Q.referenceId}]:`,f),this.#e.sendText(t.replyTarget,dt(Q)).catch(()=>{})}).finally(()=>{this.#d.delete(o),this.#E.delete(B)}),this.#E.add(B),B}let d=this.#C.claimReply({key:e,actor:i,messageId:o,text:Tu(t)||Pd(t)?"":Nu(t),addressed:t.kind!=="group"||t.rawEventType==="GROUP_AT_MESSAGE_CREATE",hasPendingQuestion:!!a,questionCompletion:a?.submitting||a?.claimedReplyMessageId?a.queue:null,isQuestionPending:()=>this.#c.has(e),send:B=>this.#e.sendText(t.replyTarget,B)});if(d){let B;return B=d.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#d.delete(o),this.#h.delete(B)}),this.#h.add(B),B}if(a&&i!==a.actor)return this.#B(t,o,e);if(a?.submitting||a?.claimedReplyMessageId)return this.#B(t,o,e);if(a){rPe(t,a)&&(a.claimedReplyMessageId=o);let f=(a.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#u(t,o,e,a)).catch(Q=>this.#L(t,o,Q)).finally(()=>{this.#d.delete(o),a.claimedReplyMessageId===o&&(a.claimedReplyMessageId=null),a.queue===f&&(a.queue=null)});return a.queue=f,f}return this.#B(t,o,e)}#B(t,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1,batchSubmission:A=null}={}){let r=wP(t,this.#A),s=t.kind!=="group"||t.rawEventType==="GROUP_AT_MESSAGE_CREATE",g=r&&s?wp(I5(t,{fetchImpl:this.#l}),{signal:this.#I}):void 0,I=(this.#s.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#m(t,i,{alreadyRecorded:a,preparedMessage:g,batchSubmission:A})).finally(()=>{e&&this.#d.delete(o),this.#s.get(i)===I&&this.#s.delete(i)});return this.#s.set(i,I),I}async waitForIdle(){await Promise.allSettled([...this.#s.values(),...[...this.#c.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#h,...this.#E])}async#y(t,o,i,e,a){if(this.#I?.throwIfAborted(),this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString();let A=await a(e,this.#t,this.#r,i,{signal:this.#I,isDirect:t.kind==="c2c",hasImages:Tu(t),hasFiles:Pd(t),pendingInteraction:this.#c.has(i)||this.#C.hasPending(i),control:{owner:this,key:i}});A?.stopped&&await Promise.allSettled([this.#M(i),this.#C.closeRoute(i)]);for(let r of A?.messages??[A?.message])r&&await this.#e.sendText(t.replyTarget,r);this.#a.lastError=null}#S(t,o,i){let e;return e=Promise.resolve().then(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),i.message&&await this.#e.sendText(t.replyTarget,i.message),this.#a.lastError=null)}).catch(async a=>{if(this.#I?.aborted)return;this.#a.lastError=a?.message??String(a);let A=tt(this.#a,a);this.#n.error?.(`[dsh-im:qq] failed to process a batch input message [${A.referenceId}]:`,a),await this.#e.sendText(t.replyTarget,dt(A)).catch(()=>{})}).finally(()=>{this.#d.delete(o),this.#E.delete(e)}),this.#E.add(e),e}async#Q(t,o,i=[],e=null){if(i.length===0)return{receipt:e,failureNoticeVisible:!1,artifactSendErrors:0};let a=await bo({artifacts:i,baseReceipt:e,deliveryId:o,aggregatePresentation:e?"qq-text-and-files":"qq-files",alwaysMerge:!0,channelKey:"qq",signal:this.#I,sendImage:A=>APe(this.#e,t,A,{signal:this.#I,timeoutMs:this.#o}),sendFile:A=>tPe(this.#e,t,A,{signal:this.#I,timeoutMs:this.#o}),onFailure:(A,r)=>tt(this.#a,r,{userMessage:$ve(A?.fileName,r),reason:r?.code}),sendFailureNotice:(A,r,s)=>this.#e.sendText(t,dt(s)),logger:this.#n});return this.#a.artifactsSent=(this.#a.artifactsSent??0)+a.artifactsSent,this.#a.artifactSendErrors=(this.#a.artifactSendErrors??0)+a.artifactSendErrors,{receipt:a.receipt,failureNoticeVisible:a.failureNoticeVisible,artifactSendErrors:a.artifactSendErrors}}async#m(t,o,{alreadyRecorded:i=!1,preparedMessage:e,batchSubmission:a=null}={}){if(this.#I?.aborted)return;let A=io(t?.messageId),r=io(t?.senderId);if(!A||!r||t.senderIsBot===!0||!["c2c","group"].includes(t.kind))return;if(!i){if(this.#r.hasSeen(A))return;this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString()}let s=i,g=async()=>{s||(await this.#r.markSeen(A),s=!0)};if(!wP(t,this.#A)){this.#a.messagesRejected+=1,this.#a.lastRejectedAt=new Date().toISOString();return}if(t.kind==="group"&&t.rawEventType!=="GROUP_AT_MESSAGE_CREATE")return;let c=t.replyTarget,I=e??I5(t,{fetchImpl:this.#l}),d=I.content,B=Wt(I),f=Lt(I),Q=null,y=a===null;try{if(!d&&!B&&!f){await this.#e.sendText(c,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002")),await g();return}let m=d.toLowerCase();if(!B&&!f&&m==="/help"){await this.#e.sendText(c,Wve()),await g();return}if(!B&&!f&&m==="/status"){await this.#t.ensureRunning({signal:this.#I}),await this.#e.sendText(c,w("QQ \u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002")),await g();return}if(!B&&!f&&m==="/new"){await this.#r.clearSession(o),await this.#e.sendText(c,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002")),await g();return}let _=B||f?null:await Qo(d,this.#t,o);if(_){for(let k of _.messages??[_.message])await this.#e.sendText(c,k);await g();return}let T=B||f?null:await Bi(d,this.#t,this.#r,o,{signal:this.#I});if(T){await this.#e.sendText(c,T.message),await g();return}let R=B?await Bo(I,{signal:this.#I}):void 0,L=this.#d.get(A);L&&(R=mo(R??d,L,()=>({channel:"qq",senderId:r,senderName:t.kind==="group"?t.senderName:void 0})));let U=[],F,q=[];try{await g(),{answer:F,artifacts:q=[]}=await ui({harness:this.#t,state:this.#r,key:o,...R!==void 0?{content:R}:{text:d},createOptions:{signal:this.#I},existsOptions:{signal:this.#I},askOptions:{timeoutMs:this.#i,signal:this.#I,control:{owner:this,key:o},progressMode:"all",onUpdate:k=>{if(k.error){let V=(io(k.toolName)??w("\u5DE5\u5177")).replace(/[\r\n]+/gu," ").slice(0,80);U.push(w("\u5DE5\u5177\u8C03\u7528\u300C{name}\u300D\u672A\u6210\u529F\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u5177\u914D\u7F6E\u6216\u7A0D\u540E\u91CD\u8BD5\u3002",{name:V}))}},onInteraction:k=>this.#b(k,{key:o,actor:r,target:c,requiresMention:t.kind==="group"}),onInteractionResolved:k=>this.#R(k),files:I.files}}),a&&(this.#f.complete(o,a.token),y=!0)}finally{await Promise.allSettled([this.#M(o),this.#C.closeRoute(o)])}this.#I?.throwIfAborted();let z=ePe(F,q),j=U.length>0?`${z} --- -${K.join(` +${U.join(` -`)}`:z,P=null,J=null;try{let k=!1;if(Q)try{await Q.update(j),k=!0,P=Zt({deliveryId:A,presentation:"qq-text",providerMessageIds:ka(Q)});try{await Q.complete()}catch(V){this.#n.warn?.("[dsh-im:qq] QQ stream completion failed after visible final content:",V)}}catch(V){Q.cancel?.(),this.#n.warn?.("[dsh-im:qq] QQ stream update failed; using markdown fallback:",V)}if(!k){let V=await c5(this.#e,c,j,{logger:this.#n});P=Zt({deliveryId:A,presentation:"qq-text",providerMessageIds:V.flatMap(Ae=>ka(Ae))})}}catch(k){J=Ma(k),this.#n.warn?.("[dsh-im:qq] final text delivery failed; continuing with result files:",k)}let U=await this.#Q(c,A,q,P),N=U.receipt?.artifacts?.some(({outcome:k})=>k==="sent"||k==="unknown");if(J&&!N&&!U.failureNoticeVisible)throw J;return J&&U.artifactSendErrors===0&&tt(this.#a,J),this.#a.messagesReplied+=1,this.#a.lastReplyAt=new Date().toISOString(),this.#a.lastError=null,!J&&U.artifactSendErrors===0&&Co(this.#a),U.receipt}catch(m){let _=null;if(!y&&a&&(m?.code==="turn-stopped"?this.#f.complete(o,a.token):_=this.#f.fail(o,a.token).message??null,y=!0),m?.code==="turn-stopped"){try{Q?.cancel?.()}catch(F){this.#n.warn?.("[dsh-im:qq] unable to cancel a stopped QQ stream:",F)}try{await this.#e.sendText(c,w("\u5DF2\u505C\u6B62\u3002"))}catch(F){this.#n.warn?.("[dsh-im:qq] unable to announce a stopped QQ turn:",F)}await g();return}try{Q?.cancel?.()}catch(F){this.#n.warn?.("[dsh-im:qq] unable to cancel a failed QQ stream:",F)}if(this.#I?.aborted)return;this.#a.lastError=m?.message??String(m);let T=Oo(m)??fo(m),R=tt(this.#a,m,{userMessage:T,reason:Ji(m)?.reason});this.#n.error?.(`[dsh-im:qq] failed to process an inbound message [${R.referenceId}]:`,m);try{let F=dt(R);await this.#e.sendText(c,_?`${F} +`)}`:z,P=null,J=null;try{let k=!1;if(Q)try{await Q.update(j),k=!0,P=Zt({deliveryId:A,presentation:"qq-text",providerMessageIds:ka(Q)});try{await Q.complete()}catch(V){this.#n.warn?.("[dsh-im:qq] QQ stream completion failed after visible final content:",V)}}catch(V){Q.cancel?.(),this.#n.warn?.("[dsh-im:qq] QQ stream update failed; using markdown fallback:",V)}if(!k){let V=await c5(this.#e,c,j,{logger:this.#n});P=Zt({deliveryId:A,presentation:"qq-text",providerMessageIds:V.flatMap(Ae=>ka(Ae))})}}catch(k){J=Ma(k),this.#n.warn?.("[dsh-im:qq] final text delivery failed; continuing with result files:",k)}let H=await this.#Q(c,A,q,P),N=H.receipt?.artifacts?.some(({outcome:k})=>k==="sent"||k==="unknown");if(J&&!N&&!H.failureNoticeVisible)throw J;return J&&H.artifactSendErrors===0&&tt(this.#a,J),this.#a.messagesReplied+=1,this.#a.lastReplyAt=new Date().toISOString(),this.#a.lastError=null,!J&&H.artifactSendErrors===0&&Co(this.#a),H.receipt}catch(m){let _=null;if(!y&&a&&(m?.code==="turn-stopped"?this.#f.complete(o,a.token):_=this.#f.fail(o,a.token).message??null,y=!0),m?.code==="turn-stopped"){try{Q?.cancel?.()}catch(L){this.#n.warn?.("[dsh-im:qq] unable to cancel a stopped QQ stream:",L)}try{await this.#e.sendText(c,w("\u5DF2\u505C\u6B62\u3002"))}catch(L){this.#n.warn?.("[dsh-im:qq] unable to announce a stopped QQ turn:",L)}await g();return}try{Q?.cancel?.()}catch(L){this.#n.warn?.("[dsh-im:qq] unable to cancel a failed QQ stream:",L)}if(this.#I?.aborted)return;this.#a.lastError=m?.message??String(m);let T=Oo(m)??fo(m),R=tt(this.#a,m,{userMessage:T,reason:Ji(m)?.reason});this.#n.error?.(`[dsh-im:qq] failed to process an inbound message [${R.referenceId}]:`,m);try{let L=dt(R);await this.#e.sendText(c,_?`${L} -${_}`:F),await g()}catch(F){this.#n.error?.("[dsh-im:qq] failed to send the safe error reply:",F)}}}async#u(t,o,i,e){this.#I?.throwIfAborted();let a=this.#c.get(i),A=e.claimedReplyMessageId===o;if(!a||a!==e||a.submitting)return A&&(!a||a!==e)?this.#w(t,o):this.#B(t,o,i,{releaseMessageId:!1});if(this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),t.kind==="group"&&t.rawEventType!=="GROUP_AT_MESSAGE_CREATE"))return;let r=io(Nu(t));if(!r||Tu(t)||Pd(t)){await this.#e.sendText(t.replyTarget,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002"));return}let s=this.#c.get(i);if(!s||s!==e||s.submitting){if(A&&(!s||s!==e)){await this.#e.sendText(t.replyTarget,NS());return}return this.#B(t,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}if(s.target=t.replyTarget,s.needsPresentation){try{await this.#D(s)}catch{this.#a.lastError=w("QQ \u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002"),this.#n.error?.("[dsh-im:qq] failed to retry an interaction question"),s.interaction.reconnect?.();return}let c=this.#c.get(i);if(!c||c!==e||c.submitting){if(A&&(!c||c!==e)){await this.#e.sendText(t.replyTarget,NS()).catch(()=>{});return}return this.#B(t,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}}let g=s.questions[s.index];if(g){if(s.answers.push(Ei(g,r)),s.index+=1,s.index{});return}if(this.#c.get(i)!==s)return;s.submitting=!1,s.answers.pop(),s.index-=1,this.#a.lastError=w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002"),this.#n.error?.("[dsh-im:qq] failed to answer a Harness interaction"),await this.#e.sendText(s.target,w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002")).catch(()=>{})}}}async#b(t,{key:o,actor:i,target:e,requiresMention:a}){if(t?.kind==="approval")return this.#C.handleRequested(t,{key:o,actor:i,requiresMention:a,send:c=>this.#e.sendText(e,c)});if(t?.kind!=="question")return;let A=t?.payload?.questions,r=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t?.rpcId!="string"||typeof r!="string"||typeof t.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!di(c))){this.#n.warn?.("[dsh-im:qq] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"QQ safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#e.sendText(e,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002")).catch(()=>{});return}let s=this.#c.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#D(s);return}if(this.#p.has(r))return;if(s){await t.respond({ok:!1,error:{code:"cancelled",message:"QQ is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,requiresMention:a,questions:A,answers:[],index:0,target:e,queue:null,claimedReplyMessageId:null,presentationPromise:null,submitting:!1,needsPresentation:!0};this.#c.set(o,g),this.#p.set(r,o),await this.#D(g)}async#R(t){if(t?.kind==="approval"){await this.#C.handleResolved(t);return}let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#p.get(o);i&&this.#k(i,o)}#D(t){if(!t.needsPresentation)return Promise.resolve();if(t.presentationPromise)return t.presentationPromise;let o=t.questions[t.index];if(!o)return Promise.resolve();let i=this.#e.sendText(t.target,hi(o,t.index,t.questions.length,{requiresMention:t.requiresMention})).then(()=>{t.needsPresentation=!1}).finally(()=>{t.presentationPromise===i&&(t.presentationPromise=null)});return t.presentationPromise=i,i}async#w(t,o){this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),await this.#e.sendText(t.replyTarget,NS()).catch(()=>{}))}#T(t,o){let i=this.#c.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#c.delete(t),this.#p.delete(i.interactionId),i)}#k(t,o){return this.#T(t,o)!==null}async#M(t){let o=this.#T(t);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The QQ interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#n.warn?.("[dsh-im:qq] failed to cancel a pending Harness interaction")}}async#L(t,o,i){if(this.#I?.aborted)return;this.#a.lastError=i?.message??String(i);let e=tt(this.#a,i);this.#n.error?.(`[dsh-im:qq] failed to process an interaction reply [${e.referenceId}]:`,i),this.#r.hasSeen(o)||await this.#r.markSeen(o).catch(()=>{}),await this.#e.sendText(t.replyTarget,dt(e)).catch(()=>{})}};function nPe(){let n=new Error("QQ WebSocket did not become ready in time");return n.code="connect-timeout",n}function sPe(){return{startedAt:null,ready:!1,qqConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...bP()}}var Ru=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o=sPe();#s=null;#c=null;#p=null;#d=null;#h=null;constructor({config:t,appSecret:o,harness:i,state:e,contextEnhancement:a,logger:A=console,replyTimeoutMs:r=6e5,connectTimeoutMs:s=2e4,createBot:g=I=>new aPe(I),typingMiddleware:c=oPe}){if(!t||!o||!i||!e)throw new TypeError("QqRuntime requires config, app secret, Harness, and state");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c}get status(){return structuredClone(this.#o)}async sendConnectionTest(t){if(!this.#o.ready||!this.#s)throw Ir(w("QQ\u673A\u5668\u4EBA"));let o=typeof this.#e.ownerUserOpenid=="string"?this.#e.ownerUserOpenid.trim():"",i=SE(this.#r),e=i?.scope==="c2c"&&typeof i.targetId=="string"?i.targetId.trim():"",a=e?{scope:"c2c",targetId:e}:o&&o!=="*"?{scope:"c2c",targetId:o}:null;if(!a)throw Ir(w("QQ\u673A\u5668\u4EBA"));return await this.#s.sendText(a,t),{sent:!0}}async sendProactiveText(t,o,{signal:i}={}){let e=t?.kind==="user"?typeof t?.route?.userOpenId=="string"?t.route.userOpenId.trim():"":t?.kind==="group"&&typeof t?.route?.groupOpenId=="string"?t.route.groupOpenId.trim():"";if(!e){let a=new TypeError("Invalid QQ proactive delivery target");throw a.code="invalid-target",a}if(!this.#o.ready||!this.#s){let a=new Error("QQ bot is not connected");throw a.code="bot-not-connected",a}return i?.throwIfAborted(),this.#s.sendText({scope:t.kind==="user"?"c2c":"group",targetId:e},o)}async start(){return this.#o.ready&&this.#s?this.status:this.#h?this.#h:(this.#h=this.#E().finally(()=>{this.#h=null}),this.#h)}async#E(){await this.stop(),this.#o.startedAt=new Date().toISOString(),this.#o.qqConnectionState="connecting",this.#o.lastError=null,await this.#t.ensureRunning(),this.#o.harnessReachable=!0;let t={error:(...d)=>this.#a.error?.(...d),warn:(...d)=>this.#a.warn?.(...d),info:(...d)=>this.#a.info?.(...d),debug:()=>{}},o=this.#I({appId:this.#e.appId,appSecret:this.#A,accountId:this.#e.botId,logger:t,transport:"websocket",tokenPrefetch:"sync",markdownSupport:!1});if(!o||typeof o.start!="function"||typeof o.stop!="function")throw new TypeError("QQ bot factory returned an invalid client");let i=new AbortController;this.#p=i,this.#s=o,this.#c=new kS({bot:o,ownerUserOpenid:this.#e.ownerUserOpenid,harness:this.#t,state:this.#r,contextEnhancement:this.#g,status:this.#o,logger:this.#a,replyTimeoutMs:this.#n,signal:i.signal}),o.use(iPe({parseFaceTags:!0})),o.use?.(this.#l({keepAlive:!0,predicate:d=>this.#e.ownerUserOpenid==="*"||d?.message?.senderId===this.#e.ownerUserOpenid}));let e,a,A=new Promise((d,B)=>{e=d,a=B}),r=()=>{let d=Date.now();this.#o.ready=!0,this.#o.qqConnectionState="connected",this.#o.lastCheckedAt=d,this.#o.lastConnectedAt=d,this.#o.lastError=null,e()},s=d=>{this.#o.ready?(this.#o.lastError=d?.message??String(d),this.#a.warn?.(`[dsh-im:qq] bot ${this.#e.botId} connection error:`,d)):a(d)},g=(d,B)=>{let f=this.#c?.accept(B);f&&f.catch(Q=>{i.signal.aborted||this.#a.error?.(`[dsh-im:qq] bot ${this.#e.botId} message handling failed:`,Q)})};o.on("ready",r),o.on("resumed",r),o.on("error",s),o.on("message",g);let c=Promise.resolve().then(()=>o.start(i.signal));this.#d=c,c.catch(d=>{i.signal.aborted||(a(d),this.#o.ready=!1,this.#o.qqConnectionState="failed",this.#o.lastError=d?.message??String(d),this.#a.error?.(`[dsh-im:qq] bot ${this.#e.botId} connection stopped:`,d))});let I;try{return await Promise.race([A,new Promise((d,B)=>{I=setTimeout(()=>B(nPe()),this.#i)})]),this.#o.ready=!0,this.#o.qqConnectionState="connected",this.#o.lastCheckedAt=Date.now(),this.#o.lastConnectedAt=Date.now(),this.status}catch(d){throw this.#o.ready=!1,this.#o.qqConnectionState="failed",this.#o.lastError=d?.message??String(d),await this.stop(),d}finally{clearTimeout(I)}}async stop(){let t=this.#s,o=this.#c,i=this.#d;this.#p?.abort(),this.#p=null,this.#s=null,this.#c=null,this.#d=null;try{t?.stop()}catch(e){this.#a.warn?.(`[dsh-im:qq] bot ${this.#e.botId} failed to stop cleanly:`,e)}return await Promise.race([i?.catch(()=>{})??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),await o?.waitForIdle(),this.#o.ready=!1,this.#o.qqConnectionState="idle",this.status}};import{startQrConnect as gPe}from"@tencent-connect/qqbot-connector";var vS=class{#e;#A;constructor({start:t=gPe,source:o="deepseek-harness"}={}){if(typeof t!="function")throw new TypeError("QQ QR connector is required");this.#e=t,this.#A=o}start(t,{signal:o}={}){if(!t||typeof t.onSuccess!="function"||typeof t.onFailure!="function")throw new TypeError("QQ QR callbacks are required");return this.#e(t,{displayQrCodeToConsole:!1,source:this.#A,signal:o})}};import{mkdir as cPe,readFile as IPe,rename as lPe,unlink as pPe,writeFile as dPe}from"node:fs/promises";import{dirname as hPe}from"node:path";var PS=Object.freeze({version:1,sessions:{},seenMessageIds:[]});function EPe(n){if(!n||typeof n!="object")return structuredClone(PS);let t={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&typeof i=="string"&&i&&(t[o]=i);return{version:1,sessions:t,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[]}}var GS=class{#e;#A=structuredClone(PS);#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{this.#A=EPe(JSON.parse(await IPe(this.#e,"utf8")))}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=structuredClone(PS),await this.#r()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){this.#A.sessions[t]=o,await this.#r()}async clearSession(t){delete this.#A.sessions[t],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(t){return this.#A.seenMessageIds.includes(t)}async markSeen(t){this.hasSeen(t)||(this.#A.seenMessageIds.push(t),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}snapshot(){return structuredClone(this.#A)}async remove(){try{await pPe(this.#e)}catch(t){if(t?.code!=="ENOENT")throw t}this.#A=structuredClone(PS)}async#r(){let t=`${JSON.stringify(this.#A,null,2)} -`,o=this.#t.then(async()=>{await cPe(hPe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await dPe(i,t,{encoding:"utf8",mode:384}),await lPe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var h5=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function CPe(n){if(!Array.isArray(n)||n.length===0)return[...h5];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...h5]}var FS=class{#e;#A;#t;#r;#g;#a;#n;#i=null;#I=null;#l=0;#o=!1;#s=!1;#c;#p;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=CPe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#a=A,this.#n=r,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#s||this.#o?this:(this.#s=!0,this.#d(0),this)}async close(){this.#o||(this.#o=!0,this.#i!==null&&this.#n(this.#i),this.#i=null,await this.#I?.catch(()=>{}),this.#p?.(null),this.#p=null)}#d(t){this.#o||(this.#i=this.#a(()=>{this.#i=null,this.#h()},t),this.#i?.unref?.())}async#h(){if(this.#o||this.#I)return;let t=this.#E();this.#I=t;try{await t}finally{this.#I===t&&(this.#I=null)}}async#E(){try{if(await this.#A.ensureRunning(),this.#o)return;let t=await this.#e.initialize();if(this.#o)return;this.#p?.(t),this.#p=null;let{configured:o,connected:i}=t.totals;if(iRa(n),B=fPe(t),f=await new e(B.config).load(),Q=Il(t.workspace??process.cwd()),y=o.WorkspaceStore??ea,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=f.list();await m.reconcile(_.map(V=>V.botId)),await Promise.all(_.map(V=>m.ensure(V.botId,{defaultAgentPreset:t.agentPreset})));let T=typeof f.remove=="function"?Pa(f,{workspaces:m}):f,R=o.qrAuth??new g({source:t.qrSource??"deepseek-harness"}),F=new Map,K=V=>Il(B.bots,V,"state.json"),L=async V=>{let Ae=F.get(V);return Ae||(Ae=await new a(K(V)).load(),F.set(V,Ae)),Ae},q=Ua(n,o.commandExecutor),{controlExecutor:z,sessionMaintenanceExecutor:j,fileIngressExecutor:P}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),J=new A({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...q?{commandExecutor:q}:{},...z?{controlExecutor:z}:{},...j?{sessionMaintenanceExecutor:j}:{},...P?{fileIngressExecutor:P}:{}}),U=new r({qrAuth:R,credentials:n.credentials,configStore:T,logger:I,createRuntime:async({botId:V,config:Ae,appSecret:ie})=>{let De=await L(V);await m.ensure(V,{defaultAgentPreset:t.agentPreset});let fe=Ga(J,{botId:V,workspaces:m,state:De,agentPresetCatalog:d});return new s({config:Ae,appSecret:ie,harness:fe.harness,state:fe.state,contextEnhancement:{botId:V,getSettings:()=>m.contextEnhancementFor(V)},replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??2e4,logger:{error:(..._e)=>I.error?.(`[${V}]`,..._e),warn:(..._e)=>I.warn?.(`[${V}]`,..._e),info:(..._e)=>I.info?.(`[${V}]`,..._e),debug:(..._e)=>I.debug?.(`[${V}]`,..._e)}})},deleteState:async({botId:V})=>{let Ae=F.get(V);if(F.delete(V),Ae&&typeof Ae.remove=="function")await Ae.remove();else try{await uPe(K(V))}catch(ie){if(ie?.code!=="ENOENT")throw ie}}}),N=Fa(U,{workspaces:m,stateFor:L,agentPresetCatalog:d}),k=c({controller:N,harness:J,logger:I,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:N,deliveryAdapter:La({channel:"qq",workspaces:m,coreController:U,stateFor:L}),ready:k.ready,async close(){await k.close(),await N.close(),J.stopManagedProcess()}}}import QPe from"qrcode";var C5="/qq",yr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),u5=Object.freeze(Object.values(yr)),yPe=new Set(["appSecret","app_secret","secretRef","ownerUserOpenid","userOpenid","verificationUrl"]);function RP(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Gd(n,t){return RP(n)&&Object.keys(n).every(o=>t.includes(o))}function TP(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function E5(n,t){return typeof n=="string"&&n.trim().length>0&&n.length<=t}function mPe(n,t){return RP(t)?n===yr.status?Gd(t,[])?null:"connection.status does not accept fields.":n===yr.beginProvisioning?Gd(t,["locale"])&&(t.locale===void 0||t.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[yr.pollProvisioning,yr.cancelProvisioning].includes(n)?Gd(t,["attemptId"])&&TP(t.attemptId)?null:`${n} requires an attemptId.`:n===yr.bindCredentials?Gd(t,["appId","appSecret"])&&E5(t.appId,256)&&E5(t.appSecret,1024)?null:"bot.bind-credentials requires AppID and AppSecret.":n===yr.reconnectBot?Gd(t,["botId","sendTest"])&&TP(t.botId)&&(t.sendTest===void 0||t.sendTest===!0)?null:"bot.reconnect requires a botId and accepts only sendTest=true.":n===yr.deleteBot?Gd(t,["botId","confirm"])&&TP(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===yr.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===yr.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===yr.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown QQ endpoint.":"Payload must be an object."}function Fd(n){if(Array.isArray(n))return n.map(Fd);if(!RP(n))return n;let t={};for(let[o,i]of Object.entries(n))yPe.has(o)||(t[o]=Fd(i));return t}async function SPe(n){return QPe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function NP(n,t){return!n||typeof n.verificationUrl!="string"?Fd(n):Fd({...n,qrCodeDataUrl:await t(n.verificationUrl)})}async function ll(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await NP(o.provisioning,t)),Fd(o)}function B5(n,{encodeQr:t=SPe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete QQ controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!u5.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown QQ endpoint."}};let r=mPe(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===yr.status)s=await ll(await n.status(),i);else if(e===yr.beginProvisioning)s=await NP(await n.startProvisioning(),i);else if(e===yr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await NP(g,i)}else if(e===yr.cancelProvisioning)s=Fd(await n.cancelProvisioning(a.attemptId));else if(e===yr.bindCredentials)s=await ll(await n.bindCredentials(a),i);else if(e===yr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};let c;if(a.sendTest===!0)if(!(g?.bots?.some(d=>d?.botId===a.botId&&d?.connected===!0)===!0)||typeof n.sendConnectionTest!="function")c=ir(Ir("QQ\u673A\u5668\u4EBA"));else{let d=null;try{await n.sendConnectionTest(a.botId)}catch(B){d=B}c=ir(d)}s=await ll({...g,...c?{testMessage:c}:{}},i)}else if(e===yr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await ll(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===yr.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>ll(g,i))}else if(e===yr.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await ll(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else s=await ll(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"qq-operation-failed",message:"QQ \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function LS(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(C5,B5(t,o),{authority:hr(i)})}async function f5(n,t={}){if(t?.controller)return LS(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await _P(n,t,t.internals),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=LS(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close QQ bot connections"),e}import{unlink as iGe}from"node:fs/promises";import{resolve as N5}from"node:path";import{createHash as wPe}from"node:crypto";import{mkdir as DPe,readFile as OPe,rename as bPe,unlink as MPe,writeFile as _Pe}from"node:fs/promises";import{dirname as TPe}from"node:path";var kP=Object.freeze({version:1,bots:Object.freeze([])}),Q5=/^slack_[a-f0-9]{24}$/,NPe=/^DSH_SLACK_BOT_TOKEN_[A-F0-9]{24}$/,RPe=/^DSH_SLACK_APP_TOKEN_[A-F0-9]{24}$/;function Lo(n){return typeof n=="string"&&n.trim()?n.trim():null}function vP(n){let t=Lo(n);if(!t)throw new TypeError("platformId is required");let o=wPe("sha256").update(t).digest("hex").slice(0,24),i=o.toUpperCase();return{botId:`slack_${o}`,botTokenRef:`DSH_SLACK_BOT_TOKEN_${i}`,appTokenRef:`DSH_SLACK_APP_TOKEN_${i}`}}function PP(n){let t=Lo(n)??"",[o,i]=t.split(":");return o&&i?`${o.slice(0,5)}\u2022\u2022\u2022 \xB7 ${i.slice(0,5)}\u2022\u2022\u2022`:t?`${t.slice(0,6)}\u2022\u2022\u2022\u2022`:w("Slack\u673A\u5668\u4EBA")}var US=class{#e;#A=kP;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=this.#g(JSON.parse(await OPe(this.#e,"utf8")));if(!t)throw new Error("dsh-im Slack config contains invalid bot data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=kP}return this}list(){return structuredClone(this.#A.bots)}get(t){let o=this.#A.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByPlatformId(t){let o=this.#A.bots.find(i=>i.platformId===t);return o?structuredClone(o):null}async save(t){let o=this.#r(t);if(!o)throw new Error("Refusing to persist incomplete Slack bot data");return this.#a(i=>{if(i.find(A=>A.botId!==o.botId&&(A.platformId===o.platformId||A.botTokenRef===o.botTokenRef||A.appTokenRef===o.appTokenRef)))throw new Error("Duplicate Slack bot identity");let a=i.findIndex(A=>A.botId===o.botId);return a===-1?i.push(o):i[a]=o,structuredClone(o)})}async remove(t){if(!Q5.test(t))throw new TypeError("Invalid Slack bot id");return this.#a(o=>{let i=o.findIndex(e=>e.botId===t);return i===-1?null:structuredClone(o.splice(i,1)[0])})}async clear(){let t=this.#t.then(async()=>{try{await MPe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=kP});this.#t=t.then(()=>{},()=>{}),await t}#r(t){if(!t||typeof t!="object")return null;let o=Lo(t.botId),i=Lo(t.platformId),e=Lo(t.botTokenRef),a=Lo(t.appTokenRef),A=Lo(t.name);if(!o||!i||!e||!a||!A||!Q5.test(o)||!NPe.test(e)||!RPe.test(a))return null;let r=vP(i);return r.botId!==o||r.botTokenRef!==e||r.appTokenRef!==a?null:Object.freeze({botId:o,platformId:i,botTokenRef:e,appTokenRef:a,name:A,username:Lo(t.username),teamId:Lo(t.teamId),teamName:Lo(t.teamName),createdAt:Lo(t.createdAt)??new Date().toISOString(),connectedAt:Lo(t.connectedAt)})}#g(t){if(!t||t.version!==1||!Array.isArray(t.bots))return null;let o=t.bots.map(A=>this.#r(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||a.has(A.botTokenRef)||a.has(A.appTokenRef))return null;i.add(A.botId),e.add(A.platformId),a.add(A.botTokenRef),a.add(A.appTokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#a(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await DPe(TPe(this.#e),{recursive:!0,mode:448});let A=`${this.#e}.tmp`;await _Pe(A,`${JSON.stringify(a,null,2)} -`,{encoding:"utf8",mode:384}),await bPe(A,this.#e),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}};var kPe="https://slack.com/api/",Gu="files.slack.com",vPe="slack.com",y5="/files-pri/",PPe=Object.freeze([Gu]),GPe="/upload/",FPe=12e4;function Es(n){return typeof n=="string"&&n.trim()?n.trim():null}function m5(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}function vu(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function LPe(n,t){if(!Number.isInteger(n)||n<1)throw new TypeError(`${t} must be a positive integer`);return n}function S5(n,t){return t?.providerCode!==void 0&&(n.providerCode=t.providerCode),Number.isInteger(t?.status)&&(n.status=t.status),n}function pl(n){let t="artifact-provider-failed",o="Slack file upload preparation failed";n?.code==="slack-file_upload_size_restricted"?(t="artifact-too-large",o="Slack rejected the result file because it is too large"):n?.code==="slack-missing-scope"?(t="artifact-permission-required",o="Slack file delivery requires the files:write scope"):n?.code?.startsWith?.("slack-")&&(t="artifact-provider-rejected",o="Slack rejected file upload preparation");let i=new Error(o,{cause:n});return i.code=t,S5(i,n)}function UPe(n){let t=new Error("Slack file completion result is uncertain",{cause:n});return t.code="artifact-delivery-uncertain",S5(t,n)}function HPe(n){return Number.isInteger(n)&&n>=300&&n<400}async function GP(n){try{await n?.body?.cancel?.()}catch{}}function KPe(n){let t=new URL(n);if(t.protocol!=="https:")throw new Error("Image download URL must use HTTPS");if(t.username||t.password||t.port&&t.port!=="443")throw new Error("Image download URL is not hosted by the messaging platform");if(t.hostname===vPe&&t.pathname.startsWith(y5)&&(t.hostname=Gu),t.hostname!==Gu||!t.pathname.startsWith(y5))throw new Error("Image download URL is not hosted by the messaging platform");return t.hash="",t}function xPe(n){let t=new URL(n);if(t.protocol!=="https:"||t.username||t.password||t.port&&t.port!=="443"||t.hostname!==Gu||!t.pathname.startsWith(GPe))throw new Error("Slack returned an unsafe file upload URL");return t.hash="",t}function YPe(n,t){let o=n?.headers?.get?.("location");if(!o)return null;try{return new URL(o,t)}catch{return null}}function jPe(n){let t=n?.headers?.get?.("x-oauth-scopes");return t==null?null:new Set(t.split(",").map(o=>o.trim()).filter(Boolean))}function JPe(n){return n?.protocol==="https:"&&!n.username&&!n.password&&(!n.port||n.port==="443")&&n.hostname.endsWith(".slack.com")&&n.hostname!==Gu&&n.pathname==="/"&&n.searchParams.has("redir")}function qPe(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),t?.addEventListener("abort",()=>{clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function wn(n,t){let o=Es(n);if(!o||!/^[A-Z][A-Z0-9]{4,30}$/i.test(o))throw new TypeError(`Invalid Slack ${t}`);return o}function hs(n,t){let o=Es(n);if(!o)throw new TypeError(`Slack ${t} is required`);return o}function Pu(n,{trim:t=!0}={}){let o=typeof n=="string"?n:"",i=t?o.trim():o;if(!i)throw new TypeError("Slack message text is required");return i.replace(/<@([A-Z0-9]+)>/gi,"@$1").replace(/]*)?>/gi,"@$1")}function zPe(n,t,o){let i=Es(t?.error)??"unknown_error",e=new Error(`Slack ${n} failed: ${i.replaceAll("_"," ")}`);return e.providerCode=i,["invalid_auth","not_authed","token_revoked","account_inactive"].includes(i)?e.code=o==="app"?"slack-invalid-app-token":"slack-invalid-bot-token":i==="missing_scope"?e.code="slack-missing-scope":i==="method_not_supported_for_channel_type"||i==="channel_type_not_supported"||i==="deprecated_endpoint"?e.code="slack-stream-unavailable":e.code=`slack-${i}`,e}function w5(n){return typeof n=="string"&&/^xoxb-[A-Za-z0-9-]{16,}$/.test(n.trim())}function D5(n){return typeof n=="string"&&/^xapp-[A-Za-z0-9-]{16,}$/.test(n.trim())}var Fu=class{#e;#A;#t;#r;#g=null;#a;constructor({botToken:t,appToken:o,fetchImpl:i=fetch,baseUrl:e=kPe,fileUploadTimeoutMs:a=FPe}){if(t!==void 0&&!w5(t))throw new TypeError("Slack Bot Token is invalid");if(o!==void 0&&!D5(o))throw new TypeError("Slack App Token is invalid");if(!t&&!o)throw new TypeError("SlackApi requires a token");if(typeof i!="function")throw new TypeError("SlackApi requires fetch");this.#e=t?.trim(),this.#A=o?.trim(),this.#t=i,this.#r=new URL(e),this.#a=LPe(a,"fileUploadTimeoutMs")}authTest(t={}){return this.#i("auth.test",{...t,tokenKind:"bot"})}openConnection(t={}){return this.#i("apps.connections.open",{...t,tokenKind:"app",body:void 0})}async fileInfo({fileId:t,signal:o}={}){let i=await this.#i("files.info",{tokenKind:"bot",signal:o,body:{file:wn(t,"file id")}});if(!i?.file||typeof i.file!="object"||Array.isArray(i.file))throw new Error("Slack files.info returned no file object");return i.file}postMessage({channelId:t,text:o,threadTs:i,signal:e}){return this.#i("chat.postMessage",{tokenKind:"bot",signal:e,body:{channel:wn(t,"channel id"),text:Pu(o),...i?{thread_ts:Es(i)}:{},mrkdwn:!0,link_names:!1,unfurl_links:!1,unfurl_media:!1}})}updateMessage({channelId:t,ts:o,text:i,signal:e}){return this.#i("chat.update",{tokenKind:"bot",signal:e,body:{channel:wn(t,"channel id"),ts:hs(o,"message timestamp"),text:Pu(i),parse:"none",link_names:!1}})}addReaction({channelId:t,messageTs:o,emojiName:i,signal:e,timeoutMs:a}){return this.#i("reactions.add",{tokenKind:"bot",signal:e,timeoutMs:a,retry:!1,body:{channel:wn(t,"channel id"),timestamp:hs(o,"message timestamp"),name:hs(i,"reaction name")}})}removeReaction({channelId:t,messageTs:o,emojiName:i,signal:e,timeoutMs:a}){return this.#i("reactions.remove",{tokenKind:"bot",signal:e,timeoutMs:a,retry:!1,body:{channel:wn(t,"channel id"),timestamp:hs(o,"message timestamp"),name:hs(i,"reaction name")}})}startStream({channelId:t,threadTs:o,recipientTeamId:i,recipientUserId:e,markdownText:a,signal:A}){return this.#i("chat.startStream",{tokenKind:"bot",signal:A,body:{channel:wn(t,"channel id"),thread_ts:hs(o,"thread timestamp"),...i?{recipient_team_id:wn(i,"team id")}:{},...e?{recipient_user_id:wn(e,"user id")}:{},...Es(a)?{markdown_text:Pu(a)}:{}}})}appendStream({channelId:t,ts:o,markdownText:i,signal:e}){return this.#i("chat.appendStream",{tokenKind:"bot",signal:e,body:{channel:wn(t,"channel id"),ts:hs(o,"stream timestamp"),markdown_text:Pu(i,{trim:!1})}})}stopStream({channelId:t,ts:o,markdownText:i,signal:e}){return this.#i("chat.stopStream",{tokenKind:"bot",signal:e,body:{channel:wn(t,"channel id"),ts:hs(o,"stream timestamp"),...Es(i)?{markdown_text:Pu(i,{trim:!1})}:{}}})}async uploadFile({channelId:t,threadTs:o,file:i,signal:e}){if(!i||typeof i!="object"||typeof i.fileName!="string"||!i.fileName||!Buffer.isBuffer(i.bytes))throw new TypeError("A Slack file is required");if(e?.aborted)throw vu(e);let a=m5(e,this.#a),A;try{A=await this.#i("files.getUploadURLExternal",{tokenKind:"bot",signal:a,timeoutMs:this.#a,body:{filename:i.fileName,length:i.bytes.byteLength}})}catch(I){throw e?.aborted?vu(e):pl(I)}let r,s;try{r=hs(A?.file_id,"file id"),s=xPe(A?.upload_url)}catch(I){throw pl(I)}let g;try{g=await this.#t(s,{method:"POST",headers:{"content-type":i.mediaType??"application/octet-stream"},body:i.bytes,signal:a,redirect:"error"})}catch(I){throw e?.aborted?vu(e):pl(I)}if(!Number.isInteger(g?.status))throw pl(new Error("Slack file upload returned an invalid response"));if(g.status!==200){await GP(g);let I=new Error(`Slack file upload failed with HTTP ${g.status}`);throw I.status=g.status,g.status===413?I.code="artifact-too-large":g.status===429?I.code="artifact-rate-limited":I.code="artifact-provider-rejected",I}await GP(g);let c;try{c={files:[{id:r,title:i.fileName}],channel_id:wn(t,"channel id"),...o?{thread_ts:hs(o,"thread timestamp")}:{}}}catch(I){throw pl(I)}if(a.aborted)throw e?.aborted?vu(e):pl(a.reason);try{let I=await this.#i("files.completeUploadExternal",{tokenKind:"bot",signal:a,timeoutMs:this.#a,retry:!1,body:c});if(!Array.isArray(I?.files)||!I.files.some(d=>Es(d?.id)===r))throw new Error("Slack file completion did not confirm the uploaded file");return I}catch(I){throw e?.aborted?vu(e):I?.code==="slack-missing-scope"?pl(I):UPe(I)}}async downloadFile({url:t,signal:o,maxBytes:i}){return this.#n({url:t,signal:o,maxBytes:i,stream:!1})}async downloadFileStream({url:t,signal:o}){return this.#n({url:t,signal:o,stream:!0})}async#n({url:t,signal:o,maxBytes:i,stream:e}){if(!this.#e)throw new TypeError("Slack bot token is required for file download");let a=KPe(t),r={fetchImpl:async(s,g)=>{let c=await this.#t(s,g);if(!HPe(c?.status))return c;let I=YPe(c,s);if(this.#g&&!this.#g.has("files:read")||JPe(I))throw await GP(c),new Bt("slack-file-access-required","Slack redirected a private file request to the workspace because file access was not granted",w("Slack \u672A\u6388\u6743\u673A\u5668\u4EBA\u8BFB\u53D6\u8BE5\u6587\u4EF6\u3002\u8BF7\u4E3A\u5E94\u7528\u6DFB\u52A0 files:read \u540E\u91CD\u65B0\u5B89\u88C5\uFF0C\u518D\u91CD\u65B0\u53D1\u9001\u56FE\u7247\u3002"));return c},headers:{authorization:`Bearer ${this.#e}`},signal:o,allowedHosts:PPe};return e?kp(a,r):uo(a,{...r,maxBytes:i})}async#i(t,{tokenKind:o,body:i,signal:e,timeoutMs:a=15e3,retry:A=!0}){let r=o==="app"?this.#A:this.#e;if(!r)throw new TypeError(`Slack ${o} token is required for ${t}`);let s=t==="files.getUploadURLExternal"||t==="files.info",g;try{g=await this.#t(new URL(t,this.#r),{method:"POST",headers:{authorization:`Bearer ${r}`,"content-type":i===void 0||s?"application/x-www-form-urlencoded;charset=utf-8":"application/json;charset=utf-8","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.2.2)"},...i===void 0?{}:{body:s?new URLSearchParams(i).toString():JSON.stringify(i)},signal:m5(e,a),redirect:"error"})}catch(I){throw I?.name==="AbortError"||I?.name==="TimeoutError"?I:new Error(`Slack ${t} transport failed`)}if(o==="bot"){let I=jPe(g);I&&(this.#g=I)}let c;try{c=await g.json()}catch{throw new Error(`Slack ${t} returned invalid JSON`)}if(g.status===429&&A){let I=Number(g.headers.get("retry-after"))||1;return await qPe(Math.min(1e4,Math.max(100,I*1e3)),e),this.#i(t,{tokenKind:o,body:i,signal:e,timeoutMs:a,retry:!1})}if(!g.ok||c?.ok!==!0){let I=zPe(t,c,o);throw I.status=g.status,I}return c}};async function O5({botToken:n,appToken:t},o={}){if(!w5(n)){let r=new TypeError(w("Slack Bot Token \u5FC5\u987B\u4EE5 xoxb- \u5F00\u5934\u3002"));throw r.code="slack-invalid-bot-token",r}if(!D5(t)){let r=new TypeError(w("Slack App Token \u5FC5\u987B\u4EE5 xapp- \u5F00\u5934\u3002"));throw r.code="slack-invalid-app-token",r}let i=new Fu({botToken:n,appToken:t,...o}),[e,a]=await Promise.all([i.authTest(),i.openConnection()]);if(!e?.team_id||!e?.user_id||!e?.bot_id)throw new Error(w("Slack Bot Token \u6CA1\u6709\u8FD4\u56DE\u5B8C\u6574\u7684\u673A\u5668\u4EBA\u8EAB\u4EFD\u3002"));let A;try{A=new URL(a?.url)}catch{A=null}if(!A||A.protocol!=="wss:"){let r=new Error(w("Slack App Token \u65E0\u6CD5\u521B\u5EFA Socket Mode \u8FDE\u63A5\uFF0C\u8BF7\u786E\u8BA4\u5DF2\u542F\u7528 Socket Mode \u548C connections:write\u3002"));throw r.code="slack-socket-mode",r}return{platformId:`${e.team_id}:${e.user_id}`,name:Es(e.user)??"DeepSeek Harness",username:Es(e.user),teamId:String(e.team_id),teamName:Es(e.team)}}var FP=Object.freeze({key:"slack",label:"Slack",connectionLabel:" Socket Mode \u957F\u8FDE\u63A5",reactions:Object.freeze({processing:"eyes",success:"white_check_mark",error:"x"})}),HS=class extends $n{constructor(t){super({descriptor:FP,...t})}};function mg(n){return typeof n=="string"&&n.trim()?n.trim():null}function KS(n,t){return Object.freeze({code:n,message:t})}var Lu=class{#e;#A;#t;#r;#g;#a;#n=new Map;#i=new Map;#I=new Map;#l=0;#o=!1;constructor({credentials:t,configStore:o,inspectCredentials:i=O5,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.resolve!="function"||typeof t.set!="function"||typeof t.unset!="function")throw new TypeError("Slack requires the DSH credential provider");if(!o||typeof o.list!="function"||typeof o.save!="function"||typeof o.remove!="function")throw new TypeError("Slack requires a config store");if(typeof i!="function"||typeof e!="function")throw new TypeError("Slack controller dependencies are incomplete");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A}async initialize(){if(this.#o)return this.status();for(let t of this.#A.list())await this.#h(t.botId,async()=>{if(this.#o||this.#n.get(t.botId)?.status?.ready)return;let o=await this.#p(t);if(!o){this.#i.set(t.botId,KS("missing-token",w("Slack\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002")));return}try{await this.#s(t,o),this.#i.delete(t.botId)}catch(i){this.#i.set(t.botId,KS("connection-failed",w("Slack Socket Mode \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"))),this.#a.warn?.(`[dsh-im:slack] bot ${t.botId} failed to initialize:`,i)}finally{this.#E()}});return this.status()}async bindCredentials({botToken:t,appToken:o}={}){if(this.#o)throw new Error("Slack controller is closed");let i=mg(t),e=mg(o);if(!i||!e)throw new TypeError("Slack Bot Token and App Token are required");let a=await this.#t({botToken:i,appToken:e}),A=mg(a?.platformId),r=mg(a?.name);if(!A||!r)throw new Error("Slack returned an invalid bot identity");let s=vP(A);return await this.#h(s.botId,async()=>{if(this.#o)throw new Error("Slack controller is closed");let g=this.#A.getByPlatformId(A),c=await this.#e.resolve(s.botTokenRef).catch(()=>{}),I=await this.#e.resolve(s.appTokenRef).catch(()=>{}),d={...s,platformId:A,name:r,username:mg(a.username),teamId:mg(a.teamId),teamName:mg(a.teamName),createdAt:g?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};try{await this.#e.set(s.botTokenRef,i),await this.#e.set(s.appTokenRef,e),await this.#A.save(d)}catch(B){throw await Promise.all([this.#d(s.botTokenRef,c),this.#d(s.appTokenRef,I)]),B}try{await this.#s(d,{botToken:i,appToken:e}),this.#i.delete(s.botId)}catch(B){this.#i.set(s.botId,KS("connection-failed",w("Slack\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0CSocket Mode \u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#a.warn?.(`[dsh-im:slack] bot ${s.botId} credential connection failed:`,B)}this.#E()}),this.status()}async reconnectBot(t){let o=this.#A.get(t);if(!o)throw new Error("Unknown Slack bot");return await this.#h(t,async()=>{let i=await this.#p(o);if(!i)throw new Error("Slack bot credentials are missing");try{await this.#s(o,i),this.#i.delete(t)}catch(e){throw this.#i.set(t,KS("connection-failed",w("Slack Socket Mode \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u68C0\u67E5\u4E24\u4E2A Token\u3002"))),e}finally{this.#E()}}),this.status()}async sendConnectionTest(t){let o=this.#A.get(t);if(!o)throw new Error("Unknown Slack bot");return this.#h(t,async()=>{let i=this.#n.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error(w("Slack\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw e.code="test-target-unavailable",e}return await i.sendConnectionTest(ba(`${o.name}\uFF08${PP(o.platformId)}\uFF09`,w("Slack\u673A\u5668\u4EBA"))),{sent:!0}})}async sendProactiveText(t,o,i,e={}){if(!this.#A.get(t))throw new Error("Unknown Slack bot");return this.#h(t,async()=>{let A=this.#n.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("Slack\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#A.get(t);if(!o)throw new Error("Unknown Slack bot");return await this.#h(t,async()=>{let i=await this.#e.resolve(o.botTokenRef).catch(()=>{}),e=await this.#e.resolve(o.appTokenRef).catch(()=>{});await this.#c(t);try{await this.#e.unset(o.botTokenRef),await this.#e.unset(o.appTokenRef),await this.#A.remove(t)}catch(a){throw await Promise.all([this.#d(o.botTokenRef,i),this.#d(o.appTokenRef,e)]),i?.value&&e?.value&&await this.#s(o,{botToken:i.value,appToken:e.value}).catch(()=>{}),new Error("Unable to remove the Slack bot safely.",{cause:a})}await this.#g({botId:t,config:o}).catch(a=>{this.#a.warn?.(`[dsh-im:slack] bot ${t} state cleanup failed:`,a)}),this.#i.delete(t),this.#E()}),this.status()}status(){let t=this.#A.list().map(i=>{let e=this.#n.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#i.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:a,configured:!0,bot:{name:i.name,username:i.username,teamName:i.teamName,idMasked:PP(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?w(`Slack${FP.connectionLabel}\u8FD0\u884C\u6B63\u5E38`):A==="error"?w("Slack\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):w("Slack\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},lastMessageError:Vr(e?.lastMessageError),error:structuredClone(this.#i.get(i.botId)??null)}}),o=t.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#l,state:t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o}}}async close(){this.#o||(this.#o=!0,await Promise.allSettled([...this.#I.values()]),await Promise.allSettled([...this.#n.keys()].map(t=>this.#c(t))))}async#s(t,{botToken:o,appToken:i}){if(this.#o)throw new Error("Slack controller is closed");if(await this.#c(t.botId),this.#o)throw new Error("Slack controller is closed");let e=await this.#r({botId:t.botId,config:t,botToken:o,appToken:i});if(!e||typeof e.start!="function"||typeof e.stop!="function")throw new TypeError("createRuntime returned an invalid Slack runtime");this.#n.set(t.botId,e);try{await e.start()}catch(a){throw await e.stop().catch(()=>{}),this.#n.delete(t.botId),a}}async#c(t){let o=this.#n.get(t);this.#n.delete(t),await o?.stop().catch(i=>{this.#a.warn?.(`[dsh-im:slack] bot ${t} failed to stop cleanly:`,i)})}async#p(t){let[o,i]=await Promise.all([this.#e.resolve(t.botTokenRef).catch(()=>{}),this.#e.resolve(t.appTokenRef).catch(()=>{})]),e=mg(o?.value),a=mg(i?.value);return e&&a?{botToken:e,appToken:a}:null}async#d(t,o){o?.value?await this.#e.set(t,o.value).catch(()=>{}):await this.#e.unset(t).catch(()=>{})}#h(t,o){let a=(this.#I.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#I.get(t)===a&&this.#I.delete(t)});return this.#I.set(t,a),a}#E(){this.#l+=1}};var xS=class extends lr{constructor(t){super({...t,rpcIdPrefix:"slack",logPrefix:"dsh-slack"})}};var b5=Object.freeze([1e3,3e3,5e3,1e4,3e4]),UP=38e3,M5=11e3,T5=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function LP(n,t,o){if(typeof n.addEventListener=="function")n.addEventListener(t,o);else if(typeof n.on=="function")n.on(t,o);else throw new TypeError("Slack WebSocket does not support events")}function VPe(n){let t=n?.data??n;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("utf8"):t instanceof ArrayBuffer?Buffer.from(t).toString("utf8"):ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):null}function WPe(n){let t=new URL(n);if(t.protocol!=="wss:")throw new Error("Slack returned an insecure Socket Mode URL");return t.href}function ZPe(n){return typeof n=="string"?n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">"):""}function XPe(n,t){return ZPe(n).replace(new RegExp(`<@${t}>`,"gi"),"").trim()}function HP(n){return typeof n?.url_private_download=="string"&&n.url_private_download?n.url_private_download:n?.url_private}function $Pe(n,t){let o=typeof n?.mimetype=="string"?n.mimetype.toLowerCase():"",i=HP(n);return!T5.has(o)||typeof i!="string"||!i?null:{name:typeof n.name=="string"?n.name:void 0,mediaType:o,size:Number.isSafeInteger(n.size)&&n.size>=0?n.size:void 0,load:e=>t(i,e)}}function eGe(n,t,o){let i=typeof n?.mimetype=="string"&&n.mimetype?n.mimetype.toLowerCase():void 0,e=HP(n);if(T5.has(i))return null;let a=n?.file_access==="check_file_info"&&typeof n?.id=="string"&&n.id;return(typeof e!="string"||!e)&&!a?null:{name:typeof n?.name=="string"&&n.name?n.name:typeof n?.title=="string"&&n.title?n.title:a?n.id:"slack-file",...i?{mediaType:i}:{},size:Number.isSafeInteger(n?.size)&&n.size>=0?n.size:void 0,load:async({signal:A}={})=>{if(!a)return t(e,{signal:A});let r=await o(n.id,{signal:A}),s=HP(r);if(typeof s!="string"||!s)throw new Error("Slack files.info returned no downloadable URL");let g=await t(s,{signal:A}),c=typeof r?.name=="string"&&r.name?r.name:typeof r?.title=="string"&&r.title?r.title:n.id,I=typeof r?.mimetype=="string"&&r.mimetype?r.mimetype.toLowerCase():void 0;return Buffer.isBuffer(g)||g instanceof Uint8Array?{data:g,name:c,...I?{mediaType:I}:{}}:{...g,name:c,...I?{mediaType:I}:{}}}}}function AGe(n,t,{loadFile:o=async()=>{throw new Error("Slack file downloader is unavailable")},loadFileStream:i=o,loadFileInfo:e=async()=>{throw new Error("Slack file metadata loader is unavailable")}}={}){let a=n?.event;if(!a||!n?.event_id||!a.channel||!a.user||!a.ts)return null;let A=a.type==="message"&&a.channel_type==="im",r=a.type==="app_mention";if(!A&&!r||a.subtype&&a.subtype!=="file_share"||a.bot_id||a.app_id)return null;let s=String(a.thread_ts??a.ts);return{messageId:String(n.event_id),senderId:String(a.user),senderIsBot:String(a.user)===String(t),kind:A?"direct":"group",conversationId:A?String(a.channel):`${a.channel}:${s}`,content:XPe(a.text??"",t),plainText:!Array.isArray(a.files)||a.files.length===0,images:Array.isArray(a.files)?a.files.map(g=>$Pe(g,o)).filter(Boolean):[],files:Array.isArray(a.files)?a.files.map(g=>eGe(g,i,e)).filter(Boolean):[],addressed:A||r,reactionTarget:{channelId:String(a.channel),messageTs:String(a.ts)},replyTarget:{channelId:String(a.channel),threadTs:s,recipientUserId:String(a.user),recipientTeamId:String(a.user_team??n.team_id??"")},connectionTestTarget:{channelId:String(a.channel)}}}function tGe(n){if(typeof n!="string")return!1;let t="__DSH_IM_TOOL_NAME__",o=w("\u6B63\u5728\u4F7F\u7528{name}\u2026",{name:t}),i=o.indexOf(t);if(i<0)return!1;let e=o.slice(0,i),a=o.slice(i+t.length),A=n.trim();return A.startsWith(e)&&A.endsWith(a)&&A.length>e.length+a.length}async function _5(n,t,o,i,e){if(i)for(let a=0;a{let y=es(Q,UP)[0]??"";if(!y||!y.startsWith(A))return;let m=y.slice(A.length);m&&(await _5(n,t,a,m,o),A=y)},f=()=>{I||c||s!==null||g||!r||(s=setTimeout(()=>{s=null;let Q=r;r="",g=B(Q).catch(y=>{c=!0,i.warn?.("[dsh-im:slack] streaming append failed:",y)}).finally(()=>{g=null,f()})},350),s?.unref?.())};return{messageId:a,get providerMessageIds(){return[...d]},update(Q){I||c||typeof Q!="string"||!Q.trim()||tGe(Q)||(r=Q,f())},async finish(Q){if(I)throw new Error("Slack message stream is already closed");I=!0,s!==null&&clearTimeout(s),s=null,r="",await g?.catch(()=>{});let y=es(Q,UP),m=y[0]??w("\u5904\u7406\u5B8C\u6210\u3002");!c&&m.startsWith(A)?(await _5(n,t,a,m.slice(A.length),o),await n.stopStream({channelId:t.channelId,ts:a,signal:o})):(await n.stopStream({channelId:t.channelId,ts:a,signal:o}).catch(()=>{}),await n.updateMessage({channelId:t.channelId,ts:a,text:m,signal:o}));for(let _ of y.slice(1)){let T=await n.postMessage({channelId:t.channelId,threadTs:t.threadTs,text:_,signal:o});typeof T?.ts=="string"&&T.ts&&d.push(T.ts)}},cancel(){I=!0,r="",s!==null&&clearTimeout(s),s=null,n.stopStream({channelId:t.channelId,ts:a,signal:o}).catch(()=>{})}}}var KP=class{#e;#A;#t;constructor({api:t,signal:o,logger:i}){this.#e=t,this.#A=o,this.#t=i}async sendText(t,o){let i=es(o,UP),e=[];for(let a of i){let A=await this.#e.postMessage({channelId:t.channelId,threadTs:t.threadTs,text:a,signal:this.#A});typeof A?.ts=="string"&&A.ts&&e.push(A.ts)}return{providerMessageIds:e}}async addReaction(t,o,{signal:i}={}){let e=String(o??"").trim();return await this.#e.addReaction({channelId:t.channelId,messageTs:t.messageTs,emojiName:e,signal:i??this.#A}),e}removeReaction(t,o,{signal:i}={}){return this.#e.removeReaction({channelId:t.channelId,messageTs:t.messageTs,emojiName:o,signal:i??this.#A})}openStream(t){return rGe({api:this.#e,target:t,signal:this.#A,logger:this.#t})}sendFile(t,o){return this.#e.uploadFile({channelId:t.channelId,threadTs:t.threadTs,file:o,signal:this.#A})}};function aGe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...Xi()}}var Uu=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s=aGe();#c=null;#p=null;#d=null;#h=null;#E=null;#C=null;#f=0;#B=0;#y=!0;#S=null;constructor({config:t,botToken:o,appToken:i,harness:e,state:a,contextEnhancement:A,logger:r=console,replyTimeoutMs:s=6e5,connectTimeoutMs:g=2e4,createApi:c=d=>new Fu(d),createWebSocket:I=d=>new WebSocket(d)}){if(!t||!o||!i||!e||!a)throw new TypeError("SlackRuntime requires config, both tokens, Harness, and state");if(typeof I!="function")throw new TypeError("SlackRuntime requires WebSocket");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c,this.#o=I}get status(){return structuredClone(this.#s)}async sendConnectionTest(t){if(!this.#s.ready||!this.#p){let o=new Error("Slack bot is not connected");throw o.code="test-target-unavailable",o}return this.#p.sendConnectionTest(t)}async sendProactiveText(t,o,i={}){if(!this.#s.ready||!this.#p){let A=new Error("Slack bot is not connected");throw A.code="bot-not-connected",A}let e=typeof t?.route?.channelId=="string"?t.route.channelId.trim():"",a=typeof t?.route?.threadTs=="string"?t.route.threadTs.trim():"";if(!e||t?.kind!=="conversation"&&t?.kind!=="thread"||t.kind==="thread"&&!a||t.kind==="conversation"&&a){let A=new TypeError("Invalid Slack proactive delivery target");throw A.code="invalid-target",A}return this.#p.sendProactiveText({channelId:e,...a?{threadTs:a}:{}},o,i)}async start(){return this.#s.ready&&this.#h?this.status:this.#S?this.#S:(this.#S=this.#Q().finally(()=>{this.#S=null}),this.#S)}async#Q(){await this.stop(),this.#y=!1,this.#f=0,this.#s.startedAt=new Date().toISOString(),this.#s.connectionState="connecting",this.#s.lastError=null,await this.#r.ensureRunning(),this.#s.harnessReachable=!0;let t=new AbortController;this.#d=t;let o=this.#l({botToken:this.#A,appToken:this.#t});this.#c=o;try{let i=await o.authTest({signal:t.signal});if(`${i?.team_id}:${i?.user_id}`!==this.#e.platformId)throw new Error("Slack Bot Token identity does not match the saved bot");let e=new KP({api:o,signal:t.signal,logger:this.#n});this.#p=new HS({bot:e,harness:this.#r,state:this.#g,contextEnhancement:this.#a,status:this.#s,logger:this.#n,replyTimeoutMs:this.#i,signal:t.signal});let a;try{await Promise.race([this.#m(),new Promise((A,r)=>{a=setTimeout(()=>r(new Error("Slack Socket Mode did not become ready in time")),this.#I),a?.unref?.()})])}finally{clearTimeout(a)}return this.status}catch(i){throw this.#s.ready=!1,this.#s.connectionState="failed",this.#s.lastError=i?.message??String(i),await this.stop(),i}}async#m(){if(this.#y)throw new Error("Slack runtime is stopped");let t=await this.#c.openConnection({signal:this.#d?.signal});return this.#u(t?.url)}#u(t){if(this.#y)return Promise.reject(new Error("Slack runtime is stopped"));let o=++this.#B,i=this.#o(WPe(t));this.#h=i;let e=!1;return new Promise((a,A)=>{let r=s=>{if(e||o!==this.#B)return;e=!0,this.#E=s?.connection_info?.app_id??null,this.#f=0;let g=Date.now();this.#s.ready=!0,this.#s.connectionState="connected",this.#s.lastCheckedAt=g,this.#s.lastConnectedAt=g,this.#s.lastError=null,a()};LP(i,"message",s=>{if(o!==this.#B||this.#y)return;let g=VPe(s);if(!g)return;let c;try{c=JSON.parse(g)}catch{this.#n.warn?.("[dsh-im:slack] ignored malformed Socket Mode JSON");return}if(c.type==="hello"){r(c);return}if(c.envelope_id&&i.readyState===1&&(i.send(JSON.stringify({envelope_id:c.envelope_id})),this.#s.lastCheckedAt=Date.now()),c.type==="disconnect"){i.close(4e3,"Slack requested reconnect");return}if(c.type!=="events_api"||c.payload?.type!=="event_callback"||this.#E&&c.payload.api_app_id&&c.payload.api_app_id!==this.#E)return;let I=AGe(c.payload,this.#e.platformId.split(":")[1],{loadFile:(B,f)=>this.#c.downloadFile({url:B,...f}),loadFileStream:(B,f)=>this.#c.downloadFileStream({url:B,...f}),loadFileInfo:(B,f)=>this.#c.fileInfo({fileId:B,...f})}),d=this.#p;I&&d&&d.accept(I).catch(B=>{o!==this.#B||this.#y||this.#n.error?.(`[dsh-im:slack] bot ${this.#e.botId} message handling failed:`,B)})}),LP(i,"close",(s={})=>{if(o!==this.#B)return;if(this.#h===i&&(this.#h=null),this.#y){e||A(new DOMException("Stopped","AbortError"));return}let g=Number(s.code)||0,c=new Error(`Slack Socket Mode closed (${g||"unknown"})`);this.#s.ready=!1,this.#s.connectionState="connecting",this.#s.lastError=c.message,e||(e=!0,A(c)),this.#b()}),LP(i,"error",()=>{o!==this.#B||this.#y||(this.#s.lastError="Slack Socket Mode WebSocket error")})})}#b(){if(this.#y||this.#C!==null)return;let t=b5[Math.min(this.#f,b5.length-1)];this.#f+=1,this.#C=setTimeout(()=>{this.#C=null,this.#m().catch(o=>{this.#y||(this.#n.warn?.("[dsh-im:slack] Socket Mode reconnect failed:",o),this.#b())})},t),this.#C?.unref?.()}async stop(){this.#y=!0,this.#B+=1,this.#d?.abort(),this.#d=null,this.#C!==null&&clearTimeout(this.#C),this.#C=null;let t=this.#h,o=this.#p;this.#h=null,this.#p=null,this.#c=null,this.#E=null;try{t&&t.readyState<2&&t.close(1e3,"Plugin stopped")}catch(i){this.#n.warn?.(`[dsh-im:slack] bot ${this.#e.botId} failed to close Socket Mode:`,i)}return await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#s.ready=!1,this.#s.connectionState="idle",this.status}};var YS=class extends As{};async function xP(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-im slack requires ctx.credentials");let i=Aa(n,t),e=o.ConfigStore??US,a=o.StateStore??YS,A=o.HarnessClient??xS,r=o.Controller??Lu,s=o.Runtime??Uu,g=o.createConnectionSupervisor??vp,c=typeof n.logger=="function"?n.logger("dsh-im:slack"):n.logger??console,I=()=>Ra(n),d=k_(t,"slack"),B=await new e(d.config).load(),f=N5(t.workspace??process.cwd()),Q=o.WorkspaceStore??ea,y=o.workspaces??await new Q(d.workspaces,{defaultWorkspace:f}).load(),m=B.list();await y.reconcile(m.map(N=>N.botId)),await Promise.all(m.map(N=>y.ensure(N.botId,{defaultAgentPreset:t.agentPreset})));let _=typeof B.remove=="function"?Pa(B,{workspaces:y}):B,T=new Map,R=N=>N5(d.bots,N,"state.json"),F=async N=>{let k=T.get(N);return k||(k=await new a(R(N)).load(),T.set(N,k)),k},K=Ua(n,o.commandExecutor),{controlExecutor:L,sessionMaintenanceExecutor:q,fileIngressExecutor:z}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),j=new A({...i,workspace:f,autostart:!1,dshBin:t.dshBin??"dsh",...K?{commandExecutor:K}:{},...L?{controlExecutor:L}:{},...q?{sessionMaintenanceExecutor:q}:{},...z?{fileIngressExecutor:z}:{}}),P=new r({credentials:n.credentials,configStore:_,logger:c,...o.inspectCredentials?{inspectCredentials:o.inspectCredentials}:{},createRuntime:async({botId:N,config:k,botToken:V,appToken:Ae})=>{let ie=await F(N);await y.ensure(N,{defaultAgentPreset:t.agentPreset});let De=Ga(j,{botId:N,workspaces:y,state:ie,agentPresetCatalog:I});return new s({config:k,botToken:V,appToken:Ae,harness:De.harness,state:De.state,contextEnhancement:{botId:N,getSettings:()=>y.contextEnhancementFor(N)},replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??2e4,logger:{error:(...fe)=>c.error?.(`[${N}]`,...fe),warn:(...fe)=>c.warn?.(`[${N}]`,...fe),info:(...fe)=>c.info?.(`[${N}]`,...fe),debug:(...fe)=>c.debug?.(`[${N}]`,...fe)}})},deleteState:async({botId:N})=>{let k=T.get(N);if(T.delete(N),k&&typeof k.remove=="function")await k.remove();else try{await iGe(R(N))}catch(V){if(V?.code!=="ENOENT")throw V}}}),J=Fa(P,{workspaces:y,stateFor:F,agentPresetCatalog:I}),U=g({channel:"slack",controller:J,harness:j,logger:c,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:J,deliveryAdapter:La({channel:"slack",workspaces:y,coreController:P,stateFor:F}),ready:U.ready,async close(){await U.close(),await J.close(),j.stopManagedProcess()}}}var k5="/slack",ti=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),v5=Object.freeze(Object.values(ti)),oGe=new Set(["token","botToken","appToken","botTokenRef","appTokenRef","tokenRef","platformId","secret","secretRef"]);function jP(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function jS(n,t){return jP(n)&&Object.keys(n).every(o=>t.includes(o))}function R5(n){return typeof n=="string"&&/^slack_[a-f0-9]{24}$/.test(n)}function nGe(n){return typeof n=="string"&&/^xoxb-[A-Za-z0-9-]{16,}$/.test(n.trim())&&n.length<=4096}function sGe(n){return typeof n=="string"&&/^xapp-[A-Za-z0-9-]{16,}$/.test(n.trim())&&n.length<=4096}function gGe(n,t){return jP(t)?n===ti.status?jS(t,[])?null:"connection.status does not accept fields.":n===ti.bindCredentials?jS(t,["botToken","appToken"])&&nGe(t.botToken)&&sGe(t.appToken)?null:"bot.bind-credentials requires xoxb Bot Token and xapp App Token.":n===ti.reconnectBot?jS(t,["botId","sendTest"])&&R5(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId.":n===ti.deleteBot?jS(t,["botId","confirm"])&&R5(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===ti.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===ti.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===ti.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown Slack endpoint.":"Payload must be an object."}function YP(n){if(Array.isArray(n))return n.map(YP);if(!jP(n))return n;let t={};for(let[o,i]of Object.entries(n))oGe.has(o)||(t[o]=YP(i));return t}function cGe(n){let t=Ya(n);return t||(n?.code==="slack-invalid-bot-token"?{code:"invalid-bot-token",message:"Slack Bot Token \u65E0\u6548\uFF0C\u8BF7\u786E\u8BA4\u4F7F\u7528\u4EE5 xoxb- \u5F00\u5934\u7684\u4EE4\u724C\u3002"}:n?.code==="slack-invalid-app-token"?{code:"invalid-app-token",message:"Slack App Token \u65E0\u6548\uFF0C\u8BF7\u786E\u8BA4\u4F7F\u7528\u4EE5 xapp- \u5F00\u5934\u7684\u4EE4\u724C\u3002"}:n?.code==="slack-missing-scope"?{code:"missing-scope",message:"Slack \u5E94\u7528\u6743\u9650\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u91CD\u65B0\u5BFC\u5165 Manifest \u5E76\u5B89\u88C5\u5230\u5DE5\u4F5C\u533A\u3002"}:n?.code==="slack-socket-mode"?{code:"socket-mode-unavailable",message:n.message}:{code:"slack-operation-failed",message:"Slack \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"})}function P5(n){for(let t of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[t]!="function")throw new TypeError(`A complete Slack controller is required (${t})`);return async(t,o,i)=>{if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!v5.includes(t))return{ok:!1,error:{code:"bad-request",message:"Unknown Slack endpoint."}};let e=gGe(t,o);if(e)return{ok:!1,error:{code:"bad-request",message:e}};try{let a;if(t===ti.status)a=await n.status();else if(t===ti.bindCredentials)a=await n.bindCredentials(o);else if(t===ti.reconnectBot){if(a=await n.reconnectBot(o.botId),i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(o.sendTest===!0){let A=null;try{if(a?.bots?.find(r=>r?.botId===o.botId)?.connected!==!0){let r=new Error("Bot is not connected");throw r.code="test-target-unavailable",r}if(typeof n.sendConnectionTest!="function"){let r=new Error("Connection test is unavailable");throw r.code="test-target-unavailable",r}await n.sendConnectionTest(o.botId)}catch(r){A=r}a={...a,testMessage:ir(A)}}}else if(t===ti.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");a=await n.updateWorkspace(o.botId,o.workspace)}else if(t===ti.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");a=await n.updateContextEnhancement(o.botId,o.config)}else if(t===ti.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");a=await n.updateAgentPreset(o.botId,o.agentPreset)}else a=await n.deleteBot(o.botId);return i?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:YP(a)}}catch(a){return i?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:cGe(a)}}}}function JS(n,t,o){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(k5,P5(t),{authority:hr(o)})}async function G5(n,t={}){if(t?.controller)return JS(n,t.controller,t.rpcAuthority);let o=await xP(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=JS(n,o.controller,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Slack bot connections"),e}var F5=Object.freeze({botPrefix:"telegram",tokenRefPrefix:"DSH_TELEGRAM_BOT_TOKEN"}),Hu=Object.freeze({compatible:"compatible",privateAllowlist:"private-allowlist"}),IGe=/^[1-9]\d{0,15}$/;function L5(n){if(n===void 0)return Object.freeze([]);if(!Array.isArray(n))throw new TypeError("allowedUsers must be an array of numeric Telegram User IDs");let t=n.map(o=>{let i=typeof o=="number"&&Number.isSafeInteger(o)?String(o):typeof o=="string"?o.trim():"";if(!IGe.test(i))throw new TypeError("allowedUsers contains an invalid Telegram User ID");return i});return Object.freeze([...new Set(t)])}function Mc(n={}){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("Telegram access policy must be an object");let t=n.accessMode??Hu.compatible;if(!Object.values(Hu).includes(t))throw new TypeError("Telegram accessMode must be compatible or private-allowlist");return Object.freeze({accessMode:t,allowedUsers:L5(n.allowedUsers)})}function lGe(n){let t=Object.hasOwn(n,"accessMode"),o=Object.hasOwn(n,"allowedUsers");if(!t&&!o)return{};try{let i=Mc(n);return{...t?{accessMode:i.accessMode}:{},...o||t?{allowedUsers:i.allowedUsers}:{}}}catch{return null}}function U5(n){return KE(n,F5)}function H5(n){return kQ(n,w("Telegram\u673A\u5668\u4EBA"))}var qS=class extends Np{constructor(t){super(t,{channel:"Telegram",...F5,normalizeBotExtension:lGe})}async save(t){let o=t?.platformId?this.getByPlatformId(String(t.platformId)):null;return super.save({...o,...t})}};var zS=class extends lr{constructor(t){super({...t,rpcIdPrefix:"telegram",logPrefix:"dsh-telegram"})}};var pGe="https://api.telegram.org/",K5=Object.freeze(["api.telegram.org"]),dGe=12e4;function Sg(n){return typeof n=="string"&&n.trim()?n.trim():null}function x5(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}function JP(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function hGe(n,t){if(!Number.isInteger(n)||n<1)throw new TypeError(`${t} must be a positive integer`);return n}function j5(n,t){return t?.providerCode!==void 0&&(n.providerCode=t.providerCode),t?.retry_after!==void 0&&(n.retry_after=t.retry_after,n.retryAfter=t.retry_after),Number.isInteger(t?.status)&&(n.status=t.status),n}function qP(n){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("A Telegram rich message is required");let t=["markdown","html","blocks"].filter(i=>n[i]!==void 0);if(t.length!==1)throw new TypeError("A Telegram rich message requires exactly one format");let o=t[0];if((o==="markdown"||o==="html")&&(typeof n[o]!="string"||!n[o].trim()))throw new TypeError("Telegram rich message text is invalid");if(o==="blocks"&&!Array.isArray(n.blocks))throw new TypeError("Telegram rich message blocks are invalid");return n}function EGe(n,t="document"){let o=Number(n?.providerCode),i=Number(n?.status),e=Sg(n?.message)??"",a="artifact-provider-rejected",A=`Telegram rejected the ${t}.`;o===401||o===403||i===401||i===403?(a="artifact-permission-required",A=`Telegram denied permission to send the ${t}.`):o===413||i===413||/(?:file|request|entity).{0,20}(?:too (?:big|large)|size limit)|too (?:big|large)/i.test(e)?(a="artifact-too-large",A=`The ${t} exceeds Telegram's size limit.`):o===429||i===429?(a="artifact-rate-limited",A=`Telegram rate-limited ${t} delivery.`):(o>=500||i>=500)&&(a="artifact-delivery-uncertain",A=`Telegram ${t} delivery result is uncertain.`);let r=new Error(A,{cause:n});return r.code=a,j5(r,n)}function Y5(n,t="document"){let o=new Error(`Telegram ${t} delivery result is uncertain`,{cause:n});return o.code="artifact-delivery-uncertain",j5(o,n)}function CGe(n){return typeof n=="string"&&/^\d{5,20}:[A-Za-z0-9_-]{20,}$/.test(n.trim())}var uGe=/^[a-z0-9_]{1,32}$/;function BGe(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.command=="string"&&uGe.test(n.command)&&typeof n.description=="string"&&n.description.length>=1&&n.description.length<=256}var zP=Object.freeze({type:"commands"}),Ku=class{#e;#A;#t;#r;#g;constructor({token:t,fetchImpl:o=fetch,FormDataImpl:i=globalThis.FormData,baseUrl:e=pGe,fileUploadTimeoutMs:a=dGe}){if(!CGe(t))throw new TypeError("Telegram Bot Token is invalid");if(typeof o!="function")throw new TypeError("TelegramApi requires fetch");if(typeof i!="function")throw new TypeError("TelegramApi requires FormData");this.#e=t.trim(),this.#A=o,this.#t=i,this.#r=new URL(e),this.#g=hGe(a,"fileUploadTimeoutMs")}async getMe(t={}){return this.#i("getMe",{},t)}async getWebhookInfo(t={}){return this.#i("getWebhookInfo",{},t)}async getUpdates({offset:t,timeout:o=25,signal:i}={}){let e={timeout:o,limit:100,allowed_updates:["message"],...Number.isSafeInteger(t)?{offset:t}:{}};return this.#i("getUpdates",e,{signal:i,timeoutMs:Math.max(1e4,(o+10)*1e3)})}async getFile({fileId:t,signal:o}={}){let i=Sg(t);if(!i||!/^[A-Za-z0-9_-]{1,512}$/.test(i))throw new TypeError("Telegram file id is invalid");return this.#i("getFile",{file_id:i},{signal:o})}async downloadFile({fileId:t,signal:o,maxBytes:i}={}){let e=await this.#a(t,o);return uo(e,{fetchImpl:this.#A,signal:o,maxBytes:i,allowedHosts:K5})}async downloadFileStream({fileId:t,signal:o}={}){let i=await this.#a(t,o);return kp(i,{fetchImpl:this.#A,signal:o,allowedHosts:K5})}async#a(t,o){let i=await this.getFile({fileId:t,signal:o}),e=Sg(i?.file_path);if(!e||e.startsWith("/")||e.includes("\\")||e.includes("?")||e.includes("#"))throw new Error("Telegram returned an invalid file path");let a;try{a=e.split("/").map(r=>decodeURIComponent(r))}catch{throw new Error("Telegram returned an invalid file path")}if(a.some(r=>!r||r==="."||r===".."))throw new Error("Telegram returned an invalid file path");let A=new URL(this.#r);return A.pathname=`/file/bot${this.#e}/${e}`,A}async sendMessage({chatId:t,text:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#i("sendMessage",{chat_id:t,text:o,link_preview_options:{is_disabled:!0},...i?{reply_parameters:{message_id:i,allow_sending_without_reply:!0}}:{},...e?{message_thread_id:e}:{}},{signal:a})}async setMessageReaction({chatId:t,messageId:o,emoji:i,signal:e,timeoutMs:a}){let A=Sg(i);return this.#i("setMessageReaction",{chat_id:t,message_id:o,reaction:A?[{type:"emoji",emoji:A}]:[]},{signal:e,timeoutMs:a})}async sendRichMessage({chatId:t,richMessage:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#i("sendRichMessage",{chat_id:t,rich_message:qP(o),...i?{reply_parameters:{message_id:i,allow_sending_without_reply:!0}}:{},...e?{message_thread_id:e}:{}},{signal:a})}async sendRichMessageDraft({chatId:t,draftId:o,richMessage:i,messageThreadId:e,signal:a}){if(!Number.isSafeInteger(o)||o===0)throw new TypeError("Telegram rich message draft id must be a non-zero integer");return this.#i("sendRichMessageDraft",{chat_id:t,draft_id:o,rich_message:qP(i),...e?{message_thread_id:e}:{}},{signal:a})}async sendDocument({chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#n("sendDocument","document","document",{chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a})}async sendPhoto({chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#n("sendPhoto","photo","photo",{chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a})}async#n(t,o,i,{chatId:e,file:a,replyToMessageId:A,messageThreadId:r,signal:s}){if(!a||typeof a!="object"||typeof a.fileName!="string"||!a.fileName||!Buffer.isBuffer(a.bytes))throw new TypeError(`A Telegram ${i} is required`);let g=new this.#t;if(g.append("chat_id",String(e)),g.append(o,new Blob([a.bytes],{type:a.mediaType??"application/octet-stream"}),a.fileName),A&&g.append("reply_parameters",JSON.stringify({message_id:A,allow_sending_without_reply:!0})),r&&g.append("message_thread_id",String(r)),s?.aborted)throw JP(s);let c=x5(s,this.#g);try{return await this.#i(t,g,{signal:c,timeoutMs:this.#g,multipart:!0})}catch(I){throw s?.aborted?JP(s):I?.deliveryOutcome==="unknown"?Y5(I?.cause??I,i):I?.code?.startsWith?.("telegram-")?EGe(I,i):Y5(I,i)}}async editMessageText({chatId:t,messageId:o,text:i,richMessage:e,signal:a}){if(i===void 0==(e===void 0))throw new TypeError("Telegram message edit requires exactly one of text or richMessage");return this.#i("editMessageText",{chat_id:t,message_id:o,...i===void 0?{rich_message:qP(e)}:{text:i,link_preview_options:{is_disabled:!0}}},{signal:a})}async sendChatAction({chatId:t,messageThreadId:o,signal:i}){return this.#i("sendChatAction",{chat_id:t,action:"typing",...o?{message_thread_id:o}:{}},{signal:i})}async setMyCommands({commands:t,scope:o,languageCode:i,signal:e}={}){if(!Array.isArray(t)||t.length===0||t.some(a=>!BGe(a)))throw new TypeError("Telegram bot commands are invalid");return this.#i("setMyCommands",{commands:t,...o?{scope:o}:{},...Sg(i)?{language_code:Sg(i)}:{}},{signal:e})}async setChatMenuButton({menuButton:t=zP,signal:o}={}){if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("Telegram menu button is invalid");return this.#i("setChatMenuButton",{menu_button:t},{signal:o})}async#i(t,o,{signal:i,timeoutMs:e=15e3,multipart:a=!1}={}){if(i?.aborted)throw JP(i);let A=new URL(this.#r);A.pathname=`${A.pathname.replace(/\/$/,"")}/bot${this.#e}/${t}`;let r;try{r=await this.#A(A,{method:"POST",...a?{}:{headers:{"content-type":"application/json"}},body:a?o:JSON.stringify(o),signal:x5(i,e),redirect:"error"})}catch(g){let c=new Error(`Telegram ${t} transport failed`,{cause:g});throw c.code=g?.name==="TimeoutError"?"telegram-timeout":g?.name==="AbortError"?"telegram-aborted-after-dispatch":"telegram-transport-error",c.deliveryOutcome="unknown",c}let s;try{s=await r.json()}catch{let g=new Error(`Telegram ${t} returned invalid JSON`);throw g.status=r?.status,g.code="telegram-response-invalid",g.deliveryOutcome="unknown",g}if(!r.ok||s?.ok!==!0){let g=Sg(s?.description),c=new Error(g??`Telegram ${t} failed`);c.code=Number.isInteger(s?.error_code)?`telegram-${s.error_code}`:"telegram-api-error",c.status=r.status,Number.isInteger(s?.error_code)&&(c.providerCode=s.error_code);let I=Number(s?.parameters?.retry_after);throw Number.isFinite(I)&&I>=0&&(c.retry_after=I,c.retryAfter=I),c}return s.result}};async function J5(n,t={}){let i=await new Ku({token:n,...t}).getMe();if(!i?.id||i?.is_bot!==!0)throw new Error("Telegram token does not belong to a bot");return{platformId:String(i.id),name:Sg([i.first_name,i.last_name].filter(Boolean).join(" "))??w("Telegram\u673A\u5668\u4EBA"),username:Sg(i.username)}}var VP=Object.freeze({key:"telegram",label:"Telegram",connectionLabel:" Bot API \u957F\u8F6E\u8BE2",reactions:Object.freeze({processing:"\u{1F440}",success:"\u{1F44D}",error:"\u{1F44E}"})}),VS=class extends $n{constructor(t){super({descriptor:VP,...t})}};var xu=class extends Rp{#e;constructor(t){super({...t,descriptor:VP,inspectToken:t.inspectToken??J5,deriveIdentity:U5,maskPlatformId:H5}),this.#e=t.configStore}status(){let t=super.status();return{...t,bots:t.bots.map(o=>{let i=this.#e.get(o.botId),e=Mc(i??{});return{...o,accessPolicy:e}})}}async setAccessPolicy(t,o){let i=Mc(o);return this.updateBotConfig(t,e=>({...e,...i}))}};import{randomInt as OGe}from"node:crypto";import{EnvHttpProxyAgent as fGe,FormData as QGe,fetch as yGe}from"undici";var mGe=4;function q5(){let n=new fGe({connections:mGe}),t=!1;return{fetchImpl:(o,i={})=>yGe(o,{...i,dispatcher:n}),FormDataImpl:QGe,async destroy(){t||(t=!0,await n.destroy())}}}function ZP(n){if(typeof n!="string"||!n.trim())throw new TypeError("Telegram message text must be a non-empty string");return n}function XP(n){return n==="&"?5:n==="<"||n===">"?4:1}function WP(n){return Array.from(n).reduce((t,o)=>t+XP(o),0)}function SGe(n,t,o,i){let e=t+Math.floor(i*.5);for(let a=o-1;a>=e;a-=1)if(n[a]===` +${_}`:L),await g()}catch(L){this.#n.error?.("[dsh-im:qq] failed to send the safe error reply:",L)}}}async#u(t,o,i,e){this.#I?.throwIfAborted();let a=this.#c.get(i),A=e.claimedReplyMessageId===o;if(!a||a!==e||a.submitting)return A&&(!a||a!==e)?this.#w(t,o):this.#B(t,o,i,{releaseMessageId:!1});if(this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),t.kind==="group"&&t.rawEventType!=="GROUP_AT_MESSAGE_CREATE"))return;let r=io(Nu(t));if(!r||Tu(t)||Pd(t)){await this.#e.sendText(t.replyTarget,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002"));return}let s=this.#c.get(i);if(!s||s!==e||s.submitting){if(A&&(!s||s!==e)){await this.#e.sendText(t.replyTarget,NS());return}return this.#B(t,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}if(s.target=t.replyTarget,s.needsPresentation){try{await this.#D(s)}catch{this.#a.lastError=w("QQ \u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002"),this.#n.error?.("[dsh-im:qq] failed to retry an interaction question"),s.interaction.reconnect?.();return}let c=this.#c.get(i);if(!c||c!==e||c.submitting){if(A&&(!c||c!==e)){await this.#e.sendText(t.replyTarget,NS()).catch(()=>{});return}return this.#B(t,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}}let g=s.questions[s.index];if(g){if(s.answers.push(Ei(g,r)),s.index+=1,s.index{});return}if(this.#c.get(i)!==s)return;s.submitting=!1,s.answers.pop(),s.index-=1,this.#a.lastError=w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002"),this.#n.error?.("[dsh-im:qq] failed to answer a Harness interaction"),await this.#e.sendText(s.target,w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002")).catch(()=>{})}}}async#b(t,{key:o,actor:i,target:e,requiresMention:a}){if(t?.kind==="approval")return this.#C.handleRequested(t,{key:o,actor:i,requiresMention:a,send:c=>this.#e.sendText(e,c)});if(t?.kind!=="question")return;let A=t?.payload?.questions,r=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t?.rpcId!="string"||typeof r!="string"||typeof t.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!di(c))){this.#n.warn?.("[dsh-im:qq] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"QQ safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#e.sendText(e,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002")).catch(()=>{});return}let s=this.#c.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#D(s);return}if(this.#p.has(r))return;if(s){await t.respond({ok:!1,error:{code:"cancelled",message:"QQ is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,requiresMention:a,questions:A,answers:[],index:0,target:e,queue:null,claimedReplyMessageId:null,presentationPromise:null,submitting:!1,needsPresentation:!0};this.#c.set(o,g),this.#p.set(r,o),await this.#D(g)}async#R(t){if(t?.kind==="approval"){await this.#C.handleResolved(t);return}let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#p.get(o);i&&this.#k(i,o)}#D(t){if(!t.needsPresentation)return Promise.resolve();if(t.presentationPromise)return t.presentationPromise;let o=t.questions[t.index];if(!o)return Promise.resolve();let i=this.#e.sendText(t.target,hi(o,t.index,t.questions.length,{requiresMention:t.requiresMention})).then(()=>{t.needsPresentation=!1}).finally(()=>{t.presentationPromise===i&&(t.presentationPromise=null)});return t.presentationPromise=i,i}async#w(t,o){this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),await this.#e.sendText(t.replyTarget,NS()).catch(()=>{}))}#T(t,o){let i=this.#c.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#c.delete(t),this.#p.delete(i.interactionId),i)}#k(t,o){return this.#T(t,o)!==null}async#M(t){let o=this.#T(t);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The QQ interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#n.warn?.("[dsh-im:qq] failed to cancel a pending Harness interaction")}}async#L(t,o,i){if(this.#I?.aborted)return;this.#a.lastError=i?.message??String(i);let e=tt(this.#a,i);this.#n.error?.(`[dsh-im:qq] failed to process an interaction reply [${e.referenceId}]:`,i),this.#r.hasSeen(o)||await this.#r.markSeen(o).catch(()=>{}),await this.#e.sendText(t.replyTarget,dt(e)).catch(()=>{})}};function nPe(){let n=new Error("QQ WebSocket did not become ready in time");return n.code="connect-timeout",n}function sPe(){return{startedAt:null,ready:!1,qqConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...bP()}}var Ru=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o=sPe();#s=null;#c=null;#p=null;#d=null;#h=null;constructor({config:t,appSecret:o,harness:i,state:e,contextEnhancement:a,logger:A=console,replyTimeoutMs:r=6e5,connectTimeoutMs:s=2e4,createBot:g=I=>new aPe(I),typingMiddleware:c=oPe}){if(!t||!o||!i||!e)throw new TypeError("QqRuntime requires config, app secret, Harness, and state");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c}get status(){return structuredClone(this.#o)}async sendConnectionTest(t){if(!this.#o.ready||!this.#s)throw Ir(w("QQ\u673A\u5668\u4EBA"));let o=typeof this.#e.ownerUserOpenid=="string"?this.#e.ownerUserOpenid.trim():"",i=SE(this.#r),e=i?.scope==="c2c"&&typeof i.targetId=="string"?i.targetId.trim():"",a=e?{scope:"c2c",targetId:e}:o&&o!=="*"?{scope:"c2c",targetId:o}:null;if(!a)throw Ir(w("QQ\u673A\u5668\u4EBA"));return await this.#s.sendText(a,t),{sent:!0}}async sendProactiveText(t,o,{signal:i}={}){let e=t?.kind==="user"?typeof t?.route?.userOpenId=="string"?t.route.userOpenId.trim():"":t?.kind==="group"&&typeof t?.route?.groupOpenId=="string"?t.route.groupOpenId.trim():"";if(!e){let a=new TypeError("Invalid QQ proactive delivery target");throw a.code="invalid-target",a}if(!this.#o.ready||!this.#s){let a=new Error("QQ bot is not connected");throw a.code="bot-not-connected",a}return i?.throwIfAborted(),this.#s.sendText({scope:t.kind==="user"?"c2c":"group",targetId:e},o)}async start(){return this.#o.ready&&this.#s?this.status:this.#h?this.#h:(this.#h=this.#E().finally(()=>{this.#h=null}),this.#h)}async#E(){await this.stop(),this.#o.startedAt=new Date().toISOString(),this.#o.qqConnectionState="connecting",this.#o.lastError=null,await this.#t.ensureRunning(),this.#o.harnessReachable=!0;let t={error:(...d)=>this.#a.error?.(...d),warn:(...d)=>this.#a.warn?.(...d),info:(...d)=>this.#a.info?.(...d),debug:()=>{}},o=this.#I({appId:this.#e.appId,appSecret:this.#A,accountId:this.#e.botId,logger:t,transport:"websocket",tokenPrefetch:"sync",markdownSupport:!1});if(!o||typeof o.start!="function"||typeof o.stop!="function")throw new TypeError("QQ bot factory returned an invalid client");let i=new AbortController;this.#p=i,this.#s=o,this.#c=new kS({bot:o,ownerUserOpenid:this.#e.ownerUserOpenid,harness:this.#t,state:this.#r,contextEnhancement:this.#g,status:this.#o,logger:this.#a,replyTimeoutMs:this.#n,signal:i.signal}),o.use(iPe({parseFaceTags:!0})),o.use?.(this.#l({keepAlive:!0,predicate:d=>this.#e.ownerUserOpenid==="*"||d?.message?.senderId===this.#e.ownerUserOpenid}));let e,a,A=new Promise((d,B)=>{e=d,a=B}),r=()=>{let d=Date.now();this.#o.ready=!0,this.#o.qqConnectionState="connected",this.#o.lastCheckedAt=d,this.#o.lastConnectedAt=d,this.#o.lastError=null,e()},s=d=>{this.#o.ready?(this.#o.lastError=d?.message??String(d),this.#a.warn?.(`[dsh-im:qq] bot ${this.#e.botId} connection error:`,d)):a(d)},g=(d,B)=>{let f=this.#c?.accept(B);f&&f.catch(Q=>{i.signal.aborted||this.#a.error?.(`[dsh-im:qq] bot ${this.#e.botId} message handling failed:`,Q)})};o.on("ready",r),o.on("resumed",r),o.on("error",s),o.on("message",g);let c=Promise.resolve().then(()=>o.start(i.signal));this.#d=c,c.catch(d=>{i.signal.aborted||(a(d),this.#o.ready=!1,this.#o.qqConnectionState="failed",this.#o.lastError=d?.message??String(d),this.#a.error?.(`[dsh-im:qq] bot ${this.#e.botId} connection stopped:`,d))});let I;try{return await Promise.race([A,new Promise((d,B)=>{I=setTimeout(()=>B(nPe()),this.#i)})]),this.#o.ready=!0,this.#o.qqConnectionState="connected",this.#o.lastCheckedAt=Date.now(),this.#o.lastConnectedAt=Date.now(),this.status}catch(d){throw this.#o.ready=!1,this.#o.qqConnectionState="failed",this.#o.lastError=d?.message??String(d),await this.stop(),d}finally{clearTimeout(I)}}async stop(){let t=this.#s,o=this.#c,i=this.#d;this.#p?.abort(),this.#p=null,this.#s=null,this.#c=null,this.#d=null;try{t?.stop()}catch(e){this.#a.warn?.(`[dsh-im:qq] bot ${this.#e.botId} failed to stop cleanly:`,e)}return await Promise.race([i?.catch(()=>{})??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),await o?.waitForIdle(),this.#o.ready=!1,this.#o.qqConnectionState="idle",this.status}};import{startQrConnect as gPe}from"@tencent-connect/qqbot-connector";var vS=class{#e;#A;constructor({start:t=gPe,source:o="deepseek-harness"}={}){if(typeof t!="function")throw new TypeError("QQ QR connector is required");this.#e=t,this.#A=o}start(t,{signal:o}={}){if(!t||typeof t.onSuccess!="function"||typeof t.onFailure!="function")throw new TypeError("QQ QR callbacks are required");return this.#e(t,{displayQrCodeToConsole:!1,source:this.#A,signal:o})}};import{mkdir as cPe,readFile as IPe,rename as lPe,unlink as pPe,writeFile as dPe}from"node:fs/promises";import{dirname as hPe}from"node:path";var PS=Object.freeze({version:1,sessions:{},seenMessageIds:[]});function EPe(n){if(!n||typeof n!="object")return structuredClone(PS);let t={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&typeof i=="string"&&i&&(t[o]=i);return{version:1,sessions:t,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[]}}var GS=class{#e;#A=structuredClone(PS);#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{this.#A=EPe(JSON.parse(await IPe(this.#e,"utf8")))}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=structuredClone(PS),await this.#r()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){this.#A.sessions[t]=o,await this.#r()}async clearSession(t){delete this.#A.sessions[t],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(t){return this.#A.seenMessageIds.includes(t)}async markSeen(t){this.hasSeen(t)||(this.#A.seenMessageIds.push(t),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}snapshot(){return structuredClone(this.#A)}async remove(){try{await pPe(this.#e)}catch(t){if(t?.code!=="ENOENT")throw t}this.#A=structuredClone(PS)}async#r(){let t=`${JSON.stringify(this.#A,null,2)} +`,o=this.#t.then(async()=>{await cPe(hPe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await dPe(i,t,{encoding:"utf8",mode:384}),await lPe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var h5=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function CPe(n){if(!Array.isArray(n)||n.length===0)return[...h5];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...h5]}var FS=class{#e;#A;#t;#r;#g;#a;#n;#i=null;#I=null;#l=0;#o=!1;#s=!1;#c;#p;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=CPe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#a=A,this.#n=r,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#s||this.#o?this:(this.#s=!0,this.#d(0),this)}async close(){this.#o||(this.#o=!0,this.#i!==null&&this.#n(this.#i),this.#i=null,await this.#I?.catch(()=>{}),this.#p?.(null),this.#p=null)}#d(t){this.#o||(this.#i=this.#a(()=>{this.#i=null,this.#h()},t),this.#i?.unref?.())}async#h(){if(this.#o||this.#I)return;let t=this.#E();this.#I=t;try{await t}finally{this.#I===t&&(this.#I=null)}}async#E(){try{if(await this.#A.ensureRunning(),this.#o)return;let t=await this.#e.initialize();if(this.#o)return;this.#p?.(t),this.#p=null;let{configured:o,connected:i}=t.totals;if(iRa(n),B=fPe(t),f=await new e(B.config).load(),Q=Il(t.workspace??process.cwd()),y=o.WorkspaceStore??ea,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=f.list();await m.reconcile(_.map(V=>V.botId)),await Promise.all(_.map(V=>m.ensure(V.botId,{defaultAgentPreset:t.agentPreset})));let T=typeof f.remove=="function"?Pa(f,{workspaces:m}):f,R=o.qrAuth??new g({source:t.qrSource??"deepseek-harness"}),L=new Map,U=V=>Il(B.bots,V,"state.json"),F=async V=>{let Ae=L.get(V);return Ae||(Ae=await new a(U(V)).load(),L.set(V,Ae)),Ae},q=Ua(n,o.commandExecutor),{controlExecutor:z,sessionMaintenanceExecutor:j,fileIngressExecutor:P}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),J=new A({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...q?{commandExecutor:q}:{},...z?{controlExecutor:z}:{},...j?{sessionMaintenanceExecutor:j}:{},...P?{fileIngressExecutor:P}:{}}),H=new r({qrAuth:R,credentials:n.credentials,configStore:T,logger:I,createRuntime:async({botId:V,config:Ae,appSecret:ie})=>{let De=await F(V);await m.ensure(V,{defaultAgentPreset:t.agentPreset});let fe=Ga(J,{botId:V,workspaces:m,state:De,agentPresetCatalog:d});return new s({config:Ae,appSecret:ie,harness:fe.harness,state:fe.state,contextEnhancement:{botId:V,getSettings:()=>m.contextEnhancementFor(V)},replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??2e4,logger:{error:(..._e)=>I.error?.(`[${V}]`,..._e),warn:(..._e)=>I.warn?.(`[${V}]`,..._e),info:(..._e)=>I.info?.(`[${V}]`,..._e),debug:(..._e)=>I.debug?.(`[${V}]`,..._e)}})},deleteState:async({botId:V})=>{let Ae=L.get(V);if(L.delete(V),Ae&&typeof Ae.remove=="function")await Ae.remove();else try{await uPe(U(V))}catch(ie){if(ie?.code!=="ENOENT")throw ie}}}),N=Fa(H,{workspaces:m,stateFor:F,agentPresetCatalog:d}),k=c({controller:N,harness:J,logger:I,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:N,deliveryAdapter:La({channel:"qq",workspaces:m,coreController:H,stateFor:F}),ready:k.ready,async close(){await k.close(),await N.close(),J.stopManagedProcess()}}}import QPe from"qrcode";var C5="/qq",yr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),u5=Object.freeze(Object.values(yr)),yPe=new Set(["appSecret","app_secret","secretRef","ownerUserOpenid","userOpenid","verificationUrl"]);function RP(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Gd(n,t){return RP(n)&&Object.keys(n).every(o=>t.includes(o))}function TP(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function E5(n,t){return typeof n=="string"&&n.trim().length>0&&n.length<=t}function mPe(n,t){return RP(t)?n===yr.status?Gd(t,[])?null:"connection.status does not accept fields.":n===yr.beginProvisioning?Gd(t,["locale"])&&(t.locale===void 0||t.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[yr.pollProvisioning,yr.cancelProvisioning].includes(n)?Gd(t,["attemptId"])&&TP(t.attemptId)?null:`${n} requires an attemptId.`:n===yr.bindCredentials?Gd(t,["appId","appSecret"])&&E5(t.appId,256)&&E5(t.appSecret,1024)?null:"bot.bind-credentials requires AppID and AppSecret.":n===yr.reconnectBot?Gd(t,["botId","sendTest"])&&TP(t.botId)&&(t.sendTest===void 0||t.sendTest===!0)?null:"bot.reconnect requires a botId and accepts only sendTest=true.":n===yr.deleteBot?Gd(t,["botId","confirm"])&&TP(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===yr.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===yr.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===yr.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown QQ endpoint.":"Payload must be an object."}function Fd(n){if(Array.isArray(n))return n.map(Fd);if(!RP(n))return n;let t={};for(let[o,i]of Object.entries(n))yPe.has(o)||(t[o]=Fd(i));return t}async function SPe(n){return QPe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function NP(n,t){return!n||typeof n.verificationUrl!="string"?Fd(n):Fd({...n,qrCodeDataUrl:await t(n.verificationUrl)})}async function ll(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await NP(o.provisioning,t)),Fd(o)}function B5(n,{encodeQr:t=SPe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete QQ controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!u5.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown QQ endpoint."}};let r=mPe(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===yr.status)s=await ll(await n.status(),i);else if(e===yr.beginProvisioning)s=await NP(await n.startProvisioning(),i);else if(e===yr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await NP(g,i)}else if(e===yr.cancelProvisioning)s=Fd(await n.cancelProvisioning(a.attemptId));else if(e===yr.bindCredentials)s=await ll(await n.bindCredentials(a),i);else if(e===yr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};let c;if(a.sendTest===!0)if(!(g?.bots?.some(d=>d?.botId===a.botId&&d?.connected===!0)===!0)||typeof n.sendConnectionTest!="function")c=ir(Ir("QQ\u673A\u5668\u4EBA"));else{let d=null;try{await n.sendConnectionTest(a.botId)}catch(B){d=B}c=ir(d)}s=await ll({...g,...c?{testMessage:c}:{}},i)}else if(e===yr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await ll(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===yr.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>ll(g,i))}else if(e===yr.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await ll(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else s=await ll(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"qq-operation-failed",message:"QQ \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function LS(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(C5,B5(t,o),{authority:hr(i)})}async function f5(n,t={}){if(t?.controller)return LS(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await _P(n,t,t.internals),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=LS(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close QQ bot connections"),e}import{unlink as iGe}from"node:fs/promises";import{resolve as N5}from"node:path";import{createHash as wPe}from"node:crypto";import{mkdir as DPe,readFile as OPe,rename as bPe,unlink as MPe,writeFile as _Pe}from"node:fs/promises";import{dirname as TPe}from"node:path";var kP=Object.freeze({version:1,bots:Object.freeze([])}),Q5=/^slack_[a-f0-9]{24}$/,NPe=/^DSH_SLACK_BOT_TOKEN_[A-F0-9]{24}$/,RPe=/^DSH_SLACK_APP_TOKEN_[A-F0-9]{24}$/;function Lo(n){return typeof n=="string"&&n.trim()?n.trim():null}function vP(n){let t=Lo(n);if(!t)throw new TypeError("platformId is required");let o=wPe("sha256").update(t).digest("hex").slice(0,24),i=o.toUpperCase();return{botId:`slack_${o}`,botTokenRef:`DSH_SLACK_BOT_TOKEN_${i}`,appTokenRef:`DSH_SLACK_APP_TOKEN_${i}`}}function PP(n){let t=Lo(n)??"",[o,i]=t.split(":");return o&&i?`${o.slice(0,5)}\u2022\u2022\u2022 \xB7 ${i.slice(0,5)}\u2022\u2022\u2022`:t?`${t.slice(0,6)}\u2022\u2022\u2022\u2022`:w("Slack\u673A\u5668\u4EBA")}var US=class{#e;#A=kP;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=this.#g(JSON.parse(await OPe(this.#e,"utf8")));if(!t)throw new Error("dsh-im Slack config contains invalid bot data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=kP}return this}list(){return structuredClone(this.#A.bots)}get(t){let o=this.#A.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByPlatformId(t){let o=this.#A.bots.find(i=>i.platformId===t);return o?structuredClone(o):null}async save(t){let o=this.#r(t);if(!o)throw new Error("Refusing to persist incomplete Slack bot data");return this.#a(i=>{if(i.find(A=>A.botId!==o.botId&&(A.platformId===o.platformId||A.botTokenRef===o.botTokenRef||A.appTokenRef===o.appTokenRef)))throw new Error("Duplicate Slack bot identity");let a=i.findIndex(A=>A.botId===o.botId);return a===-1?i.push(o):i[a]=o,structuredClone(o)})}async remove(t){if(!Q5.test(t))throw new TypeError("Invalid Slack bot id");return this.#a(o=>{let i=o.findIndex(e=>e.botId===t);return i===-1?null:structuredClone(o.splice(i,1)[0])})}async clear(){let t=this.#t.then(async()=>{try{await MPe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=kP});this.#t=t.then(()=>{},()=>{}),await t}#r(t){if(!t||typeof t!="object")return null;let o=Lo(t.botId),i=Lo(t.platformId),e=Lo(t.botTokenRef),a=Lo(t.appTokenRef),A=Lo(t.name);if(!o||!i||!e||!a||!A||!Q5.test(o)||!NPe.test(e)||!RPe.test(a))return null;let r=vP(i);return r.botId!==o||r.botTokenRef!==e||r.appTokenRef!==a?null:Object.freeze({botId:o,platformId:i,botTokenRef:e,appTokenRef:a,name:A,username:Lo(t.username),teamId:Lo(t.teamId),teamName:Lo(t.teamName),createdAt:Lo(t.createdAt)??new Date().toISOString(),connectedAt:Lo(t.connectedAt)})}#g(t){if(!t||t.version!==1||!Array.isArray(t.bots))return null;let o=t.bots.map(A=>this.#r(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||a.has(A.botTokenRef)||a.has(A.appTokenRef))return null;i.add(A.botId),e.add(A.platformId),a.add(A.botTokenRef),a.add(A.appTokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#a(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await DPe(TPe(this.#e),{recursive:!0,mode:448});let A=`${this.#e}.tmp`;await _Pe(A,`${JSON.stringify(a,null,2)} +`,{encoding:"utf8",mode:384}),await bPe(A,this.#e),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}};var kPe="https://slack.com/api/",Gu="files.slack.com",vPe="slack.com",y5="/files-pri/",PPe=Object.freeze([Gu]),GPe="/upload/",FPe=12e4;function Es(n){return typeof n=="string"&&n.trim()?n.trim():null}function m5(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}function vu(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function LPe(n,t){if(!Number.isInteger(n)||n<1)throw new TypeError(`${t} must be a positive integer`);return n}function S5(n,t){return t?.providerCode!==void 0&&(n.providerCode=t.providerCode),Number.isInteger(t?.status)&&(n.status=t.status),n}function pl(n){let t="artifact-provider-failed",o="Slack file upload preparation failed";n?.code==="slack-file_upload_size_restricted"?(t="artifact-too-large",o="Slack rejected the result file because it is too large"):n?.code==="slack-missing-scope"?(t="artifact-permission-required",o="Slack file delivery requires the files:write scope"):n?.code?.startsWith?.("slack-")&&(t="artifact-provider-rejected",o="Slack rejected file upload preparation");let i=new Error(o,{cause:n});return i.code=t,S5(i,n)}function UPe(n){let t=new Error("Slack file completion result is uncertain",{cause:n});return t.code="artifact-delivery-uncertain",S5(t,n)}function HPe(n){return Number.isInteger(n)&&n>=300&&n<400}async function GP(n){try{await n?.body?.cancel?.()}catch{}}function KPe(n){let t=new URL(n);if(t.protocol!=="https:")throw new Error("Image download URL must use HTTPS");if(t.username||t.password||t.port&&t.port!=="443")throw new Error("Image download URL is not hosted by the messaging platform");if(t.hostname===vPe&&t.pathname.startsWith(y5)&&(t.hostname=Gu),t.hostname!==Gu||!t.pathname.startsWith(y5))throw new Error("Image download URL is not hosted by the messaging platform");return t.hash="",t}function xPe(n){let t=new URL(n);if(t.protocol!=="https:"||t.username||t.password||t.port&&t.port!=="443"||t.hostname!==Gu||!t.pathname.startsWith(GPe))throw new Error("Slack returned an unsafe file upload URL");return t.hash="",t}function YPe(n,t){let o=n?.headers?.get?.("location");if(!o)return null;try{return new URL(o,t)}catch{return null}}function jPe(n){let t=n?.headers?.get?.("x-oauth-scopes");return t==null?null:new Set(t.split(",").map(o=>o.trim()).filter(Boolean))}function JPe(n){return n?.protocol==="https:"&&!n.username&&!n.password&&(!n.port||n.port==="443")&&n.hostname.endsWith(".slack.com")&&n.hostname!==Gu&&n.pathname==="/"&&n.searchParams.has("redir")}function qPe(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),t?.addEventListener("abort",()=>{clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function wn(n,t){let o=Es(n);if(!o||!/^[A-Z][A-Z0-9]{4,30}$/i.test(o))throw new TypeError(`Invalid Slack ${t}`);return o}function hs(n,t){let o=Es(n);if(!o)throw new TypeError(`Slack ${t} is required`);return o}function Pu(n,{trim:t=!0}={}){let o=typeof n=="string"?n:"",i=t?o.trim():o;if(!i)throw new TypeError("Slack message text is required");return i.replace(/<@([A-Z0-9]+)>/gi,"@$1").replace(/]*)?>/gi,"@$1")}function zPe(n,t,o){let i=Es(t?.error)??"unknown_error",e=new Error(`Slack ${n} failed: ${i.replaceAll("_"," ")}`);return e.providerCode=i,["invalid_auth","not_authed","token_revoked","account_inactive"].includes(i)?e.code=o==="app"?"slack-invalid-app-token":"slack-invalid-bot-token":i==="missing_scope"?e.code="slack-missing-scope":i==="method_not_supported_for_channel_type"||i==="channel_type_not_supported"||i==="deprecated_endpoint"?e.code="slack-stream-unavailable":e.code=`slack-${i}`,e}function w5(n){return typeof n=="string"&&/^xoxb-[A-Za-z0-9-]{16,}$/.test(n.trim())}function D5(n){return typeof n=="string"&&/^xapp-[A-Za-z0-9-]{16,}$/.test(n.trim())}var Fu=class{#e;#A;#t;#r;#g=null;#a;constructor({botToken:t,appToken:o,fetchImpl:i=fetch,baseUrl:e=kPe,fileUploadTimeoutMs:a=FPe}){if(t!==void 0&&!w5(t))throw new TypeError("Slack Bot Token is invalid");if(o!==void 0&&!D5(o))throw new TypeError("Slack App Token is invalid");if(!t&&!o)throw new TypeError("SlackApi requires a token");if(typeof i!="function")throw new TypeError("SlackApi requires fetch");this.#e=t?.trim(),this.#A=o?.trim(),this.#t=i,this.#r=new URL(e),this.#a=LPe(a,"fileUploadTimeoutMs")}authTest(t={}){return this.#i("auth.test",{...t,tokenKind:"bot"})}openConnection(t={}){return this.#i("apps.connections.open",{...t,tokenKind:"app",body:void 0})}async fileInfo({fileId:t,signal:o}={}){let i=await this.#i("files.info",{tokenKind:"bot",signal:o,body:{file:wn(t,"file id")}});if(!i?.file||typeof i.file!="object"||Array.isArray(i.file))throw new Error("Slack files.info returned no file object");return i.file}postMessage({channelId:t,text:o,threadTs:i,signal:e}){return this.#i("chat.postMessage",{tokenKind:"bot",signal:e,body:{channel:wn(t,"channel id"),text:Pu(o),...i?{thread_ts:Es(i)}:{},mrkdwn:!0,link_names:!1,unfurl_links:!1,unfurl_media:!1}})}updateMessage({channelId:t,ts:o,text:i,signal:e}){return this.#i("chat.update",{tokenKind:"bot",signal:e,body:{channel:wn(t,"channel id"),ts:hs(o,"message timestamp"),text:Pu(i),parse:"none",link_names:!1}})}addReaction({channelId:t,messageTs:o,emojiName:i,signal:e,timeoutMs:a}){return this.#i("reactions.add",{tokenKind:"bot",signal:e,timeoutMs:a,retry:!1,body:{channel:wn(t,"channel id"),timestamp:hs(o,"message timestamp"),name:hs(i,"reaction name")}})}removeReaction({channelId:t,messageTs:o,emojiName:i,signal:e,timeoutMs:a}){return this.#i("reactions.remove",{tokenKind:"bot",signal:e,timeoutMs:a,retry:!1,body:{channel:wn(t,"channel id"),timestamp:hs(o,"message timestamp"),name:hs(i,"reaction name")}})}startStream({channelId:t,threadTs:o,recipientTeamId:i,recipientUserId:e,markdownText:a,signal:A}){return this.#i("chat.startStream",{tokenKind:"bot",signal:A,body:{channel:wn(t,"channel id"),thread_ts:hs(o,"thread timestamp"),...i?{recipient_team_id:wn(i,"team id")}:{},...e?{recipient_user_id:wn(e,"user id")}:{},...Es(a)?{markdown_text:Pu(a)}:{}}})}appendStream({channelId:t,ts:o,markdownText:i,signal:e}){return this.#i("chat.appendStream",{tokenKind:"bot",signal:e,body:{channel:wn(t,"channel id"),ts:hs(o,"stream timestamp"),markdown_text:Pu(i,{trim:!1})}})}stopStream({channelId:t,ts:o,markdownText:i,signal:e}){return this.#i("chat.stopStream",{tokenKind:"bot",signal:e,body:{channel:wn(t,"channel id"),ts:hs(o,"stream timestamp"),...Es(i)?{markdown_text:Pu(i,{trim:!1})}:{}}})}async uploadFile({channelId:t,threadTs:o,file:i,signal:e}){if(!i||typeof i!="object"||typeof i.fileName!="string"||!i.fileName||!Buffer.isBuffer(i.bytes))throw new TypeError("A Slack file is required");if(e?.aborted)throw vu(e);let a=m5(e,this.#a),A;try{A=await this.#i("files.getUploadURLExternal",{tokenKind:"bot",signal:a,timeoutMs:this.#a,body:{filename:i.fileName,length:i.bytes.byteLength}})}catch(I){throw e?.aborted?vu(e):pl(I)}let r,s;try{r=hs(A?.file_id,"file id"),s=xPe(A?.upload_url)}catch(I){throw pl(I)}let g;try{g=await this.#t(s,{method:"POST",headers:{"content-type":i.mediaType??"application/octet-stream"},body:i.bytes,signal:a,redirect:"error"})}catch(I){throw e?.aborted?vu(e):pl(I)}if(!Number.isInteger(g?.status))throw pl(new Error("Slack file upload returned an invalid response"));if(g.status!==200){await GP(g);let I=new Error(`Slack file upload failed with HTTP ${g.status}`);throw I.status=g.status,g.status===413?I.code="artifact-too-large":g.status===429?I.code="artifact-rate-limited":I.code="artifact-provider-rejected",I}await GP(g);let c;try{c={files:[{id:r,title:i.fileName}],channel_id:wn(t,"channel id"),...o?{thread_ts:hs(o,"thread timestamp")}:{}}}catch(I){throw pl(I)}if(a.aborted)throw e?.aborted?vu(e):pl(a.reason);try{let I=await this.#i("files.completeUploadExternal",{tokenKind:"bot",signal:a,timeoutMs:this.#a,retry:!1,body:c});if(!Array.isArray(I?.files)||!I.files.some(d=>Es(d?.id)===r))throw new Error("Slack file completion did not confirm the uploaded file");return I}catch(I){throw e?.aborted?vu(e):I?.code==="slack-missing-scope"?pl(I):UPe(I)}}async downloadFile({url:t,signal:o,maxBytes:i}){return this.#n({url:t,signal:o,maxBytes:i,stream:!1})}async downloadFileStream({url:t,signal:o}){return this.#n({url:t,signal:o,stream:!0})}async#n({url:t,signal:o,maxBytes:i,stream:e}){if(!this.#e)throw new TypeError("Slack bot token is required for file download");let a=KPe(t),r={fetchImpl:async(s,g)=>{let c=await this.#t(s,g);if(!HPe(c?.status))return c;let I=YPe(c,s);if(this.#g&&!this.#g.has("files:read")||JPe(I))throw await GP(c),new Bt("slack-file-access-required","Slack redirected a private file request to the workspace because file access was not granted",w("Slack \u672A\u6388\u6743\u673A\u5668\u4EBA\u8BFB\u53D6\u8BE5\u6587\u4EF6\u3002\u8BF7\u4E3A\u5E94\u7528\u6DFB\u52A0 files:read \u540E\u91CD\u65B0\u5B89\u88C5\uFF0C\u518D\u91CD\u65B0\u53D1\u9001\u56FE\u7247\u3002"));return c},headers:{authorization:`Bearer ${this.#e}`},signal:o,allowedHosts:PPe};return e?kp(a,r):uo(a,{...r,maxBytes:i})}async#i(t,{tokenKind:o,body:i,signal:e,timeoutMs:a=15e3,retry:A=!0}){let r=o==="app"?this.#A:this.#e;if(!r)throw new TypeError(`Slack ${o} token is required for ${t}`);let s=t==="files.getUploadURLExternal"||t==="files.info",g;try{g=await this.#t(new URL(t,this.#r),{method:"POST",headers:{authorization:`Bearer ${r}`,"content-type":i===void 0||s?"application/x-www-form-urlencoded;charset=utf-8":"application/json;charset=utf-8","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.2.2)"},...i===void 0?{}:{body:s?new URLSearchParams(i).toString():JSON.stringify(i)},signal:m5(e,a),redirect:"error"})}catch(I){throw I?.name==="AbortError"||I?.name==="TimeoutError"?I:new Error(`Slack ${t} transport failed`)}if(o==="bot"){let I=jPe(g);I&&(this.#g=I)}let c;try{c=await g.json()}catch{throw new Error(`Slack ${t} returned invalid JSON`)}if(g.status===429&&A){let I=Number(g.headers.get("retry-after"))||1;return await qPe(Math.min(1e4,Math.max(100,I*1e3)),e),this.#i(t,{tokenKind:o,body:i,signal:e,timeoutMs:a,retry:!1})}if(!g.ok||c?.ok!==!0){let I=zPe(t,c,o);throw I.status=g.status,I}return c}};async function O5({botToken:n,appToken:t},o={}){if(!w5(n)){let r=new TypeError(w("Slack Bot Token \u5FC5\u987B\u4EE5 xoxb- \u5F00\u5934\u3002"));throw r.code="slack-invalid-bot-token",r}if(!D5(t)){let r=new TypeError(w("Slack App Token \u5FC5\u987B\u4EE5 xapp- \u5F00\u5934\u3002"));throw r.code="slack-invalid-app-token",r}let i=new Fu({botToken:n,appToken:t,...o}),[e,a]=await Promise.all([i.authTest(),i.openConnection()]);if(!e?.team_id||!e?.user_id||!e?.bot_id)throw new Error(w("Slack Bot Token \u6CA1\u6709\u8FD4\u56DE\u5B8C\u6574\u7684\u673A\u5668\u4EBA\u8EAB\u4EFD\u3002"));let A;try{A=new URL(a?.url)}catch{A=null}if(!A||A.protocol!=="wss:"){let r=new Error(w("Slack App Token \u65E0\u6CD5\u521B\u5EFA Socket Mode \u8FDE\u63A5\uFF0C\u8BF7\u786E\u8BA4\u5DF2\u542F\u7528 Socket Mode \u548C connections:write\u3002"));throw r.code="slack-socket-mode",r}return{platformId:`${e.team_id}:${e.user_id}`,name:Es(e.user)??"DeepSeek Harness",username:Es(e.user),teamId:String(e.team_id),teamName:Es(e.team)}}var FP=Object.freeze({key:"slack",label:"Slack",connectionLabel:" Socket Mode \u957F\u8FDE\u63A5",reactions:Object.freeze({processing:"eyes",success:"white_check_mark",error:"x"})}),HS=class extends $n{constructor(t){super({descriptor:FP,...t})}};function mg(n){return typeof n=="string"&&n.trim()?n.trim():null}function KS(n,t){return Object.freeze({code:n,message:t})}var Lu=class{#e;#A;#t;#r;#g;#a;#n=new Map;#i=new Map;#I=new Map;#l=0;#o=!1;constructor({credentials:t,configStore:o,inspectCredentials:i=O5,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.resolve!="function"||typeof t.set!="function"||typeof t.unset!="function")throw new TypeError("Slack requires the DSH credential provider");if(!o||typeof o.list!="function"||typeof o.save!="function"||typeof o.remove!="function")throw new TypeError("Slack requires a config store");if(typeof i!="function"||typeof e!="function")throw new TypeError("Slack controller dependencies are incomplete");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A}async initialize(){if(this.#o)return this.status();for(let t of this.#A.list())await this.#h(t.botId,async()=>{if(this.#o||this.#n.get(t.botId)?.status?.ready)return;let o=await this.#p(t);if(!o){this.#i.set(t.botId,KS("missing-token",w("Slack\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002")));return}try{await this.#s(t,o),this.#i.delete(t.botId)}catch(i){this.#i.set(t.botId,KS("connection-failed",w("Slack Socket Mode \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"))),this.#a.warn?.(`[dsh-im:slack] bot ${t.botId} failed to initialize:`,i)}finally{this.#E()}});return this.status()}async bindCredentials({botToken:t,appToken:o}={}){if(this.#o)throw new Error("Slack controller is closed");let i=mg(t),e=mg(o);if(!i||!e)throw new TypeError("Slack Bot Token and App Token are required");let a=await this.#t({botToken:i,appToken:e}),A=mg(a?.platformId),r=mg(a?.name);if(!A||!r)throw new Error("Slack returned an invalid bot identity");let s=vP(A);return await this.#h(s.botId,async()=>{if(this.#o)throw new Error("Slack controller is closed");let g=this.#A.getByPlatformId(A),c=await this.#e.resolve(s.botTokenRef).catch(()=>{}),I=await this.#e.resolve(s.appTokenRef).catch(()=>{}),d={...s,platformId:A,name:r,username:mg(a.username),teamId:mg(a.teamId),teamName:mg(a.teamName),createdAt:g?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};try{await this.#e.set(s.botTokenRef,i),await this.#e.set(s.appTokenRef,e),await this.#A.save(d)}catch(B){throw await Promise.all([this.#d(s.botTokenRef,c),this.#d(s.appTokenRef,I)]),B}try{await this.#s(d,{botToken:i,appToken:e}),this.#i.delete(s.botId)}catch(B){this.#i.set(s.botId,KS("connection-failed",w("Slack\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0CSocket Mode \u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#a.warn?.(`[dsh-im:slack] bot ${s.botId} credential connection failed:`,B)}this.#E()}),this.status()}async reconnectBot(t){let o=this.#A.get(t);if(!o)throw new Error("Unknown Slack bot");return await this.#h(t,async()=>{let i=await this.#p(o);if(!i)throw new Error("Slack bot credentials are missing");try{await this.#s(o,i),this.#i.delete(t)}catch(e){throw this.#i.set(t,KS("connection-failed",w("Slack Socket Mode \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u68C0\u67E5\u4E24\u4E2A Token\u3002"))),e}finally{this.#E()}}),this.status()}async sendConnectionTest(t){let o=this.#A.get(t);if(!o)throw new Error("Unknown Slack bot");return this.#h(t,async()=>{let i=this.#n.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error(w("Slack\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw e.code="test-target-unavailable",e}return await i.sendConnectionTest(ba(`${o.name}\uFF08${PP(o.platformId)}\uFF09`,w("Slack\u673A\u5668\u4EBA"))),{sent:!0}})}async sendProactiveText(t,o,i,e={}){if(!this.#A.get(t))throw new Error("Unknown Slack bot");return this.#h(t,async()=>{let A=this.#n.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("Slack\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#A.get(t);if(!o)throw new Error("Unknown Slack bot");return await this.#h(t,async()=>{let i=await this.#e.resolve(o.botTokenRef).catch(()=>{}),e=await this.#e.resolve(o.appTokenRef).catch(()=>{});await this.#c(t);try{await this.#e.unset(o.botTokenRef),await this.#e.unset(o.appTokenRef),await this.#A.remove(t)}catch(a){throw await Promise.all([this.#d(o.botTokenRef,i),this.#d(o.appTokenRef,e)]),i?.value&&e?.value&&await this.#s(o,{botToken:i.value,appToken:e.value}).catch(()=>{}),new Error("Unable to remove the Slack bot safely.",{cause:a})}await this.#g({botId:t,config:o}).catch(a=>{this.#a.warn?.(`[dsh-im:slack] bot ${t} state cleanup failed:`,a)}),this.#i.delete(t),this.#E()}),this.status()}status(){let t=this.#A.list().map(i=>{let e=this.#n.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#i.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:a,configured:!0,bot:{name:i.name,username:i.username,teamName:i.teamName,idMasked:PP(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?w(`Slack${FP.connectionLabel}\u8FD0\u884C\u6B63\u5E38`):A==="error"?w("Slack\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):w("Slack\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},lastMessageError:Vr(e?.lastMessageError),error:structuredClone(this.#i.get(i.botId)??null)}}),o=t.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#l,state:t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o}}}async close(){this.#o||(this.#o=!0,await Promise.allSettled([...this.#I.values()]),await Promise.allSettled([...this.#n.keys()].map(t=>this.#c(t))))}async#s(t,{botToken:o,appToken:i}){if(this.#o)throw new Error("Slack controller is closed");if(await this.#c(t.botId),this.#o)throw new Error("Slack controller is closed");let e=await this.#r({botId:t.botId,config:t,botToken:o,appToken:i});if(!e||typeof e.start!="function"||typeof e.stop!="function")throw new TypeError("createRuntime returned an invalid Slack runtime");this.#n.set(t.botId,e);try{await e.start()}catch(a){throw await e.stop().catch(()=>{}),this.#n.delete(t.botId),a}}async#c(t){let o=this.#n.get(t);this.#n.delete(t),await o?.stop().catch(i=>{this.#a.warn?.(`[dsh-im:slack] bot ${t} failed to stop cleanly:`,i)})}async#p(t){let[o,i]=await Promise.all([this.#e.resolve(t.botTokenRef).catch(()=>{}),this.#e.resolve(t.appTokenRef).catch(()=>{})]),e=mg(o?.value),a=mg(i?.value);return e&&a?{botToken:e,appToken:a}:null}async#d(t,o){o?.value?await this.#e.set(t,o.value).catch(()=>{}):await this.#e.unset(t).catch(()=>{})}#h(t,o){let a=(this.#I.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#I.get(t)===a&&this.#I.delete(t)});return this.#I.set(t,a),a}#E(){this.#l+=1}};var xS=class extends lr{constructor(t){super({...t,rpcIdPrefix:"slack",logPrefix:"dsh-slack"})}};var b5=Object.freeze([1e3,3e3,5e3,1e4,3e4]),UP=38e3,M5=11e3,T5=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function LP(n,t,o){if(typeof n.addEventListener=="function")n.addEventListener(t,o);else if(typeof n.on=="function")n.on(t,o);else throw new TypeError("Slack WebSocket does not support events")}function VPe(n){let t=n?.data??n;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("utf8"):t instanceof ArrayBuffer?Buffer.from(t).toString("utf8"):ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):null}function WPe(n){let t=new URL(n);if(t.protocol!=="wss:")throw new Error("Slack returned an insecure Socket Mode URL");return t.href}function ZPe(n){return typeof n=="string"?n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">"):""}function XPe(n,t){return ZPe(n).replace(new RegExp(`<@${t}>`,"gi"),"").trim()}function HP(n){return typeof n?.url_private_download=="string"&&n.url_private_download?n.url_private_download:n?.url_private}function $Pe(n,t){let o=typeof n?.mimetype=="string"?n.mimetype.toLowerCase():"",i=HP(n);return!T5.has(o)||typeof i!="string"||!i?null:{name:typeof n.name=="string"?n.name:void 0,mediaType:o,size:Number.isSafeInteger(n.size)&&n.size>=0?n.size:void 0,load:e=>t(i,e)}}function eGe(n,t,o){let i=typeof n?.mimetype=="string"&&n.mimetype?n.mimetype.toLowerCase():void 0,e=HP(n);if(T5.has(i))return null;let a=n?.file_access==="check_file_info"&&typeof n?.id=="string"&&n.id;return(typeof e!="string"||!e)&&!a?null:{name:typeof n?.name=="string"&&n.name?n.name:typeof n?.title=="string"&&n.title?n.title:a?n.id:"slack-file",...i?{mediaType:i}:{},size:Number.isSafeInteger(n?.size)&&n.size>=0?n.size:void 0,load:async({signal:A}={})=>{if(!a)return t(e,{signal:A});let r=await o(n.id,{signal:A}),s=HP(r);if(typeof s!="string"||!s)throw new Error("Slack files.info returned no downloadable URL");let g=await t(s,{signal:A}),c=typeof r?.name=="string"&&r.name?r.name:typeof r?.title=="string"&&r.title?r.title:n.id,I=typeof r?.mimetype=="string"&&r.mimetype?r.mimetype.toLowerCase():void 0;return Buffer.isBuffer(g)||g instanceof Uint8Array?{data:g,name:c,...I?{mediaType:I}:{}}:{...g,name:c,...I?{mediaType:I}:{}}}}}function AGe(n,t,{loadFile:o=async()=>{throw new Error("Slack file downloader is unavailable")},loadFileStream:i=o,loadFileInfo:e=async()=>{throw new Error("Slack file metadata loader is unavailable")}}={}){let a=n?.event;if(!a||!n?.event_id||!a.channel||!a.user||!a.ts)return null;let A=a.type==="message"&&a.channel_type==="im",r=a.type==="app_mention";if(!A&&!r||a.subtype&&a.subtype!=="file_share"||a.bot_id||a.app_id)return null;let s=String(a.thread_ts??a.ts);return{messageId:String(n.event_id),senderId:String(a.user),senderIsBot:String(a.user)===String(t),kind:A?"direct":"group",conversationId:A?String(a.channel):`${a.channel}:${s}`,content:XPe(a.text??"",t),plainText:!Array.isArray(a.files)||a.files.length===0,images:Array.isArray(a.files)?a.files.map(g=>$Pe(g,o)).filter(Boolean):[],files:Array.isArray(a.files)?a.files.map(g=>eGe(g,i,e)).filter(Boolean):[],addressed:A||r,reactionTarget:{channelId:String(a.channel),messageTs:String(a.ts)},replyTarget:{channelId:String(a.channel),threadTs:s,recipientUserId:String(a.user),recipientTeamId:String(a.user_team??n.team_id??"")},connectionTestTarget:{channelId:String(a.channel)}}}function tGe(n){if(typeof n!="string")return!1;let t="__DSH_IM_TOOL_NAME__",o=w("\u6B63\u5728\u4F7F\u7528{name}\u2026",{name:t}),i=o.indexOf(t);if(i<0)return!1;let e=o.slice(0,i),a=o.slice(i+t.length),A=n.trim();return A.startsWith(e)&&A.endsWith(a)&&A.length>e.length+a.length}async function _5(n,t,o,i,e){if(i)for(let a=0;a{let y=es(Q,UP)[0]??"";if(!y||!y.startsWith(A))return;let m=y.slice(A.length);m&&(await _5(n,t,a,m,o),A=y)},f=()=>{I||c||s!==null||g||!r||(s=setTimeout(()=>{s=null;let Q=r;r="",g=B(Q).catch(y=>{c=!0,i.warn?.("[dsh-im:slack] streaming append failed:",y)}).finally(()=>{g=null,f()})},350),s?.unref?.())};return{messageId:a,get providerMessageIds(){return[...d]},update(Q){I||c||typeof Q!="string"||!Q.trim()||tGe(Q)||(r=Q,f())},async finish(Q){if(I)throw new Error("Slack message stream is already closed");I=!0,s!==null&&clearTimeout(s),s=null,r="",await g?.catch(()=>{});let y=es(Q,UP),m=y[0]??w("\u5904\u7406\u5B8C\u6210\u3002");!c&&m.startsWith(A)?(await _5(n,t,a,m.slice(A.length),o),await n.stopStream({channelId:t.channelId,ts:a,signal:o})):(await n.stopStream({channelId:t.channelId,ts:a,signal:o}).catch(()=>{}),await n.updateMessage({channelId:t.channelId,ts:a,text:m,signal:o}));for(let _ of y.slice(1)){let T=await n.postMessage({channelId:t.channelId,threadTs:t.threadTs,text:_,signal:o});typeof T?.ts=="string"&&T.ts&&d.push(T.ts)}},cancel(){I=!0,r="",s!==null&&clearTimeout(s),s=null,n.stopStream({channelId:t.channelId,ts:a,signal:o}).catch(()=>{})}}}var KP=class{#e;#A;#t;constructor({api:t,signal:o,logger:i}){this.#e=t,this.#A=o,this.#t=i}async sendText(t,o){let i=es(o,UP),e=[];for(let a of i){let A=await this.#e.postMessage({channelId:t.channelId,threadTs:t.threadTs,text:a,signal:this.#A});typeof A?.ts=="string"&&A.ts&&e.push(A.ts)}return{providerMessageIds:e}}async addReaction(t,o,{signal:i}={}){let e=String(o??"").trim();return await this.#e.addReaction({channelId:t.channelId,messageTs:t.messageTs,emojiName:e,signal:i??this.#A}),e}removeReaction(t,o,{signal:i}={}){return this.#e.removeReaction({channelId:t.channelId,messageTs:t.messageTs,emojiName:o,signal:i??this.#A})}openStream(t){return rGe({api:this.#e,target:t,signal:this.#A,logger:this.#t})}sendFile(t,o){return this.#e.uploadFile({channelId:t.channelId,threadTs:t.threadTs,file:o,signal:this.#A})}};function aGe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...Xi()}}var Uu=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s=aGe();#c=null;#p=null;#d=null;#h=null;#E=null;#C=null;#f=0;#B=0;#y=!0;#S=null;constructor({config:t,botToken:o,appToken:i,harness:e,state:a,contextEnhancement:A,logger:r=console,replyTimeoutMs:s=6e5,connectTimeoutMs:g=2e4,createApi:c=d=>new Fu(d),createWebSocket:I=d=>new WebSocket(d)}){if(!t||!o||!i||!e||!a)throw new TypeError("SlackRuntime requires config, both tokens, Harness, and state");if(typeof I!="function")throw new TypeError("SlackRuntime requires WebSocket");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c,this.#o=I}get status(){return structuredClone(this.#s)}async sendConnectionTest(t){if(!this.#s.ready||!this.#p){let o=new Error("Slack bot is not connected");throw o.code="test-target-unavailable",o}return this.#p.sendConnectionTest(t)}async sendProactiveText(t,o,i={}){if(!this.#s.ready||!this.#p){let A=new Error("Slack bot is not connected");throw A.code="bot-not-connected",A}let e=typeof t?.route?.channelId=="string"?t.route.channelId.trim():"",a=typeof t?.route?.threadTs=="string"?t.route.threadTs.trim():"";if(!e||t?.kind!=="conversation"&&t?.kind!=="thread"||t.kind==="thread"&&!a||t.kind==="conversation"&&a){let A=new TypeError("Invalid Slack proactive delivery target");throw A.code="invalid-target",A}return this.#p.sendProactiveText({channelId:e,...a?{threadTs:a}:{}},o,i)}async start(){return this.#s.ready&&this.#h?this.status:this.#S?this.#S:(this.#S=this.#Q().finally(()=>{this.#S=null}),this.#S)}async#Q(){await this.stop(),this.#y=!1,this.#f=0,this.#s.startedAt=new Date().toISOString(),this.#s.connectionState="connecting",this.#s.lastError=null,await this.#r.ensureRunning(),this.#s.harnessReachable=!0;let t=new AbortController;this.#d=t;let o=this.#l({botToken:this.#A,appToken:this.#t});this.#c=o;try{let i=await o.authTest({signal:t.signal});if(`${i?.team_id}:${i?.user_id}`!==this.#e.platformId)throw new Error("Slack Bot Token identity does not match the saved bot");let e=new KP({api:o,signal:t.signal,logger:this.#n});this.#p=new HS({bot:e,harness:this.#r,state:this.#g,contextEnhancement:this.#a,status:this.#s,logger:this.#n,replyTimeoutMs:this.#i,signal:t.signal});let a;try{await Promise.race([this.#m(),new Promise((A,r)=>{a=setTimeout(()=>r(new Error("Slack Socket Mode did not become ready in time")),this.#I),a?.unref?.()})])}finally{clearTimeout(a)}return this.status}catch(i){throw this.#s.ready=!1,this.#s.connectionState="failed",this.#s.lastError=i?.message??String(i),await this.stop(),i}}async#m(){if(this.#y)throw new Error("Slack runtime is stopped");let t=await this.#c.openConnection({signal:this.#d?.signal});return this.#u(t?.url)}#u(t){if(this.#y)return Promise.reject(new Error("Slack runtime is stopped"));let o=++this.#B,i=this.#o(WPe(t));this.#h=i;let e=!1;return new Promise((a,A)=>{let r=s=>{if(e||o!==this.#B)return;e=!0,this.#E=s?.connection_info?.app_id??null,this.#f=0;let g=Date.now();this.#s.ready=!0,this.#s.connectionState="connected",this.#s.lastCheckedAt=g,this.#s.lastConnectedAt=g,this.#s.lastError=null,a()};LP(i,"message",s=>{if(o!==this.#B||this.#y)return;let g=VPe(s);if(!g)return;let c;try{c=JSON.parse(g)}catch{this.#n.warn?.("[dsh-im:slack] ignored malformed Socket Mode JSON");return}if(c.type==="hello"){r(c);return}if(c.envelope_id&&i.readyState===1&&(i.send(JSON.stringify({envelope_id:c.envelope_id})),this.#s.lastCheckedAt=Date.now()),c.type==="disconnect"){i.close(4e3,"Slack requested reconnect");return}if(c.type!=="events_api"||c.payload?.type!=="event_callback"||this.#E&&c.payload.api_app_id&&c.payload.api_app_id!==this.#E)return;let I=AGe(c.payload,this.#e.platformId.split(":")[1],{loadFile:(B,f)=>this.#c.downloadFile({url:B,...f}),loadFileStream:(B,f)=>this.#c.downloadFileStream({url:B,...f}),loadFileInfo:(B,f)=>this.#c.fileInfo({fileId:B,...f})}),d=this.#p;I&&d&&d.accept(I).catch(B=>{o!==this.#B||this.#y||this.#n.error?.(`[dsh-im:slack] bot ${this.#e.botId} message handling failed:`,B)})}),LP(i,"close",(s={})=>{if(o!==this.#B)return;if(this.#h===i&&(this.#h=null),this.#y){e||A(new DOMException("Stopped","AbortError"));return}let g=Number(s.code)||0,c=new Error(`Slack Socket Mode closed (${g||"unknown"})`);this.#s.ready=!1,this.#s.connectionState="connecting",this.#s.lastError=c.message,e||(e=!0,A(c)),this.#b()}),LP(i,"error",()=>{o!==this.#B||this.#y||(this.#s.lastError="Slack Socket Mode WebSocket error")})})}#b(){if(this.#y||this.#C!==null)return;let t=b5[Math.min(this.#f,b5.length-1)];this.#f+=1,this.#C=setTimeout(()=>{this.#C=null,this.#m().catch(o=>{this.#y||(this.#n.warn?.("[dsh-im:slack] Socket Mode reconnect failed:",o),this.#b())})},t),this.#C?.unref?.()}async stop(){this.#y=!0,this.#B+=1,this.#d?.abort(),this.#d=null,this.#C!==null&&clearTimeout(this.#C),this.#C=null;let t=this.#h,o=this.#p;this.#h=null,this.#p=null,this.#c=null,this.#E=null;try{t&&t.readyState<2&&t.close(1e3,"Plugin stopped")}catch(i){this.#n.warn?.(`[dsh-im:slack] bot ${this.#e.botId} failed to close Socket Mode:`,i)}return await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#s.ready=!1,this.#s.connectionState="idle",this.status}};var YS=class extends As{};async function xP(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-im slack requires ctx.credentials");let i=Aa(n,t),e=o.ConfigStore??US,a=o.StateStore??YS,A=o.HarnessClient??xS,r=o.Controller??Lu,s=o.Runtime??Uu,g=o.createConnectionSupervisor??vp,c=typeof n.logger=="function"?n.logger("dsh-im:slack"):n.logger??console,I=()=>Ra(n),d=k_(t,"slack"),B=await new e(d.config).load(),f=N5(t.workspace??process.cwd()),Q=o.WorkspaceStore??ea,y=o.workspaces??await new Q(d.workspaces,{defaultWorkspace:f}).load(),m=B.list();await y.reconcile(m.map(N=>N.botId)),await Promise.all(m.map(N=>y.ensure(N.botId,{defaultAgentPreset:t.agentPreset})));let _=typeof B.remove=="function"?Pa(B,{workspaces:y}):B,T=new Map,R=N=>N5(d.bots,N,"state.json"),L=async N=>{let k=T.get(N);return k||(k=await new a(R(N)).load(),T.set(N,k)),k},U=Ua(n,o.commandExecutor),{controlExecutor:F,sessionMaintenanceExecutor:q,fileIngressExecutor:z}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),j=new A({...i,workspace:f,autostart:!1,dshBin:t.dshBin??"dsh",...U?{commandExecutor:U}:{},...F?{controlExecutor:F}:{},...q?{sessionMaintenanceExecutor:q}:{},...z?{fileIngressExecutor:z}:{}}),P=new r({credentials:n.credentials,configStore:_,logger:c,...o.inspectCredentials?{inspectCredentials:o.inspectCredentials}:{},createRuntime:async({botId:N,config:k,botToken:V,appToken:Ae})=>{let ie=await L(N);await y.ensure(N,{defaultAgentPreset:t.agentPreset});let De=Ga(j,{botId:N,workspaces:y,state:ie,agentPresetCatalog:I});return new s({config:k,botToken:V,appToken:Ae,harness:De.harness,state:De.state,contextEnhancement:{botId:N,getSettings:()=>y.contextEnhancementFor(N)},replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??2e4,logger:{error:(...fe)=>c.error?.(`[${N}]`,...fe),warn:(...fe)=>c.warn?.(`[${N}]`,...fe),info:(...fe)=>c.info?.(`[${N}]`,...fe),debug:(...fe)=>c.debug?.(`[${N}]`,...fe)}})},deleteState:async({botId:N})=>{let k=T.get(N);if(T.delete(N),k&&typeof k.remove=="function")await k.remove();else try{await iGe(R(N))}catch(V){if(V?.code!=="ENOENT")throw V}}}),J=Fa(P,{workspaces:y,stateFor:L,agentPresetCatalog:I}),H=g({channel:"slack",controller:J,harness:j,logger:c,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:J,deliveryAdapter:La({channel:"slack",workspaces:y,coreController:P,stateFor:L}),ready:H.ready,async close(){await H.close(),await J.close(),j.stopManagedProcess()}}}var k5="/slack",ti=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),v5=Object.freeze(Object.values(ti)),oGe=new Set(["token","botToken","appToken","botTokenRef","appTokenRef","tokenRef","platformId","secret","secretRef"]);function jP(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function jS(n,t){return jP(n)&&Object.keys(n).every(o=>t.includes(o))}function R5(n){return typeof n=="string"&&/^slack_[a-f0-9]{24}$/.test(n)}function nGe(n){return typeof n=="string"&&/^xoxb-[A-Za-z0-9-]{16,}$/.test(n.trim())&&n.length<=4096}function sGe(n){return typeof n=="string"&&/^xapp-[A-Za-z0-9-]{16,}$/.test(n.trim())&&n.length<=4096}function gGe(n,t){return jP(t)?n===ti.status?jS(t,[])?null:"connection.status does not accept fields.":n===ti.bindCredentials?jS(t,["botToken","appToken"])&&nGe(t.botToken)&&sGe(t.appToken)?null:"bot.bind-credentials requires xoxb Bot Token and xapp App Token.":n===ti.reconnectBot?jS(t,["botId","sendTest"])&&R5(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId.":n===ti.deleteBot?jS(t,["botId","confirm"])&&R5(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===ti.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===ti.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===ti.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown Slack endpoint.":"Payload must be an object."}function YP(n){if(Array.isArray(n))return n.map(YP);if(!jP(n))return n;let t={};for(let[o,i]of Object.entries(n))oGe.has(o)||(t[o]=YP(i));return t}function cGe(n){let t=Ya(n);return t||(n?.code==="slack-invalid-bot-token"?{code:"invalid-bot-token",message:"Slack Bot Token \u65E0\u6548\uFF0C\u8BF7\u786E\u8BA4\u4F7F\u7528\u4EE5 xoxb- \u5F00\u5934\u7684\u4EE4\u724C\u3002"}:n?.code==="slack-invalid-app-token"?{code:"invalid-app-token",message:"Slack App Token \u65E0\u6548\uFF0C\u8BF7\u786E\u8BA4\u4F7F\u7528\u4EE5 xapp- \u5F00\u5934\u7684\u4EE4\u724C\u3002"}:n?.code==="slack-missing-scope"?{code:"missing-scope",message:"Slack \u5E94\u7528\u6743\u9650\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u91CD\u65B0\u5BFC\u5165 Manifest \u5E76\u5B89\u88C5\u5230\u5DE5\u4F5C\u533A\u3002"}:n?.code==="slack-socket-mode"?{code:"socket-mode-unavailable",message:n.message}:{code:"slack-operation-failed",message:"Slack \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"})}function P5(n){for(let t of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[t]!="function")throw new TypeError(`A complete Slack controller is required (${t})`);return async(t,o,i)=>{if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!v5.includes(t))return{ok:!1,error:{code:"bad-request",message:"Unknown Slack endpoint."}};let e=gGe(t,o);if(e)return{ok:!1,error:{code:"bad-request",message:e}};try{let a;if(t===ti.status)a=await n.status();else if(t===ti.bindCredentials)a=await n.bindCredentials(o);else if(t===ti.reconnectBot){if(a=await n.reconnectBot(o.botId),i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(o.sendTest===!0){let A=null;try{if(a?.bots?.find(r=>r?.botId===o.botId)?.connected!==!0){let r=new Error("Bot is not connected");throw r.code="test-target-unavailable",r}if(typeof n.sendConnectionTest!="function"){let r=new Error("Connection test is unavailable");throw r.code="test-target-unavailable",r}await n.sendConnectionTest(o.botId)}catch(r){A=r}a={...a,testMessage:ir(A)}}}else if(t===ti.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");a=await n.updateWorkspace(o.botId,o.workspace)}else if(t===ti.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");a=await n.updateContextEnhancement(o.botId,o.config)}else if(t===ti.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");a=await n.updateAgentPreset(o.botId,o.agentPreset)}else a=await n.deleteBot(o.botId);return i?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:YP(a)}}catch(a){return i?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:cGe(a)}}}}function JS(n,t,o){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(k5,P5(t),{authority:hr(o)})}async function G5(n,t={}){if(t?.controller)return JS(n,t.controller,t.rpcAuthority);let o=await xP(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=JS(n,o.controller,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Slack bot connections"),e}var F5=Object.freeze({botPrefix:"telegram",tokenRefPrefix:"DSH_TELEGRAM_BOT_TOKEN"}),Hu=Object.freeze({compatible:"compatible",privateAllowlist:"private-allowlist"}),IGe=/^[1-9]\d{0,15}$/;function L5(n){if(n===void 0)return Object.freeze([]);if(!Array.isArray(n))throw new TypeError("allowedUsers must be an array of numeric Telegram User IDs");let t=n.map(o=>{let i=typeof o=="number"&&Number.isSafeInteger(o)?String(o):typeof o=="string"?o.trim():"";if(!IGe.test(i))throw new TypeError("allowedUsers contains an invalid Telegram User ID");return i});return Object.freeze([...new Set(t)])}function Mc(n={}){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("Telegram access policy must be an object");let t=n.accessMode??Hu.compatible;if(!Object.values(Hu).includes(t))throw new TypeError("Telegram accessMode must be compatible or private-allowlist");return Object.freeze({accessMode:t,allowedUsers:L5(n.allowedUsers)})}function lGe(n){let t=Object.hasOwn(n,"accessMode"),o=Object.hasOwn(n,"allowedUsers");if(!t&&!o)return{};try{let i=Mc(n);return{...t?{accessMode:i.accessMode}:{},...o||t?{allowedUsers:i.allowedUsers}:{}}}catch{return null}}function U5(n){return KE(n,F5)}function H5(n){return kQ(n,w("Telegram\u673A\u5668\u4EBA"))}var qS=class extends Np{constructor(t){super(t,{channel:"Telegram",...F5,normalizeBotExtension:lGe})}async save(t){let o=t?.platformId?this.getByPlatformId(String(t.platformId)):null;return super.save({...o,...t})}};var zS=class extends lr{constructor(t){super({...t,rpcIdPrefix:"telegram",logPrefix:"dsh-telegram"})}};var pGe="https://api.telegram.org/",K5=Object.freeze(["api.telegram.org"]),dGe=12e4;function Sg(n){return typeof n=="string"&&n.trim()?n.trim():null}function x5(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}function JP(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function hGe(n,t){if(!Number.isInteger(n)||n<1)throw new TypeError(`${t} must be a positive integer`);return n}function j5(n,t){return t?.providerCode!==void 0&&(n.providerCode=t.providerCode),t?.retry_after!==void 0&&(n.retry_after=t.retry_after,n.retryAfter=t.retry_after),Number.isInteger(t?.status)&&(n.status=t.status),n}function qP(n){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("A Telegram rich message is required");let t=["markdown","html","blocks"].filter(i=>n[i]!==void 0);if(t.length!==1)throw new TypeError("A Telegram rich message requires exactly one format");let o=t[0];if((o==="markdown"||o==="html")&&(typeof n[o]!="string"||!n[o].trim()))throw new TypeError("Telegram rich message text is invalid");if(o==="blocks"&&!Array.isArray(n.blocks))throw new TypeError("Telegram rich message blocks are invalid");return n}function EGe(n,t="document"){let o=Number(n?.providerCode),i=Number(n?.status),e=Sg(n?.message)??"",a="artifact-provider-rejected",A=`Telegram rejected the ${t}.`;o===401||o===403||i===401||i===403?(a="artifact-permission-required",A=`Telegram denied permission to send the ${t}.`):o===413||i===413||/(?:file|request|entity).{0,20}(?:too (?:big|large)|size limit)|too (?:big|large)/i.test(e)?(a="artifact-too-large",A=`The ${t} exceeds Telegram's size limit.`):o===429||i===429?(a="artifact-rate-limited",A=`Telegram rate-limited ${t} delivery.`):(o>=500||i>=500)&&(a="artifact-delivery-uncertain",A=`Telegram ${t} delivery result is uncertain.`);let r=new Error(A,{cause:n});return r.code=a,j5(r,n)}function Y5(n,t="document"){let o=new Error(`Telegram ${t} delivery result is uncertain`,{cause:n});return o.code="artifact-delivery-uncertain",j5(o,n)}function CGe(n){return typeof n=="string"&&/^\d{5,20}:[A-Za-z0-9_-]{20,}$/.test(n.trim())}var uGe=/^[a-z0-9_]{1,32}$/;function BGe(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.command=="string"&&uGe.test(n.command)&&typeof n.description=="string"&&n.description.length>=1&&n.description.length<=256}var zP=Object.freeze({type:"commands"}),Ku=class{#e;#A;#t;#r;#g;constructor({token:t,fetchImpl:o=fetch,FormDataImpl:i=globalThis.FormData,baseUrl:e=pGe,fileUploadTimeoutMs:a=dGe}){if(!CGe(t))throw new TypeError("Telegram Bot Token is invalid");if(typeof o!="function")throw new TypeError("TelegramApi requires fetch");if(typeof i!="function")throw new TypeError("TelegramApi requires FormData");this.#e=t.trim(),this.#A=o,this.#t=i,this.#r=new URL(e),this.#g=hGe(a,"fileUploadTimeoutMs")}async getMe(t={}){return this.#i("getMe",{},t)}async getWebhookInfo(t={}){return this.#i("getWebhookInfo",{},t)}async getUpdates({offset:t,timeout:o=25,signal:i}={}){let e={timeout:o,limit:100,allowed_updates:["message"],...Number.isSafeInteger(t)?{offset:t}:{}};return this.#i("getUpdates",e,{signal:i,timeoutMs:Math.max(1e4,(o+10)*1e3)})}async getFile({fileId:t,signal:o}={}){let i=Sg(t);if(!i||!/^[A-Za-z0-9_-]{1,512}$/.test(i))throw new TypeError("Telegram file id is invalid");return this.#i("getFile",{file_id:i},{signal:o})}async downloadFile({fileId:t,signal:o,maxBytes:i}={}){let e=await this.#a(t,o);return uo(e,{fetchImpl:this.#A,signal:o,maxBytes:i,allowedHosts:K5})}async downloadFileStream({fileId:t,signal:o}={}){let i=await this.#a(t,o);return kp(i,{fetchImpl:this.#A,signal:o,allowedHosts:K5})}async#a(t,o){let i=await this.getFile({fileId:t,signal:o}),e=Sg(i?.file_path);if(!e||e.startsWith("/")||e.includes("\\")||e.includes("?")||e.includes("#"))throw new Error("Telegram returned an invalid file path");let a;try{a=e.split("/").map(r=>decodeURIComponent(r))}catch{throw new Error("Telegram returned an invalid file path")}if(a.some(r=>!r||r==="."||r===".."))throw new Error("Telegram returned an invalid file path");let A=new URL(this.#r);return A.pathname=`/file/bot${this.#e}/${e}`,A}async sendMessage({chatId:t,text:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#i("sendMessage",{chat_id:t,text:o,link_preview_options:{is_disabled:!0},...i?{reply_parameters:{message_id:i,allow_sending_without_reply:!0}}:{},...e?{message_thread_id:e}:{}},{signal:a})}async setMessageReaction({chatId:t,messageId:o,emoji:i,signal:e,timeoutMs:a}){let A=Sg(i);return this.#i("setMessageReaction",{chat_id:t,message_id:o,reaction:A?[{type:"emoji",emoji:A}]:[]},{signal:e,timeoutMs:a})}async sendRichMessage({chatId:t,richMessage:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#i("sendRichMessage",{chat_id:t,rich_message:qP(o),...i?{reply_parameters:{message_id:i,allow_sending_without_reply:!0}}:{},...e?{message_thread_id:e}:{}},{signal:a})}async sendRichMessageDraft({chatId:t,draftId:o,richMessage:i,messageThreadId:e,signal:a}){if(!Number.isSafeInteger(o)||o===0)throw new TypeError("Telegram rich message draft id must be a non-zero integer");return this.#i("sendRichMessageDraft",{chat_id:t,draft_id:o,rich_message:qP(i),...e?{message_thread_id:e}:{}},{signal:a})}async sendDocument({chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#n("sendDocument","document","document",{chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a})}async sendPhoto({chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#n("sendPhoto","photo","photo",{chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a})}async#n(t,o,i,{chatId:e,file:a,replyToMessageId:A,messageThreadId:r,signal:s}){if(!a||typeof a!="object"||typeof a.fileName!="string"||!a.fileName||!Buffer.isBuffer(a.bytes))throw new TypeError(`A Telegram ${i} is required`);let g=new this.#t;if(g.append("chat_id",String(e)),g.append(o,new Blob([a.bytes],{type:a.mediaType??"application/octet-stream"}),a.fileName),A&&g.append("reply_parameters",JSON.stringify({message_id:A,allow_sending_without_reply:!0})),r&&g.append("message_thread_id",String(r)),s?.aborted)throw JP(s);let c=x5(s,this.#g);try{return await this.#i(t,g,{signal:c,timeoutMs:this.#g,multipart:!0})}catch(I){throw s?.aborted?JP(s):I?.deliveryOutcome==="unknown"?Y5(I?.cause??I,i):I?.code?.startsWith?.("telegram-")?EGe(I,i):Y5(I,i)}}async editMessageText({chatId:t,messageId:o,text:i,richMessage:e,signal:a}){if(i===void 0==(e===void 0))throw new TypeError("Telegram message edit requires exactly one of text or richMessage");return this.#i("editMessageText",{chat_id:t,message_id:o,...i===void 0?{rich_message:qP(e)}:{text:i,link_preview_options:{is_disabled:!0}}},{signal:a})}async sendChatAction({chatId:t,messageThreadId:o,signal:i}){return this.#i("sendChatAction",{chat_id:t,action:"typing",...o?{message_thread_id:o}:{}},{signal:i})}async setMyCommands({commands:t,scope:o,languageCode:i,signal:e}={}){if(!Array.isArray(t)||t.length===0||t.some(a=>!BGe(a)))throw new TypeError("Telegram bot commands are invalid");return this.#i("setMyCommands",{commands:t,...o?{scope:o}:{},...Sg(i)?{language_code:Sg(i)}:{}},{signal:e})}async setChatMenuButton({menuButton:t=zP,signal:o}={}){if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("Telegram menu button is invalid");return this.#i("setChatMenuButton",{menu_button:t},{signal:o})}async#i(t,o,{signal:i,timeoutMs:e=15e3,multipart:a=!1}={}){if(i?.aborted)throw JP(i);let A=new URL(this.#r);A.pathname=`${A.pathname.replace(/\/$/,"")}/bot${this.#e}/${t}`;let r;try{r=await this.#A(A,{method:"POST",...a?{}:{headers:{"content-type":"application/json"}},body:a?o:JSON.stringify(o),signal:x5(i,e),redirect:"error"})}catch(g){let c=new Error(`Telegram ${t} transport failed`,{cause:g});throw c.code=g?.name==="TimeoutError"?"telegram-timeout":g?.name==="AbortError"?"telegram-aborted-after-dispatch":"telegram-transport-error",c.deliveryOutcome="unknown",c}let s;try{s=await r.json()}catch{let g=new Error(`Telegram ${t} returned invalid JSON`);throw g.status=r?.status,g.code="telegram-response-invalid",g.deliveryOutcome="unknown",g}if(!r.ok||s?.ok!==!0){let g=Sg(s?.description),c=new Error(g??`Telegram ${t} failed`);c.code=Number.isInteger(s?.error_code)?`telegram-${s.error_code}`:"telegram-api-error",c.status=r.status,Number.isInteger(s?.error_code)&&(c.providerCode=s.error_code);let I=Number(s?.parameters?.retry_after);throw Number.isFinite(I)&&I>=0&&(c.retry_after=I,c.retryAfter=I),c}return s.result}};async function J5(n,t={}){let i=await new Ku({token:n,...t}).getMe();if(!i?.id||i?.is_bot!==!0)throw new Error("Telegram token does not belong to a bot");return{platformId:String(i.id),name:Sg([i.first_name,i.last_name].filter(Boolean).join(" "))??w("Telegram\u673A\u5668\u4EBA"),username:Sg(i.username)}}var VP=Object.freeze({key:"telegram",label:"Telegram",connectionLabel:" Bot API \u957F\u8F6E\u8BE2",reactions:Object.freeze({processing:"\u{1F440}",success:"\u{1F44D}",error:"\u{1F44E}"})}),VS=class extends $n{constructor(t){super({descriptor:VP,...t})}};var xu=class extends Rp{#e;constructor(t){super({...t,descriptor:VP,inspectToken:t.inspectToken??J5,deriveIdentity:U5,maskPlatformId:H5}),this.#e=t.configStore}status(){let t=super.status();return{...t,bots:t.bots.map(o=>{let i=this.#e.get(o.botId),e=Mc(i??{});return{...o,accessPolicy:e}})}}async setAccessPolicy(t,o){let i=Mc(o);return this.updateBotConfig(t,e=>({...e,...i}))}};import{randomInt as OGe}from"node:crypto";import{EnvHttpProxyAgent as fGe,FormData as QGe,fetch as yGe}from"undici";var mGe=4;function q5(){let n=new fGe({connections:mGe}),t=!1;return{fetchImpl:(o,i={})=>yGe(o,{...i,dispatcher:n}),FormDataImpl:QGe,async destroy(){t||(t=!0,await n.destroy())}}}function ZP(n){if(typeof n!="string"||!n.trim())throw new TypeError("Telegram message text must be a non-empty string");return n}function XP(n){return n==="&"?5:n==="<"||n===">"?4:1}function WP(n){return Array.from(n).reduce((t,o)=>t+XP(o),0)}function SGe(n,t,o,i){let e=t+Math.floor(i*.5);for(let a=o-1;a>=e;a-=1)if(n[a]===` `||n[a]===" ")return a+1;return o}function $P(n,t,o=()=>1){if(typeof n!="string")throw new TypeError("Telegram message text must be a string");if(!n)return[];let i=Array.from(n),e=[],a=0;for(;at)break;r+=s,A+=1}if(A===a)throw new Error("Telegram message character exceeds the chunk limit");A",">")}function z5(n,t){return $P(n,t,XP).map(o=>({source:o,markdown:Yu(o)}))}function DGe(n,t,o,i){let e=n.slice(t.length,n.length-o.length),a=WP(t)+Math.max(WP(o),WP("```"))+1,A=i-a;if(A<1)throw new Error("Telegram Rich Markdown code fence exceeds the limit");let r=$P(e,A,XP);return r.map((s,g)=>{let c=g===r.length-1,I=s.endsWith(` `)?"":` `,d=c?o:"```",B=`${g===0?t:""}${s}${c?o:""}`,f=Yu(`${t}${s}${I}${d}`);if(Array.from(f).length>i)throw new Error("Telegram Rich Markdown code block exceeds the limit");return{source:B,markdown:f}})}function eG(n){let t=ZP(n);return V5(t),Yu(t)}function AG(n,t=3e4){if(!Number.isInteger(t)||t<128||t>32768)throw new TypeError("Telegram Rich Markdown limit is invalid");let o=ZP(n),i=V5(o),e=Yu(o);if(Array.from(e).length<=t)return[{source:o,markdown:e}];let a=[],A=0;for(let r=0;rA&&a.push(...z5(o.slice(A,s.index),t));let c=g.index+g[0].length,I=o.slice(s.index,c),d=Yu(I);Array.from(d).length<=t?a.push({source:I,markdown:d}):a.push(...DGe(I,s[0],g[0],t)),A=c}return A4096)throw new TypeError("Telegram regular message limit is invalid");return $P(ZP(n),t,o=>o.length)}var bGe=Object.freeze([{command:"new",description:"\u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"},{command:"compact",description:"\u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"},{command:"workspace",description:"\u5207\u6362\u5DE5\u4F5C\u533A"},{command:"workspacelist",description:"\u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"},{command:"sessionlist",description:"\u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"},{command:"sessions",description:"\u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"},{command:"session",description:"\u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"},{command:"models",description:"\u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"},{command:"model",description:"\u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"},{command:"presetlist",description:"\u5217\u51FA\u53EF\u7528 Agent Preset"},{command:"presets",description:"\u5217\u51FA\u53EF\u7528 Agent Preset"},{command:"preset",description:"\u67E5\u770B\u6216\u8BBE\u7F6E\u65B0\u4F1A\u8BDD Agent Preset"},{command:"stop",description:"\u505C\u6B62\u5F53\u524D\u4EFB\u52A1"},{command:"steer",description:"\u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"},{command:"batch",description:"\u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF09"},{command:"send",description:"\u63D0\u4EA4\u5F53\u524D\u6279\u6B21"},{command:"cancel",description:"\u53D6\u6D88\u5F53\u524D\u6279\u6B21"},{command:"status",description:"\u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"},{command:"version",description:"\u67E5\u770B\u63D2\u4EF6\u7248\u672C"},{command:"help",description:"\u663E\u793A\u5E2E\u52A9"}]);function MGe(){return bGe.map(n=>({...n,description:w(n.description)}))}function _Ge(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function TGe(n,t){return t?[[n?.text,n?.entities],[n?.caption,n?.caption_entities]].some(([o,i])=>typeof o=="string"&&Array.isArray(i)&&i.some(e=>e?.type!=="mention"||!Number.isInteger(e.offset)||!Number.isInteger(e.length)?!1:o.slice(e.offset,e.offset+e.length).toLowerCase()===`@${t.toLowerCase()}`)):!1}function NGe(n,t){return!t||typeof n!="string"?n:n.replace(new RegExp(`@${_Ge(t)}\\b`,"ig"),"").trim()}var RGe=new Set(["image/jpeg","image/png","image/webp","image/gif"]),kGe=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]);function Z5(n){let t=n?.mime_type??n?.mimetype,o=typeof t=="string"?t.toLowerCase():"";if(RGe.has(o))return o;let i=typeof n?.file_name=="string"?n.file_name.toLowerCase():"";for(let[e,a]of kGe)if(i.endsWith(e))return a;return null}function iG(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function W5(n){return iG(n?.file_size)??(Number(n?.width)||0)*(Number(n?.height)||0)}function vGe(n,t){let o,i,e;if(Array.isArray(n?.photo)&&n.photo.length>0)o=n.photo.reduce((a,A)=>W5(A)>W5(a)?A:a),i="image/jpeg",e=`${o.file_unique_id??o.file_id??"telegram-photo"}.jpg`;else if(n?.document){let a=Z5(n.document);if(!a)return null;o=n.document,i=a,e=typeof o.file_name=="string"?o.file_name:void 0}return!o||typeof o.file_id!="string"?null:{name:e,mediaType:i,size:iG(o.file_size),load:a=>t(o.file_id,a)}}function PGe(n,t){let o=n?.document;if(!o||Z5(o)||typeof o.file_id!="string"||!o.file_id)return null;let i=typeof o.mime_type=="string"&&o.mime_type?o.mime_type.toLowerCase():void 0;return{name:typeof o.file_name=="string"&&o.file_name?o.file_name:String(o.file_unique_id??o.file_id),...i?{mediaType:i}:{},size:iG(o.file_size),load:({signal:e}={})=>t(o.file_id,{signal:e})}}function GGe(n,{botId:t,username:o,loadFile:i=async()=>{throw new Error("Telegram file downloader is unavailable")},loadFileStream:e=i}){let a=n?.message,A=a?.chat?.id,r=a?.from?.id,s=a?.message_id;if(!Number.isSafeInteger(n?.update_id)||A===void 0||r===void 0||!Number.isSafeInteger(s)||!["private","group","supergroup"].includes(a.chat?.type))return null;let g=a.chat.type==="private",c=g||String(a.reply_to_message?.from?.id??"")===String(t)||TGe(a,o),I=Number.isSafeInteger(a.message_thread_id)?a.message_thread_id:void 0,d=vGe(a,i),B=PGe(a,e);return{messageId:String(n.update_id),senderId:String(r),contextSource:()=>({senderName:[a.from?.first_name,a.from?.last_name].filter(f=>typeof f=="string"&&f.trim()).map(f=>f.trim()).join(" ")||a.from?.username}),senderIsBot:a.from?.is_bot===!0,kind:g?"direct":"group",conversationId:I===void 0?String(A):`${A}:${I}`,content:NGe(a.text??a.caption??"",o),plainText:typeof a.text=="string",images:d?[d]:[],files:B?[B]:[],addressed:c,reactionTarget:{chatId:A,messageId:s},replyTarget:{chatId:A,chatType:a.chat.type,replyToMessageId:s,messageThreadId:I},connectionTestTarget:{chatId:A,messageThreadId:I}}}function FGe(n,{accessMode:t=Hu.compatible,allowedPrivateUserIds:o=new Set}={}){return t!==Hu.privateAllowlist?!0:n?.kind==="direct"&&o instanceof Set&&o.has(String(n.senderId))}function rG(n){return Number.isSafeInteger(n?.message_id)?String(n.message_id):null}function ju(n){let t=Number(n?.providerCode),o=Number(n?.status),i=n?.deliveryOutcome==="unknown"||t>=500||o>=500||["telegram-timeout","telegram-aborted-after-dispatch","telegram-transport-error","telegram-response-invalid"].includes(n?.code);return{outcome:i?"unknown":"failed",reason:typeof n?.code=="string"&&n.code?n.code:i?"telegram-delivery-uncertain":"telegram-provider-rejected"}}function Pi(n,t,o="sent",i){return{presentation:n,providerMessageIds:[...new Set(t)],deliveryOutcome:o,...i?{reason:i}:{}}}var WS=class{#e;#A;#t;#r;#g;#a=!1;#n=null;constructor({update:t,finish:o,fail:i,providerMessageIds:e=[],presentation:a,logger:A}){this.#e=t,this.#A=o,this.#t=i,this.#g=e,this.presentation=a,this.#r=A}get providerMessageIds(){return[...this.#g]}async update(t){if(this.#a)return;let o=Vn(t),i=`${o.format}:${o.text}`;if(i!==this.#n){this.#n=i;try{return await this.#e(o)}catch(e){this.#r.warn?.("[dsh-im:telegram] rich stream update failed:",e);return}}}async finish(t){if(this.#a)throw new Error("Message stream is already closed");this.#a=!0;let o=await this.#A(Vn(t));return this.#g.push(...o?.providerMessageIds??[]),o}async fail(t){if(this.#a)return;this.#a=!0;let o=await this.#t(Vn(t,"plain"));return this.#g.push(...o?.providerMessageIds??[]),o}cancel(){this.#a=!0}},aG=class{#e;#A;#t;constructor({api:t,signal:o,logger:i=console}){this.#e=t,this.#A=o,this.#t=i}async sendText(t,o){let i=tG(o),e=[];for(let[a,A]of i.entries()){let r=await this.#e.sendMessage({chatId:t.chatId,text:A,replyToMessageId:a===0?t.replyToMessageId:void 0,messageThreadId:t.messageThreadId,signal:this.#A});Number.isSafeInteger(r?.message_id)&&e.push(String(r.message_id))}return{providerMessageIds:e}}async addReaction(t,o,{signal:i}={}){let e=String(o??"").trim();return await this.#e.setMessageReaction({chatId:t.chatId,messageId:t.messageId,emoji:e,signal:i??this.#A}),e}removeReaction(t,o,{signal:i}={}){return this.#e.setMessageReaction({chatId:t.chatId,messageId:t.messageId,signal:i??this.#A})}sendTyping(t){return this.#e.sendChatAction({chatId:t.chatId,messageThreadId:t.messageThreadId,signal:this.#A})}sendFile(t,o){return this.#e.sendDocument({chatId:t.chatId,file:o,replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A})}sendImage(t,o){return this.#e.sendPhoto({chatId:t.chatId,file:o,replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A})}async#r(t,o,{placeholderMessageId:i}={}){let e=tG(o),a=i===void 0?[]:[String(i)],A=0;if(i!==void 0)try{await this.#e.editMessageText({chatId:t.chatId,messageId:i,text:e[0],signal:this.#A}),A=1}catch(r){let s=ju(r);if(s.outcome==="unknown")return Pi("text-fallback",a,"unknown",s.reason);let g=await this.#r(t,o),c=g.deliveryOutcome==="sent"?"\u56DE\u590D\u5DF2\u53D1\u9001\u3002":g.deliveryOutcome==="unknown"?"\u56DE\u590D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\u3002":"\u6D88\u606F\u53D1\u9001\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";try{await this.#e.editMessageText({chatId:t.chatId,messageId:i,text:c,signal:this.#A})}catch(I){this.#t.warn?.("[dsh-im:telegram] unable to replace the processing placeholder:",I)}return Pi("text-fallback",[...a,...g.providerMessageIds],g.deliveryOutcome,g.reason)}for(let r=A;rI.source).join(""),c=await this.#r({...t,replyToMessageId:a===0?t.replyToMessageId:void 0},g);return Pi(c.presentation,[...e,...c.providerMessageIds],c.deliveryOutcome,c.reason)}return Pi("telegram-rich-final",e)}async#a(t,o,i){if(i.format==="plain")return this.#r(t,i.text,{placeholderMessageId:o});let e;try{e=AG(i.text)}catch{return this.#r(t,i.text,{placeholderMessageId:o})}let a=[String(o)];try{await this.#e.editMessageText({chatId:t.chatId,messageId:o,richMessage:{markdown:e[0].markdown},signal:this.#A})}catch(A){let r=ju(A);return r.outcome==="unknown"?Pi("telegram-rich-final",a,"unknown",r.reason):this.#r(t,i.text,{placeholderMessageId:o})}for(let[A,r]of e.slice(1).entries())try{let s=await this.#e.sendRichMessage({chatId:t.chatId,richMessage:{markdown:r.markdown},messageThreadId:t.messageThreadId,signal:this.#A}),g=rG(s);g&&a.push(g)}catch(s){let g=ju(s);if(g.outcome==="unknown")return Pi("telegram-rich-final",a,"unknown",g.reason);let c=e.slice(A+1).map(d=>d.source).join(""),I=await this.#r({...t,replyToMessageId:void 0},c);return Pi(I.presentation,[...a,...I.providerMessageIds],I.deliveryOutcome,I.reason)}return Pi("telegram-rich-final",a)}sendDelivery(t,o){return this.#g(t,Vn(o))}async openDeliveryStream(t){if(t.chatType==="private"){let e=OGe(1,2147483647),a=async r=>{let s={markdown:eG(r.text)};return await this.#e.sendRichMessageDraft({chatId:t.chatId,draftId:e,richMessage:s,messageThreadId:t.messageThreadId,signal:this.#A}),Pi("telegram-rich-draft",[])},A=new WS({update:a,finish:r=>this.#g(t,r),fail:r=>this.#r(t,r.text),presentation:"telegram-rich-draft",logger:this.#t});return await A.update(Vn("\u6B63\u5728\u5904\u7406\u2026","plain")),A}let i=(await this.#e.sendMessage({chatId:t.chatId,text:"\u6B63\u5728\u5904\u7406\u2026",replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A}))?.message_id;if(!Number.isSafeInteger(i))throw new Error("Telegram did not return a placeholder message id");return new WS({update:async e=>e.format==="plain"?(await this.#e.editMessageText({chatId:t.chatId,messageId:i,text:e.text,signal:this.#A}),Pi("text-fallback",[String(i)])):(await this.#e.editMessageText({chatId:t.chatId,messageId:i,richMessage:{markdown:eG(e.text)},signal:this.#A}),Pi("telegram-rich-draft",[String(i)])),finish:e=>this.#a(t,i,e),fail:e=>this.#r(t,e.text,{placeholderMessageId:i}),providerMessageIds:[String(i)],presentation:"telegram-regular",logger:this.#t})}async openStream(t){return LQ({limit:4e3,create:async i=>(await this.#e.sendMessage({chatId:t.chatId,text:i,replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A})).message_id,edit:(i,e)=>this.#e.editMessageText({chatId:t.chatId,messageId:i,text:e,signal:this.#A}),sendRemainder:i=>this.#e.sendMessage({chatId:t.chatId,text:i,messageThreadId:t.messageThreadId,signal:this.#A}),messageIdForResult:i=>i?.message_id}).start()}};function LGe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...Xi()}}var Ju=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s=LGe();#c=null;#p=null;#d=null;#h=null;#E=null;#C=null;constructor({config:t,token:o,harness:i,state:e,contextEnhancement:a,logger:A=console,replyTimeoutMs:r=6e5,createApi:s=c=>new Ku(c),createHttpTransport:g=q5}){if(!t||!o||!i||!e)throw new TypeError("TelegramRuntime requires config, token, Harness, and state");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g;let c=Mc(t);this.#l=c.accessMode,this.#o=new Set(c.allowedUsers)}get status(){return structuredClone(this.#s)}async sendConnectionTest(t){if(!this.#s.ready||!this.#d){let o=new Error("Telegram bot is not connected");throw o.code="test-target-unavailable",o}return this.#d.sendConnectionTest(t)}async sendProactiveText(t,o,i={}){if(!this.#s.ready||!this.#d){let r=new Error("Telegram bot is not connected");throw r.code="bot-not-connected",r}let e=typeof t?.route?.chatId=="string"?t.route.chatId.trim():"",a=Number(e),A=t?.route?.messageThreadId;if(!/^-?\d+$/.test(e)||!Number.isSafeInteger(a)||t?.kind!=="chat"&&t?.kind!=="topic"||t.kind==="topic"&&(!Number.isSafeInteger(A)||A<=0)||t.kind==="chat"&&A!==void 0){let r=new TypeError("Invalid Telegram proactive delivery target");throw r.code="invalid-target",r}return this.#d.sendProactiveText({chatId:a,...t.kind==="topic"?{messageThreadId:A}:{}},o,i)}async start(){return this.#s.ready&&this.#E?this.status:this.#C?this.#C:(this.#C=this.#f().finally(()=>{this.#C=null}),this.#C)}async#f(){await this.stop(),this.#s.startedAt=new Date().toISOString(),this.#s.connectionState="connecting",this.#s.lastError=null,await this.#t.ensureRunning(),this.#s.harnessReachable=!0;let t=new AbortController;this.#h=t;try{let o=this.#I();this.#c=o;let i=this.#i({token:this.#A,fetchImpl:o.fetchImpl,FormDataImpl:o.FormDataImpl});this.#p=i;let e=await i.getMe({signal:t.signal});if(String(e?.id??"")!==this.#e.platformId||e?.is_bot!==!0)throw new Error("Telegram token identity does not match the saved bot");let a=await i.getWebhookInfo({signal:t.signal});if(typeof a?.url=="string"&&a.url){let g=new Error(w("\u8BE5 Telegram \u673A\u5668\u4EBA\u5DF2\u914D\u7F6E Webhook\uFF0C\u8BF7\u5148\u5728\u539F\u670D\u52A1\u4E2D\u79FB\u9664 Webhook \u540E\u91CD\u8BD5\u3002"));throw g.code="webhook-configured",g}try{await i.setMyCommands({commands:MGe(),signal:t.signal}),await i.setChatMenuButton({menuButton:zP,signal:t.signal})}catch(g){this.#a.warn?.(`[dsh-im:telegram] bot ${this.#e.botId} command menu setup failed:`,g)}let A=new aG({api:i,signal:t.signal,logger:this.#a});this.#d=new VS({bot:A,harness:this.#t,state:this.#r,contextEnhancement:this.#g,status:this.#s,logger:this.#a,replyTimeoutMs:this.#n,signal:t.signal});let r=this.#r.cursor();if(r===null){let g=await i.getUpdates({offset:-1,timeout:0,signal:t.signal});r=g.length>0?g.at(-1).update_id+1:0,await this.#r.setCursor(r)}let s=Date.now();return this.#s.ready=!0,this.#s.connectionState="connected",this.#s.lastCheckedAt=s,this.#s.lastConnectedAt=s,this.#E=this.#B(r,t.signal),this.#E.catch(g=>{t.signal.aborted||(this.#s.ready=!1,this.#s.connectionState="failed",this.#s.lastError=g?.message??String(g),this.#a.error?.(`[dsh-im:telegram] bot ${this.#e.botId} polling stopped:`,g))}),this.status}catch(o){throw this.#s.ready=!1,this.#s.connectionState="failed",this.#s.lastError=o?.message??String(o),await this.stop(),o}}async#B(t,o){let i=t;for(;!o.aborted;){let e=await this.#p.getUpdates({offset:i,timeout:25,signal:o});if(this.#s.lastCheckedAt=Date.now(),o.aborted)return;let a=e.map(A=>{let r=A?.message?.chat?.type;return{update:A,contextSnapshot:Xr(this.#g,r==="private"?"direct":r==="group"||r==="supergroup"?"group":null)}});for(let{update:A,contextSnapshot:r}of a){if(o.aborted)return;let s=GGe(A,{botId:this.#e.platformId,username:this.#e.username,loadFile:(g,c)=>this.#p.downloadFile({fileId:g,...c}),loadFileStream:(g,c)=>this.#p.downloadFileStream({fileId:g,...c})});s&&FGe(s,{accessMode:this.#l,allowedPrivateUserIds:this.#o})?this.#d.accept(s,{contextSnapshot:r}).catch(g=>{o.aborted||this.#a.error?.(`[dsh-im:telegram] bot ${this.#e.botId} message handling failed:`,g)}):s&&(this.#s.messagesRejected+=1,this.#s.lastRejectedAt=new Date().toISOString()),i=A.update_id+1,await this.#r.setCursor(i)}}}async stop(){let t=this.#E,o=this.#d,i=this.#c;this.#h?.abort(),this.#h=null,this.#E=null,this.#c=null,this.#p=null,this.#d=null,await Promise.race([t?.catch(()=>{})??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]);try{await i?.destroy()}catch{this.#a.warn?.("[dsh-im:telegram] Telegram HTTP transport cleanup failed")}return this.#s.ready=!1,this.#s.connectionState="idle",this.status}};var ZS=class extends As{};function oG(n,t={},o={}){return KQ(n,t,o,{channel:"telegram",ConfigStore:qS,StateStore:ZS,HarnessClient:zS,Controller:xu,Runtime:Ju})}var X5="/telegram",nG=Object.freeze({...ta,setAccessPolicy:"bot.access-policy.set"}),UGe=Object.freeze(Object.values(nG));function $5(n){if(typeof n?.setAccessPolicy!="function")throw new TypeError("A complete Telegram controller is required (setAccessPolicy)");let t=YQ(n,{channel:"Telegram"});return async(o,i,e)=>{if(o!==nG.setAccessPolicy)return t(o,i,e);if(e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};let a=i&&typeof i=="object"&&!Array.isArray(i)?Object.keys(i):[];if(a.length!==3||!a.every(r=>["botId","accessMode","allowedUsers"].includes(r))||typeof i.botId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(i.botId))return{ok:!1,error:{code:"bad-request",message:"bot.access-policy.set requires a valid policy."}};let A;try{A=Mc(i)}catch{return{ok:!1,error:{code:"bad-request",message:"\u8BF7\u8F93\u5165\u6709\u6548\u7684 Telegram \u8BBF\u95EE\u6A21\u5F0F\u548C\u6570\u5B57 User ID\u3002"}}}try{let r=await n.setAccessPolicy(i.botId,A);return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:r}}catch{return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:{code:"telegram-operation-failed",message:"Telegram \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function XS(n,t,o){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(X5,$5(t),{authority:hr(o)})}async function eZ(n,t={}){if(t?.controller)return XS(n,t.controller,t.rpcAuthority);let o=await oG(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=XS(n,o.controller,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Telegram bot connections"),e}import{unlink as TFe}from"node:fs/promises";import{homedir as NFe}from"node:os";import{join as Zu,resolve as Cl}from"node:path";import{createHash as HGe}from"node:crypto";import{mkdir as KGe,readFile as xGe,rename as YGe,unlink as jGe,writeFile as JGe}from"node:fs/promises";import{dirname as qGe}from"node:path";var sG=Object.freeze({version:1,bots:Object.freeze([])});function dl(n){return typeof n=="string"&&n.trim()?n.trim():null}function AZ(n){let t=dl(n);return t&&/^wecom_[a-f0-9]{24}$/.test(t)?t:null}function zGe(n){let t=dl(n);return t&&/^DSH_WECOM_BOT_SECRET_[A-F0-9]{24}$/.test(t)?t:null}function ew(n){let t=dl(n);if(!t)throw new TypeError("Enterprise WeChat bot ID is required");let o=HGe("sha256").update(t).digest("hex").slice(0,24);return{botId:`wecom_${o}`,secretRef:`DSH_WECOM_BOT_SECRET_${o.toUpperCase()}`}}function gG(n){let t=dl(n)??"";return t?t.length<=10?`${t.slice(0,3)}\u2022\u2022\u2022`:`${t.slice(0,6)}\u2022\u2022\u2022\u2022${t.slice(-4)}`:w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA")}function tZ(n){if(!n||typeof n!="object")return null;let t=AZ(n.botId),o=dl(n.remoteBotId),i=zGe(n.secretRef);if(!t||!o||!i)return null;let e=ew(o);return e.botId!==t||e.secretRef!==i?null:Object.freeze({botId:t,remoteBotId:o,secretRef:i,createdAt:dl(n.createdAt)??new Date().toISOString(),connectedAt:dl(n.connectedAt)})}function VGe(n){if(!n||n.version!==1||!Array.isArray(n.bots))return null;let t=n.bots.map(tZ);if(t.some(a=>a===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of t){if(o.has(a.botId)||i.has(a.remoteBotId)||e.has(a.secretRef))return null;o.add(a.botId),i.add(a.remoteBotId),e.add(a.secretRef)}return Object.freeze({version:1,bots:Object.freeze(t)})}var $S=class{#e;#A=sG;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=VGe(JSON.parse(await xGe(this.#e,"utf8")));if(!t)throw new Error("dsh-im Enterprise WeChat config contains invalid bot data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=sG}return this}list(){return structuredClone(this.#A.bots)}get(t){let o=this.#A.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByRemoteBotId(t){let o=this.#A.bots.find(i=>i.remoteBotId===t);return o?structuredClone(o):null}async save(t){let o=tZ(t);if(!o)throw new Error("Refusing to persist incomplete Enterprise WeChat bot data");return this.#r(i=>{let e=i.find(r=>r.remoteBotId===o.remoteBotId&&r.botId!==o.botId),a=i.find(r=>r.secretRef===o.secretRef&&r.botId!==o.botId);if(e||a)throw new Error("Duplicate Enterprise WeChat bot identity");let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!AZ(t))throw new TypeError("Invalid Enterprise WeChat bot ID");return this.#r(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await jGe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=sG});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#g(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#g(t){await KGe(qGe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await JGe(o,`${JSON.stringify(t,null,2)} @@ -480,22 +480,22 @@ ${_}`:F),await g()}catch(F){this.#n.error?.("[dsh-im:qq] failed to send the safe `,o=this.#t.then(async()=>{await eFe(iFe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await aFe(i,t,{encoding:"utf8",mode:384}),await tFe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as nFe}from"node:crypto";var iZ=new Set(["pending","connecting"]),qu=new Set(["connected","failed","cancelled","expired"]);function hl(n){return typeof n=="string"&&n.trim()?n.trim():null}function Gi(n,t){return Object.freeze({code:n,message:t})}function El(n){return n?{attemptId:n.id,status:n.state,pollIntervalMs:n.pollIntervalMs,qrRevision:n.qrRevision,...n.verificationUrl?{verificationUrl:n.verificationUrl}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.botId?{botId:n.botId}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}var zu=class{#e;#A;#t;#r;#g;#a;#n=new Map;#i=new Map;#I=new Map;#l=null;#o=new Map;#s=0;#c=!1;constructor({qrAuth:t,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.start!="function"||typeof t.poll!="function")throw new TypeError("Enterprise WeChat QR auth is required");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WecomController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WecomController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A}async initialize(){if(this.#c)return this.status();for(let t of this.#t.list())await this.#y(t.botId,async()=>{let o=this.#n.get(t.botId)?.status;if(this.#c||o?.ready||o?.wecomConnectionState==="connecting")return;let i=await this.#f(t.secretRef);if(!i){this.#i.set(t.botId,Gi("missing-secret",w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002")));return}try{await this.#E(t,i),this.#i.delete(t.botId)}catch{this.#i.set(t.botId,Gi("connection-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"))),this.#a.warn?.(`[dsh-im:wecom] bot ${t.botId} failed to initialize`)}finally{this.#Q()}});return this.status()}async startProvisioning(){if(this.#c)throw new Error("Enterprise WeChat controller is closed");this.#l&&await this.cancelProvisioning(this.#l);let t={id:nFe(),state:"pending",createdAt:Date.now(),expiresAt:null,pollIntervalMs:3e3,qrRevision:1,verificationUrl:null,scode:null,botId:null,error:null,controller:new AbortController,polling:null,transition:null};this.#I.set(t.id,t),this.#l=t.id,this.#Q();try{let o=await this.#e.start({signal:t.controller.signal});if(t.scode=hl(o.scode),t.verificationUrl=hl(o.verificationUrl),t.expiresAt=Number(o.expiresAt),t.pollIntervalMs=Math.min(1e4,Math.max(500,Number(o.pollIntervalMs)||3e3)),!t.scode||!t.verificationUrl||!Number.isFinite(t.expiresAt))throw new Error("Enterprise WeChat QR auth returned incomplete data");return this.#Q(),El(t)}catch(o){throw t.state=t.controller.signal.aborted?"cancelled":"failed",t.error=t.controller.signal.aborted?Gi("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):Gi("qr-start-failed",w("\u65E0\u6CD5\u751F\u6210\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),this.#S(t),o}}async registrationStatus(t){let o=this.#I.get(t);if(!o||qu.has(o.state))return El(o);if(o.state==="connecting")return await o.transition?.catch(()=>{}),El(o);if(Date.now()>=o.expiresAt)return o.state="expired",o.error=Gi("expired",w("\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002")),o.controller.abort(),this.#S(o),El(o);if(!o.polling){let i=this.#p(o).finally(()=>{o.polling===i&&(o.polling=null)});o.polling=i}return await o.polling.catch(()=>{}),El(o)}async bindCredentials({botId:t,secret:o}={}){if(this.#c)throw new Error("Enterprise WeChat controller is closed");let i=hl(t),e=hl(o);if(!i||!e)throw new TypeError("Enterprise WeChat Bot ID and Secret are required");if(this.#l&&await this.cancelProvisioning(this.#l),this.#c)throw new Error("Enterprise WeChat controller is closed");let a=ew(i);return await this.#y(a.botId,async()=>{if(this.#c)throw new Error("Enterprise WeChat controller is closed");let A=this.#t.getByRemoteBotId(i),r=await this.#A.resolve(a.secretRef).catch(()=>{});if(this.#c)throw new Error("Enterprise WeChat controller is closed");let s={botId:a.botId,remoteBotId:i,secretRef:a.secretRef,createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(a.secretRef,e);try{await this.#t.save(s)}catch(g){throw await this.#B(a.secretRef,r),g}try{await this.#E(s,e),this.#i.delete(a.botId)}catch{this.#i.set(a.botId,Gi("connection-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#a.warn?.(`[dsh-im:wecom] bot ${a.botId} credential connection failed`)}this.#Q()}),this.status()}async cancelProvisioning(t){let o=this.#I.get(t);return o?(qu.has(o.state)||(o.controller.abort(),await Promise.allSettled([o.polling,o.transition].filter(Boolean)),qu.has(o.state)||(o.state="cancelled"),o.error??=Gi("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")),this.#S(o)),El(o)):null}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#y(t,async()=>{let i=await this.#f(o.secretRef);if(!i)throw new Error("Enterprise WeChat bot secret is missing");try{await this.#E(o,i),this.#i.delete(t)}catch(e){throw this.#i.set(t,Gi("connection-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),e}finally{this.#Q()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Enterprise WeChat bot");return this.#y(t,async()=>{let i=this.#n.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function")throw Ir(w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"));return i.sendConnectionTest(ba(w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\uFF08{botId}\uFF09",{botId:gG(o.remoteBotId)})))})}async sendProactiveText(t,o,i,e={}){if(!this.#t.get(t))throw new Error("Unknown Enterprise WeChat bot");return this.#y(t,async()=>{let A=this.#n.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#y(t,async()=>{let i=await this.#A.resolve(o.secretRef).catch(()=>{});await this.#C(t);try{await this.#A.unset(o.secretRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.secretRef,i.value).catch(()=>{}),await this.#E(o,i.value).catch(()=>{})),new Error("Unable to remove the Enterprise WeChat bot safely.",{cause:e})}await this.#g({botId:t,config:o}).catch(e=>{this.#a.warn?.(`[dsh-im:wecom] bot ${t} state cleanup failed:`,e)}),this.#i.delete(t),this.#Q()}),this.status()}status(){let t=this.#t.list().map(e=>{let a=this.#n.get(e.botId)?.status??null,A=a?.ready===!0&&a.wecomConnectionState==="connected"&&a.harnessReachable===!0,r=A?"connected":a?.wecomConnectionState==="connecting"?"connecting":this.#i.has(e.botId)||a?.wecomConnectionState==="failed"?"error":"offline";return{botId:e.botId,state:r,connected:A,configured:!0,bot:{name:w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"),appIdMasked:gG(e.remoteBotId)},health:{status:A?"healthy":r==="error"?"error":"offline",summary:A?w("\u4F01\u4E1A\u5FAE\u4FE1 WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38"):r==="error"?w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},lastMessageError:Vr(a?.lastMessageError),error:structuredClone(this.#i.get(e.botId)??null)}}),o=t.filter(e=>e.connected).length,i=this.#l?this.#I.get(this.#l):null;return{schemaVersion:1,revision:this.#s,state:i&&iZ.has(i.state)?"provisioning":t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o},...i&&iZ.has(i.state)?{provisioning:El(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#l&&await this.cancelProvisioning(this.#l),await Promise.allSettled([...this.#o.values()]),await Promise.allSettled([...this.#n.keys()].map(t=>this.#C(t))))}async#p(t){try{let o=await this.#e.poll({scode:t.scode,signal:t.controller.signal});if(t.controller.signal.aborted||qu.has(t.state)||o.status==="waiting")return;if(o.status==="expired"){t.state="expired",t.error=Gi("expired",w("\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002")),this.#S(t);return}if(o.status!=="success"){t.state="failed",t.error=Gi("qr-connect-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u6CA1\u6709\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002")),this.#S(t);return}t.state="connecting",t.verificationUrl=null,t.expiresAt=null,t.scode=null,this.#Q();let i=this.#d(t,o);t.transition=i,await i}catch{if(t.controller.signal.aborted)return;t.state="failed",t.error=Gi("qr-connect-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002")),this.#a.warn?.("[dsh-im:wecom] QR polling failed"),this.#S(t)}}async#d(t,o){try{let i=hl(o.remoteBotId),e=hl(o.secret);if(!i||!e)throw new Error("Enterprise WeChat authorization returned incomplete credentials");t.botId=await this.#h(t,{remoteBotId:i,secret:e}),t.state="connected",t.error=null}catch{t.controller.signal.aborted?(t.state="cancelled",t.error=Gi("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=Gi("activation-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u63A5\u5165\u914D\u7F6E\u3002")),this.#a.error?.("[dsh-im:wecom] provisioning failed"))}finally{this.#S(t)}}async#h(t,{remoteBotId:o,secret:i}){let e=ew(o),a=this.#t.getByRemoteBotId(o),A=await this.#A.resolve(e.secretRef).catch(()=>{}),r={botId:e.botId,remoteBotId:o,secretRef:e.secretRef,createdAt:a?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};return this.#y(e.botId,async()=>{await this.#A.set(e.secretRef,i);try{if(t.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#t.save(r)}catch(s){throw await this.#B(e.secretRef,A),s}try{if(t.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#E(r,i),this.#i.delete(e.botId)}catch(s){if(t.controller.signal.aborted)throw await this.#C(e.botId),a?await this.#t.save(a).catch(()=>{}):await this.#t.remove(e.botId).catch(()=>null)&&await this.#g({botId:e.botId,config:r}).catch(c=>{this.#a.warn?.("[dsh-im:wecom] cancelled bot state cleanup failed:",c)}),await this.#B(e.secretRef,A),s;this.#i.set(e.botId,Gi("connection-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#a.warn?.(`[dsh-im:wecom] bot ${e.botId} activation connection failed`)}return this.#Q(),e.botId})}async#E(t,o){if(this.#c)throw new Error("Enterprise WeChat controller is closed");if(await this.#C(t.botId),this.#c)throw new Error("Enterprise WeChat controller is closed");let i=await this.#r({botId:t.botId,config:t,secret:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid Enterprise WeChat runtime");this.#n.set(t.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#n.delete(t.botId),e}}async#C(t){let o=this.#n.get(t);this.#n.delete(t),await o?.stop().catch(i=>{this.#a.warn?.(`[dsh-im:wecom] bot ${t} failed to stop cleanly:`,i)})}async#f(t){let o=await this.#A.resolve(t).catch(()=>{});return hl(o?.value)}async#B(t,o){o?.value?await this.#A.set(t,o.value).catch(()=>{}):await this.#A.unset(t).catch(()=>{})}#y(t,o){let a=(this.#o.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#o.get(t)===a&&this.#o.delete(t)});return this.#o.set(t,a),a}#S(t){t.scode=null,t.verificationUrl=null,t.expiresAt=null,this.#l===t.id&&(this.#l=null),this.#Q();let o=[...this.#I.values()].filter(i=>qu.has(i.state));for(;o.length>16;)this.#I.delete(o.shift().id)}#Q(){this.#s+=1}};import{WSAuthFailureError as wFe,WSClient as DFe,WSReconnectExhaustedError as OFe}from"@wecom/aibot-node-sdk";import{generateReqId as sFe}from"@wecom/aibot-node-sdk";var pG=12e4;function gFe(){return[w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002"),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` `)}var cFe=18e3,oZ=5*1024*1024,gZ=4;function ua(n){return typeof n=="string"&&n.trim()?n.trim():null}function Cs(n){return n?.body&&typeof n.body=="object"?n.body:{}}function nZ(n){let t=Cs(n);return t.chattype==="group"?`group:${t.chatid}`:`direct:${t.from?.userid}`}function EG(n){let t=Cs(n),o="";return t.msgtype==="text"?o=typeof t.text?.content=="string"?t.text.content.trim():"":t.msgtype==="voice"?o=typeof t.voice?.content=="string"?t.voice.content.trim():"":t.msgtype==="mixed"&&Array.isArray(t.mixed?.msg_item)&&(o=t.mixed.msg_item.filter(i=>i?.msgtype==="text"&&typeof i.text?.content=="string").map(i=>i.text.content).join(` `).trim()),t.chattype==="group"?o.replace(/^\s*@\S+(?:\s+|$)/u,"").trim():o}function IFe(n){let t=Cs(n);return t.msgtype==="image"?[t.image]:t.msgtype!=="mixed"||!Array.isArray(t.mixed?.msg_item)?[]:t.mixed.msg_item.filter(o=>o?.msgtype==="image").map(o=>o.image)}function lFe(n){let t=Cs(n);return t.msgtype==="file"&&t.file&&typeof t.file=="object"?[t.file]:[]}function pFe(n,t){let o=ua(t?.url);if(!o)return null;let i=ua(t?.aeskey)??void 0;return{async load({signal:e,maxBytes:a}){if(e?.throwIfAborted(),typeof n?.downloadFile!="function")throw new Error("Enterprise WeChat image download is unavailable");let A=await n.downloadFile(o,i);e?.throwIfAborted();let r=A?.buffer;if(!Buffer.isBuffer(r)&&!(r instanceof Uint8Array))throw new Error("Enterprise WeChat image download returned no data");let s=Buffer.from(r);if(Number.isFinite(a)&&s.length>a)throw new Bt("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,w("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));return{data:s,name:A?.filename}}}}function dFe(n,t){let o=ua(t?.url);if(!o)return null;let i=ua(t?.aeskey)??void 0;return{name:ua(t?.filename??t?.file_name??t?.name)??"file",async load({signal:e}={}){if(e?.throwIfAborted(),typeof n?.downloadFile!="function")throw new Error("Enterprise WeChat file download is unavailable");let a=await n.downloadFile(o,i);e?.throwIfAborted();let A=a?.buffer??a?.data;if(!Buffer.isBuffer(A)&&!(A instanceof Uint8Array))throw new Error("Enterprise WeChat file download returned no data");return{data:Buffer.from(A),...ua(a?.filename)?{name:a.filename.trim()}:{}}}}}function cG(n,t){return{content:EG(n),images:IFe(n).map(o=>pFe(t,o)).filter(Boolean),files:lFe(n).map(o=>dFe(t,o)).filter(Boolean)}}function hFe(n,t){return!Array.isArray(n?.files)||n.files.length===0?n:{...n,files:n.files.map(o=>{let i=o.load({signal:t});return i.catch(()=>{}),{...o,async load({signal:e}={}){e?.throwIfAborted();let a=await i;return e?.throwIfAborted(),a}}})}}function EFe(n,t){return Wt(n)?{...n,images:n.images.map(o=>{let i=o.load({signal:t,maxBytes:oZ});return i.catch(()=>{}),{...o,async load({signal:e,maxBytes:a=oZ}={}){e?.throwIfAborted();let A=await i;e?.throwIfAborted();let r=A?.data??A?.buffer??A;if((Buffer.isBuffer(r)||r instanceof Uint8Array?r.length:0)>a)throw new Bt("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,w("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));return A}}})}:n}function CFe(n){return{...n,images:n.images.map(t=>({...t,async load(){throw new Bt("image-queue-full",`Enterprise WeChat already has ${gZ} prefetched images`,w("\u5F53\u524D\u5F85\u5904\u7406\u56FE\u7247\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u53D1\u9001\u3002"))}}))}}function dG(n){return Cs(n).msgtype==="text"?EG(n):""}function uFe(n){return Cs(n).msgtype==="text"&&!!ua(EG(n))}function iw(n,t=cFe){let o=String(n??"").trim();if(!o)return[];let i=[],e="",a=0;for(let A of o){let r=Buffer.byteLength(A);e&&a+r>t?(i.push(e),e=A,a=r):(e+=A,a+=r)}return e&&i.push(e),i}function BFe(n){return n?.type==="tool"?w("\u6B63\u5728\u4F7F\u7528{name}\u2026",{name:n.name}):n?.text}function Vu(n,t="",{finish:o=!1}={}){let i=String(n??"").replace(/<\/?think>/gi,"").trim(),e=String(t??"").trim();if(!i)return e;let a=o||e?`${i}`:`${i}`;return e?`${a} -${e}`:a}function fFe(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u7684\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA\u7F3A\u5C11\u7D20\u6750\u4E0A\u4F20\u6216\u6587\u4EF6\u6D88\u606F\u80FD\u529B\uFF0C\u8BF7\u68C0\u67E5\u673A\u5668\u4EBA\u6743\u9650\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u4F01\u4E1A\u5FAE\u4FE1\u4E0D\u5141\u8BB8\u53D1\u9001\u7A7A\u6587\u4EF6\u3002",{name:o});case"artifact-changed":case"artifact-invalid":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u4F01\u4E1A\u5FAE\u4FE1\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u4F01\u4E1A\u5FAE\u4FE1\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7\u4F01\u4E1A\u5FAE\u4FE1\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function hG(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function sZ(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,hG(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}function IG(n,{dispatched:t=!1}={}){if(n?.code?.startsWith?.("artifact-"))return n;let o=Number(n?.httpStatus??n?.status??n?.response?.status),i=Number(n?.providerCode??n?.errcode??n?.body?.errcode),e=new Error("Enterprise WeChat file delivery failed",{cause:n});return o===401||o===403||i===48002?e.code="artifact-permission-required":o===413?e.code="artifact-too-large":o===429||i===45009?e.code="artifact-rate-limited":Number.isFinite(i)&&i!==0?e.code="artifact-provider-rejected":e.code=t?"artifact-delivery-uncertain":"artifact-provider-failed",Number.isFinite(o)&&(e.status=o),Number.isFinite(i)&&(e.providerCode=i),e}async function cZ(n,t,o,i,{signal:e,timeoutMs:a=pG}={}){if(e?.throwIfAborted(),typeof n?.uploadMedia!="function"||typeof n?.sendMediaMessage!="function"){let d=new Error(`Enterprise WeChat ${i} delivery is unavailable`);throw d.code="artifact-provider-unavailable",d}let A=AbortSignal.timeout(a),r=e?AbortSignal.any([e,A]):A,s;try{let d=n.uploadMedia(o.bytes,{type:i,filename:o.fileName});ln(o,d),s=await sZ(d,r)}catch(d){throw e?.aborted?hG(e):IG(d)}e?.throwIfAborted();let g=ua(s?.media_id);if(!g){let d=new Error(`Enterprise WeChat ${i} upload returned no media id`);throw d.code="artifact-provider-rejected",d}let c;try{let d=n.sendMediaMessage(t,i,g);ln(o,d),c=await sZ(d,r)}catch(d){throw e?.aborted?hG(e):IG(d,{dispatched:!0})}e?.throwIfAborted();let I=Number(c?.body?.errcode??c?.errcode);if(Number.isFinite(I)&&I!==0)throw IG({providerCode:I});return c}function QFe(n,t,o,i){return cZ(n,t,o,"image",i)}function yFe(n,t,o,i){return cZ(n,t,o,"file",i)}function mFe(n,t){return typeof n=="string"&&n.trim()?n:t.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):w("\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002")}function lG(n){return ua(n?.body?.msgid)??ua(n?.body?.message_id)}function SFe(n,t){return t.questions[t.index]&&ua(Cs(n).from?.userid)===t.actor&&ua(dG(n))}function CG(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,artifactsSent:0,artifactSendErrors:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null}}var ow=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o=new Map;#s=new Map;#c=new Map;#p=new Map;#d=new Set;#h=new Set;#E;#C=new mi;#f=0;constructor({client:t,harness:o,state:i,contextEnhancement:e,status:a=CG(),logger:A=console,replyTimeoutMs:r=6e5,generateStreamId:s=sFe,fileUploadTimeoutMs:g=pG,signal:c}){if(!t||typeof t.replyStream!="function"||typeof t.sendMessage!="function")throw new TypeError("Enterprise WeChat client is required");if(!o||!i)throw new TypeError("Harness client and state store are required");if(!Number.isInteger(g)||g<1)throw new TypeError("fileUploadTimeoutMs must be a positive integer");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#l=Math.min(g,pG),this.#I=c,this.#E=new Ci({label:"wecom",logger:A})}get status(){return structuredClone(this.#g)}accept(t){if(this.#I?.aborted)return Promise.resolve();let o=Cs(t),i=ua(o.msgid),e=ua(o.from?.userid),a=o.chattype==="group"?ua(o.chatid):e;if(!i||!e||!a||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i)||this.#p.has(i))return Promise.resolve();let A=nZ(t);this.#p.set(i,Xr(this.#r,o.chattype==="single"?"direct":"group")),o.chattype==="single"&&Eo(this.#t,{chatId:a});let r=this.#s.get(A),s=cG(t,this.#e),g=ua(s.content)??"",c=So(g),I=this.#C.status(A);if(c&&o.chattype==="group")return this.#y(t,i,a,{message:qn()});if(o.chattype==="single"&&(c||I.phase==="collecting")){let Q=/^\/batch$/iu.test(g)&&I.phase==="idle"&&(this.#o.has(A)||r||this.#E.hasPending(A))?{handled:!0,kind:"busy",message:wo()}:this.#C.handle(A,g,{plainText:uFe(t)});if(Q.handled)return Q.kind==="submit"?this.#B({...t,body:{...o,msgtype:"text",text:{content:Q.prompt}}},i,A,{batchSubmission:Q}):this.#y(t,i,a,Q)}let d=fi(g)?qi:Lt(s)?null:zi(g)?Qi:Vi(g)?Wi:Zi(g)?yi:null;if(d){let f;return f=this.#S(t,i,a,A,s,d).catch(Q=>{if(Q?.code==="turn-stopped"||this.#I?.aborted)return;this.#g.lastError=Q?.message??String(Q);let y=tt(this.#g,Q);return this.#a.error?.(`[dsh-im:wecom] failed to process a command [${y.referenceId}]`),this.#m(t,a,dt(y)).catch(()=>{})}).finally(()=>{this.#p.delete(i),this.#h.delete(f)}),this.#h.add(f),f}let B=this.#E.claimReply({key:A,actor:e,messageId:i,text:dG(t),addressed:!0,hasPendingQuestion:!!r,questionCompletion:r?.submitting||r?.claimedReplyMessageId?r.queue:null,isQuestionPending:()=>this.#s.has(A),send:f=>this.#m(t,a,f)});if(B){let f;return f=B.process(async()=>this.#t.hasSeen(i)?!1:(await this.#t.markSeen(i),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#p.delete(i),this.#d.delete(f)}),this.#d.add(f),f}if(r&&r.actor!==e)return this.#B(t,i,A);if(r?.submitting||r?.claimedReplyMessageId)return this.#B(t,i,A);if(r){SFe(t,r)&&(r.claimedReplyMessageId=i);let Q=(r.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#R(t,i,e,a,A,r)).finally(()=>{this.#p.delete(i),r.claimedReplyMessageId===i&&(r.claimedReplyMessageId=null),r.queue===Q&&(r.queue=null)});return r.queue=Q,Q}return this.#B(t,i,A)}#B(t,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1,batchSubmission:A=null}={}){let r=cG(t,this.#e),s=r.images.length,g=0,c=r;s>0&&(this.#f+s<=gZ?(g=s,this.#f+=g,c=EFe(r,this.#I)):c=CFe(r)),c=hFe(c,this.#I);let d=(this.#o.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#b(t,{alreadyRecorded:a,preparedMessage:c,batchSubmission:A})).finally(()=>{this.#f-=g,e&&this.#p.delete(o),this.#o.get(i)===d&&this.#o.delete(i)});return this.#o.set(i,d),d}#y(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),e.message&&await this.#m(t,i,e.message),this.#g.lastError=null)}).catch(async A=>{if(this.#I?.aborted)return;this.#g.lastError=A?.message??String(A);let r=tt(this.#g,A);this.#a.error?.(`[dsh-im:wecom] failed to process a batch input message [${r.referenceId}]`),await this.#m(t,i,dt(r)).catch(()=>{})}).finally(()=>{this.#p.delete(o),this.#h.delete(a)}),this.#h.add(a),a}async waitForIdle(){await Promise.allSettled([...this.#o.values(),...[...this.#s.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#d,...this.#h])}async#S(t,o,i,e,a,A){if(this.#I?.throwIfAborted(),this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString();let r=await A(a.content,this.#A,this.#t,e,{signal:this.#I,isDirect:Cs(t).chattype==="single",hasImages:Wt(a),hasFiles:Lt(a),pendingInteraction:this.#s.has(e)||this.#E.hasPending(e),control:{owner:this,key:e}});r?.stopped&&await Promise.allSettled([this.#_(e),this.#E.closeRoute(e)]);for(let s of r?.messages??[r?.message])s&&await this.#m(t,i,s);this.#g.lastError=null}async#Q(t,o){let i=[];for(let e of iw(o)){this.#I?.throwIfAborted();let a=await this.#e.sendMessage(t,{msgtype:"markdown",markdown:{content:e}}),A=lG(a);A&&i.push(A)}return i}async#m(t,o,i){this.#I?.throwIfAborted();let e=iw(i);if(e.length!==0)try{await this.#e.replyStream(t,this.#i("stream"),e[0],!0);for(let a of e.slice(1))await this.#e.sendMessage(o,{msgtype:"markdown",markdown:{content:a}})}catch{await this.#Q(o,i)}}async#u(t,o,i=[],e=null){if(i.length===0)return{receipt:e,failureNoticeVisible:!1,artifactSendErrors:0};let a=await bo({artifacts:i,baseReceipt:e,deliveryId:o,aggregatePresentation:e?"wecom-text-and-files":"wecom-files",alwaysMerge:!0,channelKey:"wecom",signal:this.#I,sendImage:A=>QFe(this.#e,t,A,{signal:this.#I,timeoutMs:this.#l}),sendFile:A=>yFe(this.#e,t,A,{signal:this.#I,timeoutMs:this.#l}),onFailure:(A,r)=>tt(this.#g,r,{userMessage:fFe(A?.fileName,r),reason:r?.code}),sendFailureNotice:(A,r,s)=>this.#Q(t,dt(s)),logger:this.#a});return this.#g.artifactsSent=(this.#g.artifactsSent??0)+a.artifactsSent,this.#g.artifactSendErrors=(this.#g.artifactSendErrors??0)+a.artifactSendErrors,{receipt:a.receipt,failureNoticeVisible:a.failureNoticeVisible,artifactSendErrors:a.artifactSendErrors}}async#b(t,{alreadyRecorded:o=!1,preparedMessage:i,batchSubmission:e=null}={}){if(this.#I?.aborted)return;let a=Cs(t),A=typeof a.msgid=="string"?a.msgid:"",r=typeof a.from?.userid=="string"?a.from.userid:"",s=a.chattype==="group"?a.chatid:r;if(!A||!r||!s||!["single","group"].includes(a.chattype))return;if(!o){if(this.#t.hasSeen(A))return;this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}let g=i??cG(t,this.#e),c=g.content,I=Wt(g),d=Lt(g),B=nZ(t),f=null,Q=!1,y=w("\u6B63\u5728\u601D\u8003\u4E2D\u2026"),m="",_=e===null,T=!1;try{if(!c&&!I&&!d){await this.#m(t,s,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002")),await this.#t.markSeen(A);return}let R=c.toLowerCase();if(!I&&!d&&R==="/help"){await this.#m(t,s,gFe()),await this.#t.markSeen(A);return}if(!I&&!d&&R==="/status"){await this.#A.ensureRunning({signal:this.#I}),await this.#m(t,s,w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002")),await this.#t.markSeen(A);return}if(!I&&!d&&R==="/new"){await this.#t.clearSession(B),await this.#m(t,s,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002")),await this.#t.markSeen(A);return}let F=I||d?null:await Qo(c,this.#A,B);if(F){for(let ie of F.messages??[F.message])await this.#m(t,s,ie);await this.#t.markSeen(A);return}let K=I||d?null:await Bi(c,this.#A,this.#t,B,{signal:this.#I});if(K){await this.#m(t,s,K.message),await this.#t.markSeen(A);return}f=this.#i("stream");try{await this.#e.replyStream(t,f,Vu(y),!1),Q=!0}catch(ie){this.#a.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",ie)}let L=I?await Bo(g,{signal:this.#I}):void 0,q=this.#p.get(A);q&&(L=mo(L??c,q,()=>({channel:"wecom",senderId:r}))),await this.#t.markSeen(A),T=!0;let{answer:z,artifacts:j=[]}=await ui({harness:this.#A,state:this.#t,key:B,text:c,content:L,createOptions:{signal:this.#I},existsOptions:{signal:this.#I},askOptions:{timeoutMs:this.#n,signal:this.#I,control:{owner:this,key:B},onUpdate:Q&&typeof this.#e.replyStreamNonBlocking=="function"?async ie=>{ie?.type==="text"?m=ie.text:y=BFe(ie)||y;let De=iw(Vu(y,m))[0];De&&await this.#e.replyStreamNonBlocking(t,f,De,!1)}:void 0,onInteraction:ie=>this.#D(ie,{key:B,actor:r,chatId:s,requiresMention:a.chattype==="group"}),onInteractionResolved:ie=>this.#w(ie),files:g.files}});e&&(this.#C.complete(B,e.token),_=!0),this.#I?.throwIfAborted();let P=mFe(z,j),J=iw(Vu(y,P,{finish:!0})),U=!1,N=null,k=null;try{if(Q&&J.length>0)try{let ie=[],De=await this.#e.replyStream(t,f,J[0],!0),fe=lG(De);fe&&ie.push(fe);for(let _e of J.slice(1)){let Ee=await this.#e.sendMessage(s,{msgtype:"markdown",markdown:{content:_e}}),Qe=lG(Ee);Qe&&ie.push(Qe)}U=!0,N=Zt({deliveryId:A,presentation:"wecom-text",providerMessageIds:ie})}catch(ie){this.#a.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",ie)}if(!U){let ie=await this.#Q(s,P);N=Zt({deliveryId:A,presentation:"wecom-text",providerMessageIds:ie})}}catch(ie){k=Ma(ie),this.#a.warn?.("[dsh-im:wecom] final text delivery failed; continuing with result files:",ie)}let V=await this.#u(s,A,j,N),Ae=V.receipt?.artifacts?.some(({outcome:ie})=>ie==="sent"||ie==="unknown");if(k&&!Ae&&!V.failureNoticeVisible)throw k;return k&&V.artifactSendErrors===0&&tt(this.#g,k),T||await this.#t.markSeen(A),this.#g.messagesReplied+=1,this.#g.lastReplyAt=new Date().toISOString(),this.#g.lastError=null,!k&&V.artifactSendErrors===0&&Co(this.#g),V.receipt}catch(R){let F=null;if(!_&&e&&(R?.code==="turn-stopped"?this.#C.complete(B,e.token):F=this.#C.fail(B,e.token).message??null,_=!0),R?.code==="turn-stopped"){Q&&f&&await this.#e.replyStream(t,f,Vu(y,w("\u5DF2\u505C\u6B62\u3002"),{finish:!0}),!0).catch(()=>{}),T||await this.#t.markSeen(A);return}if(this.#I?.aborted)return;this.#g.lastError=R?.message??String(R);let K=Oo(R)??fo(R),L=tt(this.#g,R,{userMessage:K,reason:Ji(R)?.reason});this.#a.error?.(`[dsh-im:wecom] failed to process an inbound message [${L.referenceId}]`);let q=dt(L),z=F?`${q} +${e}`:a}function fFe(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u7684\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA\u7F3A\u5C11\u7D20\u6750\u4E0A\u4F20\u6216\u6587\u4EF6\u6D88\u606F\u80FD\u529B\uFF0C\u8BF7\u68C0\u67E5\u673A\u5668\u4EBA\u6743\u9650\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u4F01\u4E1A\u5FAE\u4FE1\u4E0D\u5141\u8BB8\u53D1\u9001\u7A7A\u6587\u4EF6\u3002",{name:o});case"artifact-changed":case"artifact-invalid":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u4F01\u4E1A\u5FAE\u4FE1\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u4F01\u4E1A\u5FAE\u4FE1\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7\u4F01\u4E1A\u5FAE\u4FE1\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function hG(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function sZ(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,hG(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}function IG(n,{dispatched:t=!1}={}){if(n?.code?.startsWith?.("artifact-"))return n;let o=Number(n?.httpStatus??n?.status??n?.response?.status),i=Number(n?.providerCode??n?.errcode??n?.body?.errcode),e=new Error("Enterprise WeChat file delivery failed",{cause:n});return o===401||o===403||i===48002?e.code="artifact-permission-required":o===413?e.code="artifact-too-large":o===429||i===45009?e.code="artifact-rate-limited":Number.isFinite(i)&&i!==0?e.code="artifact-provider-rejected":e.code=t?"artifact-delivery-uncertain":"artifact-provider-failed",Number.isFinite(o)&&(e.status=o),Number.isFinite(i)&&(e.providerCode=i),e}async function cZ(n,t,o,i,{signal:e,timeoutMs:a=pG}={}){if(e?.throwIfAborted(),typeof n?.uploadMedia!="function"||typeof n?.sendMediaMessage!="function"){let d=new Error(`Enterprise WeChat ${i} delivery is unavailable`);throw d.code="artifact-provider-unavailable",d}let A=AbortSignal.timeout(a),r=e?AbortSignal.any([e,A]):A,s;try{let d=n.uploadMedia(o.bytes,{type:i,filename:o.fileName});ln(o,d),s=await sZ(d,r)}catch(d){throw e?.aborted?hG(e):IG(d)}e?.throwIfAborted();let g=ua(s?.media_id);if(!g){let d=new Error(`Enterprise WeChat ${i} upload returned no media id`);throw d.code="artifact-provider-rejected",d}let c;try{let d=n.sendMediaMessage(t,i,g);ln(o,d),c=await sZ(d,r)}catch(d){throw e?.aborted?hG(e):IG(d,{dispatched:!0})}e?.throwIfAborted();let I=Number(c?.body?.errcode??c?.errcode);if(Number.isFinite(I)&&I!==0)throw IG({providerCode:I});return c}function QFe(n,t,o,i){return cZ(n,t,o,"image",i)}function yFe(n,t,o,i){return cZ(n,t,o,"file",i)}function mFe(n,t){return typeof n=="string"&&n.trim()?n:t.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):w("\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002")}function lG(n){return ua(n?.body?.msgid)??ua(n?.body?.message_id)}function SFe(n,t){return t.questions[t.index]&&ua(Cs(n).from?.userid)===t.actor&&ua(dG(n))}function CG(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,artifactsSent:0,artifactSendErrors:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null}}var ow=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o=new Map;#s=new Map;#c=new Map;#p=new Map;#d=new Set;#h=new Set;#E;#C=new mi;#f=0;constructor({client:t,harness:o,state:i,contextEnhancement:e,status:a=CG(),logger:A=console,replyTimeoutMs:r=6e5,generateStreamId:s=sFe,fileUploadTimeoutMs:g=pG,signal:c}){if(!t||typeof t.replyStream!="function"||typeof t.sendMessage!="function")throw new TypeError("Enterprise WeChat client is required");if(!o||!i)throw new TypeError("Harness client and state store are required");if(!Number.isInteger(g)||g<1)throw new TypeError("fileUploadTimeoutMs must be a positive integer");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#l=Math.min(g,pG),this.#I=c,this.#E=new Ci({label:"wecom",logger:A})}get status(){return structuredClone(this.#g)}accept(t){if(this.#I?.aborted)return Promise.resolve();let o=Cs(t),i=ua(o.msgid),e=ua(o.from?.userid),a=o.chattype==="group"?ua(o.chatid):e;if(!i||!e||!a||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i)||this.#p.has(i))return Promise.resolve();let A=nZ(t);this.#p.set(i,Xr(this.#r,o.chattype==="single"?"direct":"group")),o.chattype==="single"&&Eo(this.#t,{chatId:a});let r=this.#s.get(A),s=cG(t,this.#e),g=ua(s.content)??"",c=So(g),I=this.#C.status(A);if(c&&o.chattype==="group")return this.#y(t,i,a,{message:qn()});if(o.chattype==="single"&&(c||I.phase==="collecting")){let Q=/^\/batch$/iu.test(g)&&I.phase==="idle"&&(this.#o.has(A)||r||this.#E.hasPending(A))?{handled:!0,kind:"busy",message:wo()}:this.#C.handle(A,g,{plainText:uFe(t)});if(Q.handled)return Q.kind==="submit"?this.#B({...t,body:{...o,msgtype:"text",text:{content:Q.prompt}}},i,A,{batchSubmission:Q}):this.#y(t,i,a,Q)}let d=fi(g)?qi:Lt(s)?null:zi(g)?Qi:Vi(g)?Wi:Zi(g)?yi:null;if(d){let f;return f=this.#S(t,i,a,A,s,d).catch(Q=>{if(Q?.code==="turn-stopped"||this.#I?.aborted)return;this.#g.lastError=Q?.message??String(Q);let y=tt(this.#g,Q);return this.#a.error?.(`[dsh-im:wecom] failed to process a command [${y.referenceId}]`),this.#m(t,a,dt(y)).catch(()=>{})}).finally(()=>{this.#p.delete(i),this.#h.delete(f)}),this.#h.add(f),f}let B=this.#E.claimReply({key:A,actor:e,messageId:i,text:dG(t),addressed:!0,hasPendingQuestion:!!r,questionCompletion:r?.submitting||r?.claimedReplyMessageId?r.queue:null,isQuestionPending:()=>this.#s.has(A),send:f=>this.#m(t,a,f)});if(B){let f;return f=B.process(async()=>this.#t.hasSeen(i)?!1:(await this.#t.markSeen(i),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#p.delete(i),this.#d.delete(f)}),this.#d.add(f),f}if(r&&r.actor!==e)return this.#B(t,i,A);if(r?.submitting||r?.claimedReplyMessageId)return this.#B(t,i,A);if(r){SFe(t,r)&&(r.claimedReplyMessageId=i);let Q=(r.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#R(t,i,e,a,A,r)).finally(()=>{this.#p.delete(i),r.claimedReplyMessageId===i&&(r.claimedReplyMessageId=null),r.queue===Q&&(r.queue=null)});return r.queue=Q,Q}return this.#B(t,i,A)}#B(t,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1,batchSubmission:A=null}={}){let r=cG(t,this.#e),s=r.images.length,g=0,c=r;s>0&&(this.#f+s<=gZ?(g=s,this.#f+=g,c=EFe(r,this.#I)):c=CFe(r)),c=hFe(c,this.#I);let d=(this.#o.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#b(t,{alreadyRecorded:a,preparedMessage:c,batchSubmission:A})).finally(()=>{this.#f-=g,e&&this.#p.delete(o),this.#o.get(i)===d&&this.#o.delete(i)});return this.#o.set(i,d),d}#y(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),e.message&&await this.#m(t,i,e.message),this.#g.lastError=null)}).catch(async A=>{if(this.#I?.aborted)return;this.#g.lastError=A?.message??String(A);let r=tt(this.#g,A);this.#a.error?.(`[dsh-im:wecom] failed to process a batch input message [${r.referenceId}]`),await this.#m(t,i,dt(r)).catch(()=>{})}).finally(()=>{this.#p.delete(o),this.#h.delete(a)}),this.#h.add(a),a}async waitForIdle(){await Promise.allSettled([...this.#o.values(),...[...this.#s.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#d,...this.#h])}async#S(t,o,i,e,a,A){if(this.#I?.throwIfAborted(),this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString();let r=await A(a.content,this.#A,this.#t,e,{signal:this.#I,isDirect:Cs(t).chattype==="single",hasImages:Wt(a),hasFiles:Lt(a),pendingInteraction:this.#s.has(e)||this.#E.hasPending(e),control:{owner:this,key:e}});r?.stopped&&await Promise.allSettled([this.#_(e),this.#E.closeRoute(e)]);for(let s of r?.messages??[r?.message])s&&await this.#m(t,i,s);this.#g.lastError=null}async#Q(t,o){let i=[];for(let e of iw(o)){this.#I?.throwIfAborted();let a=await this.#e.sendMessage(t,{msgtype:"markdown",markdown:{content:e}}),A=lG(a);A&&i.push(A)}return i}async#m(t,o,i){this.#I?.throwIfAborted();let e=iw(i);if(e.length!==0)try{await this.#e.replyStream(t,this.#i("stream"),e[0],!0);for(let a of e.slice(1))await this.#e.sendMessage(o,{msgtype:"markdown",markdown:{content:a}})}catch{await this.#Q(o,i)}}async#u(t,o,i=[],e=null){if(i.length===0)return{receipt:e,failureNoticeVisible:!1,artifactSendErrors:0};let a=await bo({artifacts:i,baseReceipt:e,deliveryId:o,aggregatePresentation:e?"wecom-text-and-files":"wecom-files",alwaysMerge:!0,channelKey:"wecom",signal:this.#I,sendImage:A=>QFe(this.#e,t,A,{signal:this.#I,timeoutMs:this.#l}),sendFile:A=>yFe(this.#e,t,A,{signal:this.#I,timeoutMs:this.#l}),onFailure:(A,r)=>tt(this.#g,r,{userMessage:fFe(A?.fileName,r),reason:r?.code}),sendFailureNotice:(A,r,s)=>this.#Q(t,dt(s)),logger:this.#a});return this.#g.artifactsSent=(this.#g.artifactsSent??0)+a.artifactsSent,this.#g.artifactSendErrors=(this.#g.artifactSendErrors??0)+a.artifactSendErrors,{receipt:a.receipt,failureNoticeVisible:a.failureNoticeVisible,artifactSendErrors:a.artifactSendErrors}}async#b(t,{alreadyRecorded:o=!1,preparedMessage:i,batchSubmission:e=null}={}){if(this.#I?.aborted)return;let a=Cs(t),A=typeof a.msgid=="string"?a.msgid:"",r=typeof a.from?.userid=="string"?a.from.userid:"",s=a.chattype==="group"?a.chatid:r;if(!A||!r||!s||!["single","group"].includes(a.chattype))return;if(!o){if(this.#t.hasSeen(A))return;this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}let g=i??cG(t,this.#e),c=g.content,I=Wt(g),d=Lt(g),B=nZ(t),f=null,Q=!1,y=w("\u6B63\u5728\u601D\u8003\u4E2D\u2026"),m="",_=e===null,T=!1;try{if(!c&&!I&&!d){await this.#m(t,s,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002")),await this.#t.markSeen(A);return}let R=c.toLowerCase();if(!I&&!d&&R==="/help"){await this.#m(t,s,gFe()),await this.#t.markSeen(A);return}if(!I&&!d&&R==="/status"){await this.#A.ensureRunning({signal:this.#I}),await this.#m(t,s,w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002")),await this.#t.markSeen(A);return}if(!I&&!d&&R==="/new"){await this.#t.clearSession(B),await this.#m(t,s,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002")),await this.#t.markSeen(A);return}let L=I||d?null:await Qo(c,this.#A,B);if(L){for(let ie of L.messages??[L.message])await this.#m(t,s,ie);await this.#t.markSeen(A);return}let U=I||d?null:await Bi(c,this.#A,this.#t,B,{signal:this.#I});if(U){await this.#m(t,s,U.message),await this.#t.markSeen(A);return}f=this.#i("stream");try{await this.#e.replyStream(t,f,Vu(y),!1),Q=!0}catch(ie){this.#a.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",ie)}let F=I?await Bo(g,{signal:this.#I}):void 0,q=this.#p.get(A);q&&(F=mo(F??c,q,()=>({channel:"wecom",senderId:r}))),await this.#t.markSeen(A),T=!0;let{answer:z,artifacts:j=[]}=await ui({harness:this.#A,state:this.#t,key:B,text:c,content:F,createOptions:{signal:this.#I},existsOptions:{signal:this.#I},askOptions:{timeoutMs:this.#n,signal:this.#I,control:{owner:this,key:B},onUpdate:Q&&typeof this.#e.replyStreamNonBlocking=="function"?async ie=>{ie?.type==="text"?m=ie.text:y=BFe(ie)||y;let De=iw(Vu(y,m))[0];De&&await this.#e.replyStreamNonBlocking(t,f,De,!1)}:void 0,onInteraction:ie=>this.#D(ie,{key:B,actor:r,chatId:s,requiresMention:a.chattype==="group"}),onInteractionResolved:ie=>this.#w(ie),files:g.files}});e&&(this.#C.complete(B,e.token),_=!0),this.#I?.throwIfAborted();let P=mFe(z,j),J=iw(Vu(y,P,{finish:!0})),H=!1,N=null,k=null;try{if(Q&&J.length>0)try{let ie=[],De=await this.#e.replyStream(t,f,J[0],!0),fe=lG(De);fe&&ie.push(fe);for(let _e of J.slice(1)){let Ee=await this.#e.sendMessage(s,{msgtype:"markdown",markdown:{content:_e}}),Qe=lG(Ee);Qe&&ie.push(Qe)}H=!0,N=Zt({deliveryId:A,presentation:"wecom-text",providerMessageIds:ie})}catch(ie){this.#a.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",ie)}if(!H){let ie=await this.#Q(s,P);N=Zt({deliveryId:A,presentation:"wecom-text",providerMessageIds:ie})}}catch(ie){k=Ma(ie),this.#a.warn?.("[dsh-im:wecom] final text delivery failed; continuing with result files:",ie)}let V=await this.#u(s,A,j,N),Ae=V.receipt?.artifacts?.some(({outcome:ie})=>ie==="sent"||ie==="unknown");if(k&&!Ae&&!V.failureNoticeVisible)throw k;return k&&V.artifactSendErrors===0&&tt(this.#g,k),T||await this.#t.markSeen(A),this.#g.messagesReplied+=1,this.#g.lastReplyAt=new Date().toISOString(),this.#g.lastError=null,!k&&V.artifactSendErrors===0&&Co(this.#g),V.receipt}catch(R){let L=null;if(!_&&e&&(R?.code==="turn-stopped"?this.#C.complete(B,e.token):L=this.#C.fail(B,e.token).message??null,_=!0),R?.code==="turn-stopped"){Q&&f&&await this.#e.replyStream(t,f,Vu(y,w("\u5DF2\u505C\u6B62\u3002"),{finish:!0}),!0).catch(()=>{}),T||await this.#t.markSeen(A);return}if(this.#I?.aborted)return;this.#g.lastError=R?.message??String(R);let U=Oo(R)??fo(R),F=tt(this.#g,R,{userMessage:U,reason:Ji(R)?.reason});this.#a.error?.(`[dsh-im:wecom] failed to process an inbound message [${F.referenceId}]`);let q=dt(F),z=L?`${q} -${F}`:q;try{Q&&f?await this.#e.replyStream(t,f,Vu(y,z,{finish:!0}),!0):await this.#m(t,s,z),T||await this.#t.markSeen(A)}catch{this.#a.error?.("[dsh-im:wecom] failed to send the safe error reply")}}finally{await Promise.allSettled([this.#_(B),this.#E.closeRoute(B)])}}async#R(t,o,i,e,a,A){if(this.#I?.aborted)return;let r=this.#s.get(a),s=A.claimedReplyMessageId===o;if(!r||r!==A||r.submitting)return s&&(!r||r!==A)?this.#k(t,o,e):this.#B(t,o,a,{releaseMessageId:!1});if(this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString();let g=ua(dG(t));if(!g){await this.#m(t,e,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002")).catch(()=>{});return}let c=this.#s.get(a);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#m(t,e,w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")).catch(()=>{});return}return this.#B(t,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#B(t,o,a,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#T(c)}catch{this.#g.lastError=w("\u4F01\u4E1A\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002"),this.#a.error?.("[dsh-im:wecom] failed to retry an interaction question"),c.interaction.reconnect?.();return}let d=this.#s.get(a);if(!d||d!==A||d.submitting){if(s&&(!d||d!==A)){await this.#m(t,e,w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")).catch(()=>{});return}return this.#B(t,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}}let I=c.questions[c.index];if(I){if(c.answers.push(Ei(I,g)),c.index+=1,c.index{});return}if(this.#s.get(a)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#g.lastError=w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002"),this.#a.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#m(t,e,w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002")).catch(()=>{})}}}async#D(t,{key:o,actor:i,chatId:e,requiresMention:a}){if(t?.kind==="approval")return this.#E.handleRequested(t,{key:o,actor:i,requiresMention:a,send:c=>this.#Q(e,c)});if(t?.kind!=="question")return;let A=t?.payload?.questions,r=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t?.rpcId!="string"||typeof r!="string"||typeof t.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!di(c))){this.#a.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#Q(e,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002")).catch(()=>{});return}let s=this.#s.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#T(s);return}if(this.#c.has(r))return;if(s){this.#a.warn?.("[dsh-im:wecom] cancelled a second pending Harness question"),await t.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,requiresMention:a,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#s.set(o,g),this.#c.set(g.interactionId,o),await this.#T(g)}async#w(t){if(t?.kind==="approval"){await this.#E.handleResolved(t);return}let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#c.get(o);i&&this.#L(i,o)}#T(t){if(!t.needsPresentation)return Promise.resolve();if(t.presentationPromise)return t.presentationPromise;let o=t.questions[t.index];if(!o)return Promise.resolve();let i=this.#Q(t.chatId,hi(o,t.index,t.questions.length,{requiresMention:t.requiresMention})).then(()=>{t.needsPresentation=!1}).finally(()=>{t.presentationPromise===i&&(t.presentationPromise=null)});return t.presentationPromise=i,i}async#k(t,o,i){this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),await this.#m(t,i,w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")).catch(()=>{}))}#M(t,o){let i=this.#s.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#s.delete(t),this.#c.delete(i.interactionId),i)}#L(t,o){return this.#M(t,o)!==null}async#_(t){let o=this.#M(t);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Enterprise WeChat interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#a.warn?.("[dsh-im:wecom] failed to cancel a pending Harness interaction")}}};function bFe(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function MFe(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...CG()}}var Wu=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o=MFe();#s=null;#c=null;#p=null;#d=null;#h=null;constructor({config:t,secret:o,harness:i,state:e,contextEnhancement:a,logger:A=console,replyTimeoutMs:r=6e5,connectTimeoutMs:s=2e4,maxReconnectAttempts:g=10,createClient:c=I=>new DFe(I)}){if(!t||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c}get status(){return structuredClone(this.#o)}async start(){if(this.#o.ready&&this.#s)return this.status;if(this.#p)return this.#p;this.#h?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let t=new AbortController;return this.#d=t,this.#h=t,this.#p=this.#E(t.signal).finally(()=>{this.#d===t&&(this.#d=null),this.#p=null}),this.#p}async#E(t){await this.#C(),t.throwIfAborted(),this.#o.startedAt=new Date().toISOString(),this.#o.wecomConnectionState="connecting",this.#o.lastError=null,await this.#t.ensureRunning(),this.#o.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#l({botId:this.#e.remoteBotId,secret:this.#A,logger:o,maxReconnectAttempts:this.#I});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#s=i,this.#c=new ow({client:i,harness:this.#t,state:this.#r,contextEnhancement:this.#g,status:this.#o,logger:this.#a,replyTimeoutMs:this.#n,signal:t});let e,a,A=!1,r=new Promise((f,Q)=>{e=f,a=Q}),s=()=>{if(this.#s!==i||t.aborted)return;A=!0;let f=Date.now();this.#o.ready=!0,this.#o.wecomConnectionState="connected",this.#o.lastCheckedAt=f,this.#o.lastConnectedAt=f,this.#o.lastError=null,e()},g=()=>{this.#s===i&&(this.#o.ready=!1,this.#o.wecomConnectionState="connecting",this.#o.lastCheckedAt=Date.now())},c=()=>{this.#s===i&&(this.#o.ready=!1,this.#o.wecomConnectionState="connecting",this.#o.lastCheckedAt=Date.now())},I=f=>{if(this.#s!==i)return;let Q=f instanceof wFe||f instanceof OFe;!A&&Q&&a(f),Q&&(this.#o.ready=!1,this.#o.wecomConnectionState="failed"),this.#o.lastError=Q?f.name:"connection-error",this.#a.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} connection error`)},d=f=>this.#c?.accept(f);i.on("authenticated",s),i.on("disconnected",g),i.on("reconnecting",c),i.on("error",I),i.on("message",d);let B;try{return i.connect(),await Promise.race([r,new Promise((f,Q)=>{t.addEventListener("abort",()=>Q(t.reason),{once:!0})}),new Promise((f,Q)=>{B=setTimeout(()=>Q(bFe()),this.#i)})]),this.status}catch(f){throw t.aborted?(await this.#C(),f):(this.#o.ready=!1,this.#o.wecomConnectionState="failed",this.#o.lastError=f?.message??String(f),await this.#C(),f)}finally{clearTimeout(B)}}async stop(){let t=this.#p;return this.#d?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#h?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#h=null,await this.#C(),await t?.catch(()=>{}),this.status}async sendConnectionTest(t){return ec({state:this.#r,text:t,channelLabel:w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"),send:async({chatId:o},i)=>{if(!this.#o.ready||!this.#s)throw new Error("Enterprise WeChat runtime is not connected");await this.#s.sendMessage(o,{msgtype:"markdown",markdown:{content:i}})}})}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.chatId=="string"?t.route.chatId.trim():"";if(t?.kind!=="user"&&t?.kind!=="group"||!e){let a=new TypeError("Invalid Enterprise WeChat proactive delivery target");throw a.code="invalid-target",a}if(!this.#o.ready||!this.#s){let a=new Error("Enterprise WeChat runtime is not connected");throw a.code="bot-not-connected",a}return i?.throwIfAborted(),await this.#s.sendMessage(e,{msgtype:"markdown",markdown:{content:o}}),{sent:!0}}async#C(){let t=this.#s,o=this.#c;this.#s=null,this.#c=null;try{t?.disconnect(),t?.removeAllListeners?.()}catch{this.#a.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#o.ready=!1,this.#o.wecomConnectionState="idle"}};var IZ=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function _Fe(n){if(!Array.isArray(n)||n.length===0)return[...IZ];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...IZ]}var nw=class{#e;#A;#t;#r;#g;#a;#n;#i=null;#I=null;#l=0;#o=!1;#s=!1;#c;#p;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=_Fe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#a=A,this.#n=r,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#s||this.#o?this:(this.#s=!0,this.#d(0),this)}async close(){this.#o||(this.#o=!0,this.#i!==null&&this.#n(this.#i),this.#i=null,await this.#I?.catch(()=>{}),this.#p?.(null),this.#p=null)}#d(t){this.#o||(this.#i=this.#a(()=>{this.#i=null,this.#h()},t),this.#i?.unref?.())}async#h(){if(this.#o||this.#I)return;let t=this.#E();this.#I=t;try{await t}finally{this.#I===t&&(this.#I=null)}}async#E(){try{if(await this.#A.ensureRunning(),this.#o)return;let t=await this.#e.initialize();if(this.#o)return;this.#p?.(t),this.#p=null;let{configured:o,connected:i}=t.totals;if(iRa(n),B=RFe(t),f=await new e(B.config).load(),Q=Cl(t.workspace??process.cwd()),y=o.WorkspaceStore??ea,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=f.list();await m.reconcile(_.map(V=>V.botId)),await Promise.all(_.map(V=>m.ensure(V.botId,{defaultAgentPreset:t.agentPreset})));let T=typeof f.remove=="function"?Pa(f,{workspaces:m}):f,R=o.qrAuth??new g({source:t.qrSource??"deepseek-harness",platform:t.qrPlatform}),F=new Map,K=V=>Cl(B.bots,V,"state.json"),L=async V=>{let Ae=F.get(V);return Ae||(Ae=await new a(K(V)).load(),F.set(V,Ae)),Ae},q=Ua(n,o.commandExecutor),{controlExecutor:z,sessionMaintenanceExecutor:j,fileIngressExecutor:P}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),J=new A({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...q?{commandExecutor:q}:{},...z?{controlExecutor:z}:{},...j?{sessionMaintenanceExecutor:j}:{},...P?{fileIngressExecutor:P}:{}}),U=new r({qrAuth:R,credentials:n.credentials,configStore:T,logger:I,createRuntime:async({botId:V,config:Ae,secret:ie})=>{let De=await L(V);await m.ensure(V,{defaultAgentPreset:t.agentPreset});let fe=Ga(J,{botId:V,workspaces:m,state:De,agentPresetCatalog:d});return new s({config:Ae,secret:ie,harness:fe.harness,state:fe.state,contextEnhancement:{botId:V,getSettings:()=>m.contextEnhancementFor(V)},replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??2e4,maxReconnectAttempts:t.maxReconnectAttempts??10,logger:{error:(..._e)=>I.error?.(`[${V}]`,..._e),warn:(..._e)=>I.warn?.(`[${V}]`,..._e),info:(..._e)=>I.info?.(`[${V}]`,..._e),debug:(..._e)=>I.debug?.(`[${V}]`,..._e)}})},deleteState:async({botId:V})=>{let Ae=F.get(V);if(F.delete(V),Ae&&typeof Ae.remove=="function")await Ae.remove();else try{await TFe(K(V))}catch(ie){if(ie?.code!=="ENOENT")throw ie}}}),N=Fa(U,{workspaces:m,stateFor:L,agentPresetCatalog:d}),k=c({controller:N,harness:J,logger:I,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:N,deliveryAdapter:La({channel:"wecom",workspaces:m,coreController:U,stateFor:L}),ready:k.ready,async close(){await k.close(),await N.close(),J.stopManagedProcess()}}}import kFe from"qrcode";var pZ="/wecom",mr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),dZ=Object.freeze(Object.values(mr)),vFe=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function yG(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Ud(n,t){return yG(n)&&Object.keys(n).every(o=>t.includes(o))}function fG(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function lZ(n,t){return typeof n=="string"&&n.trim().length>0&&n.length<=t}function PFe(n,t){return yG(t)?n===mr.status?Ud(t,[])?null:"connection.status does not accept fields.":n===mr.beginProvisioning?Ud(t,["locale"])&&(t.locale===void 0||t.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[mr.pollProvisioning,mr.cancelProvisioning].includes(n)?Ud(t,["attemptId"])&&fG(t.attemptId)?null:`${n} requires an attemptId.`:n===mr.bindCredentials?Ud(t,["botId","secret"])&&lZ(t.botId,512)&&lZ(t.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===mr.reconnectBot?Ud(t,["botId","sendTest"])&&fG(t.botId)&&(t.sendTest===void 0||t.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===mr.deleteBot?Ud(t,["botId","confirm"])&&fG(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===mr.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===mr.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===mr.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function Hd(n){if(Array.isArray(n))return n.map(Hd);if(!yG(n))return n;let t={};for(let[o,i]of Object.entries(n))vFe.has(o)||(t[o]=Hd(i));return t}async function GFe(n){return kFe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function QG(n,t){return!n||typeof n.verificationUrl!="string"?Hd(n):Hd({...n,qrCodeDataUrl:await t(n.verificationUrl)})}async function ul(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await QG(o.provisioning,t)),Hd(o)}function hZ(n,{encodeQr:t=GFe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete Enterprise WeChat controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!dZ.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let r=PFe(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===mr.status)s=await ul(await n.status(),i);else if(e===mr.beginProvisioning)s=await QG(await n.startProvisioning(),i);else if(e===mr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await QG(g,i)}else if(e===mr.cancelProvisioning)s=Hd(await n.cancelProvisioning(a.attemptId));else if(e===mr.bindCredentials)s=await ul(await n.bindCredentials(a),i);else if(e===mr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};let c;if(a.sendTest===!0)if(!g?.bots?.some(d=>d?.botId===a.botId&&d?.connected===!0)||typeof n.sendConnectionTest!="function")c=ir(Ir("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=ir()}catch(d){c=ir(d)}s=await ul({...g,...c?{testMessage:c}:{}},i)}else if(e===mr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await ul(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===mr.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>ul(g,i))}else if(e===mr.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await ul(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else s=await ul(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"wecom-operation-failed",message:"\u4F01\u4E1A\u5FAE\u4FE1\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function sw(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(pZ,hZ(t,o),{authority:hr(i)})}async function EZ(n,t={}){if(t?.controller)return sw(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await BG(n,t,t.internals),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=sw(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Enterprise WeChat bot connections"),e}import{unlink as HLe}from"node:fs/promises";import{homedir as KLe}from"node:os";import{join as aB,resolve as Ql}from"node:path";import{createHash as aLe}from"node:crypto";import{mkdir as iLe,readFile as oLe,rename as nLe,unlink as sLe,writeFile as gLe}from"node:fs/promises";import{dirname as cLe}from"node:path";import{createCipheriv as FFe,createDecipheriv as LFe,createHash as CZ,randomBytes as SG,randomUUID as uZ}from"node:crypto";var gw="https://ilinkai.weixin.qq.com/",UFe="2.4.6",HFe="3",QZ="https://novac2c.cdn.weixin.qq.com/c2c",Bl=1800,wG="novac2c.cdn.weixin.qq.com",KFe="bot",xFe=2<<16|1024|6,YFe=15e3,BZ=35e3,jFe=3,JFe=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),_A=class extends Error{constructor(t,o,i={}){super(o,i),this.name="WeixinApiError",this.code=t,this.status=i.status,this.providerCode=i.providerCode}};function Mt(n){return typeof n=="string"&&n.trim()?n.trim():null}function yZ(n){let t=n==null?null:String(n).trim();return t&&/^-?[A-Za-z0-9_.:-]{1,160}$/.test(t)?t:void 0}function mZ(n,t){return Number.isInteger(t?.status)&&(n.status=t.status),t?.providerCode!==void 0&&(n.providerCode=t.providerCode),n}function Xu(n,{fallback:t="artifact-provider-rejected"}={}){if(n?.code?.startsWith?.("artifact-"))return n;let o=Number(n?.status),i=yZ(n?.providerCode),e=i??"",a=t,A="Weixin could not prepare the file for delivery.";o===401||o===403||i==="401"||i==="403"||/(?:permission|forbidden|unauthor|access.?denied)/i.test(e)?(a="artifact-permission-required",A="Weixin denied permission to send the file."):o===413||i==="413"||/(?:too.?large|size.?limit)/i.test(e)?(a="artifact-too-large",A="The file exceeds Weixin's size limit."):o===429||i==="429"||/(?:rate.?limit|too.?many)/i.test(e)?(a="artifact-rate-limited",A="Weixin rate-limited file delivery."):t==="artifact-provider-rejected"&&(A="Weixin rejected the file message.");let r=new Error(A,{cause:n});return r.code=a,mZ(r,n)}function qFe(n){let t=new Error("Weixin file delivery result is uncertain",{cause:n});return t.code="artifact-delivery-uncertain",mZ(t,n)}function mG(n){if(!n||typeof n!="object")return null;for(let t of["ret","errcode"])if(n[t]!==void 0&&n[t]!==0&&n[t]!=="0")return yZ(n[t])??"rejected";return null}function zFe(n,t){if(t?.aborted)throw Kd(t);let o=Number(n?.status);return n?.code==="network-error"||n?.code==="timeout"||n?.code==="invalid-response"||o>=500&&o<600?qFe(n):Xu(n)}function VFe(n){let t=Mt(n);return!t||t.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(t)?null:Buffer.from(t,"base64")}function SZ(n){let t=Mt(n?.aeskey);if(t){if(!/^[0-9a-fA-F]{32}$/.test(t))throw new _A("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002");return Buffer.from(t,"hex")}let o=VFe(n?.media?.aes_key);if(o?.length===16)return o;if(o?.length===32&&/^[0-9a-fA-F]{32}$/.test(o.toString("ascii")))return Buffer.from(o.toString("ascii"),"hex");throw new _A("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002")}function wZ(n,t){let o=Buffer.from(n),i=Buffer.from(t);if(i.length!==16||o.length===0||o.length%16!==0)throw new _A("invalid-image-ciphertext","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u6570\u636E\u65E0\u6548\u3002");try{let e=LFe("aes-128-ecb",i,null);return Buffer.concat([e.update(o),e.final()])}catch(e){throw new _A("image-decryption-failed","\u5FAE\u4FE1\u56FE\u7247\u89E3\u5BC6\u5931\u8D25\u3002",{cause:e})}}function DZ(n){let t=Mt(n?.encrypt_query_param);if(t)return`${QZ}/download?encrypted_query_param=${encodeURIComponent(t)}`;let o=Mt(n?.full_url);if(!o)throw new _A("missing-image-url","\u5FAE\u4FE1\u56FE\u7247\u6CA1\u6709\u53EF\u7528\u7684\u4E0B\u8F7D\u5730\u5740\u3002");let i;try{i=new URL(o)}catch{throw new _A("invalid-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u65E0\u6548\u3002")}if(i.protocol!=="https:"||i.hostname!==wG||i.port&&i.port!=="443"||!i.pathname.startsWith("/c2c/"))throw new _A("untrusted-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u4E0D\u53D7\u4FE1\u4EFB\u3002");return i.username="",i.password="",i.hash="",i.toString()}function DG(n,{fetchImpl:t=fetch}={}){if(typeof t!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.item_list??[]){let e=i?.image_item;!e||typeof e!="object"||o.push({name:o.length===0?"image":`image-${o.length+1}`,load:async({signal:a,maxBytes:A})=>{let r=SZ(e),s=DZ(e.media),g=await uo(s,{fetchImpl:t,signal:a,maxBytes:A+16,allowedHosts:[wG]});return wZ(g,r)}})}return o}async function WFe(n,{fetchImpl:t,signal:o}){let i=await t(new URL(n),{method:"GET",signal:o,redirect:"manual"});if(!i?.ok)throw await i?.body?.cancel?.().catch?.(()=>{}),new _A("file-download-failed",`\u5FAE\u4FE1\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF08HTTP ${i?.status??"unknown"}\uFF09\u3002`,{status:i?.status});return Buffer.from(await i.arrayBuffer())}function OG(n,{fetchImpl:t=fetch}={}){if(typeof t!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.item_list??[]){let e=i?.file_item;if(!e||typeof e!="object")continue;let a=Number(e.len);o.push({name:Mt(e.file_name)??(o.length===0?"file":`file-${o.length+1}`),...Number.isFinite(a)&&a>=0?{size:a}:{},load:async({signal:A}={})=>{A?.throwIfAborted();let r=SZ(e),s=DZ(e.media),g=await WFe(s,{fetchImpl:t,signal:A});return A?.throwIfAborted(),wZ(g,r)}})}return o}function bG(n){let t=n.toLowerCase().replace(/\.$/,"");return t==="weixin.qq.com"||t.endsWith(".weixin.qq.com")||t==="wechat.com"||t.endsWith(".wechat.com")}function xd(n){let t;try{t=new URL(n)}catch{throw new _A("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(t.protocol!=="https:"||!bG(t.hostname)||t.port!==""&&t.port!=="443")throw new _A("untrusted-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u8FDE\u63A5\u5730\u5740\u3002");return t.username="",t.password="",t.search="",t.hash="",t.pathname.endsWith("/")||(t.pathname+="/"),t.toString()}function ZFe(n){let t=Mt(n);if(!t)throw new _A("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(t)}catch{throw new _A("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!bG(o.hostname))throw new _A("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function OZ(){return{"iLink-App-Id":KFe,"iLink-App-ClientVersion":String(xFe)}}function XFe(n){let t={...OZ(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(SG(4).readUInt32BE(0)),"utf8").toString("base64")};return Mt(n)&&(t.Authorization=`Bearer ${n.trim()}`),t}function _c(){return{channel_version:UFe,bot_agent:"DeepSeekHarness/1.1.0"}}function $Fe(n){return Math.ceil((n+1)/16)*16}function fZ(n){let t;try{t=new URL(n)}catch{throw new _A("invalid-upload-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u6587\u4EF6\u4E0A\u4F20\u5730\u5740\u3002")}if(t.protocol!=="https:"||t.hostname!==wG||t.port&&t.port!=="443"||t.pathname!=="/c2c/upload"||t.username||t.password)throw new _A("untrusted-upload-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u6587\u4EF6\u4E0A\u4F20\u5730\u5740\u3002");return t.hash="",t}function eLe(n,t){let o=Mt(n?.upload_full_url);if(o)return fZ(o);let i=Mt(n?.upload_param);if(!i)throw new _A("missing-upload-url","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6587\u4EF6\u4E0A\u4F20\u5730\u5740\u3002");let e=new URL(`${QZ}/upload`);return e.searchParams.set("encrypted_query_param",i),e.searchParams.set("filekey",t),fZ(e)}function ALe(n,t){let o=FFe("aes-128-ecb",t,null);return Buffer.concat([o.update(n),o.final()])}async function tLe(n,t,o,{signal:i}={}){let e;for(let a=1;a<=jFe;a+=1){i?.throwIfAborted();try{let A=await n(t,{method:"POST",headers:{"content-type":"application/octet-stream"},body:o,signal:i?AbortSignal.any([i,AbortSignal.timeout(6e4)]):AbortSignal.timeout(6e4),redirect:"error"});if(A.status>=400&&A.status<500)throw new _A("upload-rejected",`\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u88AB\u62D2\u7EDD\uFF08HTTP ${A.status}\uFF09\u3002`,{status:A.status});if(A.status!==200)throw new _A("upload-failed",`\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF08HTTP ${A.status}\uFF09\u3002`,{status:A.status});let r=Mt(A.headers.get("x-encrypted-param"));if(await A.body?.cancel?.().catch(()=>{}),!r)throw new _A("invalid-upload-response","\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u54CD\u5E94\u7F3A\u5C11\u4E0B\u8F7D\u53C2\u6570\u3002");return r}catch(A){if(i?.aborted)throw Kd(i);if(A instanceof _A&&(A.code==="upload-rejected"||A.status<500))throw A;e=A}}throw e instanceof _A?e:new _A("upload-failed","\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\u3002",{cause:e})}function Kd(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function us(n,{method:t,baseUrl:o,endpoint:i,body:e,token:a,timeoutMs:A=YFe,signal:r,authenticated:s=!0}){let g=xd(o),c=new URL(i,g);if(!bG(c.hostname))throw new _A("untrusted-endpoint","\u62D2\u7EDD\u8BBF\u95EE\u4E0D\u53D7\u4FE1\u4EFB\u7684\u5FAE\u4FE1\u670D\u52A1\u5730\u5740\u3002");let I=new AbortController,d=!1,B=()=>I.abort(r?.reason);if(r?.aborted)throw Kd(r);r?.addEventListener("abort",B,{once:!0});let f=A>0?setTimeout(()=>{d=!0,I.abort()},A):null;try{let Q=await n(c,{method:t,headers:s?XFe(a):OZ(),...e===void 0?{}:{body:JSON.stringify(e)},signal:I.signal});if(!Q.ok)throw new _A("http-error",`\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${Q.status}\uFF09\u3002`,{status:Q.status});try{return await Q.json()}catch(y){throw new _A("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(Q){throw r?.aborted?Kd(r):d?new _A("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:Q}):Q instanceof _A?Q:new _A("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:Q})}finally{f&&clearTimeout(f),r?.removeEventListener("abort",B)}}function rLe(n){if(!n||typeof n!="object"||!JFe.has(n.status))throw new _A("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function bZ({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");async function t({baseUrl:o,token:i,toUserId:e,file:a,contextToken:A,runId:r,signal:s},{mediaType:g,createItem:c}){let I=Mt(e);if(!I||!a||typeof a!="object"||typeof a.fileName!="string"||!a.fileName||!Buffer.isBuffer(a.bytes))throw new TypeError("toUserId and a file are required");s?.throwIfAborted();let d=SG(16).toString("hex"),B=SG(16),f=CZ("md5").update(a.bytes).digest("hex"),Q;try{Q=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/getuploadurl",token:i,signal:s,body:{filekey:d,media_type:g,to_user_id:I,rawsize:a.bytes.byteLength,rawfilemd5:f,filesize:$Fe(a.bytes.byteLength),no_need_thumb:!0,aeskey:B.toString("hex"),base_info:_c()}})}catch(j){if(s?.aborted)throw Kd(s);let P=Number(j?.status),J=j?.code==="http-error"&&P>=400&&P<500?"artifact-provider-rejected":"artifact-provider-failed";throw Xu(j,{fallback:J})}let y=mG(Q);if(y)throw Xu(new _A("upload-url-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u4E0A\u4F20\u8BF7\u6C42\u3002",{providerCode:y}));let m=eLe(Q,d),_=ALe(a.bytes,B),T;try{T=await tLe(n,m,_,{signal:s})}catch(j){if(s?.aborted)throw Kd(s);let P=Number(j?.status),J=j?.code==="upload-rejected"||P>=400&&P<500?"artifact-provider-rejected":"artifact-provider-failed";throw Xu(j,{fallback:J})}s?.throwIfAborted();let R=Mt(a.deliveryKey)??Mt(a.artifactId)??uZ(),F=g===3?R:`${R}\0${g}`,K=`dsh-weixin-${CZ("sha256").update(F).digest("hex").slice(0,32)}`,L={encrypt_query_param:T,aes_key:Buffer.from(B.toString("hex")).toString("base64"),encrypt_type:1},q;try{q=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/sendmessage",token:i,signal:s,body:{msg:{from_user_id:"",to_user_id:I,client_id:K,message_type:2,message_state:2,item_list:[c({file:a,media:L,ciphertextSize:_.byteLength})],...Mt(A)?{context_token:A.trim()}:{},...Mt(r)?{run_id:r.trim()}:{}},base_info:_c()}})}catch(j){throw zFe(j,s)}let z=mG(q);if(z)throw Xu(new _A("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u6D88\u606F\u3002",{providerCode:z}));return{messageId:K}}return Object.freeze({inboundImages(o){return DG(o,{fetchImpl:n})},inboundFiles(o){return OG(o,{fetchImpl:n})},async beginLogin({localTokens:o=[],botType:i=HFe,signal:e}={}){let a=[...new Set(o.map(Mt).filter(Boolean))].slice(-10),A=await us(n,{method:"POST",baseUrl:gw,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(i)}`,body:{local_token_list:a},timeoutMs:1e4,signal:e}),r=Mt(A?.qrcode);if(!r)throw new _A("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:r,qrcodeUrl:ZFe(A.qrcode_img_content)}},async pollLogin({qrcode:o,baseUrl:i=gw,verifyCode:e,signal:a}){let A=Mt(o);if(!A)throw new TypeError("qrcode is required");let r=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(A)}`;Mt(e)&&(r+=`&verify_code=${encodeURIComponent(e.trim())}`);let s=await us(n,{method:"GET",baseUrl:i,endpoint:r,timeoutMs:BZ,signal:a,authenticated:!1});return rLe(s)},async getUpdates({baseUrl:o,token:i,getUpdatesBuf:e="",timeoutMs:a,signal:A}){try{return await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:e,base_info:_c()},token:i,timeoutMs:a??BZ,signal:A})}catch(r){if(r instanceof _A&&r.code==="timeout")return{ret:0,msgs:[],get_updates_buf:e};throw r}},async getConfig({baseUrl:o,token:i,toUserId:e,contextToken:a,signal:A}){let r=Mt(e);if(!r)throw new TypeError("toUserId is required");let s=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/getconfig",token:i,signal:A,timeoutMs:1e4,body:{ilink_user_id:r,...Mt(a)?{context_token:a.trim()}:{},base_info:_c()}});if(s?.ret!==void 0&&s.ret!==0)throw new _A("config-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u673A\u5668\u4EBA\u914D\u7F6E\u8BF7\u6C42\u3002");return{typingTicket:Mt(s?.typing_ticket)}},async sendTyping({baseUrl:o,token:i,toUserId:e,typingTicket:a,status:A,signal:r}){let s=Mt(e),g=Mt(a);if(!s||!g)throw new TypeError("toUserId and typingTicket are required");if(A!==1&&A!==2)throw new TypeError("typing status must be 1 or 2");let c=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/sendtyping",token:i,signal:r,timeoutMs:1e4,body:{ilink_user_id:s,typing_ticket:g,status:A,base_info:_c()}});if(c?.ret!==void 0&&c.ret!==0)throw new _A("typing-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u8F93\u5165\u72B6\u6001\u8BF7\u6C42\u3002");return!0},async sendText({baseUrl:o,token:i,toUserId:e,text:a,contextToken:A,runId:r,signal:s}){let g=Mt(e),c=Mt(a);if(!g||!c)throw new TypeError("toUserId and text are required");let I=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/sendmessage",token:i,signal:s,body:{msg:{from_user_id:"",to_user_id:g,client_id:`dsh-weixin-${uZ()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:c}}],...Mt(A)?{context_token:A.trim()}:{},...Mt(r)?{run_id:r.trim()}:{}},base_info:_c()}}),d=mG(I);if(d)throw new _A("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002",{providerCode:d});return!0},async sendFile(o){return t(o,{mediaType:3,createItem:({file:i,media:e})=>({type:4,file_item:{media:e,file_name:i.fileName,len:String(i.bytes.byteLength)}})})},async sendImage(o){return t(o,{mediaType:1,createItem:({media:i,ciphertextSize:e})=>({type:2,image_item:{media:i,mid_size:e}})})},async notifyStart({baseUrl:o,token:i,signal:e}){let a=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/msg/notifystart",token:i,signal:e,timeoutMs:1e4,body:{base_info:_c()}});if(a?.ret!==void 0&&a.ret!==0)throw new _A("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return a},async notifyStop({baseUrl:o,token:i,signal:e}){return us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/msg/notifystop",token:i,signal:e,timeoutMs:1e4,body:{base_info:_c()}})}})}function fl(n){for(let t of n?.item_list??[]){if(t?.type===1&&typeof t.text_item?.text=="string"){let o=t.text_item.text.trim();if(o)return o}if(t?.type===3&&typeof t.voice_item?.text=="string"){let o=t.voice_item.text.trim();if(o)return o}}return null}function MG(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):Mt(n?.client_id)}function MZ(n,t=Bl){if(n.length<=t)return[n];let o=[],i=n;for(;i.length>t;){let e=i.lastIndexOf(` +${L}`:q;try{Q&&f?await this.#e.replyStream(t,f,Vu(y,z,{finish:!0}),!0):await this.#m(t,s,z),T||await this.#t.markSeen(A)}catch{this.#a.error?.("[dsh-im:wecom] failed to send the safe error reply")}}finally{await Promise.allSettled([this.#_(B),this.#E.closeRoute(B)])}}async#R(t,o,i,e,a,A){if(this.#I?.aborted)return;let r=this.#s.get(a),s=A.claimedReplyMessageId===o;if(!r||r!==A||r.submitting)return s&&(!r||r!==A)?this.#k(t,o,e):this.#B(t,o,a,{releaseMessageId:!1});if(this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString();let g=ua(dG(t));if(!g){await this.#m(t,e,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002")).catch(()=>{});return}let c=this.#s.get(a);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#m(t,e,w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")).catch(()=>{});return}return this.#B(t,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#B(t,o,a,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#T(c)}catch{this.#g.lastError=w("\u4F01\u4E1A\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002"),this.#a.error?.("[dsh-im:wecom] failed to retry an interaction question"),c.interaction.reconnect?.();return}let d=this.#s.get(a);if(!d||d!==A||d.submitting){if(s&&(!d||d!==A)){await this.#m(t,e,w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")).catch(()=>{});return}return this.#B(t,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}}let I=c.questions[c.index];if(I){if(c.answers.push(Ei(I,g)),c.index+=1,c.index{});return}if(this.#s.get(a)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#g.lastError=w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002"),this.#a.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#m(t,e,w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002")).catch(()=>{})}}}async#D(t,{key:o,actor:i,chatId:e,requiresMention:a}){if(t?.kind==="approval")return this.#E.handleRequested(t,{key:o,actor:i,requiresMention:a,send:c=>this.#Q(e,c)});if(t?.kind!=="question")return;let A=t?.payload?.questions,r=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t?.rpcId!="string"||typeof r!="string"||typeof t.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!di(c))){this.#a.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#Q(e,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002")).catch(()=>{});return}let s=this.#s.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#T(s);return}if(this.#c.has(r))return;if(s){this.#a.warn?.("[dsh-im:wecom] cancelled a second pending Harness question"),await t.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,requiresMention:a,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#s.set(o,g),this.#c.set(g.interactionId,o),await this.#T(g)}async#w(t){if(t?.kind==="approval"){await this.#E.handleResolved(t);return}let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#c.get(o);i&&this.#L(i,o)}#T(t){if(!t.needsPresentation)return Promise.resolve();if(t.presentationPromise)return t.presentationPromise;let o=t.questions[t.index];if(!o)return Promise.resolve();let i=this.#Q(t.chatId,hi(o,t.index,t.questions.length,{requiresMention:t.requiresMention})).then(()=>{t.needsPresentation=!1}).finally(()=>{t.presentationPromise===i&&(t.presentationPromise=null)});return t.presentationPromise=i,i}async#k(t,o,i){this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),await this.#m(t,i,w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")).catch(()=>{}))}#M(t,o){let i=this.#s.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#s.delete(t),this.#c.delete(i.interactionId),i)}#L(t,o){return this.#M(t,o)!==null}async#_(t){let o=this.#M(t);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Enterprise WeChat interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#a.warn?.("[dsh-im:wecom] failed to cancel a pending Harness interaction")}}};function bFe(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function MFe(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...CG()}}var Wu=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o=MFe();#s=null;#c=null;#p=null;#d=null;#h=null;constructor({config:t,secret:o,harness:i,state:e,contextEnhancement:a,logger:A=console,replyTimeoutMs:r=6e5,connectTimeoutMs:s=2e4,maxReconnectAttempts:g=10,createClient:c=I=>new DFe(I)}){if(!t||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c}get status(){return structuredClone(this.#o)}async start(){if(this.#o.ready&&this.#s)return this.status;if(this.#p)return this.#p;this.#h?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let t=new AbortController;return this.#d=t,this.#h=t,this.#p=this.#E(t.signal).finally(()=>{this.#d===t&&(this.#d=null),this.#p=null}),this.#p}async#E(t){await this.#C(),t.throwIfAborted(),this.#o.startedAt=new Date().toISOString(),this.#o.wecomConnectionState="connecting",this.#o.lastError=null,await this.#t.ensureRunning(),this.#o.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#l({botId:this.#e.remoteBotId,secret:this.#A,logger:o,maxReconnectAttempts:this.#I});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#s=i,this.#c=new ow({client:i,harness:this.#t,state:this.#r,contextEnhancement:this.#g,status:this.#o,logger:this.#a,replyTimeoutMs:this.#n,signal:t});let e,a,A=!1,r=new Promise((f,Q)=>{e=f,a=Q}),s=()=>{if(this.#s!==i||t.aborted)return;A=!0;let f=Date.now();this.#o.ready=!0,this.#o.wecomConnectionState="connected",this.#o.lastCheckedAt=f,this.#o.lastConnectedAt=f,this.#o.lastError=null,e()},g=()=>{this.#s===i&&(this.#o.ready=!1,this.#o.wecomConnectionState="connecting",this.#o.lastCheckedAt=Date.now())},c=()=>{this.#s===i&&(this.#o.ready=!1,this.#o.wecomConnectionState="connecting",this.#o.lastCheckedAt=Date.now())},I=f=>{if(this.#s!==i)return;let Q=f instanceof wFe||f instanceof OFe;!A&&Q&&a(f),Q&&(this.#o.ready=!1,this.#o.wecomConnectionState="failed"),this.#o.lastError=Q?f.name:"connection-error",this.#a.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} connection error`)},d=f=>this.#c?.accept(f);i.on("authenticated",s),i.on("disconnected",g),i.on("reconnecting",c),i.on("error",I),i.on("message",d);let B;try{return i.connect(),await Promise.race([r,new Promise((f,Q)=>{t.addEventListener("abort",()=>Q(t.reason),{once:!0})}),new Promise((f,Q)=>{B=setTimeout(()=>Q(bFe()),this.#i)})]),this.status}catch(f){throw t.aborted?(await this.#C(),f):(this.#o.ready=!1,this.#o.wecomConnectionState="failed",this.#o.lastError=f?.message??String(f),await this.#C(),f)}finally{clearTimeout(B)}}async stop(){let t=this.#p;return this.#d?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#h?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#h=null,await this.#C(),await t?.catch(()=>{}),this.status}async sendConnectionTest(t){return ec({state:this.#r,text:t,channelLabel:w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"),send:async({chatId:o},i)=>{if(!this.#o.ready||!this.#s)throw new Error("Enterprise WeChat runtime is not connected");await this.#s.sendMessage(o,{msgtype:"markdown",markdown:{content:i}})}})}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.chatId=="string"?t.route.chatId.trim():"";if(t?.kind!=="user"&&t?.kind!=="group"||!e){let a=new TypeError("Invalid Enterprise WeChat proactive delivery target");throw a.code="invalid-target",a}if(!this.#o.ready||!this.#s){let a=new Error("Enterprise WeChat runtime is not connected");throw a.code="bot-not-connected",a}return i?.throwIfAborted(),await this.#s.sendMessage(e,{msgtype:"markdown",markdown:{content:o}}),{sent:!0}}async#C(){let t=this.#s,o=this.#c;this.#s=null,this.#c=null;try{t?.disconnect(),t?.removeAllListeners?.()}catch{this.#a.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#o.ready=!1,this.#o.wecomConnectionState="idle"}};var IZ=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function _Fe(n){if(!Array.isArray(n)||n.length===0)return[...IZ];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...IZ]}var nw=class{#e;#A;#t;#r;#g;#a;#n;#i=null;#I=null;#l=0;#o=!1;#s=!1;#c;#p;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=_Fe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#a=A,this.#n=r,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#s||this.#o?this:(this.#s=!0,this.#d(0),this)}async close(){this.#o||(this.#o=!0,this.#i!==null&&this.#n(this.#i),this.#i=null,await this.#I?.catch(()=>{}),this.#p?.(null),this.#p=null)}#d(t){this.#o||(this.#i=this.#a(()=>{this.#i=null,this.#h()},t),this.#i?.unref?.())}async#h(){if(this.#o||this.#I)return;let t=this.#E();this.#I=t;try{await t}finally{this.#I===t&&(this.#I=null)}}async#E(){try{if(await this.#A.ensureRunning(),this.#o)return;let t=await this.#e.initialize();if(this.#o)return;this.#p?.(t),this.#p=null;let{configured:o,connected:i}=t.totals;if(iRa(n),B=RFe(t),f=await new e(B.config).load(),Q=Cl(t.workspace??process.cwd()),y=o.WorkspaceStore??ea,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=f.list();await m.reconcile(_.map(V=>V.botId)),await Promise.all(_.map(V=>m.ensure(V.botId,{defaultAgentPreset:t.agentPreset})));let T=typeof f.remove=="function"?Pa(f,{workspaces:m}):f,R=o.qrAuth??new g({source:t.qrSource??"deepseek-harness",platform:t.qrPlatform}),L=new Map,U=V=>Cl(B.bots,V,"state.json"),F=async V=>{let Ae=L.get(V);return Ae||(Ae=await new a(U(V)).load(),L.set(V,Ae)),Ae},q=Ua(n,o.commandExecutor),{controlExecutor:z,sessionMaintenanceExecutor:j,fileIngressExecutor:P}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),J=new A({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...q?{commandExecutor:q}:{},...z?{controlExecutor:z}:{},...j?{sessionMaintenanceExecutor:j}:{},...P?{fileIngressExecutor:P}:{}}),H=new r({qrAuth:R,credentials:n.credentials,configStore:T,logger:I,createRuntime:async({botId:V,config:Ae,secret:ie})=>{let De=await F(V);await m.ensure(V,{defaultAgentPreset:t.agentPreset});let fe=Ga(J,{botId:V,workspaces:m,state:De,agentPresetCatalog:d});return new s({config:Ae,secret:ie,harness:fe.harness,state:fe.state,contextEnhancement:{botId:V,getSettings:()=>m.contextEnhancementFor(V)},replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??2e4,maxReconnectAttempts:t.maxReconnectAttempts??10,logger:{error:(..._e)=>I.error?.(`[${V}]`,..._e),warn:(..._e)=>I.warn?.(`[${V}]`,..._e),info:(..._e)=>I.info?.(`[${V}]`,..._e),debug:(..._e)=>I.debug?.(`[${V}]`,..._e)}})},deleteState:async({botId:V})=>{let Ae=L.get(V);if(L.delete(V),Ae&&typeof Ae.remove=="function")await Ae.remove();else try{await TFe(U(V))}catch(ie){if(ie?.code!=="ENOENT")throw ie}}}),N=Fa(H,{workspaces:m,stateFor:F,agentPresetCatalog:d}),k=c({controller:N,harness:J,logger:I,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:N,deliveryAdapter:La({channel:"wecom",workspaces:m,coreController:H,stateFor:F}),ready:k.ready,async close(){await k.close(),await N.close(),J.stopManagedProcess()}}}import kFe from"qrcode";var pZ="/wecom",mr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),dZ=Object.freeze(Object.values(mr)),vFe=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function yG(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Ud(n,t){return yG(n)&&Object.keys(n).every(o=>t.includes(o))}function fG(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function lZ(n,t){return typeof n=="string"&&n.trim().length>0&&n.length<=t}function PFe(n,t){return yG(t)?n===mr.status?Ud(t,[])?null:"connection.status does not accept fields.":n===mr.beginProvisioning?Ud(t,["locale"])&&(t.locale===void 0||t.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[mr.pollProvisioning,mr.cancelProvisioning].includes(n)?Ud(t,["attemptId"])&&fG(t.attemptId)?null:`${n} requires an attemptId.`:n===mr.bindCredentials?Ud(t,["botId","secret"])&&lZ(t.botId,512)&&lZ(t.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===mr.reconnectBot?Ud(t,["botId","sendTest"])&&fG(t.botId)&&(t.sendTest===void 0||t.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===mr.deleteBot?Ud(t,["botId","confirm"])&&fG(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===mr.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===mr.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===mr.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function Hd(n){if(Array.isArray(n))return n.map(Hd);if(!yG(n))return n;let t={};for(let[o,i]of Object.entries(n))vFe.has(o)||(t[o]=Hd(i));return t}async function GFe(n){return kFe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function QG(n,t){return!n||typeof n.verificationUrl!="string"?Hd(n):Hd({...n,qrCodeDataUrl:await t(n.verificationUrl)})}async function ul(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await QG(o.provisioning,t)),Hd(o)}function hZ(n,{encodeQr:t=GFe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete Enterprise WeChat controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!dZ.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let r=PFe(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===mr.status)s=await ul(await n.status(),i);else if(e===mr.beginProvisioning)s=await QG(await n.startProvisioning(),i);else if(e===mr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await QG(g,i)}else if(e===mr.cancelProvisioning)s=Hd(await n.cancelProvisioning(a.attemptId));else if(e===mr.bindCredentials)s=await ul(await n.bindCredentials(a),i);else if(e===mr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};let c;if(a.sendTest===!0)if(!g?.bots?.some(d=>d?.botId===a.botId&&d?.connected===!0)||typeof n.sendConnectionTest!="function")c=ir(Ir("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=ir()}catch(d){c=ir(d)}s=await ul({...g,...c?{testMessage:c}:{}},i)}else if(e===mr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await ul(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===mr.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>ul(g,i))}else if(e===mr.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await ul(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else s=await ul(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"wecom-operation-failed",message:"\u4F01\u4E1A\u5FAE\u4FE1\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function sw(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(pZ,hZ(t,o),{authority:hr(i)})}async function EZ(n,t={}){if(t?.controller)return sw(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await BG(n,t,t.internals),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=sw(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Enterprise WeChat bot connections"),e}import{unlink as HLe}from"node:fs/promises";import{homedir as KLe}from"node:os";import{join as aB,resolve as Ql}from"node:path";import{createHash as aLe}from"node:crypto";import{mkdir as iLe,readFile as oLe,rename as nLe,unlink as sLe,writeFile as gLe}from"node:fs/promises";import{dirname as cLe}from"node:path";import{createCipheriv as FFe,createDecipheriv as LFe,createHash as CZ,randomBytes as SG,randomUUID as uZ}from"node:crypto";var gw="https://ilinkai.weixin.qq.com/",UFe="2.4.6",HFe="3",QZ="https://novac2c.cdn.weixin.qq.com/c2c",Bl=1800,wG="novac2c.cdn.weixin.qq.com",KFe="bot",xFe=2<<16|1024|6,YFe=15e3,BZ=35e3,jFe=3,JFe=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),_A=class extends Error{constructor(t,o,i={}){super(o,i),this.name="WeixinApiError",this.code=t,this.status=i.status,this.providerCode=i.providerCode}};function Mt(n){return typeof n=="string"&&n.trim()?n.trim():null}function yZ(n){let t=n==null?null:String(n).trim();return t&&/^-?[A-Za-z0-9_.:-]{1,160}$/.test(t)?t:void 0}function mZ(n,t){return Number.isInteger(t?.status)&&(n.status=t.status),t?.providerCode!==void 0&&(n.providerCode=t.providerCode),n}function Xu(n,{fallback:t="artifact-provider-rejected"}={}){if(n?.code?.startsWith?.("artifact-"))return n;let o=Number(n?.status),i=yZ(n?.providerCode),e=i??"",a=t,A="Weixin could not prepare the file for delivery.";o===401||o===403||i==="401"||i==="403"||/(?:permission|forbidden|unauthor|access.?denied)/i.test(e)?(a="artifact-permission-required",A="Weixin denied permission to send the file."):o===413||i==="413"||/(?:too.?large|size.?limit)/i.test(e)?(a="artifact-too-large",A="The file exceeds Weixin's size limit."):o===429||i==="429"||/(?:rate.?limit|too.?many)/i.test(e)?(a="artifact-rate-limited",A="Weixin rate-limited file delivery."):t==="artifact-provider-rejected"&&(A="Weixin rejected the file message.");let r=new Error(A,{cause:n});return r.code=a,mZ(r,n)}function qFe(n){let t=new Error("Weixin file delivery result is uncertain",{cause:n});return t.code="artifact-delivery-uncertain",mZ(t,n)}function mG(n){if(!n||typeof n!="object")return null;for(let t of["ret","errcode"])if(n[t]!==void 0&&n[t]!==0&&n[t]!=="0")return yZ(n[t])??"rejected";return null}function zFe(n,t){if(t?.aborted)throw Kd(t);let o=Number(n?.status);return n?.code==="network-error"||n?.code==="timeout"||n?.code==="invalid-response"||o>=500&&o<600?qFe(n):Xu(n)}function VFe(n){let t=Mt(n);return!t||t.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(t)?null:Buffer.from(t,"base64")}function SZ(n){let t=Mt(n?.aeskey);if(t){if(!/^[0-9a-fA-F]{32}$/.test(t))throw new _A("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002");return Buffer.from(t,"hex")}let o=VFe(n?.media?.aes_key);if(o?.length===16)return o;if(o?.length===32&&/^[0-9a-fA-F]{32}$/.test(o.toString("ascii")))return Buffer.from(o.toString("ascii"),"hex");throw new _A("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002")}function wZ(n,t){let o=Buffer.from(n),i=Buffer.from(t);if(i.length!==16||o.length===0||o.length%16!==0)throw new _A("invalid-image-ciphertext","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u6570\u636E\u65E0\u6548\u3002");try{let e=LFe("aes-128-ecb",i,null);return Buffer.concat([e.update(o),e.final()])}catch(e){throw new _A("image-decryption-failed","\u5FAE\u4FE1\u56FE\u7247\u89E3\u5BC6\u5931\u8D25\u3002",{cause:e})}}function DZ(n){let t=Mt(n?.encrypt_query_param);if(t)return`${QZ}/download?encrypted_query_param=${encodeURIComponent(t)}`;let o=Mt(n?.full_url);if(!o)throw new _A("missing-image-url","\u5FAE\u4FE1\u56FE\u7247\u6CA1\u6709\u53EF\u7528\u7684\u4E0B\u8F7D\u5730\u5740\u3002");let i;try{i=new URL(o)}catch{throw new _A("invalid-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u65E0\u6548\u3002")}if(i.protocol!=="https:"||i.hostname!==wG||i.port&&i.port!=="443"||!i.pathname.startsWith("/c2c/"))throw new _A("untrusted-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u4E0D\u53D7\u4FE1\u4EFB\u3002");return i.username="",i.password="",i.hash="",i.toString()}function DG(n,{fetchImpl:t=fetch}={}){if(typeof t!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.item_list??[]){let e=i?.image_item;!e||typeof e!="object"||o.push({name:o.length===0?"image":`image-${o.length+1}`,load:async({signal:a,maxBytes:A})=>{let r=SZ(e),s=DZ(e.media),g=await uo(s,{fetchImpl:t,signal:a,maxBytes:A+16,allowedHosts:[wG]});return wZ(g,r)}})}return o}async function WFe(n,{fetchImpl:t,signal:o}){let i=await t(new URL(n),{method:"GET",signal:o,redirect:"manual"});if(!i?.ok)throw await i?.body?.cancel?.().catch?.(()=>{}),new _A("file-download-failed",`\u5FAE\u4FE1\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF08HTTP ${i?.status??"unknown"}\uFF09\u3002`,{status:i?.status});return Buffer.from(await i.arrayBuffer())}function OG(n,{fetchImpl:t=fetch}={}){if(typeof t!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.item_list??[]){let e=i?.file_item;if(!e||typeof e!="object")continue;let a=Number(e.len);o.push({name:Mt(e.file_name)??(o.length===0?"file":`file-${o.length+1}`),...Number.isFinite(a)&&a>=0?{size:a}:{},load:async({signal:A}={})=>{A?.throwIfAborted();let r=SZ(e),s=DZ(e.media),g=await WFe(s,{fetchImpl:t,signal:A});return A?.throwIfAborted(),wZ(g,r)}})}return o}function bG(n){let t=n.toLowerCase().replace(/\.$/,"");return t==="weixin.qq.com"||t.endsWith(".weixin.qq.com")||t==="wechat.com"||t.endsWith(".wechat.com")}function xd(n){let t;try{t=new URL(n)}catch{throw new _A("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(t.protocol!=="https:"||!bG(t.hostname)||t.port!==""&&t.port!=="443")throw new _A("untrusted-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u8FDE\u63A5\u5730\u5740\u3002");return t.username="",t.password="",t.search="",t.hash="",t.pathname.endsWith("/")||(t.pathname+="/"),t.toString()}function ZFe(n){let t=Mt(n);if(!t)throw new _A("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(t)}catch{throw new _A("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!bG(o.hostname))throw new _A("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function OZ(){return{"iLink-App-Id":KFe,"iLink-App-ClientVersion":String(xFe)}}function XFe(n){let t={...OZ(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(SG(4).readUInt32BE(0)),"utf8").toString("base64")};return Mt(n)&&(t.Authorization=`Bearer ${n.trim()}`),t}function _c(){return{channel_version:UFe,bot_agent:"DeepSeekHarness/1.1.0"}}function $Fe(n){return Math.ceil((n+1)/16)*16}function fZ(n){let t;try{t=new URL(n)}catch{throw new _A("invalid-upload-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u6587\u4EF6\u4E0A\u4F20\u5730\u5740\u3002")}if(t.protocol!=="https:"||t.hostname!==wG||t.port&&t.port!=="443"||t.pathname!=="/c2c/upload"||t.username||t.password)throw new _A("untrusted-upload-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u6587\u4EF6\u4E0A\u4F20\u5730\u5740\u3002");return t.hash="",t}function eLe(n,t){let o=Mt(n?.upload_full_url);if(o)return fZ(o);let i=Mt(n?.upload_param);if(!i)throw new _A("missing-upload-url","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6587\u4EF6\u4E0A\u4F20\u5730\u5740\u3002");let e=new URL(`${QZ}/upload`);return e.searchParams.set("encrypted_query_param",i),e.searchParams.set("filekey",t),fZ(e)}function ALe(n,t){let o=FFe("aes-128-ecb",t,null);return Buffer.concat([o.update(n),o.final()])}async function tLe(n,t,o,{signal:i}={}){let e;for(let a=1;a<=jFe;a+=1){i?.throwIfAborted();try{let A=await n(t,{method:"POST",headers:{"content-type":"application/octet-stream"},body:o,signal:i?AbortSignal.any([i,AbortSignal.timeout(6e4)]):AbortSignal.timeout(6e4),redirect:"error"});if(A.status>=400&&A.status<500)throw new _A("upload-rejected",`\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u88AB\u62D2\u7EDD\uFF08HTTP ${A.status}\uFF09\u3002`,{status:A.status});if(A.status!==200)throw new _A("upload-failed",`\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF08HTTP ${A.status}\uFF09\u3002`,{status:A.status});let r=Mt(A.headers.get("x-encrypted-param"));if(await A.body?.cancel?.().catch(()=>{}),!r)throw new _A("invalid-upload-response","\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u54CD\u5E94\u7F3A\u5C11\u4E0B\u8F7D\u53C2\u6570\u3002");return r}catch(A){if(i?.aborted)throw Kd(i);if(A instanceof _A&&(A.code==="upload-rejected"||A.status<500))throw A;e=A}}throw e instanceof _A?e:new _A("upload-failed","\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\u3002",{cause:e})}function Kd(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function us(n,{method:t,baseUrl:o,endpoint:i,body:e,token:a,timeoutMs:A=YFe,signal:r,authenticated:s=!0}){let g=xd(o),c=new URL(i,g);if(!bG(c.hostname))throw new _A("untrusted-endpoint","\u62D2\u7EDD\u8BBF\u95EE\u4E0D\u53D7\u4FE1\u4EFB\u7684\u5FAE\u4FE1\u670D\u52A1\u5730\u5740\u3002");let I=new AbortController,d=!1,B=()=>I.abort(r?.reason);if(r?.aborted)throw Kd(r);r?.addEventListener("abort",B,{once:!0});let f=A>0?setTimeout(()=>{d=!0,I.abort()},A):null;try{let Q=await n(c,{method:t,headers:s?XFe(a):OZ(),...e===void 0?{}:{body:JSON.stringify(e)},signal:I.signal});if(!Q.ok)throw new _A("http-error",`\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${Q.status}\uFF09\u3002`,{status:Q.status});try{return await Q.json()}catch(y){throw new _A("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(Q){throw r?.aborted?Kd(r):d?new _A("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:Q}):Q instanceof _A?Q:new _A("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:Q})}finally{f&&clearTimeout(f),r?.removeEventListener("abort",B)}}function rLe(n){if(!n||typeof n!="object"||!JFe.has(n.status))throw new _A("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function bZ({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");async function t({baseUrl:o,token:i,toUserId:e,file:a,contextToken:A,runId:r,signal:s},{mediaType:g,createItem:c}){let I=Mt(e);if(!I||!a||typeof a!="object"||typeof a.fileName!="string"||!a.fileName||!Buffer.isBuffer(a.bytes))throw new TypeError("toUserId and a file are required");s?.throwIfAborted();let d=SG(16).toString("hex"),B=SG(16),f=CZ("md5").update(a.bytes).digest("hex"),Q;try{Q=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/getuploadurl",token:i,signal:s,body:{filekey:d,media_type:g,to_user_id:I,rawsize:a.bytes.byteLength,rawfilemd5:f,filesize:$Fe(a.bytes.byteLength),no_need_thumb:!0,aeskey:B.toString("hex"),base_info:_c()}})}catch(j){if(s?.aborted)throw Kd(s);let P=Number(j?.status),J=j?.code==="http-error"&&P>=400&&P<500?"artifact-provider-rejected":"artifact-provider-failed";throw Xu(j,{fallback:J})}let y=mG(Q);if(y)throw Xu(new _A("upload-url-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u4E0A\u4F20\u8BF7\u6C42\u3002",{providerCode:y}));let m=eLe(Q,d),_=ALe(a.bytes,B),T;try{T=await tLe(n,m,_,{signal:s})}catch(j){if(s?.aborted)throw Kd(s);let P=Number(j?.status),J=j?.code==="upload-rejected"||P>=400&&P<500?"artifact-provider-rejected":"artifact-provider-failed";throw Xu(j,{fallback:J})}s?.throwIfAborted();let R=Mt(a.deliveryKey)??Mt(a.artifactId)??uZ(),L=g===3?R:`${R}\0${g}`,U=`dsh-weixin-${CZ("sha256").update(L).digest("hex").slice(0,32)}`,F={encrypt_query_param:T,aes_key:Buffer.from(B.toString("hex")).toString("base64"),encrypt_type:1},q;try{q=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/sendmessage",token:i,signal:s,body:{msg:{from_user_id:"",to_user_id:I,client_id:U,message_type:2,message_state:2,item_list:[c({file:a,media:F,ciphertextSize:_.byteLength})],...Mt(A)?{context_token:A.trim()}:{},...Mt(r)?{run_id:r.trim()}:{}},base_info:_c()}})}catch(j){throw zFe(j,s)}let z=mG(q);if(z)throw Xu(new _A("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u6D88\u606F\u3002",{providerCode:z}));return{messageId:U}}return Object.freeze({inboundImages(o){return DG(o,{fetchImpl:n})},inboundFiles(o){return OG(o,{fetchImpl:n})},async beginLogin({localTokens:o=[],botType:i=HFe,signal:e}={}){let a=[...new Set(o.map(Mt).filter(Boolean))].slice(-10),A=await us(n,{method:"POST",baseUrl:gw,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(i)}`,body:{local_token_list:a},timeoutMs:1e4,signal:e}),r=Mt(A?.qrcode);if(!r)throw new _A("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:r,qrcodeUrl:ZFe(A.qrcode_img_content)}},async pollLogin({qrcode:o,baseUrl:i=gw,verifyCode:e,signal:a}){let A=Mt(o);if(!A)throw new TypeError("qrcode is required");let r=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(A)}`;Mt(e)&&(r+=`&verify_code=${encodeURIComponent(e.trim())}`);let s=await us(n,{method:"GET",baseUrl:i,endpoint:r,timeoutMs:BZ,signal:a,authenticated:!1});return rLe(s)},async getUpdates({baseUrl:o,token:i,getUpdatesBuf:e="",timeoutMs:a,signal:A}){try{return await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:e,base_info:_c()},token:i,timeoutMs:a??BZ,signal:A})}catch(r){if(r instanceof _A&&r.code==="timeout")return{ret:0,msgs:[],get_updates_buf:e};throw r}},async getConfig({baseUrl:o,token:i,toUserId:e,contextToken:a,signal:A}){let r=Mt(e);if(!r)throw new TypeError("toUserId is required");let s=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/getconfig",token:i,signal:A,timeoutMs:1e4,body:{ilink_user_id:r,...Mt(a)?{context_token:a.trim()}:{},base_info:_c()}});if(s?.ret!==void 0&&s.ret!==0)throw new _A("config-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u673A\u5668\u4EBA\u914D\u7F6E\u8BF7\u6C42\u3002");return{typingTicket:Mt(s?.typing_ticket)}},async sendTyping({baseUrl:o,token:i,toUserId:e,typingTicket:a,status:A,signal:r}){let s=Mt(e),g=Mt(a);if(!s||!g)throw new TypeError("toUserId and typingTicket are required");if(A!==1&&A!==2)throw new TypeError("typing status must be 1 or 2");let c=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/sendtyping",token:i,signal:r,timeoutMs:1e4,body:{ilink_user_id:s,typing_ticket:g,status:A,base_info:_c()}});if(c?.ret!==void 0&&c.ret!==0)throw new _A("typing-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u8F93\u5165\u72B6\u6001\u8BF7\u6C42\u3002");return!0},async sendText({baseUrl:o,token:i,toUserId:e,text:a,contextToken:A,runId:r,signal:s}){let g=Mt(e),c=Mt(a);if(!g||!c)throw new TypeError("toUserId and text are required");let I=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/sendmessage",token:i,signal:s,body:{msg:{from_user_id:"",to_user_id:g,client_id:`dsh-weixin-${uZ()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:c}}],...Mt(A)?{context_token:A.trim()}:{},...Mt(r)?{run_id:r.trim()}:{}},base_info:_c()}}),d=mG(I);if(d)throw new _A("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002",{providerCode:d});return!0},async sendFile(o){return t(o,{mediaType:3,createItem:({file:i,media:e})=>({type:4,file_item:{media:e,file_name:i.fileName,len:String(i.bytes.byteLength)}})})},async sendImage(o){return t(o,{mediaType:1,createItem:({media:i,ciphertextSize:e})=>({type:2,image_item:{media:i,mid_size:e}})})},async notifyStart({baseUrl:o,token:i,signal:e}){let a=await us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/msg/notifystart",token:i,signal:e,timeoutMs:1e4,body:{base_info:_c()}});if(a?.ret!==void 0&&a.ret!==0)throw new _A("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return a},async notifyStop({baseUrl:o,token:i,signal:e}){return us(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/msg/notifystop",token:i,signal:e,timeoutMs:1e4,body:{base_info:_c()}})}})}function fl(n){for(let t of n?.item_list??[]){if(t?.type===1&&typeof t.text_item?.text=="string"){let o=t.text_item.text.trim();if(o)return o}if(t?.type===3&&typeof t.voice_item?.text=="string"){let o=t.voice_item.text.trim();if(o)return o}}return null}function MG(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):Mt(n?.client_id)}function MZ(n,t=Bl){if(n.length<=t)return[n];let o=[],i=n;for(;i.length>t;){let e=i.lastIndexOf(` `,t);ea===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of t){if(o.has(a.botId)||i.has(a.accountId)||e.has(a.tokenRef))return null;o.add(a.botId),i.add(a.accountId),e.add(a.tokenRef)}return Object.freeze({version:1,accounts:Object.freeze(t)})}var cw=class{#e;#A=_G;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=lLe(JSON.parse(await oLe(this.#e,"utf8")));if(!t)throw new Error("dsh-weixin config contains invalid account data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=_G}return this}list(){return structuredClone(this.#A.accounts)}get(t){let o=this.#A.accounts.find(i=>i.botId===t);return o?structuredClone(o):null}getByAccountId(t){let o=this.#A.accounts.find(i=>i.accountId===t);return o?structuredClone(o):null}async save(t){let o=TZ(t);if(!o)throw new Error("Refusing to persist incomplete dsh-weixin account data");return this.#r(i=>{let e=i.find(r=>r.accountId===o.accountId&&r.botId!==o.botId),a=i.find(r=>r.tokenRef===o.tokenRef&&r.botId!==o.botId);if(e||a)throw new Error("Duplicate Weixin account identity");let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!_Z(t))throw new TypeError("Invalid Weixin bot id");return this.#r(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await sLe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=_G});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.accounts];o=t(e);let a=Object.freeze({version:1,accounts:Object.freeze(e)});await this.#g(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#g(t){await iLe(cLe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await gLe(o,`${JSON.stringify(t,null,2)} `,{encoding:"utf8",mode:384}),await nLe(o,this.#e)}};var Iw=class extends lr{constructor(t){super({...t,rpcIdPrefix:"weixin",logPrefix:"dsh-weixin"})}};import{mkdir as pLe,readFile as dLe,rename as hLe,unlink as ELe,writeFile as CLe}from"node:fs/promises";import{dirname as uLe}from"node:path";var lw=Object.freeze({version:1,sessions:{},seenMessageIds:[],getUpdatesBuf:""});function BLe(n){if(!n||typeof n!="object")return structuredClone(lw);let t={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&typeof i=="string"&&i&&(t[o]=i);return{version:1,sessions:t,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[],getUpdatesBuf:typeof n.getUpdatesBuf=="string"?n.getUpdatesBuf:""}}var pw=class{#e;#A=structuredClone(lw);#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{this.#A=BLe(JSON.parse(await dLe(this.#e,"utf8")))}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=structuredClone(lw),await this.#r()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){this.#A.sessions[t]=o,await this.#r()}async clearSession(t){delete this.#A.sessions[t],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(t){return this.#A.seenMessageIds.includes(t)}async markSeen(t){this.hasSeen(t)||(this.#A.seenMessageIds.push(t),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}getUpdatesBuf(){return this.#A.getUpdatesBuf}async setGetUpdatesBuf(t){typeof t!="string"||t===this.#A.getUpdatesBuf||(this.#A.getUpdatesBuf=t,await this.#r())}snapshot(){return structuredClone(this.#A)}async remove(){try{await ELe(this.#e)}catch(t){if(t?.code!=="ENOENT")throw t}this.#A=structuredClone(lw)}async#r(){let t=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await pLe(uLe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await CLe(i,t,{encoding:"utf8",mode:384}),await hLe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as fLe}from"node:crypto";var NZ=new Set(["starting","pending","scanned","needs_verification","connecting"]),dw=new Set(["connected","expired","failed","cancelled"]),RZ=5*6e4,PZ=Object.freeze({"credential-read-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u8BFB\u53D6\u73B0\u6709\u767B\u5F55\u51ED\u636E\u3002\u8BF7\u68C0\u67E5 DSH \u51ED\u636E\u5B58\u50A8\u3002","credential-save-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u767B\u5F55\u51ED\u636E\u65E0\u6CD5\u5199\u5165 DSH \u51ED\u636E\u5B58\u50A8\u3002\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u662F\u5426\u53EF\u5199\u3002","account-config-save-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u8D26\u53F7\u914D\u7F6E\u65E0\u6CD5\u5199\u5165\u672C\u673A\u3002\u8BF7\u68C0\u67E5 DSH_HOME \u76EE\u5F55\u6743\u9650\u3002","runtime-prepare-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u521D\u59CB\u5316\u8D26\u53F7\u72B6\u6001\u6216\u5DE5\u4F5C\u533A\u3002\u8BF7\u68C0\u67E5 DSH_HOME \u548C\u5DE5\u4F5C\u533A\u76EE\u5F55\u3002","harness-connect-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u63D2\u4EF6\u65E0\u6CD5\u8FDE\u63A5\u672C\u673A Harness\u3002\u8BF7\u68C0\u67E5 dsh web \u5730\u5740\u548C\u7AEF\u53E3\u3002","harness-timeout":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\u3002\u8BF7\u786E\u8BA4 dsh web \u672A\u963B\u585E\u3002","harness-auth-required":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u9700\u8981\u8EAB\u4EFD\u8BA4\u8BC1\u3002\u8BF7\u68C0\u67E5\u4EE3\u7406\u3001\u7F51\u5173\u6216\u81EA\u5B9A\u4E49\u9274\u6743\u914D\u7F6E\u3002","harness-proxy-auth-required":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u672C\u673A Harness \u8BF7\u6C42\u88AB\u4EE3\u7406\u8981\u6C42\u8BA4\u8BC1\u3002\u8BF7\u8BA9\u56DE\u73AF\u5730\u5740\u7ED5\u8FC7\u4EE3\u7406\uFF0C\u5E76\u68C0\u67E5 NO_PROXY \u914D\u7F6E\u3002","harness-loopback-forbidden":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5F02\u5E38\u62D2\u7EDD\u4E86\u56DE\u73AF\u5730\u5740\u7684\u5065\u5EB7\u68C0\u67E5\u3002\u8BF7\u68C0\u67E5 HTTP \u4EE3\u7406\u3001Harness \u6E90\u7801\u7248\u672C\u548C\u6784\u5EFA\u4EA7\u7269\u3002","harness-host-untrusted":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u7684 Host \u4FE1\u4EFB\u68C0\u67E5\u62D2\u7EDD\u4E86\u975E\u56DE\u73AF\u5730\u5740\u8BF7\u6C42\u3002\u8BF7\u68C0\u67E5 harnessBaseUrl \u4E0E trustedHosts \u914D\u7F6E\u3002","harness-request-forbidden":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u5065\u5EB7\u68C0\u67E5\u6536\u5230\u4E86\u975E Harness \u6807\u51C6\u7684 403 \u62D2\u7EDD\u54CD\u5E94\u3002\u8BF7\u68C0\u67E5\u4EE3\u7406\u6216\u7F51\u5173\u914D\u7F6E\u3002","harness-api-not-found":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u627E\u4E0D\u5230 Harness \u5065\u5EB7\u68C0\u67E5\u63A5\u53E3\u3002\u8BF7\u786E\u8BA4 Harness \u4E0E\u63D2\u4EF6\u7248\u672C\u517C\u5BB9\u3002","harness-http-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u8FD4\u56DE\u670D\u52A1\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002","harness-response-invalid":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u54CD\u5E94\u3002\u8BF7\u786E\u8BA4 Harness \u4E0E\u63D2\u4EF6\u7248\u672C\u517C\u5BB9\u3002","harness-rpc-rejected":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u62D2\u7EDD\u4E86\u5065\u5EB7\u68C0\u67E5\u8BF7\u6C42\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002","harness-check-unknown-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u53D1\u751F\u672A\u77E5\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002","connection-start-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u6D88\u606F\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u540E\u91CD\u8BD5\u3002"});function Yd(n){return typeof n=="string"&&n.trim()?n.trim():null}function QLe(){return new DOMException("Provisioning was cancelled","AbortError")}function kZ(n,t){let o=Yd(n);return o?xd(o.includes("://")?o:`https://${o}`):xd(t)}function $u(n){return n?{attemptId:n.id,status:n.state,...n.verificationUrl?{verificationUrl:n.verificationUrl}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},pollIntervalMs:1e3,...n.state==="needs_verification"?{verificationRequired:!0}:{},...n.botId?{botId:n.botId}:{},...n.alreadyConnected?{alreadyConnected:!0}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}function ri(n,t){return Object.freeze({code:n,message:t})}function eB(n,t){let o=new Error(`Weixin activation failed during ${n}`,{cause:t});return o.name="WeixinActivationStageError",o.code=n,o}function yLe(n){if(n instanceof _A)return ri(n.code,n.message);let t=PZ[n?.code];return t?ri(n.code,w(t)):ri("activation-unknown-failed",w("\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u6FC0\u6D3B\u8FC7\u7A0B\u4E2D\u53D1\u751F\u672A\u77E5\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002"))}function vZ(n,t){return n instanceof _A||PZ[n?.code]?n:eB(t,n)}var AB=class{#e;#A;#t;#r;#g;#a;#n=new Map;#i=new Map;#I=new Map;#l=null;#o=new Map;#s=0;#c=!1;constructor({api:t,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.beginLogin!="function"||typeof t.pollLogin!="function")throw new TypeError("WeixinController requires a Weixin API client");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WeixinController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WeixinController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A}async initialize(){if(this.#c)return this.status();for(let t of this.#t.list())this.#n.get(t.botId)?.status?.ready!==!0&&await this.#y(t.botId,async()=>{let i=this.#t.get(t.botId);if(!(!i||this.#c))try{let e=await this.#C(i.tokenRef);if(!e){this.#i.set(i.botId,ri("missing-token",w("\u767B\u5F55\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u8D26\u53F7\u540E\u91CD\u65B0\u626B\u7801\u3002")));return}await this.#h(i,e),this.#i.delete(i.botId)}catch(e){this.#i.set(i.botId,ri("connection-failed",w("\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"))),this.#a.warn?.(`[dsh-weixin] account ${i.botId} failed to initialize:`,e)}finally{this.#Q()}});return this.status()}async startProvisioning(){if(this.#c)throw new Error("dsh-weixin controller is closed");this.#l&&await this.cancelProvisioning(this.#l);let t={id:fLe(),state:"starting",createdAt:Date.now(),expiresAt:Date.now()+RZ,controller:new AbortController,pendingVerifyCode:null,verifyResolve:null,currentBaseUrl:gw,error:null,botId:null,task:null};this.#I.set(t.id,t),this.#l=t.id,this.#Q();try{let o=(await Promise.all(this.#t.list().slice(-10).map(async e=>this.#C(e.tokenRef)))).filter(Boolean),i=await this.#e.beginLogin({localTokens:o,signal:t.controller.signal});return this.#B(t),t.qrcode=i.qrcode,t.verificationUrl=i.qrcodeUrl,t.state="pending",t.expiresAt=Date.now()+RZ,this.#Q(),t.task=this.#p(t),$u(t)}catch(o){throw t.controller.signal.aborted?(t.state="cancelled",t.error=ri("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=ri(o instanceof _A?o.code:"qr-start-failed",o instanceof _A?o.message:w("\u65E0\u6CD5\u751F\u6210\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),this.#l===t.id&&(this.#l=null),this.#Q(),o}}registrationStatus(t){return $u(this.#I.get(t))}async submitVerification(t,o){let i=this.#I.get(t);if(!i||i.state!=="needs_verification")throw new Error("The provisioning attempt is not waiting for a verification code");let e=Yd(o);if(!e||!/^\d{4,8}$/.test(e))throw new TypeError("Verification code must contain 4 to 8 digits");return i.pendingVerifyCode=e,i.state="scanned",i.verifyResolve?.(),i.verifyResolve=null,this.#Q(),$u(i)}async cancelProvisioning(t){let o=this.#I.get(t);return o?(dw.has(o.state)||(o.controller.abort(),o.verifyResolve?.(),o.verifyResolve=null,await o.task?.catch(()=>{}),dw.has(o.state)||(o.state="cancelled"),o.error??=ri("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))),this.#l===o.id&&(this.#l=null),this.#Q(),$u(o)):null}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Weixin account");return await this.#y(t,async()=>{let i=await this.#C(o.tokenRef);if(!i)throw new Error("The Weixin token is missing");try{await this.#h(o,i),this.#i.delete(t)}catch(e){throw this.#i.set(t,ri("connection-failed",w("\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),e}finally{this.#Q()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Weixin account");return this.#y(t,async()=>{let i=this.#n.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function")throw Ir(w("\u5FAE\u4FE1\u673A\u5668\u4EBA"));return i.sendConnectionTest(ba(w("\u5FAE\u4FE1\u673A\u5668\u4EBA\uFF08{name}\uFF09",{name:NG(o.accountId)})))})}async sendProactiveText(t,o,i,e={}){if(!this.#t.get(t))throw new Error("Unknown Weixin account");return this.#y(t,async()=>{let A=this.#n.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Weixin account");return await this.#y(t,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#E(t);try{await this.#A.unset(o.tokenRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#h(o,i.value).catch(()=>{})),new Error("Unable to remove the Weixin account safely.",{cause:e})}try{await this.#g({botId:t,config:o})}catch(e){this.#a.warn?.(`[dsh-weixin] account ${t} state cleanup failed:`,e)}this.#i.delete(t),this.#Q()}),this.status()}status(){let t=this.#t.list().map(e=>{let a=this.#n.get(e.botId)?.status??null,A=a?.ready===!0&&a.weixinConnectionState==="connected"&&a.harnessReachable===!0,r=A?"connected":a?.weixinConnectionState==="connecting"?"connecting":this.#i.has(e.botId)||a?.weixinConnectionState==="failed"?"error":"offline",s=this.#i.get(e.botId)??(r==="error"?ri("connection-failed",w("\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")):null);return{botId:e.botId,state:r,connected:A,configured:!0,bot:{name:w("\u5FAE\u4FE1\u673A\u5668\u4EBA"),accountIdMasked:NG(e.accountId)},health:{status:A?"healthy":r==="error"?"error":"offline",summary:A?w("\u5FAE\u4FE1\u6D88\u606F\u957F\u8F6E\u8BE2\u8FD0\u884C\u6B63\u5E38"):r==="error"?w("\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):w("\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:a?.lastCheckedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},lastMessageError:Vr(a?.lastMessageError),error:s?structuredClone(s):null}}),o=t.filter(e=>e.connected).length,i=this.#l?this.#I.get(this.#l):null;return{schemaVersion:1,revision:this.#s,state:i&&NZ.has(i.state)?"provisioning":t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o},...i&&NZ.has(i.state)?{provisioning:$u(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#l&&await this.cancelProvisioning(this.#l),await Promise.allSettled([...this.#n.keys()].map(t=>this.#E(t))))}async#p(t){try{for(;!t.controller.signal.aborted&&Date.now(){t.verifyResolve=i,t.controller.signal.aborted&&i()}),t.verifyResolve=null,this.#B(t));let o=await this.#e.pollLogin({qrcode:t.qrcode,baseUrl:t.currentBaseUrl,verifyCode:t.pendingVerifyCode,signal:t.controller.signal});if(this.#B(t),o.status==="wait")t.state="pending";else if(o.status==="scaned")t.pendingVerifyCode=null,t.state="scanned";else if(o.status==="need_verifycode")t.pendingVerifyCode=null,t.state="needs_verification";else if(o.status==="verify_code_blocked"){t.state="failed",t.error=ri("verification-blocked",w("\u914D\u5BF9\u7801\u591A\u6B21\u9519\u8BEF\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"));break}else if(o.status==="expired"){t.state="expired",t.error=ri("expired",w("\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"));break}else if(o.status==="scaned_but_redirect")t.currentBaseUrl=kZ(o.redirect_host,t.currentBaseUrl),t.state="scanned";else if(o.status==="binded_redirect"){let i=this.#t.list().find(e=>this.#n.get(e.botId)?.status?.ready===!0)??this.#t.list()[0];i?(t.state="connected",t.botId=i.botId,t.alreadyConnected=!0):(t.state="failed",t.error=ri("already-bound",w("\u8BE5\u5FAE\u4FE1\u8D26\u53F7\u5DF2\u7ED1\u5B9A\uFF0C\u4F46\u672C\u673A\u6CA1\u6709\u53EF\u6062\u590D\u7684\u51ED\u636E\u3002")));break}else if(o.status==="confirmed"){let i=Yd(o.bot_token),e=Yd(o.ilink_bot_id),a=Yd(o.ilink_user_id);if(!i||!e||!a)throw new _A("incomplete-login",w("\u5FAE\u4FE1\u6388\u6743\u6210\u529F\uFF0C\u4F46\u8FD4\u56DE\u7684\u8D26\u53F7\u51ED\u636E\u4E0D\u5B8C\u6574\u3002"));t.state="connecting",this.#Q();let A=kZ(o.baseurl,t.currentBaseUrl);t.botId=await this.#d(t,{token:i,accountId:e,ownerUserId:a,baseUrl:A}),t.state="connected",t.error=null;break}this.#Q()}!t.controller.signal.aborted&&Date.now()>=t.expiresAt&&!dw.has(t.state)&&(t.state="expired",t.error=ri("expired",w("\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002")))}catch(o){t.controller.signal.aborted||o?.name==="AbortError"?(t.state="cancelled",t.error=ri("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=yLe(o),this.#a.error?.("[dsh-weixin] provisioning failed:",o))}finally{t.pendingVerifyCode=null,t.verifyResolve?.(),t.verifyResolve=null,this.#l===t.id&&(this.#l=null),this.#Q(),this.#S()}}async#d(t,{token:o,accountId:i,ownerUserId:e,baseUrl:a}){let A=TG(i),r=this.#t.getByAccountId(i),s={botId:A.botId,accountId:i,tokenRef:A.tokenRef,ownerUserId:e,baseUrl:a,createdAt:r?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()},g;try{g=await this.#A.resolve(A.tokenRef)}catch(c){throw eB("credential-read-failed",c)}return this.#y(A.botId,async()=>{try{try{await this.#A.set(A.tokenRef,o)}catch(c){throw eB("credential-save-failed",c)}this.#B(t);try{await this.#t.save(s)}catch(c){throw eB("account-config-save-failed",c)}return this.#B(t),await this.#h(s,o),this.#B(t),this.#i.delete(A.botId),this.#Q(),A.botId}catch(c){throw await this.#E(A.botId),r?await this.#t.save(r).catch(()=>{}):this.#t.get(A.botId)&&await this.#t.remove(A.botId).catch(()=>null)&&await this.#g({botId:A.botId,config:s}).catch(d=>{this.#a.warn?.("[dsh-weixin] failed to clean up cancelled bot state:",d)}),await this.#f(A.tokenRef,g),r&&g?.value&&await this.#h(r,g.value).catch(()=>{}),c}})}async#h(t,o){await this.#E(t.botId);let i;try{i=await this.#r({botId:t.botId,config:t,token:o})}catch(e){throw vZ(e,"runtime-prepare-failed")}if(!i||typeof i.start!="function"||typeof i.stop!="function")throw eB("runtime-prepare-failed",new TypeError("createRuntime returned an invalid Weixin runtime"));try{await i.start(),this.#n.set(t.botId,i)}catch(e){throw await i.stop().catch(()=>{}),vZ(e,"connection-start-failed")}}async#E(t){let o=this.#n.get(t);this.#n.delete(t),await o?.stop().catch(i=>{this.#a.warn?.(`[dsh-weixin] account ${t} failed to stop cleanly:`,i)})}async#C(t){let o=await this.#A.resolve(t).catch(()=>{});return Yd(o?.value)}async#f(t,o){try{o?.value?await this.#A.set(t,o.value):await this.#A.unset(t)}catch(i){this.#a.error?.(`[dsh-weixin] failed to restore credential ${t}:`,i)}}#B(t){if(t.controller.signal.aborted||this.#l!==t.id)throw QLe()}#y(t,o){let a=(this.#o.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#o.get(t)===a&&this.#o.delete(t)});return this.#o.set(t,a),a}#S(){for(let[t,o]of this.#I)t!==this.#l&&dw.has(o.state)&&this.#I.size>16&&this.#I.delete(t)}#Q(){this.#s+=1}};var hw=()=>w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002"),mLe=5e3,RG=6e4,LZ=Symbol("weixin-send-diagnostic"),SLe=()=>[w("\u5FAE\u4FE1\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002"),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u6216\u5E26\u6587\u5B57\u8BC6\u522B\u7ED3\u679C\u7684\u8BED\u97F3\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` `);function wLe(n){return`p2p:${n}`}function Fr(n){return typeof n=="string"&&n.trim()?n.trim():null}function tB(n){let t=n==null?"":String(n).trim();return/^-?[A-Za-z0-9_.:-]{1,160}$/u.test(t)?t:"-"}function DLe(n){try{return tB(new URL(n).hostname.toLowerCase())}catch{return"-"}}function OLe({baseUrl:n,text:t,chunk:o,chunkIndex:i,chunkCount:e,maxMessageChars:a,contextToken:A,runId:r,error:s}){let g=Number(s?.status??s?.httpStatus),c=Number.isInteger(g)?String(g):s?.code==="send-rejected"?"2xx":"-";return["endpoint=sendmessage",`host=${DLe(n)}`,`chunk=${i+1}/${e}`,`chunkChars=${o.length}`,`chunkUtf8Bytes=${Buffer.byteLength(o,"utf8")}`,`totalChars=${t.length}`,`totalUtf8Bytes=${Buffer.byteLength(t,"utf8")}`,`limitChars=${a}`,`contextToken=${A?"yes":"no"}`,`runId=${r?"yes":"no"}`,`http=${c}`,`provider=${tB(s?.providerCode)}`,`cause=${tB(s?.code??s?.name)}`].join(" ")}function bLe(n,t){let o=OLe({...t,error:n}),i=new Error(`Weixin text delivery failed (${o})`,{cause:n}),e=tB(n?.code);i.code=e==="-"?"weixin-send-failed":e;let a=Number(n?.status??n?.httpStatus);Number.isInteger(a)&&(i.status=a);let A=tB(n?.providerCode);return A!=="-"&&(i.providerCode=A),i[LZ]=o,i}function GZ(n){let t=n;for(let o=0;t&&o<5;o+=1){let i=t[LZ];if(typeof i=="string"&&i)return{reason:"weixin-send-failed",userMessage:[w("\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u5FAE\u4FE1\u53D1\u9001\u5931\u8D25\uFF0C\u53EF\u80FD\u53EA\u6536\u5230\u90E8\u5206\u5185\u5BB9\u3002\u8BF7\u5C06\u4E0B\u9762\u7684\u8BCA\u65AD\u4FE1\u606F\u5B8C\u6574\u53CD\u9988\u7ED9\u7BA1\u7406\u5458\u3002"),w("\u5FAE\u4FE1\u53D1\u9001\u8BCA\u65AD\uFF1A{diagnostic}",{diagnostic:i})].join(` -`)};t=t.cause}}function FZ(n,t){return{content:fl(n)??"",images:typeof t?.inboundImages=="function"?t.inboundImages(n):DG(n),files:typeof t?.inboundFiles=="function"?t.inboundFiles(n):OG(n)}}function Ew(n){return Array.isArray(n?.item_list)&&n.item_list.some(t=>t?.image_item&&typeof t.image_item=="object")}function Cw(n){return Array.isArray(n?.item_list)&&n.item_list.some(t=>t?.file_item&&typeof t.file_item=="object")}function MLe(n){return Array.isArray(n?.item_list)&&n.item_list.length>0&&n.item_list.every(t=>t?.type===1&&typeof t.text_item?.text=="string")&&!!Fr(fl(n))}function _Le(n,t){return t.questions[t.index]&&Fr(n?.from_user_id)===t.actor&&!Ew(n)&&!Cw(n)&&Fr(fl(n))}function TLe(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5FAE\u4FE1\u673A\u5668\u4EBA\u5F53\u524D\u6CA1\u6709\u6587\u4EF6\u6D88\u606F\u53D1\u9001\u6743\u9650\uFF0C\u8BF7\u68C0\u67E5\u673A\u5668\u4EBA\u6587\u4EF6\u6D88\u606F\u80FD\u529B\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u5FAE\u4FE1\u4F1A\u8BDD\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u5FAE\u4FE1\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5FAE\u4FE1\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6D88\u606F\u3002",{name:o});case"artifact-invalid":case"artifact-changed":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7\u5FAE\u4FE1\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function kG(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null}}var uw=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c;#p=new Map;#d=new Map;#h=new Map;#E=new Map;#C=new Set;#f=new Set;#B;#y=new mi;#S=null;#Q=null;#m=null;#u=0;#b=Promise.resolve();#R=!1;#D=0;#w=!1;constructor({api:t,baseUrl:o,token:i,ownerUserId:e,harness:a,state:A,contextEnhancement:r,status:s=kG(),logger:g=console,replyTimeoutMs:c=6e5,maxMessageChars:I=Bl,typingKeepaliveMs:d=mLe,signal:B}){if(!t||typeof t.sendText!="function")throw new TypeError("Weixin API is required");if(!o||!i||!e)throw new TypeError("Weixin account credentials are required");if(!a||!A)throw new TypeError("Harness client and state store are required");if(!Number.isFinite(d)||d<=0)throw new TypeError("typingKeepaliveMs must be a positive number");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c,this.#o=I,this.#s=d,this.#c=B,this.#B=new Ci({label:"weixin",logger:g})}get status(){return structuredClone(this.#i)}accept(t){if(this.#c?.aborted||t?.message_type===2)return Promise.resolve();let o=MG(t),i=Fr(t?.from_user_id);if(!o||!i||this.#a.hasSeen(o)||this.#E.has(o))return Promise.resolve();this.#E.set(o,Xr(this.#n,"direct")),i===this.#r&&Eo(this.#a,{toUserId:i});let e=wLe(i),a=Fr(t?.context_token)??void 0,A=Fr(t?.run_id)??void 0,r=this.#d.get(e),s=Fr(fl(t))??"",g=So(s),c=this.#y.status(e);if(i===this.#r&&(g||c.phase==="collecting")){let f=/^\/batch$/iu.test(s)&&c.phase==="idle"&&(this.#p.has(e)||r||this.#B.hasPending(e))?{handled:!0,kind:"busy",message:wo()}:this.#y.handle(e,s,{plainText:MLe(t)});if(f.handled)return f.kind==="submit"?this.#T({...t,item_list:[{type:1,text_item:{text:f.prompt}}]},o,e,{batchSubmission:f}):this.#k(t,o,e,i,a,A,f)}let I=fi(s)?qi:Cw(t)?null:zi(s)?Qi:Vi(s)?Wi:Zi(s)?yi:null;if(I&&i===this.#r){let B;return B=this.#M(t,o,e,i,a,A,s,I).catch(f=>{if(f?.code==="turn-stopped"||this.#c?.aborted)return;this.#i.lastError=f?.message??String(f);let Q=tt(this.#i,f);return this.#I.error?.(`[dsh-weixin] failed to process a command [${Q.referenceId}]:`,f),this.#K(e,i,dt(Q),a,A).catch(()=>{})}).finally(()=>{this.#E.delete(o),this.#f.delete(B)}),this.#f.add(B),B}let d=this.#B.claimReply({key:e,actor:i,messageId:o,text:Ew(t)||Cw(t)?"":fl(t),addressed:!0,hasPendingQuestion:!!r,questionCompletion:r?.submitting||r?.claimedReplyMessageId?r.queue:null,isQuestionPending:()=>this.#d.has(e),send:B=>this.#F(i,B,a,A)});if(d){let B;return B=d.process(async()=>this.#a.hasSeen(o)?!1:(await this.#a.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#E.delete(o),this.#C.delete(B)}),this.#C.add(B),B}if(r?.submitting||r?.claimedReplyMessageId)return this.#T(t,o,e);if(r){_Le(t,r)&&(r.claimedReplyMessageId=o);let f=(r.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#_(t,o,e,r)).catch(Q=>this.#z(t,o,Q)).finally(()=>{this.#E.delete(o),r.claimedReplyMessageId===o&&(r.claimedReplyMessageId=null),r.queue===f&&(r.queue=null)});return r.queue=f,f}return this.#T(t,o,e)}#T(t,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1,batchSubmission:A=null}={}){let r=t.from_user_id===this.#r?wp(FZ(t,this.#e),{signal:this.#c}):void 0,g=(this.#p.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#L(t,i,{alreadyRecorded:a,preparedMessage:r,batchSubmission:A})).finally(()=>{e&&this.#E.delete(o),this.#p.get(i)===g&&this.#p.delete(i)});return this.#p.set(i,g),g}#k(t,o,i,e,a,A,r){let s;return s=Promise.resolve().then(async()=>{this.#a.hasSeen(o)||(await this.#a.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),r.message&&await this.#K(i,e,r.message,a,A),this.#i.lastError=null)}).catch(async g=>{if(this.#c?.aborted)return;this.#i.lastError=g?.message??String(g);let c=tt(this.#i,g);this.#I.error?.(`[dsh-weixin] failed to process a batch input message [${c.referenceId}]:`,g),await this.#K(i,e,dt(c),a,A).catch(()=>{})}).finally(()=>{this.#E.delete(o),this.#f.delete(s)}),this.#f.add(s),s}async waitForIdle(){await Promise.allSettled([...this.#p.values(),...[...this.#d.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#C,...this.#f,this.#b])}async close(){this.#R=!0,await this.#Ae({signal:AbortSignal.timeout(5e3)})}async#M(t,o,i,e,a,A,r,s){if(this.#c?.throwIfAborted(),this.#a.hasSeen(o))return;await this.#a.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString();let g=await s(r,this.#g,this.#a,i,{signal:this.#c,isDirect:!0,hasImages:Ew(t),hasFiles:Cw(t),pendingInteraction:this.#d.has(i)||this.#B.hasPending(i),control:{owner:this,key:i}});g?.stopped&&await Promise.allSettled([this.#q(i),this.#B.closeRoute(i)]);for(let c of g?.messages??[g?.message])c&&(g?.stopped?await this.#F(e,c,a,A):await this.#K(i,e,c,a,A));this.#i.lastError=null}async#L(t,o,{alreadyRecorded:i=!1,preparedMessage:e,batchSubmission:a=null}={}){this.#c?.throwIfAborted();let A=MG(t),r=Fr(t?.from_user_id);if(!A||!r)return;if(!i){if(this.#a.hasSeen(A))return;this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString()}if(r!==this.#r){this.#i.messagesRejected+=1,this.#i.lastRejectedAt=new Date().toISOString();return}let s=typeof t.context_token=="string"?t.context_token:void 0,g=typeof t.run_id=="string"?t.run_id:void 0,c=a===null,I=!1;try{let d=e??FZ(t,this.#e),B=d.content,f=Wt(d),Q=Lt(d);if(!B&&!f&&!Q){await this.#F(r,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\uFF0C\u4EE5\u53CA\u5FAE\u4FE1\u5DF2\u8F6C\u6210\u6587\u5B57\u7684\u8BED\u97F3\u6D88\u606F\u3002"),s,g),await this.#a.markSeen(A);return}let y=B.trim().toLowerCase();if(!f&&!Q&&y==="/help"){await this.#F(r,SLe(),s,g),await this.#a.markSeen(A);return}if(!f&&!Q&&y==="/status"){await this.#g.ensureRunning({signal:this.#c}),await this.#F(r,w("\u5FAE\u4FE1\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),s,g),await this.#a.markSeen(A);return}if(!f&&!Q&&y==="/new"){await this.#a.clearSession(o),await this.#F(r,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),s,g),await this.#a.markSeen(A);return}let m=f||Q?null:await Qo(B,this.#g,o);if(m){for(let z of m.messages??[m.message])await this.#F(r,z,s,g);await this.#a.markSeen(A);return}let _=f||Q?null:await Bi(B,this.#g,this.#a,o,{signal:this.#c});if(_){await this.#F(r,_.message,s,g),await this.#a.markSeen(A);return}let T,R=[];await this.#$(r,s);try{let z=f?await Bo(d,{signal:this.#c}):void 0,j=this.#E.get(A);j&&(z=mo(z??B,j,()=>({channel:"weixin",senderId:r}))),await this.#a.markSeen(A),I=!0,{answer:T,artifacts:R=[]}=await ui({harness:this.#g,state:this.#a,key:o,...z!==void 0?{content:z}:{text:B},createOptions:{signal:this.#c},existsOptions:{signal:this.#c},askOptions:{timeoutMs:this.#l,signal:this.#c,control:{owner:this,key:o},onUpdate:()=>this.#X(o,r,s),onInteraction:P=>this.#U(P,{key:o,actor:r,contextToken:s,runId:g}),onInteractionResolved:async P=>{await this.#v(P),await this.#X(o,r,s)},files:d.files}}),a&&(this.#y.complete(o,a.token),c=!0)}finally{await Promise.allSettled([this.#Ae(),this.#q(o),this.#B.closeRoute(o)])}let F=typeof T=="string"&&T.trim()?T:R.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):T,K=null,L=null;try{L=Zt({deliveryId:A,presentation:"weixin-text",providerMessageIds:await this.#F(r,F,s,g)})}catch(z){K=Ma(z)}let q=await this.#x(r,A,R,s,g,L);if(K&&!q.userVisible)throw K;return K&&q.artifactSendErrors===0&&tt(this.#i,K,GZ(K)),I||await this.#a.markSeen(A),this.#i.messagesReplied+=1,this.#i.lastReplyAt=new Date().toISOString(),this.#i.lastError=null,!K&&q.artifactSendErrors===0&&Co(this.#i),q.receipt}catch(d){let B=null;if(!c&&a&&(d?.code==="turn-stopped"?this.#y.complete(o,a.token):B=this.#y.fail(o,a.token).message??null,c=!0),d?.code==="turn-stopped"){I||await this.#a.markSeen(A);return}if(this.#c?.aborted)return;this.#i.lastError=d?.message??String(d);let f=Oo(d)??fo(d),Q=Ji(d),y=GZ(d),m=tt(this.#i,d,{userMessage:f??y?.userMessage,reason:Q?.reason??y?.reason});this.#I.error?.(`[dsh-weixin] failed to process an inbound message [${m.referenceId}]:`,d);try{await this.#F(r,B?`${dt(m)} +`)};t=t.cause}}function FZ(n,t){return{content:fl(n)??"",images:typeof t?.inboundImages=="function"?t.inboundImages(n):DG(n),files:typeof t?.inboundFiles=="function"?t.inboundFiles(n):OG(n)}}function Ew(n){return Array.isArray(n?.item_list)&&n.item_list.some(t=>t?.image_item&&typeof t.image_item=="object")}function Cw(n){return Array.isArray(n?.item_list)&&n.item_list.some(t=>t?.file_item&&typeof t.file_item=="object")}function MLe(n){return Array.isArray(n?.item_list)&&n.item_list.length>0&&n.item_list.every(t=>t?.type===1&&typeof t.text_item?.text=="string")&&!!Fr(fl(n))}function _Le(n,t){return t.questions[t.index]&&Fr(n?.from_user_id)===t.actor&&!Ew(n)&&!Cw(n)&&Fr(fl(n))}function TLe(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5FAE\u4FE1\u673A\u5668\u4EBA\u5F53\u524D\u6CA1\u6709\u6587\u4EF6\u6D88\u606F\u53D1\u9001\u6743\u9650\uFF0C\u8BF7\u68C0\u67E5\u673A\u5668\u4EBA\u6587\u4EF6\u6D88\u606F\u80FD\u529B\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u5FAE\u4FE1\u4F1A\u8BDD\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u5FAE\u4FE1\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5FAE\u4FE1\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6D88\u606F\u3002",{name:o});case"artifact-invalid":case"artifact-changed":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7\u5FAE\u4FE1\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function kG(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null}}var uw=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c;#p=new Map;#d=new Map;#h=new Map;#E=new Map;#C=new Set;#f=new Set;#B;#y=new mi;#S=null;#Q=null;#m=null;#u=0;#b=Promise.resolve();#R=!1;#D=0;#w=!1;constructor({api:t,baseUrl:o,token:i,ownerUserId:e,harness:a,state:A,contextEnhancement:r,status:s=kG(),logger:g=console,replyTimeoutMs:c=6e5,maxMessageChars:I=Bl,typingKeepaliveMs:d=mLe,signal:B}){if(!t||typeof t.sendText!="function")throw new TypeError("Weixin API is required");if(!o||!i||!e)throw new TypeError("Weixin account credentials are required");if(!a||!A)throw new TypeError("Harness client and state store are required");if(!Number.isFinite(d)||d<=0)throw new TypeError("typingKeepaliveMs must be a positive number");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=c,this.#o=I,this.#s=d,this.#c=B,this.#B=new Ci({label:"weixin",logger:g})}get status(){return structuredClone(this.#i)}accept(t){if(this.#c?.aborted||t?.message_type===2)return Promise.resolve();let o=MG(t),i=Fr(t?.from_user_id);if(!o||!i||this.#a.hasSeen(o)||this.#E.has(o))return Promise.resolve();this.#E.set(o,Xr(this.#n,"direct")),i===this.#r&&Eo(this.#a,{toUserId:i});let e=wLe(i),a=Fr(t?.context_token)??void 0,A=Fr(t?.run_id)??void 0,r=this.#d.get(e),s=Fr(fl(t))??"",g=So(s),c=this.#y.status(e);if(i===this.#r&&(g||c.phase==="collecting")){let f=/^\/batch$/iu.test(s)&&c.phase==="idle"&&(this.#p.has(e)||r||this.#B.hasPending(e))?{handled:!0,kind:"busy",message:wo()}:this.#y.handle(e,s,{plainText:MLe(t)});if(f.handled)return f.kind==="submit"?this.#T({...t,item_list:[{type:1,text_item:{text:f.prompt}}]},o,e,{batchSubmission:f}):this.#k(t,o,e,i,a,A,f)}let I=fi(s)?qi:Cw(t)?null:zi(s)?Qi:Vi(s)?Wi:Zi(s)?yi:null;if(I&&i===this.#r){let B;return B=this.#M(t,o,e,i,a,A,s,I).catch(f=>{if(f?.code==="turn-stopped"||this.#c?.aborted)return;this.#i.lastError=f?.message??String(f);let Q=tt(this.#i,f);return this.#I.error?.(`[dsh-weixin] failed to process a command [${Q.referenceId}]:`,f),this.#K(e,i,dt(Q),a,A).catch(()=>{})}).finally(()=>{this.#E.delete(o),this.#f.delete(B)}),this.#f.add(B),B}let d=this.#B.claimReply({key:e,actor:i,messageId:o,text:Ew(t)||Cw(t)?"":fl(t),addressed:!0,hasPendingQuestion:!!r,questionCompletion:r?.submitting||r?.claimedReplyMessageId?r.queue:null,isQuestionPending:()=>this.#d.has(e),send:B=>this.#F(i,B,a,A)});if(d){let B;return B=d.process(async()=>this.#a.hasSeen(o)?!1:(await this.#a.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#E.delete(o),this.#C.delete(B)}),this.#C.add(B),B}if(r?.submitting||r?.claimedReplyMessageId)return this.#T(t,o,e);if(r){_Le(t,r)&&(r.claimedReplyMessageId=o);let f=(r.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#_(t,o,e,r)).catch(Q=>this.#z(t,o,Q)).finally(()=>{this.#E.delete(o),r.claimedReplyMessageId===o&&(r.claimedReplyMessageId=null),r.queue===f&&(r.queue=null)});return r.queue=f,f}return this.#T(t,o,e)}#T(t,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1,batchSubmission:A=null}={}){let r=t.from_user_id===this.#r?wp(FZ(t,this.#e),{signal:this.#c}):void 0,g=(this.#p.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#L(t,i,{alreadyRecorded:a,preparedMessage:r,batchSubmission:A})).finally(()=>{e&&this.#E.delete(o),this.#p.get(i)===g&&this.#p.delete(i)});return this.#p.set(i,g),g}#k(t,o,i,e,a,A,r){let s;return s=Promise.resolve().then(async()=>{this.#a.hasSeen(o)||(await this.#a.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),r.message&&await this.#K(i,e,r.message,a,A),this.#i.lastError=null)}).catch(async g=>{if(this.#c?.aborted)return;this.#i.lastError=g?.message??String(g);let c=tt(this.#i,g);this.#I.error?.(`[dsh-weixin] failed to process a batch input message [${c.referenceId}]:`,g),await this.#K(i,e,dt(c),a,A).catch(()=>{})}).finally(()=>{this.#E.delete(o),this.#f.delete(s)}),this.#f.add(s),s}async waitForIdle(){await Promise.allSettled([...this.#p.values(),...[...this.#d.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#C,...this.#f,this.#b])}async close(){this.#R=!0,await this.#Ae({signal:AbortSignal.timeout(5e3)})}async#M(t,o,i,e,a,A,r,s){if(this.#c?.throwIfAborted(),this.#a.hasSeen(o))return;await this.#a.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString();let g=await s(r,this.#g,this.#a,i,{signal:this.#c,isDirect:!0,hasImages:Ew(t),hasFiles:Cw(t),pendingInteraction:this.#d.has(i)||this.#B.hasPending(i),control:{owner:this,key:i}});g?.stopped&&await Promise.allSettled([this.#q(i),this.#B.closeRoute(i)]);for(let c of g?.messages??[g?.message])c&&(g?.stopped?await this.#F(e,c,a,A):await this.#K(i,e,c,a,A));this.#i.lastError=null}async#L(t,o,{alreadyRecorded:i=!1,preparedMessage:e,batchSubmission:a=null}={}){this.#c?.throwIfAborted();let A=MG(t),r=Fr(t?.from_user_id);if(!A||!r)return;if(!i){if(this.#a.hasSeen(A))return;this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString()}if(r!==this.#r){this.#i.messagesRejected+=1,this.#i.lastRejectedAt=new Date().toISOString();return}let s=typeof t.context_token=="string"?t.context_token:void 0,g=typeof t.run_id=="string"?t.run_id:void 0,c=a===null,I=!1;try{let d=e??FZ(t,this.#e),B=d.content,f=Wt(d),Q=Lt(d);if(!B&&!f&&!Q){await this.#F(r,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\uFF0C\u4EE5\u53CA\u5FAE\u4FE1\u5DF2\u8F6C\u6210\u6587\u5B57\u7684\u8BED\u97F3\u6D88\u606F\u3002"),s,g),await this.#a.markSeen(A);return}let y=B.trim().toLowerCase();if(!f&&!Q&&y==="/help"){await this.#F(r,SLe(),s,g),await this.#a.markSeen(A);return}if(!f&&!Q&&y==="/status"){await this.#g.ensureRunning({signal:this.#c}),await this.#F(r,w("\u5FAE\u4FE1\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),s,g),await this.#a.markSeen(A);return}if(!f&&!Q&&y==="/new"){await this.#a.clearSession(o),await this.#F(r,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),s,g),await this.#a.markSeen(A);return}let m=f||Q?null:await Qo(B,this.#g,o);if(m){for(let z of m.messages??[m.message])await this.#F(r,z,s,g);await this.#a.markSeen(A);return}let _=f||Q?null:await Bi(B,this.#g,this.#a,o,{signal:this.#c});if(_){await this.#F(r,_.message,s,g),await this.#a.markSeen(A);return}let T,R=[];await this.#$(r,s);try{let z=f?await Bo(d,{signal:this.#c}):void 0,j=this.#E.get(A);j&&(z=mo(z??B,j,()=>({channel:"weixin",senderId:r}))),await this.#a.markSeen(A),I=!0,{answer:T,artifacts:R=[]}=await ui({harness:this.#g,state:this.#a,key:o,...z!==void 0?{content:z}:{text:B},createOptions:{signal:this.#c},existsOptions:{signal:this.#c},askOptions:{timeoutMs:this.#l,signal:this.#c,control:{owner:this,key:o},onUpdate:()=>this.#X(o,r,s),onInteraction:P=>this.#U(P,{key:o,actor:r,contextToken:s,runId:g}),onInteractionResolved:async P=>{await this.#v(P),await this.#X(o,r,s)},files:d.files}}),a&&(this.#y.complete(o,a.token),c=!0)}finally{await Promise.allSettled([this.#Ae(),this.#q(o),this.#B.closeRoute(o)])}let L=typeof T=="string"&&T.trim()?T:R.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):T,U=null,F=null;try{F=Zt({deliveryId:A,presentation:"weixin-text",providerMessageIds:await this.#F(r,L,s,g)})}catch(z){U=Ma(z)}let q=await this.#x(r,A,R,s,g,F);if(U&&!q.userVisible)throw U;return U&&q.artifactSendErrors===0&&tt(this.#i,U,GZ(U)),I||await this.#a.markSeen(A),this.#i.messagesReplied+=1,this.#i.lastReplyAt=new Date().toISOString(),this.#i.lastError=null,!U&&q.artifactSendErrors===0&&Co(this.#i),q.receipt}catch(d){let B=null;if(!c&&a&&(d?.code==="turn-stopped"?this.#y.complete(o,a.token):B=this.#y.fail(o,a.token).message??null,c=!0),d?.code==="turn-stopped"){I||await this.#a.markSeen(A);return}if(this.#c?.aborted)return;this.#i.lastError=d?.message??String(d);let f=Oo(d)??fo(d),Q=Ji(d),y=GZ(d),m=tt(this.#i,d,{userMessage:f??y?.userMessage,reason:Q?.reason??y?.reason});this.#I.error?.(`[dsh-weixin] failed to process an inbound message [${m.referenceId}]:`,d);try{await this.#F(r,B?`${dt(m)} -${B}`:dt(m),s,g),I||await this.#a.markSeen(A)}catch(_){this.#I.error?.("[dsh-weixin] failed to send the safe error reply:",_)}}}async#_(t,o,i,e){this.#c?.throwIfAborted();let a=this.#d.get(i),A=e.claimedReplyMessageId===o;if(!a||a!==e||a.submitting)return A&&(!a||a!==e)?this.#N(t,o):this.#T(t,o,i,{releaseMessageId:!1});if(this.#a.hasSeen(o))return;await this.#a.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString();let r=Fr(fl(t)),s=Fr(t?.context_token)??void 0,g=Fr(t?.run_id)??void 0;if(!r||Ew(t)){await this.#F(e.actor,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002"),s,g);return}let c=this.#d.get(i);if(!c||c!==e||c.submitting){if(A&&(!c||c!==e)){await this.#F(e.actor,hw(),s,g);return}return this.#T(t,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.contextToken=s,c.runId=g,c.needsPresentation){try{await this.#P(c)}catch{this.#i.lastError=w("\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002"),this.#I.error?.("[dsh-weixin] failed to retry an interaction question"),c.interaction.reconnect?.();return}let d=this.#d.get(i);if(!d||d!==e||d.submitting){if(A&&(!d||d!==e)){await this.#F(e.actor,hw(),s,g).catch(()=>{});return}return this.#T(t,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}}let I=c.questions[c.index];if(I){if(c.answers.push(Ei(I,r)),c.index+=1,c.index{});return}if(this.#d.get(i)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#i.lastError=w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002"),this.#I.error?.("[dsh-weixin] failed to answer a Harness interaction"),await this.#F(c.actor,w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002"),c.contextToken,c.runId).catch(()=>{})}}}async#U(t,{key:o,actor:i,contextToken:e,runId:a}){if(t?.kind==="approval")return this.#B.handleRequested(t,{key:o,actor:i,send:c=>this.#F(i,c,e,a)});if(t?.kind!=="question")return;let A=t?.payload?.questions,r=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t?.rpcId!="string"||typeof r!="string"||typeof t.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!di(c))){this.#I.warn?.("[dsh-weixin] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"Weixin safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#F(i,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002"),e,a).catch(()=>{});return}let s=this.#d.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#P(s);return}if(this.#h.has(r))return;if(s){await t.respond({ok:!1,error:{code:"cancelled",message:"Weixin is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,questions:A,answers:[],index:0,contextToken:e,runId:a,queue:null,claimedReplyMessageId:null,presentationPromise:null,submitting:!1,needsPresentation:!0};this.#d.set(o,g),this.#h.set(r,o),await this.#P(g)}async#v(t){if(t?.kind==="approval"){await this.#B.handleResolved(t);return}let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#h.get(o);i&&this.#H(i,o)}#P(t){if(!t.needsPresentation)return Promise.resolve();if(t.presentationPromise)return t.presentationPromise;let o=t.questions[t.index];if(!o)return Promise.resolve();let i=this.#F(t.actor,hi(o,t.index,t.questions.length),t.contextToken,t.runId).then(()=>{t.needsPresentation=!1}).finally(()=>{t.presentationPromise===i&&(t.presentationPromise=null)});return t.presentationPromise=i,i}async#N(t,o){this.#a.hasSeen(o)||(await this.#a.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),await this.#F(Fr(t?.from_user_id),hw(),Fr(t?.context_token)??void 0,Fr(t?.run_id)??void 0).catch(()=>{}))}#Y(t,o){let i=this.#d.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#d.delete(t),this.#h.delete(i.interactionId),i)}#H(t,o){return this.#Y(t,o)!==null}async#q(t){let o=this.#Y(t);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Weixin interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#I.warn?.("[dsh-weixin] failed to cancel a pending Harness interaction")}}async#z(t,o,i){if(this.#c?.aborted)return;this.#i.lastError=i?.message??String(i);let e=tt(this.#i,i);this.#I.error?.(`[dsh-weixin] failed to process an interaction reply [${e.referenceId}]:`,i),this.#a.hasSeen(o)||await this.#a.markSeen(o).catch(()=>{}),await this.#F(Fr(t?.from_user_id),dt(e),Fr(t?.context_token)??void 0,Fr(t?.run_id)??void 0).catch(()=>{})}async#F(t,o,i,e){await this.#Ae();let a=[],A=MZ(o,this.#o);for(let r=0;r{}).then(t);return this.#b=o.catch(()=>{}),o}async#$(t,o){let i=Fr(t);if(!i||this.#R||this.#c?.aborted||Date.now(){if(e!==this.#u||this.#R)return!1;let a=this.#S;if(!a){let A=await this.#e.getConfig({baseUrl:this.#A,token:this.#t,toUserId:i,contextToken:o,signal:this.#c});if(a=Fr(A?.typingTicket),!a)return this.#D=Date.now()+RG,!1;if(e!==this.#u||this.#R)return!1;this.#S=a,this.#D=0}return this.#Q=i,await this.#e.sendTyping({baseUrl:this.#A,token:this.#t,toUserId:i,typingTicket:a,status:1,signal:this.#c}),e!==this.#u||this.#R?!1:(this.#w=!1,this.#D=0,this.#te(e),!0)})}catch(a){return e===this.#u&&(this.#j(),this.#w=!!(this.#Q&&this.#S),this.#D=Date.now()+RG),!this.#c?.aborted&&!this.#R&&this.#I.warn?.("[dsh-weixin] typing indicator failed:",a),!1}}async#Ae({signal:t=AbortSignal.timeout(5e3)}={}){++this.#u,this.#j();let o=this.#Q,i=this.#S,e=this.#w;if(this.#Q=null,typeof this.#e.sendTyping!="function")return!1;try{return await this.#G(async()=>{if(!o||!i)return!1;try{await this.#e.sendTyping({baseUrl:this.#A,token:this.#t,toUserId:o,typingTicket:i,status:2,signal:t})}finally{e&&this.#S===i&&(this.#S=null),this.#w=!1}return!0})}catch(a){return t?.aborted||this.#I.warn?.("[dsh-weixin] typing cancellation failed:",a),!1}}#te(t){if(this.#j(),t!==this.#u||!this.#Q||this.#R)return;let o=setTimeout(()=>{this.#m===o&&(this.#m=null),this.#G(async()=>t!==this.#u||!this.#Q||this.#R?!1:(await this.#e.sendTyping({baseUrl:this.#A,token:this.#t,toUserId:this.#Q,typingTicket:this.#S,status:1,signal:this.#c}),!0)).then(i=>{i&&this.#te(t)}).catch(i=>{t===this.#u&&(this.#w=!!(this.#Q&&this.#S),this.#D=Date.now()+RG,!this.#c?.aborted&&!this.#R&&this.#I.warn?.("[dsh-weixin] typing keepalive failed:",i))})},this.#s);o.unref?.(),this.#m=o}#j(){this.#m&&clearTimeout(this.#m),this.#m=null}#X(t,o,i){return this.#d.has(t)||this.#B.hasPending(t)?Promise.resolve(!1):this.#$(o,i)}async#x(t,o,i,e,a,A){let r=(g,c)=>this.#e[g]({baseUrl:this.#A,token:this.#t,toUserId:t,file:c,contextToken:e,runId:a,signal:this.#c}),s=await bo({artifacts:i,baseReceipt:A,deliveryId:o,aggregatePresentation:A?"weixin-text-and-files":"weixin-files",channelKey:"weixin",signal:this.#c,sendImage:typeof this.#e.sendImage=="function"?g=>r("sendImage",g):void 0,sendFile:typeof this.#e.sendFile=="function"?g=>r("sendFile",g):void 0,onFailure:(g,c)=>tt(this.#i,c,{userMessage:TLe(g?.fileName,c),reason:c?.code}),sendFailureNotice:(g,c,I)=>this.#F(t,dt(I),e,a),logger:this.#I});return this.#i.artifactsSent=(this.#i.artifactsSent??0)+s.artifactsSent,this.#i.artifactSendErrors=(this.#i.artifactSendErrors??0)+s.artifactSendErrors,{receipt:s.receipt,userVisible:s.userVisible,artifactSendErrors:s.artifactSendErrors}}};var NLe=Object.freeze([250,1e3,3e3]),RLe=new Set(["harness-connect-failed","harness-timeout","harness-auth-required","harness-proxy-auth-required","harness-loopback-forbidden","harness-host-untrusted","harness-request-forbidden","harness-api-not-found","harness-http-failed","harness-response-invalid","harness-rpc-rejected"]);function kLe(n){if(n===void 0)return[...NLe];if(!Array.isArray(n))throw new TypeError("startRetryDelaysMs must be an array");return n.map(t=>{if(!Number.isFinite(t)||t<0)throw new TypeError("startRetryDelaysMs must contain non-negative delays");return t})}function vLe(n){return n instanceof _A?n.code==="network-error"||n.code==="timeout"?!0:n.code==="http-error"&&(n.status===408||n.status===425||n.status===429||n.status>=500):!1}function PLe(n,t){let o=new Error(`Weixin runtime failed during ${n}`,{cause:t});return o.name="WeixinRuntimeStartError",o.code=n,o}function GLe(n){let t=RLe.has(n?.code)?n.code:"harness-check-unknown-failed";return PLe(t,n)}function UZ(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let a=setTimeout(()=>{t?.removeEventListener("abort",A),o()},n),A=()=>{clearTimeout(a),t?.removeEventListener("abort",A),i(t.reason??new DOMException("Aborted","AbortError"))};t?.addEventListener("abort",A,{once:!0})})}function FLe(n){if(!Array.isArray(n)||n.length<2)return Array.isArray(n)?n:[];let t=["seq","create_time_ms"].find(o=>n.every(i=>typeof i?.[o]=="number"&&Number.isFinite(i[o])||typeof i?.[o]=="string"&&i[o].trim()&&Number.isFinite(Number(i[o]))));return t?n.map((o,i)=>({message:o,index:i,order:Number(o[t])})).sort((o,i)=>o.order-i.order||o.index-i.index).map(({message:o})=>o):n}function LLe(){return{startedAt:null,ready:!1,weixinConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastError:null,...kG()}}var rB=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o=LLe();#s=null;#c=null;#p=null;#d=null;constructor({api:t,config:o,token:i,harness:e,state:a,contextEnhancement:A,logger:r=console,replyTimeoutMs:s=6e5,maxMessageChars:g=Bl,startRetryDelaysMs:c}){if(!t||!o||!i||!e||!a)throw new TypeError("WeixinRuntime requires API, account, token, Harness, and state");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=kLe(c)}get status(){return structuredClone(this.#o)}async start(){return this.#o.ready&&this.#p?this.status:this.#d?this.#d:(this.#d=this.#h().finally(()=>{this.#d=null}),this.#d)}async#h(){await this.stop(),this.#o.startedAt=new Date().toISOString(),this.#o.weixinConnectionState="connecting",this.#o.lastError=null;try{try{await this.#r.ensureRunning()}catch(o){throw GLe(o)}this.#o.harnessReachable=!0,await this.#E(),this.#c=new AbortController;let t=this.#c.signal;return this.#s=new uw({api:this.#e,baseUrl:this.#A.baseUrl,token:this.#t,ownerUserId:this.#A.ownerUserId,harness:this.#r,state:this.#g,contextEnhancement:this.#a,status:this.#o,logger:this.#n,replyTimeoutMs:this.#i,maxMessageChars:this.#I,signal:t}),this.#o.ready=!0,this.#o.weixinConnectionState="connected",this.#o.lastCheckedAt=Date.now(),this.#p=this.#C(t).catch(o=>{t.aborted||(this.#o.ready=!1,this.#o.weixinConnectionState="failed",this.#o.lastError=o?.message??String(o),this.#n.error?.(`[dsh-weixin] account ${this.#A.botId} monitor stopped:`,o))}),this.status}catch(t){throw this.#c?.abort(),this.#c=null,this.#s=null,this.#o.ready=!1,this.#o.weixinConnectionState="failed",this.#o.lastError=t?.message??String(t),t}}async#E(){for(let t=0;;t+=1)try{return await this.#e.notifyStart({baseUrl:this.#A.baseUrl,token:this.#t})}catch(o){let i=this.#l[t];if(i===void 0||!vLe(o))throw o;this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} start request failed; retrying in ${i}ms:`,o),await UZ(i)}}async#C(t){let o=0;for(;!t.aborted;)try{let i=await this.#e.getUpdates({baseUrl:this.#A.baseUrl,token:this.#t,getUpdatesBuf:this.#g.getUpdatesBuf(),signal:t});if(t.aborted)return;if(i?.ret!==void 0&&i.ret!==0||i?.errcode!==void 0&&i.errcode!==0){let a=i.errcode??i.ret;throw new _A(a===-14?"stale-token":"updates-rejected",a===-14?w("\u5FAE\u4FE1\u767B\u5F55\u51ED\u636E\u5DF2\u5931\u6548\uFF0C\u8BF7\u79FB\u9664\u8D26\u53F7\u540E\u91CD\u65B0\u626B\u7801\u3002"):w("\u5FAE\u4FE1\u6D88\u606F\u540C\u6B65\u8BF7\u6C42\u88AB\u62D2\u7EDD\u3002"))}o=0,this.#o.ready=!0,this.#o.weixinConnectionState="connected",this.#o.lastCheckedAt=Date.now(),this.#o.lastError=null;for(let a of FLe(i?.msgs))this.#s.accept(a).catch(A=>{t.aborted||this.#n.error?.(`[dsh-weixin] account ${this.#A.botId} message handling failed:`,A)});typeof i?.get_updates_buf=="string"&&i.get_updates_buf&&await this.#g.setGetUpdatesBuf(i.get_updates_buf)}catch(i){if(t.aborted)return;if(o+=1,this.#o.lastError=i?.message??String(i),this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} poll failed (${o}/3):`,i),i instanceof _A&&i.code==="stale-token"||o>=3)throw i;await UZ(Math.min(2e3*2**(o-1),1e4),t)}}async stop(){let t=this.#p,o=this.#s,i=!!(this.#c||t||this.#o.ready);if(this.#c?.abort(),this.#c=null,this.#p=null,await o?.close?.(),await t?.catch(()=>{}),await o?.waitForIdle(),this.#s=null,i)try{await this.#e.notifyStop({baseUrl:this.#A.baseUrl,token:this.#t,signal:AbortSignal.timeout(1e4)})}catch(e){this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} stop notification failed:`,e)}return this.#o.ready=!1,this.#o.weixinConnectionState="idle",this.status}async sendConnectionTest(t){let o=SE(this.#g),i=typeof o?.toUserId=="string"&&o.toUserId.trim()?o.toUserId.trim():typeof this.#A.ownerUserId=="string"&&this.#A.ownerUserId.trim()?this.#A.ownerUserId.trim():null;if(!i)throw Ir(w("\u5FAE\u4FE1\u673A\u5668\u4EBA"));if(!this.#o.ready||!this.#c)throw new Error("Weixin runtime is not connected");return await this.#e.sendText({baseUrl:this.#A.baseUrl,token:this.#t,toUserId:i,text:t,signal:this.#c.signal}),{sent:!0}}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.toUserId=="string"?t.route.toUserId.trim():"";if(t?.kind!=="user"||!e){let a=new TypeError("Invalid Weixin proactive delivery target");throw a.code="invalid-target",a}if(!this.#o.ready||!this.#c){let a=new Error("Weixin runtime is not connected");throw a.code="bot-not-connected",a}return i?.throwIfAborted(),await this.#e.sendText({baseUrl:this.#A.baseUrl,token:this.#t,toUserId:e,text:o,signal:i??this.#c.signal}),{sent:!0}}};var HZ=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function ULe(n){if(!Array.isArray(n)||n.length===0)return[...HZ];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...HZ]}var Bw=class{#e;#A;#t;#r;#g;#a;#n;#i=null;#I=null;#l=0;#o=!1;#s=!1;#c;#p;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=ULe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#a=A,this.#n=r,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#s||this.#o?this:(this.#s=!0,this.#d(0),this)}async close(){this.#o||(this.#o=!0,this.#i!==null&&this.#n(this.#i),this.#i=null,await this.#I?.catch(()=>{}),this.#p?.(null),this.#p=null)}#d(t){this.#o||(this.#i=this.#a(()=>{this.#i=null,this.#h()},t),this.#i?.unref?.())}async#h(){if(this.#o||this.#I)return;let t=this.#E();this.#I=t;try{await t}finally{this.#I===t&&(this.#I=null)}}async#E(){try{if(await this.#A.ensureRunning(),this.#o)return;let t=await this.#e.initialize();if(this.#o)return;this.#p?.(t),this.#p=null;let{configured:o,connected:i}=t.totals;if(iRa(n),B=xLe(t),f=await new e(B.config).load(),Q=Ql(t.workspace??process.cwd()),y=o.WorkspaceStore??ea,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=f.list();await m.reconcile(_.map(k=>k.botId)),await Promise.all(_.map(k=>m.ensure(k.botId,{defaultAgentPreset:t.agentPreset})));let T=typeof f.remove=="function"?Pa(f,{workspaces:m}):f,R=new Map,F=k=>Ql(B.accounts,k,"state.json"),K=async k=>{let V=R.get(k);return V||(V=await new a(F(k)).load(),R.set(k,V)),V},L=Ua(n,o.commandExecutor),{controlExecutor:q,sessionMaintenanceExecutor:z,fileIngressExecutor:j}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),P=new A({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...L?{commandExecutor:L}:{},...q?{controlExecutor:q}:{},...z?{sessionMaintenanceExecutor:z}:{},...j?{fileIngressExecutor:j}:{}}),J=new r({api:g,credentials:n.credentials,configStore:T,logger:I,createRuntime:async({botId:k,config:V,token:Ae})=>{let ie=await K(k);await m.ensure(k,{defaultAgentPreset:t.agentPreset});let De=Ga(P,{botId:k,workspaces:m,state:ie,agentPresetCatalog:d});return new s({api:g,config:V,token:Ae,harness:De.harness,state:De.state,contextEnhancement:{botId:k,getSettings:()=>m.contextEnhancementFor(k)},replyTimeoutMs:t.replyTimeoutMs??6e5,maxMessageChars:t.maxMessageChars??Bl,logger:{error:(...fe)=>I.error?.(`[${k}]`,...fe),warn:(...fe)=>I.warn?.(`[${k}]`,...fe),info:(...fe)=>I.info?.(`[${k}]`,...fe),debug:(...fe)=>I.debug?.(`[${k}]`,...fe)}})},deleteState:async({botId:k})=>{let V=R.get(k);if(R.delete(k),V&&typeof V.remove=="function")await V.remove();else try{await HLe(F(k))}catch(Ae){if(Ae?.code!=="ENOENT")throw Ae}}}),U=Fa(J,{workspaces:m,stateFor:K,agentPresetCatalog:d}),N=c({controller:U,harness:P,logger:I,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:U,deliveryAdapter:La({channel:"weixin",workspaces:m,coreController:J,stateFor:K}),ready:N.ready,async close(){await N.close(),await U.close(),P.stopManagedProcess()}}}import YLe from"qrcode";var KZ="/weixin",Sr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",submitVerification:"provision.verify",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),xZ=Object.freeze(Object.values(Sr));function YZ(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function jd(n,t){return YZ(n)&&Object.keys(n).every(o=>t.includes(o))}function fw(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function jLe(n,t){return YZ(t)?n===Sr.status?jd(t,[])?null:"connection.status does not accept fields.":n===Sr.beginProvisioning?jd(t,["locale"])&&(t.locale===void 0||t.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Sr.pollProvisioning,Sr.cancelProvisioning].includes(n)?jd(t,["attemptId"])&&fw(t.attemptId)?null:`${n} requires an attemptId.`:n===Sr.submitVerification?jd(t,["attemptId","verifyCode"])&&fw(t.attemptId)&&typeof t.verifyCode=="string"&&/^\d{4,8}$/.test(t.verifyCode)?null:"provision.verify requires an attemptId and a 4-to-8-digit code.":n===Sr.reconnectBot?jd(t,["botId","sendTest"])&&fw(t.botId)&&(t.sendTest===void 0||t.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Sr.deleteBot?jd(t,["botId","confirm"])&&fw(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Sr.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Sr.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===Sr.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown Weixin endpoint.":"Payload must be an object."}function Qw(n){return{ok:!1,error:{code:"bad-request",message:n}}}function iB(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function JLe(){return{ok:!1,error:{code:"weixin-operation-failed",message:"\u5FAE\u4FE1\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}async function qLe(n){return YLe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function yw(n,t){return!n||!n.verificationUrl?n:{...n,qrCodeDataUrl:await t(n.verificationUrl)}}async function Jd(n,t){let o=structuredClone(n);return o.provisioning&&(o.provisioning=await yw(o.provisioning,t)),o}function zLe(n){if(!n||typeof n.status!="function"||typeof n.startProvisioning!="function"||typeof n.registrationStatus!="function"||typeof n.submitVerification!="function"||typeof n.cancelProvisioning!="function"||typeof n.reconnectBot!="function"||typeof n.deleteBot!="function")throw new TypeError("A complete Weixin controller is required")}function jZ(n,{encodeQr:t=qLe}={}){zLe(n);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return iB();if(!xZ.includes(e))return Qw("Unknown Weixin endpoint.");let r=jLe(e,a);if(r)return Qw(r);try{let s;if(e===Sr.status)s=await Jd(await n.status(),i);else if(e===Sr.beginProvisioning){let g=await n.startProvisioning();if(A?.aborted)return await n.cancelProvisioning(g.attemptId),iB();s=await yw(g,i)}else if(e===Sr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return Qw("The provisioning attempt no longer exists.");s=await yw(g,i)}else if(e===Sr.submitVerification)s=await yw(await n.submitVerification(a.attemptId,a.verifyCode),i);else if(e===Sr.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return Qw("The provisioning attempt no longer exists.")}else if(e===Sr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return iB();let c;if(a.sendTest===!0)if(!g?.bots?.some(d=>d?.botId===a.botId&&d?.connected===!0)||typeof n.sendConnectionTest!="function")c=ir(Ir("\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=ir()}catch(d){c=ir(d)}s=await Jd({...g,...c?{testMessage:c}:{}},i)}else if(e===Sr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await Jd(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===Sr.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>Jd(g,i))}else if(e===Sr.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await Jd(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else s=await Jd(await n.deleteBot(a.botId),i);return A?.aborted?iB():{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?iB():g?{ok:!1,error:g}:JLe()}}}function mw(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(KZ,jZ(t,o),{authority:hr(i)})}async function JZ(n,t={}){if(t?.controller)return mw(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await PG(n,t,t.internals),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=mw(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-weixin: close account connections"),e}import{rm as uZe,unlink as BZe}from"node:fs/promises";import{homedir as fZe}from"node:os";import{join as uE,resolve as Xg}from"node:path";import{createHash as VLe}from"node:crypto";import{mkdir as WLe,readFile as ZLe,rename as XLe,unlink as $Le,writeFile as e2e}from"node:fs/promises";import{dirname as A2e}from"node:path";var GG=Object.freeze({version:2,bots:Object.freeze([])}),qZ=/^whatsapp_[a-f0-9]{24}$/,t2e=/^[a-f0-9-]{36}$/,r2e=/^[1-9]\d{4,14}$/,zd=Object.freeze({selfOnly:"self-only",privateAllowlist:"private-allowlist",open:"open"});function qd(n){return typeof n=="string"&&n.trim()?n.trim():null}function Sw(n){let t=qd(n)?.toLowerCase();return/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(t??"")?t:null}function FG(n){let t=Sw(n);if(!t)throw new TypeError("A valid WhatsApp account JID is required");return`whatsapp_${VLe("sha256").update(t).digest("hex").slice(0,24)}`}function LG(n){let t=Sw(n)?.split("@")[0]??"";return t?t.length<=7?`${t.slice(0,2)}\u2022\u2022\u2022${t.slice(-2)}`:`${t.slice(0,4)}\u2022\u2022\u2022\u2022${t.slice(-4)}`:w("WhatsApp\u8D26\u53F7")}function a2e(n){if(n===void 0)return Object.freeze([]);if(!Array.isArray(n))throw new TypeError("allowedNumbers must be an array of WhatsApp phone numbers");let t=n.map(o=>{let i=typeof o=="string"?o.trim().replace(/^\+/,""):"";if(!r2e.test(i))throw new TypeError("allowedNumbers contains an invalid WhatsApp phone number");return i});return Object.freeze([...new Set(t)])}function wg(n={}){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("WhatsApp access policy must be an object");let t=n.accessMode??zd.selfOnly;if(!Object.values(zd).includes(t))throw new TypeError("WhatsApp accessMode is invalid");return Object.freeze({accessMode:t,allowedNumbers:a2e(n.allowedNumbers)})}var ww=class{#e;#A=GG;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=this.#g(JSON.parse(await ZLe(this.#e,"utf8")));if(!t)throw new Error("dsh-im WhatsApp config contains invalid account data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=GG}return this}list(){return structuredClone(this.#A.bots)}get(t){let o=this.#A.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByAccountJid(t){let o=Sw(t),i=this.#A.bots.find(e=>e.accountJid===o);return i?structuredClone(i):null}async save(t){let o=this.#r(t);if(!o)throw new Error("Refusing to persist incomplete WhatsApp account data");return this.#a(i=>{let e=i.find(r=>r.accountJid===o.accountJid&&r.botId!==o.botId),a=i.find(r=>r.authDirectory===o.authDirectory&&r.botId!==o.botId);if(e||a)throw new Error("Duplicate WhatsApp account identity");let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!qZ.test(t))throw new TypeError("Invalid WhatsApp bot id");return this.#a(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await $Le(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=GG});this.#t=t.then(()=>{},()=>{}),await t}#r(t){if(!t||typeof t!="object")return null;let o=Sw(t.accountJid),i=qd(t.botId),e=qd(t.authDirectory),a=qd(t.name);if(!o||!i||!e||!a||!qZ.test(i)||!t2e.test(e)||FG(o)!==i)return null;let A;try{A=wg(t)}catch{return null}return Object.freeze({botId:i,accountJid:o,authDirectory:e,name:a,createdAt:qd(t.createdAt)??new Date().toISOString(),connectedAt:qd(t.connectedAt),...A})}#g(t){if(!t||t.version!==2||!Array.isArray(t.bots))return null;let o=t.bots.map(A=>this.#r(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.accountJid)||a.has(A.authDirectory))return null;i.add(A.botId),e.add(A.accountJid),a.add(A.authDirectory)}return Object.freeze({version:2,bots:Object.freeze(o)})}async#a(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:2,bots:Object.freeze(e)});await this.#n(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#n(t){await WLe(A2e(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await e2e(o,`${JSON.stringify(t,null,2)} -`,{encoding:"utf8",mode:384}),await XLe(o,this.#e)}};var Dw=class extends lr{constructor(t){super({...t,rpcIdPrefix:"whatsapp",logPrefix:"dsh-whatsapp"})}};var Ow=class extends As{};import{randomUUID as i2e}from"node:crypto";var zZ=new Set(["starting","pending","connecting"]),bw=new Set(["connected","failed","cancelled"]),o2e=6e4;function Nc(n,t){return Object.freeze({code:n,message:t})}function Mw(n){return n?{attemptId:n.id,status:n.state,qrRevision:n.qrRevision,pollIntervalMs:1e3,...n.qrValue?{qrValue:n.qrValue}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.botId?{botId:n.botId}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}var oB=class{#e;#A;#t;#r;#g;#a;#n;#i=new Map;#I=new Map;#l=new Map;#o=new Map;#s=null;#c=0;#p=!1;constructor({configStore:t,authPath:o,createSession:i,createRuntime:e,deleteAuth:a=async()=>{},deleteState:A=async()=>{},logger:r=console}){if(!t||typeof t.list!="function"||typeof t.save!="function"||typeof t.remove!="function")throw new TypeError("WhatsappController requires a config store");if(typeof o!="function"||typeof i!="function"||typeof e!="function")throw new TypeError("WhatsappController dependencies are incomplete");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r}async initialize(){if(this.#p)return this.status();for(let t of this.#e.list())await this.#f(t.botId,async()=>{if(!(this.#p||this.#i.get(t.botId)?.status?.ready))try{await this.#E(t),this.#I.delete(t.botId)}catch(o){this.#I.set(t.botId,Nc(o?.code==="relink-required"?"relink-required":"connection-failed",o?.code==="relink-required"?w("WhatsApp \u5173\u8054\u8BBE\u5907\u5DF2\u5931\u6548\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002"):w("WhatsApp \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"))),this.#n.warn?.(`[dsh-im:whatsapp] bot ${t.botId} failed to initialize`)}finally{this.#B()}});return this.status()}async startProvisioning(){if(this.#p)throw new Error("WhatsApp controller is closed");this.#s&&await this.cancelProvisioning(this.#s);let t,o,i=!1,e=new Promise((r,s)=>{t=()=>{i||(i=!0,r())},o=g=>{i||(i=!0,s(g))}}),a=i2e(),A={id:a,state:"starting",authDirectory:a,createdAt:Date.now(),expiresAt:null,qrRevision:0,qrValue:null,controller:new AbortController,session:null,task:null,error:null,botId:null};this.#l.set(a,A),this.#s=a,this.#B();try{let r=await this.#t({authDir:this.#A(A.authDirectory),signal:A.controller.signal,logger:this.#n,onQr:s=>{A.controller.signal.aborted||bw.has(A.state)||typeof s!="string"||!s||(A.qrValue=s,A.qrRevision+=1,A.expiresAt=Date.now()+o2e,A.state="pending",this.#B(),t())}});return A.session=r,A.task=r.ready.then(s=>this.#d(A,s)).catch(s=>this.#h(A,s,o)),await e,Mw(A)}catch(r){throw await this.#h(A,r,o),r}}registrationStatus(t){return Mw(this.#l.get(t))}async cancelProvisioning(t){let o=this.#l.get(t);return o?(bw.has(o.state)||(o.controller.abort(),await o.session?.close().catch(()=>{}),await o.task?.catch(()=>{}),bw.has(o.state)||(o.state="cancelled",o.error=Nc("cancelled",w("\u626B\u7801\u63A5\u5165\u5DF2\u53D6\u6D88\u3002"))),await this.#g(o.authDirectory).catch(()=>{})),this.#s===o.id&&(this.#s=null),this.#B(),Mw(o)):null}async reconnectBot(t){let o=this.#e.get(t);if(!o)throw new Error("Unknown WhatsApp bot");return await this.#f(t,async()=>{try{await this.#E(o),this.#I.delete(t)}catch(i){throw this.#I.set(t,Nc(i?.code==="relink-required"?"relink-required":"connection-failed",i?.code==="relink-required"?w("WhatsApp \u5173\u8054\u8BBE\u5907\u5DF2\u5931\u6548\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002"):w("WhatsApp \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),i}finally{this.#B()}}),this.status()}async sendConnectionTest(t){let o=this.#e.get(t);if(!o)throw new Error("Unknown WhatsApp bot");return this.#f(t,async()=>{let i=this.#i.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw e.code="test-target-unavailable",e}return i.sendConnectionTest(ba(`${o.name}\uFF08${LG(o.accountJid)}\uFF09`,w("WhatsApp\u673A\u5668\u4EBA")))})}async sendProactiveText(t,o,i,e={}){if(!this.#e.get(t))throw new Error("Unknown WhatsApp bot");return this.#f(t,async()=>{let A=this.#i.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async setAccessPolicy(t,o){if(this.#p)throw new Error("WhatsApp controller is closed");let i=wg(o);return await this.#f(t,async()=>{if(this.#p)throw new Error("WhatsApp controller is closed");let e=this.#e.get(t);if(!e)throw new Error("Unknown WhatsApp bot");let a=await this.#e.save({...e,...i});this.#i.get(t)?.setAccessPolicy?.(a),this.#B()}),this.status()}async deleteBot(t){let o=this.#e.get(t);if(!o)throw new Error("Unknown WhatsApp bot");return await this.#f(t,async()=>{await this.#C(t);try{await this.#e.remove(t)}catch(i){throw await this.#E(o).catch(()=>{}),i}await Promise.allSettled([this.#g(o.authDirectory),this.#a({botId:t,config:o})]),this.#I.delete(t),this.#B()}),this.status()}status(){let t=this.#e.list().map(e=>{let a=this.#i.get(e.botId)?.status??null,A=a?.ready===!0&&a.connectionState==="connected"&&a.harnessReachable===!0,r=A?"connected":a?.connectionState==="connecting"?"connecting":this.#I.has(e.botId)||a?.connectionState==="failed"?"error":"offline";return{botId:e.botId,state:r,connected:A,configured:!0,bot:{name:e.name,idMasked:LG(e.accountJid)},health:{status:A?"healthy":r==="error"?"error":"offline",summary:A?w("WhatsApp Web \u5173\u8054\u8BBE\u5907\u8FD0\u884C\u6B63\u5E38"):r==="error"?w("WhatsApp \u8FDE\u63A5\u672A\u5C31\u7EEA"):w("WhatsApp \u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},lastMessageError:Vr(a?.lastMessageError),accessPolicy:wg(e),error:structuredClone(this.#I.get(e.botId)??null)}}),o=t.filter(e=>e.connected).length,i=this.#s?this.#l.get(this.#s):null;return{schemaVersion:1,revision:this.#c,state:i&&zZ.has(i.state)?"provisioning":t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o},...i&&zZ.has(i.state)?{provisioning:Mw(i)}:{}}}async close(){this.#p||(this.#p=!0,this.#s&&await this.cancelProvisioning(this.#s),await Promise.allSettled([...this.#o.values()]),await Promise.allSettled([...this.#i.keys()].map(t=>this.#C(t))))}async#d(t,o){if(t.controller.signal.aborted||this.#p)return;t.state="connecting",t.qrValue=null,t.expiresAt=null,this.#B();let i=FG(o.accountJid);t.botId=i,await t.session?.close();let e=this.#e.get(i),a={botId:i,accountJid:o.accountJid,authDirectory:t.authDirectory,name:o.name,createdAt:e?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString(),accessMode:e?.accessMode,allowedNumbers:e?.allowedNumbers};try{if(t.controller.signal.aborted||this.#p)throw Object.assign(new Error,{name:"AbortError"});if(await this.#e.save(a),t.controller.signal.aborted||this.#p)throw Object.assign(new Error,{name:"AbortError"});try{await this.#E(a),this.#I.delete(i)}catch{this.#I.set(i,Nc("connection-failed",w("WhatsApp \u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#n.warn?.(`[dsh-im:whatsapp] bot ${i} did not reconnect after QR binding`)}e?.authDirectory&&e.authDirectory!==a.authDirectory&&await this.#g(e.authDirectory).catch(()=>{}),t.state="connected",t.error=null}catch(A){t.controller.signal.aborted||this.#p||A?.name==="AbortError"?(await this.#C(i),e?await this.#e.save(e).catch(()=>{}):await this.#e.remove(i).catch(()=>null)&&await this.#a({botId:i,config:a}).catch(s=>{this.#n.warn?.("[dsh-im:whatsapp] cancelled bot state cleanup failed:",s)}),await this.#g(t.authDirectory).catch(()=>{}),e&&await this.#E(e).catch(()=>{}),t.state="cancelled",t.error=Nc("cancelled",w("\u626B\u7801\u63A5\u5165\u5DF2\u53D6\u6D88\u3002"))):(await this.#g(t.authDirectory).catch(()=>{}),t.state="failed",t.error=Nc("activation-failed",w("WhatsApp \u5DF2\u626B\u7801\uFF0C\u4F46\u65E0\u6CD5\u4FDD\u5B58\u5173\u8054\u8BBE\u5907\u3002")),this.#n.error?.("[dsh-im:whatsapp] unable to persist linked-device session"))}finally{this.#s===t.id&&(this.#s=null),this.#B()}}async#h(t,o,i=()=>{}){bw.has(t.state)||(t.controller.signal.aborted||o?.name==="AbortError"?(t.state="cancelled",t.error=Nc("cancelled",w("\u626B\u7801\u63A5\u5165\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=Nc("qr-connect-failed",w("\u65E0\u6CD5\u8FDE\u63A5 WhatsApp\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"))),this.#s===t.id&&(this.#s=null),await t.session?.close().catch(()=>{}),await this.#g(t.authDirectory).catch(()=>{}),this.#B(),i(o))}async#E(t){if(this.#p)throw new Error("WhatsApp controller is closed");if(await this.#C(t.botId),this.#p)throw new Error("WhatsApp controller is closed");let o=await this.#r({botId:t.botId,config:t,authDir:this.#A(t.authDirectory)});if(!o||typeof o.start!="function"||typeof o.stop!="function")throw new TypeError("createRuntime returned an invalid WhatsApp runtime");this.#i.set(t.botId,o);try{await o.start()}catch(i){throw await o.stop().catch(()=>{}),this.#i.delete(t.botId),i}}async#C(t){let o=this.#i.get(t);this.#i.delete(t),await o?.stop().catch(()=>{})}#f(t,o){let a=(this.#o.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#o.get(t)===a&&this.#o.delete(t)});return this.#o.set(t,a),a}#B(){this.#c+=1}};import{createHash as tZe,randomBytes as Fce}from"node:crypto";var v=Je(Sm(),1),D=v.default.Reader,G=v.default.Writer,l=v.default.util,p=v.default.roots.default||(v.default.roots.default={});function se(n,t){if(typeof n=="string")return n;if(typeof n=="number")return String(n);if(n&&typeof n.low=="number"&&typeof n.high=="number"){let o=BigInt(n.low>>>0),e=BigInt(n.high>>>0)<<32n|o;return!t&&n.high<0?(e-(1n<<64n)).toString():e.toString()}return String(n)}function ge(n,t){if(typeof n=="number")return n;if(typeof n=="string")return Number(n);if(n&&typeof n.low=="number"&&typeof n.high=="number"){let o=BigInt(n.low>>>0),e=BigInt(n.high>>>0)<<32n|o;return!t&&n.high<0?Number(e-(1n<<64n)):Number(e)}return Number(n)}var oe=p.proto=(()=>{let n={};return n.ADVDeviceIdentity=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.rawId=e.uint32();break}case 2:{s.timestamp=e.uint64();break}case 3:{s.keyIndex=e.uint32();break}case 4:{s.accountType=e.int32();break}case 5:{s.deviceType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ADVDeviceIdentity)return e;var a=new p.proto.ADVDeviceIdentity;switch(e.rawId!=null&&(a.rawId=e.rawId>>>0),e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!0:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber(!0))),e.keyIndex!=null&&(a.keyIndex=e.keyIndex>>>0),e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"E2EE":case 0:a.accountType=0;break;case"HOSTED":case 1:a.accountType=1;break}switch(e.deviceType){default:if(typeof e.deviceType=="number"){a.deviceType=e.deviceType;break}break;case"E2EE":case 0:a.deviceType=0;break;case"HOSTED":case 1:a.deviceType=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.rawId!=null&&e.hasOwnProperty("rawId")&&(A.rawId=e.rawId,a.oneofs&&(A._rawId="rawId")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp,!0):a.longs===Number?ge(e.timestamp,!0):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),e.keyIndex!=null&&e.hasOwnProperty("keyIndex")&&(A.keyIndex=e.keyIndex,a.oneofs&&(A._keyIndex="keyIndex")),e.accountType!=null&&e.hasOwnProperty("accountType")&&(A.accountType=a.enums===String?p.proto.ADVEncryptionType[e.accountType]===void 0?e.accountType:p.proto.ADVEncryptionType[e.accountType]:e.accountType,a.oneofs&&(A._accountType="accountType")),e.deviceType!=null&&e.hasOwnProperty("deviceType")&&(A.deviceType=a.enums===String?p.proto.ADVEncryptionType[e.deviceType]===void 0?e.deviceType:p.proto.ADVEncryptionType[e.deviceType]:e.deviceType,a.oneofs&&(A._deviceType="deviceType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVDeviceIdentity"},t})(),n.ADVEncryptionType=(function(){let t={},o=Object.create(t);return o[t[0]="E2EE"]=0,o[t[1]="HOSTED"]=1,o})(),n.ADVKeyIndexList=(function(){function t(i){if(this.validIndexes=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.rawId=e.uint32();break}case 2:{s.timestamp=e.uint64();break}case 3:{s.currentIndex=e.uint32();break}case 4:{if(s.validIndexes&&s.validIndexes.length||(s.validIndexes=[]),(g&7)===2)for(var c=e.uint32()+e.pos;e.pos>>0),e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!0:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber(!0))),e.currentIndex!=null&&(a.currentIndex=e.currentIndex>>>0),e.validIndexes){if(!Array.isArray(e.validIndexes))throw TypeError(".proto.ADVKeyIndexList.validIndexes: array expected");a.validIndexes=[];for(var A=0;A>>0}switch(e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"E2EE":case 0:a.accountType=0;break;case"HOSTED":case 1:a.accountType=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.validIndexes=[]),e.rawId!=null&&e.hasOwnProperty("rawId")&&(A.rawId=e.rawId,a.oneofs&&(A._rawId="rawId")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp,!0):a.longs===Number?ge(e.timestamp,!0):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),e.currentIndex!=null&&e.hasOwnProperty("currentIndex")&&(A.currentIndex=e.currentIndex,a.oneofs&&(A._currentIndex="currentIndex")),e.validIndexes&&e.validIndexes.length){A.validIndexes=[];for(var r=0;r>>3){case 1:{s.details=e.bytes();break}case 2:{s.accountSignatureKey=e.bytes();break}case 3:{s.accountSignature=e.bytes();break}case 4:{s.deviceSignature=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ADVSignedDeviceIdentity)return e;var a=new p.proto.ADVSignedDeviceIdentity;return e.details!=null&&(typeof e.details=="string"?l.base64.decode(e.details,a.details=l.newBuffer(l.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.accountSignatureKey!=null&&(typeof e.accountSignatureKey=="string"?l.base64.decode(e.accountSignatureKey,a.accountSignatureKey=l.newBuffer(l.base64.length(e.accountSignatureKey)),0):e.accountSignatureKey.length>=0&&(a.accountSignatureKey=e.accountSignatureKey)),e.accountSignature!=null&&(typeof e.accountSignature=="string"?l.base64.decode(e.accountSignature,a.accountSignature=l.newBuffer(l.base64.length(e.accountSignature)),0):e.accountSignature.length>=0&&(a.accountSignature=e.accountSignature)),e.deviceSignature!=null&&(typeof e.deviceSignature=="string"?l.base64.decode(e.deviceSignature,a.deviceSignature=l.newBuffer(l.base64.length(e.deviceSignature)),0):e.deviceSignature.length>=0&&(a.deviceSignature=e.deviceSignature)),a},t.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?l.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.accountSignatureKey!=null&&e.hasOwnProperty("accountSignatureKey")&&(A.accountSignatureKey=a.bytes===String?l.base64.encode(e.accountSignatureKey,0,e.accountSignatureKey.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignatureKey):e.accountSignatureKey,a.oneofs&&(A._accountSignatureKey="accountSignatureKey")),e.accountSignature!=null&&e.hasOwnProperty("accountSignature")&&(A.accountSignature=a.bytes===String?l.base64.encode(e.accountSignature,0,e.accountSignature.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignature):e.accountSignature,a.oneofs&&(A._accountSignature="accountSignature")),e.deviceSignature!=null&&e.hasOwnProperty("deviceSignature")&&(A.deviceSignature=a.bytes===String?l.base64.encode(e.deviceSignature,0,e.deviceSignature.length):a.bytes===Array?Array.prototype.slice.call(e.deviceSignature):e.deviceSignature,a.oneofs&&(A._deviceSignature="deviceSignature")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVSignedDeviceIdentity"},t})(),n.ADVSignedDeviceIdentityHMAC=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.details=e.bytes();break}case 2:{s.hmac=e.bytes();break}case 3:{s.accountType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ADVSignedDeviceIdentityHMAC)return e;var a=new p.proto.ADVSignedDeviceIdentityHMAC;switch(e.details!=null&&(typeof e.details=="string"?l.base64.decode(e.details,a.details=l.newBuffer(l.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.hmac!=null&&(typeof e.hmac=="string"?l.base64.decode(e.hmac,a.hmac=l.newBuffer(l.base64.length(e.hmac)),0):e.hmac.length>=0&&(a.hmac=e.hmac)),e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"E2EE":case 0:a.accountType=0;break;case"HOSTED":case 1:a.accountType=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?l.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.hmac!=null&&e.hasOwnProperty("hmac")&&(A.hmac=a.bytes===String?l.base64.encode(e.hmac,0,e.hmac.length):a.bytes===Array?Array.prototype.slice.call(e.hmac):e.hmac,a.oneofs&&(A._hmac="hmac")),e.accountType!=null&&e.hasOwnProperty("accountType")&&(A.accountType=a.enums===String?p.proto.ADVEncryptionType[e.accountType]===void 0?e.accountType:p.proto.ADVEncryptionType[e.accountType]:e.accountType,a.oneofs&&(A._accountType="accountType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVSignedDeviceIdentityHMAC"},t})(),n.ADVSignedKeyIndexList=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.details=e.bytes();break}case 2:{s.accountSignature=e.bytes();break}case 3:{s.accountSignatureKey=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ADVSignedKeyIndexList)return e;var a=new p.proto.ADVSignedKeyIndexList;return e.details!=null&&(typeof e.details=="string"?l.base64.decode(e.details,a.details=l.newBuffer(l.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.accountSignature!=null&&(typeof e.accountSignature=="string"?l.base64.decode(e.accountSignature,a.accountSignature=l.newBuffer(l.base64.length(e.accountSignature)),0):e.accountSignature.length>=0&&(a.accountSignature=e.accountSignature)),e.accountSignatureKey!=null&&(typeof e.accountSignatureKey=="string"?l.base64.decode(e.accountSignatureKey,a.accountSignatureKey=l.newBuffer(l.base64.length(e.accountSignatureKey)),0):e.accountSignatureKey.length>=0&&(a.accountSignatureKey=e.accountSignatureKey)),a},t.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?l.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.accountSignature!=null&&e.hasOwnProperty("accountSignature")&&(A.accountSignature=a.bytes===String?l.base64.encode(e.accountSignature,0,e.accountSignature.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignature):e.accountSignature,a.oneofs&&(A._accountSignature="accountSignature")),e.accountSignatureKey!=null&&e.hasOwnProperty("accountSignatureKey")&&(A.accountSignatureKey=a.bytes===String?l.base64.encode(e.accountSignatureKey,0,e.accountSignatureKey.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignatureKey):e.accountSignatureKey,a.oneofs&&(A._accountSignatureKey="accountSignatureKey")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVSignedKeyIndexList"},t})(),n.AIHomeState=(function(){function t(i){if(this.capabilityOptions=[],this.conversationOptions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lastFetchTime=e.int64();break}case 2:{s.capabilityOptions&&s.capabilityOptions.length||(s.capabilityOptions=[]),s.capabilityOptions.push(p.proto.AIHomeState.AIHomeOption.decode(e,e.uint32()));break}case 3:{s.conversationOptions&&s.conversationOptions.length||(s.conversationOptions=[]),s.conversationOptions.push(p.proto.AIHomeState.AIHomeOption.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIHomeState)return e;var a=new p.proto.AIHomeState;if(e.lastFetchTime!=null&&(l.Long?(a.lastFetchTime=l.Long.fromValue(e.lastFetchTime)).unsigned=!1:typeof e.lastFetchTime=="string"?a.lastFetchTime=parseInt(e.lastFetchTime,10):typeof e.lastFetchTime=="number"?a.lastFetchTime=e.lastFetchTime:typeof e.lastFetchTime=="object"&&(a.lastFetchTime=new l.LongBits(e.lastFetchTime.low>>>0,e.lastFetchTime.high>>>0).toNumber())),e.capabilityOptions){if(!Array.isArray(e.capabilityOptions))throw TypeError(".proto.AIHomeState.capabilityOptions: array expected");a.capabilityOptions=[];for(var A=0;A>>3){case 1:{c.type=A.int32();break}case 2:{c.title=A.string();break}case 3:{c.promptText=A.string();break}case 4:{c.sessionId=A.string();break}case 5:{c.imageWdsIdentifier=A.string();break}case 6:{c.imageTintColor=A.string();break}case 7:{c.imageBackgroundColor=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIHomeState.AIHomeOption)return A;var r=new p.proto.AIHomeState.AIHomeOption;switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"PROMPT":case 0:r.type=0;break;case"CREATE_IMAGE":case 1:r.type=1;break;case"ANIMATE_PHOTO":case 2:r.type=2;break;case"ANALYZE_FILE":case 3:r.type=3;break}return A.title!=null&&(r.title=String(A.title)),A.promptText!=null&&(r.promptText=String(A.promptText)),A.sessionId!=null&&(r.sessionId=String(A.sessionId)),A.imageWdsIdentifier!=null&&(r.imageWdsIdentifier=String(A.imageWdsIdentifier)),A.imageTintColor!=null&&(r.imageTintColor=String(A.imageTintColor)),A.imageBackgroundColor!=null&&(r.imageBackgroundColor=String(A.imageBackgroundColor)),r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.AIHomeState.AIHomeOption.AIHomeActionType[A.type]===void 0?A.type:p.proto.AIHomeState.AIHomeOption.AIHomeActionType[A.type]:A.type,r.oneofs&&(s._type="type")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.promptText!=null&&A.hasOwnProperty("promptText")&&(s.promptText=A.promptText,r.oneofs&&(s._promptText="promptText")),A.sessionId!=null&&A.hasOwnProperty("sessionId")&&(s.sessionId=A.sessionId,r.oneofs&&(s._sessionId="sessionId")),A.imageWdsIdentifier!=null&&A.hasOwnProperty("imageWdsIdentifier")&&(s.imageWdsIdentifier=A.imageWdsIdentifier,r.oneofs&&(s._imageWdsIdentifier="imageWdsIdentifier")),A.imageTintColor!=null&&A.hasOwnProperty("imageTintColor")&&(s.imageTintColor=A.imageTintColor,r.oneofs&&(s._imageTintColor="imageTintColor")),A.imageBackgroundColor!=null&&A.hasOwnProperty("imageBackgroundColor")&&(s.imageBackgroundColor=A.imageBackgroundColor,r.oneofs&&(s._imageBackgroundColor="imageBackgroundColor")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIHomeState.AIHomeOption"},i.AIHomeActionType=(function(){let a={},A=Object.create(a);return A[a[0]="PROMPT"]=0,A[a[1]="CREATE_IMAGE"]=1,A[a[2]="ANIMATE_PHOTO"]=2,A[a[3]="ANALYZE_FILE"]=3,A})(),i})(),t})(),n.AIQueryFanout=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.message=p.proto.Message.decode(e,e.uint32());break}case 3:{s.timestamp=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIQueryFanout)return e;var a=new p.proto.AIQueryFanout;if(e.messageKey!=null){if(typeof e.messageKey!="object")throw TypeError(".proto.AIQueryFanout.messageKey: object expected");a.messageKey=p.proto.MessageKey.fromObject(e.messageKey)}if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.AIQueryFanout.message: object expected");a.message=p.proto.Message.fromObject(e.message)}return e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.messageKey!=null&&e.hasOwnProperty("messageKey")&&(A.messageKey=p.proto.MessageKey.toObject(e.messageKey,a),a.oneofs&&(A._messageKey="messageKey")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=p.proto.Message.toObject(e.message,a),a.oneofs&&(A._message="message")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp):a.longs===Number?ge(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIQueryFanout"},t})(),n.AIRegenerateMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.responseTimestampMs=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRegenerateMetadata)return e;var a=new p.proto.AIRegenerateMetadata;if(e.messageKey!=null){if(typeof e.messageKey!="object")throw TypeError(".proto.AIRegenerateMetadata.messageKey: object expected");a.messageKey=p.proto.MessageKey.fromObject(e.messageKey)}return e.responseTimestampMs!=null&&(l.Long?(a.responseTimestampMs=l.Long.fromValue(e.responseTimestampMs)).unsigned=!1:typeof e.responseTimestampMs=="string"?a.responseTimestampMs=parseInt(e.responseTimestampMs,10):typeof e.responseTimestampMs=="number"?a.responseTimestampMs=e.responseTimestampMs:typeof e.responseTimestampMs=="object"&&(a.responseTimestampMs=new l.LongBits(e.responseTimestampMs.low>>>0,e.responseTimestampMs.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.messageKey!=null&&e.hasOwnProperty("messageKey")&&(A.messageKey=p.proto.MessageKey.toObject(e.messageKey,a),a.oneofs&&(A._messageKey="messageKey")),e.responseTimestampMs!=null&&e.hasOwnProperty("responseTimestampMs")&&(typeof e.responseTimestampMs=="number"?A.responseTimestampMs=a.longs===String?String(e.responseTimestampMs):e.responseTimestampMs:A.responseTimestampMs=a.longs===String?se(e.responseTimestampMs):a.longs===Number?ge(e.responseTimestampMs):e.responseTimestampMs,a.oneofs&&(A._responseTimestampMs="responseTimestampMs")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRegenerateMetadata"},t})(),n.AIRichResponseCodeMetadata=(function(){function t(i){if(this.codeBlocks=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.codeLanguage=e.string();break}case 2:{s.codeBlocks&&s.codeBlocks.length||(s.codeBlocks=[]),s.codeBlocks.push(p.proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseCodeMetadata)return e;var a=new p.proto.AIRichResponseCodeMetadata;if(e.codeLanguage!=null&&(a.codeLanguage=String(e.codeLanguage)),e.codeBlocks){if(!Array.isArray(e.codeBlocks))throw TypeError(".proto.AIRichResponseCodeMetadata.codeBlocks: array expected");a.codeBlocks=[];for(var A=0;A>>3){case 1:{c.highlightType=A.int32();break}case 2:{c.codeContent=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock)return A;var r=new p.proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock;switch(A.highlightType){default:if(typeof A.highlightType=="number"){r.highlightType=A.highlightType;break}break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_DEFAULT":case 0:r.highlightType=0;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_KEYWORD":case 1:r.highlightType=1;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_METHOD":case 2:r.highlightType=2;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_STRING":case 3:r.highlightType=3;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_NUMBER":case 4:r.highlightType=4;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_COMMENT":case 5:r.highlightType=5;break}return A.codeContent!=null&&(r.codeContent=String(A.codeContent)),r},i.toObject=function(A,r){r||(r={});var s={};return A.highlightType!=null&&A.hasOwnProperty("highlightType")&&(s.highlightType=r.enums===String?p.proto.AIRichResponseCodeMetadata.AIRichResponseCodeHighlightType[A.highlightType]===void 0?A.highlightType:p.proto.AIRichResponseCodeMetadata.AIRichResponseCodeHighlightType[A.highlightType]:A.highlightType,r.oneofs&&(s._highlightType="highlightType")),A.codeContent!=null&&A.hasOwnProperty("codeContent")&&(s.codeContent=A.codeContent,r.oneofs&&(s._codeContent="codeContent")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock"},i})(),t.AIRichResponseCodeHighlightType=(function(){let i={},e=Object.create(i);return e[i[0]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_DEFAULT"]=0,e[i[1]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_KEYWORD"]=1,e[i[2]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_METHOD"]=2,e[i[3]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_STRING"]=3,e[i[4]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_NUMBER"]=4,e[i[5]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_COMMENT"]=5,e})(),t})(),n.AIRichResponseContentItemsMetadata=(function(){function t(i){if(this.itemsMetadata=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.itemsMetadata&&s.itemsMetadata.length||(s.itemsMetadata=[]),s.itemsMetadata.push(p.proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata.decode(e,e.uint32()));break}case 2:{s.contentType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseContentItemsMetadata)return e;var a=new p.proto.AIRichResponseContentItemsMetadata;if(e.itemsMetadata){if(!Array.isArray(e.itemsMetadata))throw TypeError(".proto.AIRichResponseContentItemsMetadata.itemsMetadata: array expected");a.itemsMetadata=[];for(var A=0;A>>3){case 1:{c.reelItem=p.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata)return A;var r=new p.proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata;if(A.reelItem!=null){if(typeof A.reelItem!="object")throw TypeError(".proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata.reelItem: object expected");r.reelItem=p.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem.fromObject(A.reelItem)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.reelItem!=null&&A.hasOwnProperty("reelItem")&&(s.reelItem=p.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem.toObject(A.reelItem,r),r.oneofs&&(s.aIRichResponseContentItem="reelItem")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata"},i})(),t.AIRichResponseReelItem=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.title=A.string();break}case 2:{c.profileIconUrl=A.string();break}case 3:{c.thumbnailUrl=A.string();break}case 4:{c.videoUrl=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem)return A;var r=new p.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem;return A.title!=null&&(r.title=String(A.title)),A.profileIconUrl!=null&&(r.profileIconUrl=String(A.profileIconUrl)),A.thumbnailUrl!=null&&(r.thumbnailUrl=String(A.thumbnailUrl)),A.videoUrl!=null&&(r.videoUrl=String(A.videoUrl)),r},i.toObject=function(A,r){r||(r={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.profileIconUrl!=null&&A.hasOwnProperty("profileIconUrl")&&(s.profileIconUrl=A.profileIconUrl,r.oneofs&&(s._profileIconUrl="profileIconUrl")),A.thumbnailUrl!=null&&A.hasOwnProperty("thumbnailUrl")&&(s.thumbnailUrl=A.thumbnailUrl,r.oneofs&&(s._thumbnailUrl="thumbnailUrl")),A.videoUrl!=null&&A.hasOwnProperty("videoUrl")&&(s.videoUrl=A.videoUrl,r.oneofs&&(s._videoUrl="videoUrl")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem"},i})(),t.ContentType=(function(){let i={},e=Object.create(i);return e[i[0]="DEFAULT"]=0,e[i[1]="CAROUSEL"]=1,e})(),t})(),n.AIRichResponseDynamicMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}case 2:{s.version=e.uint64();break}case 3:{s.url=e.string();break}case 4:{s.loopCount=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseDynamicMetadata)return e;var a=new p.proto.AIRichResponseDynamicMetadata;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_UNKNOWN":case 0:a.type=0;break;case"AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE":case 1:a.type=1;break;case"AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF":case 2:a.type=2;break}return e.version!=null&&(l.Long?(a.version=l.Long.fromValue(e.version)).unsigned=!0:typeof e.version=="string"?a.version=parseInt(e.version,10):typeof e.version=="number"?a.version=e.version:typeof e.version=="object"&&(a.version=new l.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber(!0))),e.url!=null&&(a.url=String(e.url)),e.loopCount!=null&&(a.loopCount=e.loopCount>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType[e.type]===void 0?e.type:p.proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType[e.type]:e.type,a.oneofs&&(A._type="type")),e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?A.version=a.longs===String?String(e.version):e.version:A.version=a.longs===String?se(e.version,!0):a.longs===Number?ge(e.version,!0):e.version,a.oneofs&&(A._version="version")),e.url!=null&&e.hasOwnProperty("url")&&(A.url=e.url,a.oneofs&&(A._url="url")),e.loopCount!=null&&e.hasOwnProperty("loopCount")&&(A.loopCount=e.loopCount,a.oneofs&&(A._loopCount="loopCount")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseDynamicMetadata"},t.AIRichResponseDynamicMetadataType=(function(){let i={},e=Object.create(i);return e[i[0]="AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_UNKNOWN"]=0,e[i[1]="AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE"]=1,e[i[2]="AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF"]=2,e})(),t})(),n.AIRichResponseGridImageMetadata=(function(){function t(i){if(this.imageUrls=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.gridImageUrl=p.proto.AIRichResponseImageURL.decode(e,e.uint32());break}case 2:{s.imageUrls&&s.imageUrls.length||(s.imageUrls=[]),s.imageUrls.push(p.proto.AIRichResponseImageURL.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseGridImageMetadata)return e;var a=new p.proto.AIRichResponseGridImageMetadata;if(e.gridImageUrl!=null){if(typeof e.gridImageUrl!="object")throw TypeError(".proto.AIRichResponseGridImageMetadata.gridImageUrl: object expected");a.gridImageUrl=p.proto.AIRichResponseImageURL.fromObject(e.gridImageUrl)}if(e.imageUrls){if(!Array.isArray(e.imageUrls))throw TypeError(".proto.AIRichResponseGridImageMetadata.imageUrls: array expected");a.imageUrls=[];for(var A=0;A>>3){case 1:{s.imagePreviewUrl=e.string();break}case 2:{s.imageHighResUrl=e.string();break}case 3:{s.sourceUrl=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseImageURL)return e;var a=new p.proto.AIRichResponseImageURL;return e.imagePreviewUrl!=null&&(a.imagePreviewUrl=String(e.imagePreviewUrl)),e.imageHighResUrl!=null&&(a.imageHighResUrl=String(e.imageHighResUrl)),e.sourceUrl!=null&&(a.sourceUrl=String(e.sourceUrl)),a},t.toObject=function(e,a){a||(a={});var A={};return e.imagePreviewUrl!=null&&e.hasOwnProperty("imagePreviewUrl")&&(A.imagePreviewUrl=e.imagePreviewUrl,a.oneofs&&(A._imagePreviewUrl="imagePreviewUrl")),e.imageHighResUrl!=null&&e.hasOwnProperty("imageHighResUrl")&&(A.imageHighResUrl=e.imageHighResUrl,a.oneofs&&(A._imageHighResUrl="imageHighResUrl")),e.sourceUrl!=null&&e.hasOwnProperty("sourceUrl")&&(A.sourceUrl=e.sourceUrl,a.oneofs&&(A._sourceUrl="sourceUrl")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseImageURL"},t})(),n.AIRichResponseInlineImageMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.imageUrl=p.proto.AIRichResponseImageURL.decode(e,e.uint32());break}case 2:{s.imageText=e.string();break}case 3:{s.alignment=e.int32();break}case 4:{s.tapLinkUrl=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseInlineImageMetadata)return e;var a=new p.proto.AIRichResponseInlineImageMetadata;if(e.imageUrl!=null){if(typeof e.imageUrl!="object")throw TypeError(".proto.AIRichResponseInlineImageMetadata.imageUrl: object expected");a.imageUrl=p.proto.AIRichResponseImageURL.fromObject(e.imageUrl)}switch(e.imageText!=null&&(a.imageText=String(e.imageText)),e.alignment){default:if(typeof e.alignment=="number"){a.alignment=e.alignment;break}break;case"AI_RICH_RESPONSE_IMAGE_LAYOUT_LEADING_ALIGNED":case 0:a.alignment=0;break;case"AI_RICH_RESPONSE_IMAGE_LAYOUT_TRAILING_ALIGNED":case 1:a.alignment=1;break;case"AI_RICH_RESPONSE_IMAGE_LAYOUT_CENTER_ALIGNED":case 2:a.alignment=2;break}return e.tapLinkUrl!=null&&(a.tapLinkUrl=String(e.tapLinkUrl)),a},t.toObject=function(e,a){a||(a={});var A={};return e.imageUrl!=null&&e.hasOwnProperty("imageUrl")&&(A.imageUrl=p.proto.AIRichResponseImageURL.toObject(e.imageUrl,a),a.oneofs&&(A._imageUrl="imageUrl")),e.imageText!=null&&e.hasOwnProperty("imageText")&&(A.imageText=e.imageText,a.oneofs&&(A._imageText="imageText")),e.alignment!=null&&e.hasOwnProperty("alignment")&&(A.alignment=a.enums===String?p.proto.AIRichResponseInlineImageMetadata.AIRichResponseImageAlignment[e.alignment]===void 0?e.alignment:p.proto.AIRichResponseInlineImageMetadata.AIRichResponseImageAlignment[e.alignment]:e.alignment,a.oneofs&&(A._alignment="alignment")),e.tapLinkUrl!=null&&e.hasOwnProperty("tapLinkUrl")&&(A.tapLinkUrl=e.tapLinkUrl,a.oneofs&&(A._tapLinkUrl="tapLinkUrl")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseInlineImageMetadata"},t.AIRichResponseImageAlignment=(function(){let i={},e=Object.create(i);return e[i[0]="AI_RICH_RESPONSE_IMAGE_LAYOUT_LEADING_ALIGNED"]=0,e[i[1]="AI_RICH_RESPONSE_IMAGE_LAYOUT_TRAILING_ALIGNED"]=1,e[i[2]="AI_RICH_RESPONSE_IMAGE_LAYOUT_CENTER_ALIGNED"]=2,e})(),t})(),n.AIRichResponseLatexMetadata=(function(){function t(i){if(this.expressions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.text=e.string();break}case 2:{s.expressions&&s.expressions.length||(s.expressions=[]),s.expressions.push(p.proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseLatexMetadata)return e;var a=new p.proto.AIRichResponseLatexMetadata;if(e.text!=null&&(a.text=String(e.text)),e.expressions){if(!Array.isArray(e.expressions))throw TypeError(".proto.AIRichResponseLatexMetadata.expressions: array expected");a.expressions=[];for(var A=0;A>>3){case 1:{c.latexExpression=A.string();break}case 2:{c.url=A.string();break}case 3:{c.width=A.double();break}case 4:{c.height=A.double();break}case 5:{c.fontHeight=A.double();break}case 6:{c.imageTopPadding=A.double();break}case 7:{c.imageLeadingPadding=A.double();break}case 8:{c.imageBottomPadding=A.double();break}case 9:{c.imageTrailingPadding=A.double();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression)return A;var r=new p.proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression;return A.latexExpression!=null&&(r.latexExpression=String(A.latexExpression)),A.url!=null&&(r.url=String(A.url)),A.width!=null&&(r.width=Number(A.width)),A.height!=null&&(r.height=Number(A.height)),A.fontHeight!=null&&(r.fontHeight=Number(A.fontHeight)),A.imageTopPadding!=null&&(r.imageTopPadding=Number(A.imageTopPadding)),A.imageLeadingPadding!=null&&(r.imageLeadingPadding=Number(A.imageLeadingPadding)),A.imageBottomPadding!=null&&(r.imageBottomPadding=Number(A.imageBottomPadding)),A.imageTrailingPadding!=null&&(r.imageTrailingPadding=Number(A.imageTrailingPadding)),r},i.toObject=function(A,r){r||(r={});var s={};return A.latexExpression!=null&&A.hasOwnProperty("latexExpression")&&(s.latexExpression=A.latexExpression,r.oneofs&&(s._latexExpression="latexExpression")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=r.json&&!isFinite(A.width)?String(A.width):A.width,r.oneofs&&(s._width="width")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=r.json&&!isFinite(A.height)?String(A.height):A.height,r.oneofs&&(s._height="height")),A.fontHeight!=null&&A.hasOwnProperty("fontHeight")&&(s.fontHeight=r.json&&!isFinite(A.fontHeight)?String(A.fontHeight):A.fontHeight,r.oneofs&&(s._fontHeight="fontHeight")),A.imageTopPadding!=null&&A.hasOwnProperty("imageTopPadding")&&(s.imageTopPadding=r.json&&!isFinite(A.imageTopPadding)?String(A.imageTopPadding):A.imageTopPadding,r.oneofs&&(s._imageTopPadding="imageTopPadding")),A.imageLeadingPadding!=null&&A.hasOwnProperty("imageLeadingPadding")&&(s.imageLeadingPadding=r.json&&!isFinite(A.imageLeadingPadding)?String(A.imageLeadingPadding):A.imageLeadingPadding,r.oneofs&&(s._imageLeadingPadding="imageLeadingPadding")),A.imageBottomPadding!=null&&A.hasOwnProperty("imageBottomPadding")&&(s.imageBottomPadding=r.json&&!isFinite(A.imageBottomPadding)?String(A.imageBottomPadding):A.imageBottomPadding,r.oneofs&&(s._imageBottomPadding="imageBottomPadding")),A.imageTrailingPadding!=null&&A.hasOwnProperty("imageTrailingPadding")&&(s.imageTrailingPadding=r.json&&!isFinite(A.imageTrailingPadding)?String(A.imageTrailingPadding):A.imageTrailingPadding,r.oneofs&&(s._imageTrailingPadding="imageTrailingPadding")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression"},i})(),t})(),n.AIRichResponseMapMetadata=(function(){function t(i){if(this.annotations=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.centerLatitude=e.double();break}case 2:{s.centerLongitude=e.double();break}case 3:{s.latitudeDelta=e.double();break}case 4:{s.longitudeDelta=e.double();break}case 5:{s.annotations&&s.annotations.length||(s.annotations=[]),s.annotations.push(p.proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation.decode(e,e.uint32()));break}case 6:{s.showInfoList=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseMapMetadata)return e;var a=new p.proto.AIRichResponseMapMetadata;if(e.centerLatitude!=null&&(a.centerLatitude=Number(e.centerLatitude)),e.centerLongitude!=null&&(a.centerLongitude=Number(e.centerLongitude)),e.latitudeDelta!=null&&(a.latitudeDelta=Number(e.latitudeDelta)),e.longitudeDelta!=null&&(a.longitudeDelta=Number(e.longitudeDelta)),e.annotations){if(!Array.isArray(e.annotations))throw TypeError(".proto.AIRichResponseMapMetadata.annotations: array expected");a.annotations=[];for(var A=0;A>>3){case 1:{c.annotationNumber=A.uint32();break}case 2:{c.latitude=A.double();break}case 3:{c.longitude=A.double();break}case 4:{c.title=A.string();break}case 5:{c.body=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation)return A;var r=new p.proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation;return A.annotationNumber!=null&&(r.annotationNumber=A.annotationNumber>>>0),A.latitude!=null&&(r.latitude=Number(A.latitude)),A.longitude!=null&&(r.longitude=Number(A.longitude)),A.title!=null&&(r.title=String(A.title)),A.body!=null&&(r.body=String(A.body)),r},i.toObject=function(A,r){r||(r={});var s={};return A.annotationNumber!=null&&A.hasOwnProperty("annotationNumber")&&(s.annotationNumber=A.annotationNumber,r.oneofs&&(s._annotationNumber="annotationNumber")),A.latitude!=null&&A.hasOwnProperty("latitude")&&(s.latitude=r.json&&!isFinite(A.latitude)?String(A.latitude):A.latitude,r.oneofs&&(s._latitude="latitude")),A.longitude!=null&&A.hasOwnProperty("longitude")&&(s.longitude=r.json&&!isFinite(A.longitude)?String(A.longitude):A.longitude,r.oneofs&&(s._longitude="longitude")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=A.body,r.oneofs&&(s._body="body")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation"},i})(),t})(),n.AIRichResponseMessage=(function(){function t(i){if(this.submessages=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageType=e.int32();break}case 2:{s.submessages&&s.submessages.length||(s.submessages=[]),s.submessages.push(p.proto.AIRichResponseSubMessage.decode(e,e.uint32()));break}case 3:{s.unifiedResponse=p.proto.AIRichResponseUnifiedResponse.decode(e,e.uint32());break}case 4:{s.contextInfo=p.proto.ContextInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseMessage)return e;var a=new p.proto.AIRichResponseMessage;switch(e.messageType){default:if(typeof e.messageType=="number"){a.messageType=e.messageType;break}break;case"AI_RICH_RESPONSE_TYPE_UNKNOWN":case 0:a.messageType=0;break;case"AI_RICH_RESPONSE_TYPE_STANDARD":case 1:a.messageType=1;break}if(e.submessages){if(!Array.isArray(e.submessages))throw TypeError(".proto.AIRichResponseMessage.submessages: array expected");a.submessages=[];for(var A=0;A>>3){case 1:{s.messageType=e.int32();break}case 2:{s.gridImageMetadata=p.proto.AIRichResponseGridImageMetadata.decode(e,e.uint32());break}case 3:{s.messageText=e.string();break}case 4:{s.imageMetadata=p.proto.AIRichResponseInlineImageMetadata.decode(e,e.uint32());break}case 5:{s.codeMetadata=p.proto.AIRichResponseCodeMetadata.decode(e,e.uint32());break}case 6:{s.tableMetadata=p.proto.AIRichResponseTableMetadata.decode(e,e.uint32());break}case 7:{s.dynamicMetadata=p.proto.AIRichResponseDynamicMetadata.decode(e,e.uint32());break}case 8:{s.latexMetadata=p.proto.AIRichResponseLatexMetadata.decode(e,e.uint32());break}case 9:{s.mapMetadata=p.proto.AIRichResponseMapMetadata.decode(e,e.uint32());break}case 10:{s.contentItemsMetadata=p.proto.AIRichResponseContentItemsMetadata.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseSubMessage)return e;var a=new p.proto.AIRichResponseSubMessage;switch(e.messageType){default:if(typeof e.messageType=="number"){a.messageType=e.messageType;break}break;case"AI_RICH_RESPONSE_UNKNOWN":case 0:a.messageType=0;break;case"AI_RICH_RESPONSE_GRID_IMAGE":case 1:a.messageType=1;break;case"AI_RICH_RESPONSE_TEXT":case 2:a.messageType=2;break;case"AI_RICH_RESPONSE_INLINE_IMAGE":case 3:a.messageType=3;break;case"AI_RICH_RESPONSE_TABLE":case 4:a.messageType=4;break;case"AI_RICH_RESPONSE_CODE":case 5:a.messageType=5;break;case"AI_RICH_RESPONSE_DYNAMIC":case 6:a.messageType=6;break;case"AI_RICH_RESPONSE_MAP":case 7:a.messageType=7;break;case"AI_RICH_RESPONSE_LATEX":case 8:a.messageType=8;break;case"AI_RICH_RESPONSE_CONTENT_ITEMS":case 9:a.messageType=9;break}if(e.gridImageMetadata!=null){if(typeof e.gridImageMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.gridImageMetadata: object expected");a.gridImageMetadata=p.proto.AIRichResponseGridImageMetadata.fromObject(e.gridImageMetadata)}if(e.messageText!=null&&(a.messageText=String(e.messageText)),e.imageMetadata!=null){if(typeof e.imageMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.imageMetadata: object expected");a.imageMetadata=p.proto.AIRichResponseInlineImageMetadata.fromObject(e.imageMetadata)}if(e.codeMetadata!=null){if(typeof e.codeMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.codeMetadata: object expected");a.codeMetadata=p.proto.AIRichResponseCodeMetadata.fromObject(e.codeMetadata)}if(e.tableMetadata!=null){if(typeof e.tableMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.tableMetadata: object expected");a.tableMetadata=p.proto.AIRichResponseTableMetadata.fromObject(e.tableMetadata)}if(e.dynamicMetadata!=null){if(typeof e.dynamicMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.dynamicMetadata: object expected");a.dynamicMetadata=p.proto.AIRichResponseDynamicMetadata.fromObject(e.dynamicMetadata)}if(e.latexMetadata!=null){if(typeof e.latexMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.latexMetadata: object expected");a.latexMetadata=p.proto.AIRichResponseLatexMetadata.fromObject(e.latexMetadata)}if(e.mapMetadata!=null){if(typeof e.mapMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.mapMetadata: object expected");a.mapMetadata=p.proto.AIRichResponseMapMetadata.fromObject(e.mapMetadata)}if(e.contentItemsMetadata!=null){if(typeof e.contentItemsMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.contentItemsMetadata: object expected");a.contentItemsMetadata=p.proto.AIRichResponseContentItemsMetadata.fromObject(e.contentItemsMetadata)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.messageType!=null&&e.hasOwnProperty("messageType")&&(A.messageType=a.enums===String?p.proto.AIRichResponseSubMessageType[e.messageType]===void 0?e.messageType:p.proto.AIRichResponseSubMessageType[e.messageType]:e.messageType,a.oneofs&&(A._messageType="messageType")),e.gridImageMetadata!=null&&e.hasOwnProperty("gridImageMetadata")&&(A.gridImageMetadata=p.proto.AIRichResponseGridImageMetadata.toObject(e.gridImageMetadata,a),a.oneofs&&(A._gridImageMetadata="gridImageMetadata")),e.messageText!=null&&e.hasOwnProperty("messageText")&&(A.messageText=e.messageText,a.oneofs&&(A._messageText="messageText")),e.imageMetadata!=null&&e.hasOwnProperty("imageMetadata")&&(A.imageMetadata=p.proto.AIRichResponseInlineImageMetadata.toObject(e.imageMetadata,a),a.oneofs&&(A._imageMetadata="imageMetadata")),e.codeMetadata!=null&&e.hasOwnProperty("codeMetadata")&&(A.codeMetadata=p.proto.AIRichResponseCodeMetadata.toObject(e.codeMetadata,a),a.oneofs&&(A._codeMetadata="codeMetadata")),e.tableMetadata!=null&&e.hasOwnProperty("tableMetadata")&&(A.tableMetadata=p.proto.AIRichResponseTableMetadata.toObject(e.tableMetadata,a),a.oneofs&&(A._tableMetadata="tableMetadata")),e.dynamicMetadata!=null&&e.hasOwnProperty("dynamicMetadata")&&(A.dynamicMetadata=p.proto.AIRichResponseDynamicMetadata.toObject(e.dynamicMetadata,a),a.oneofs&&(A._dynamicMetadata="dynamicMetadata")),e.latexMetadata!=null&&e.hasOwnProperty("latexMetadata")&&(A.latexMetadata=p.proto.AIRichResponseLatexMetadata.toObject(e.latexMetadata,a),a.oneofs&&(A._latexMetadata="latexMetadata")),e.mapMetadata!=null&&e.hasOwnProperty("mapMetadata")&&(A.mapMetadata=p.proto.AIRichResponseMapMetadata.toObject(e.mapMetadata,a),a.oneofs&&(A._mapMetadata="mapMetadata")),e.contentItemsMetadata!=null&&e.hasOwnProperty("contentItemsMetadata")&&(A.contentItemsMetadata=p.proto.AIRichResponseContentItemsMetadata.toObject(e.contentItemsMetadata,a),a.oneofs&&(A._contentItemsMetadata="contentItemsMetadata")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseSubMessage"},t})(),n.AIRichResponseSubMessageType=(function(){let t={},o=Object.create(t);return o[t[0]="AI_RICH_RESPONSE_UNKNOWN"]=0,o[t[1]="AI_RICH_RESPONSE_GRID_IMAGE"]=1,o[t[2]="AI_RICH_RESPONSE_TEXT"]=2,o[t[3]="AI_RICH_RESPONSE_INLINE_IMAGE"]=3,o[t[4]="AI_RICH_RESPONSE_TABLE"]=4,o[t[5]="AI_RICH_RESPONSE_CODE"]=5,o[t[6]="AI_RICH_RESPONSE_DYNAMIC"]=6,o[t[7]="AI_RICH_RESPONSE_MAP"]=7,o[t[8]="AI_RICH_RESPONSE_LATEX"]=8,o[t[9]="AI_RICH_RESPONSE_CONTENT_ITEMS"]=9,o})(),n.AIRichResponseTableMetadata=(function(){function t(i){if(this.rows=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.rows&&s.rows.length||(s.rows=[]),s.rows.push(p.proto.AIRichResponseTableMetadata.AIRichResponseTableRow.decode(e,e.uint32()));break}case 2:{s.title=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseTableMetadata)return e;var a=new p.proto.AIRichResponseTableMetadata;if(e.rows){if(!Array.isArray(e.rows))throw TypeError(".proto.AIRichResponseTableMetadata.rows: array expected");a.rows=[];for(var A=0;A>>3){case 1:{c.items&&c.items.length||(c.items=[]),c.items.push(A.string());break}case 2:{c.isHeading=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseTableMetadata.AIRichResponseTableRow)return A;var r=new p.proto.AIRichResponseTableMetadata.AIRichResponseTableRow;if(A.items){if(!Array.isArray(A.items))throw TypeError(".proto.AIRichResponseTableMetadata.AIRichResponseTableRow.items: array expected");r.items=[];for(var s=0;s>>3){case 1:{s.data=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseUnifiedResponse)return e;var a=new p.proto.AIRichResponseUnifiedResponse;return e.data!=null&&(typeof e.data=="string"?l.base64.decode(e.data,a.data=l.newBuffer(l.base64.length(e.data)),0):e.data.length>=0&&(a.data=e.data)),a},t.toObject=function(e,a){a||(a={});var A={};return e.data!=null&&e.hasOwnProperty("data")&&(A.data=a.bytes===String?l.base64.encode(e.data,0,e.data.length):a.bytes===Array?Array.prototype.slice.call(e.data):e.data,a.oneofs&&(A._data="data")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseUnifiedResponse"},t})(),n.AIThreadInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.serverInfo=p.proto.AIThreadInfo.AIThreadServerInfo.decode(e,e.uint32());break}case 2:{s.clientInfo=p.proto.AIThreadInfo.AIThreadClientInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIThreadInfo)return e;var a=new p.proto.AIThreadInfo;if(e.serverInfo!=null){if(typeof e.serverInfo!="object")throw TypeError(".proto.AIThreadInfo.serverInfo: object expected");a.serverInfo=p.proto.AIThreadInfo.AIThreadServerInfo.fromObject(e.serverInfo)}if(e.clientInfo!=null){if(typeof e.clientInfo!="object")throw TypeError(".proto.AIThreadInfo.clientInfo: object expected");a.clientInfo=p.proto.AIThreadInfo.AIThreadClientInfo.fromObject(e.clientInfo)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.serverInfo!=null&&e.hasOwnProperty("serverInfo")&&(A.serverInfo=p.proto.AIThreadInfo.AIThreadServerInfo.toObject(e.serverInfo,a),a.oneofs&&(A._serverInfo="serverInfo")),e.clientInfo!=null&&e.hasOwnProperty("clientInfo")&&(A.clientInfo=p.proto.AIThreadInfo.AIThreadClientInfo.toObject(e.clientInfo,a),a.oneofs&&(A._clientInfo="clientInfo")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIThreadInfo"},t.AIThreadClientInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.type=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIThreadInfo.AIThreadClientInfo)return A;var r=new p.proto.AIThreadInfo.AIThreadClientInfo;switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNKNOWN":case 0:r.type=0;break;case"DEFAULT":case 1:r.type=1;break;case"INCOGNITO":case 2:r.type=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.AIThreadInfo.AIThreadClientInfo.AIThreadType[A.type]===void 0?A.type:p.proto.AIThreadInfo.AIThreadClientInfo.AIThreadType[A.type]:A.type,r.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIThreadInfo.AIThreadClientInfo"},i.AIThreadType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="DEFAULT"]=1,A[a[2]="INCOGNITO"]=2,A})(),i})(),t.AIThreadServerInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.title=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIThreadInfo.AIThreadServerInfo)return A;var r=new p.proto.AIThreadInfo.AIThreadServerInfo;return A.title!=null&&(r.title=String(A.title)),r},i.toObject=function(A,r){r||(r={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIThreadInfo.AIThreadServerInfo"},i})(),t})(),n.Account=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lid=e.string();break}case 2:{s.username=e.string();break}case 3:{s.countryCode=e.string();break}case 4:{s.isUsernameDeleted=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Account)return e;var a=new p.proto.Account;return e.lid!=null&&(a.lid=String(e.lid)),e.username!=null&&(a.username=String(e.username)),e.countryCode!=null&&(a.countryCode=String(e.countryCode)),e.isUsernameDeleted!=null&&(a.isUsernameDeleted=!!e.isUsernameDeleted),a},t.toObject=function(e,a){a||(a={});var A={};return e.lid!=null&&e.hasOwnProperty("lid")&&(A.lid=e.lid,a.oneofs&&(A._lid="lid")),e.username!=null&&e.hasOwnProperty("username")&&(A.username=e.username,a.oneofs&&(A._username="username")),e.countryCode!=null&&e.hasOwnProperty("countryCode")&&(A.countryCode=e.countryCode,a.oneofs&&(A._countryCode="countryCode")),e.isUsernameDeleted!=null&&e.hasOwnProperty("isUsernameDeleted")&&(A.isUsernameDeleted=e.isUsernameDeleted,a.oneofs&&(A._isUsernameDeleted="isUsernameDeleted")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Account"},t})(),n.ActionLink=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.url=e.string();break}case 2:{s.buttonTitle=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ActionLink)return e;var a=new p.proto.ActionLink;return e.url!=null&&(a.url=String(e.url)),e.buttonTitle!=null&&(a.buttonTitle=String(e.buttonTitle)),a},t.toObject=function(e,a){a||(a={});var A={};return e.url!=null&&e.hasOwnProperty("url")&&(A.url=e.url,a.oneofs&&(A._url="url")),e.buttonTitle!=null&&e.hasOwnProperty("buttonTitle")&&(A.buttonTitle=e.buttonTitle,a.oneofs&&(A._buttonTitle="buttonTitle")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ActionLink"},t})(),n.AutoDownloadSettings=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.downloadImages=e.bool();break}case 2:{s.downloadAudio=e.bool();break}case 3:{s.downloadVideo=e.bool();break}case 4:{s.downloadDocuments=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AutoDownloadSettings)return e;var a=new p.proto.AutoDownloadSettings;return e.downloadImages!=null&&(a.downloadImages=!!e.downloadImages),e.downloadAudio!=null&&(a.downloadAudio=!!e.downloadAudio),e.downloadVideo!=null&&(a.downloadVideo=!!e.downloadVideo),e.downloadDocuments!=null&&(a.downloadDocuments=!!e.downloadDocuments),a},t.toObject=function(e,a){a||(a={});var A={};return e.downloadImages!=null&&e.hasOwnProperty("downloadImages")&&(A.downloadImages=e.downloadImages,a.oneofs&&(A._downloadImages="downloadImages")),e.downloadAudio!=null&&e.hasOwnProperty("downloadAudio")&&(A.downloadAudio=e.downloadAudio,a.oneofs&&(A._downloadAudio="downloadAudio")),e.downloadVideo!=null&&e.hasOwnProperty("downloadVideo")&&(A.downloadVideo=e.downloadVideo,a.oneofs&&(A._downloadVideo="downloadVideo")),e.downloadDocuments!=null&&e.hasOwnProperty("downloadDocuments")&&(A.downloadDocuments=e.downloadDocuments,a.oneofs&&(A._downloadDocuments="downloadDocuments")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AutoDownloadSettings"},t})(),n.AvatarUserSettings=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.fbid=e.string();break}case 2:{s.password=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AvatarUserSettings)return e;var a=new p.proto.AvatarUserSettings;return e.fbid!=null&&(a.fbid=String(e.fbid)),e.password!=null&&(a.password=String(e.password)),a},t.toObject=function(e,a){a||(a={});var A={};return e.fbid!=null&&e.hasOwnProperty("fbid")&&(A.fbid=e.fbid,a.oneofs&&(A._fbid="fbid")),e.password!=null&&e.hasOwnProperty("password")&&(A.password=e.password,a.oneofs&&(A._password="password")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AvatarUserSettings"},t})(),n.BizAccountLinkInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.whatsappBizAcctFbid=e.uint64();break}case 2:{s.whatsappAcctNumber=e.string();break}case 3:{s.issueTime=e.uint64();break}case 4:{s.hostStorage=e.int32();break}case 5:{s.accountType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BizAccountLinkInfo)return e;var a=new p.proto.BizAccountLinkInfo;switch(e.whatsappBizAcctFbid!=null&&(l.Long?(a.whatsappBizAcctFbid=l.Long.fromValue(e.whatsappBizAcctFbid)).unsigned=!0:typeof e.whatsappBizAcctFbid=="string"?a.whatsappBizAcctFbid=parseInt(e.whatsappBizAcctFbid,10):typeof e.whatsappBizAcctFbid=="number"?a.whatsappBizAcctFbid=e.whatsappBizAcctFbid:typeof e.whatsappBizAcctFbid=="object"&&(a.whatsappBizAcctFbid=new l.LongBits(e.whatsappBizAcctFbid.low>>>0,e.whatsappBizAcctFbid.high>>>0).toNumber(!0))),e.whatsappAcctNumber!=null&&(a.whatsappAcctNumber=String(e.whatsappAcctNumber)),e.issueTime!=null&&(l.Long?(a.issueTime=l.Long.fromValue(e.issueTime)).unsigned=!0:typeof e.issueTime=="string"?a.issueTime=parseInt(e.issueTime,10):typeof e.issueTime=="number"?a.issueTime=e.issueTime:typeof e.issueTime=="object"&&(a.issueTime=new l.LongBits(e.issueTime.low>>>0,e.issueTime.high>>>0).toNumber(!0))),e.hostStorage){default:if(typeof e.hostStorage=="number"){a.hostStorage=e.hostStorage;break}break;case"ON_PREMISE":case 0:a.hostStorage=0;break;case"FACEBOOK":case 1:a.hostStorage=1;break}switch(e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"ENTERPRISE":case 0:a.accountType=0;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.whatsappBizAcctFbid!=null&&e.hasOwnProperty("whatsappBizAcctFbid")&&(typeof e.whatsappBizAcctFbid=="number"?A.whatsappBizAcctFbid=a.longs===String?String(e.whatsappBizAcctFbid):e.whatsappBizAcctFbid:A.whatsappBizAcctFbid=a.longs===String?se(e.whatsappBizAcctFbid,!0):a.longs===Number?ge(e.whatsappBizAcctFbid,!0):e.whatsappBizAcctFbid,a.oneofs&&(A._whatsappBizAcctFbid="whatsappBizAcctFbid")),e.whatsappAcctNumber!=null&&e.hasOwnProperty("whatsappAcctNumber")&&(A.whatsappAcctNumber=e.whatsappAcctNumber,a.oneofs&&(A._whatsappAcctNumber="whatsappAcctNumber")),e.issueTime!=null&&e.hasOwnProperty("issueTime")&&(typeof e.issueTime=="number"?A.issueTime=a.longs===String?String(e.issueTime):e.issueTime:A.issueTime=a.longs===String?se(e.issueTime,!0):a.longs===Number?ge(e.issueTime,!0):e.issueTime,a.oneofs&&(A._issueTime="issueTime")),e.hostStorage!=null&&e.hasOwnProperty("hostStorage")&&(A.hostStorage=a.enums===String?p.proto.BizAccountLinkInfo.HostStorageType[e.hostStorage]===void 0?e.hostStorage:p.proto.BizAccountLinkInfo.HostStorageType[e.hostStorage]:e.hostStorage,a.oneofs&&(A._hostStorage="hostStorage")),e.accountType!=null&&e.hasOwnProperty("accountType")&&(A.accountType=a.enums===String?p.proto.BizAccountLinkInfo.AccountType[e.accountType]===void 0?e.accountType:p.proto.BizAccountLinkInfo.AccountType[e.accountType]:e.accountType,a.oneofs&&(A._accountType="accountType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BizAccountLinkInfo"},t.AccountType=(function(){let i={},e=Object.create(i);return e[i[0]="ENTERPRISE"]=0,e})(),t.HostStorageType=(function(){let i={},e=Object.create(i);return e[i[0]="ON_PREMISE"]=0,e[i[1]="FACEBOOK"]=1,e})(),t})(),n.BizAccountPayload=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.vnameCert=p.proto.VerifiedNameCertificate.decode(e,e.uint32());break}case 2:{s.bizAcctLinkInfo=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BizAccountPayload)return e;var a=new p.proto.BizAccountPayload;if(e.vnameCert!=null){if(typeof e.vnameCert!="object")throw TypeError(".proto.BizAccountPayload.vnameCert: object expected");a.vnameCert=p.proto.VerifiedNameCertificate.fromObject(e.vnameCert)}return e.bizAcctLinkInfo!=null&&(typeof e.bizAcctLinkInfo=="string"?l.base64.decode(e.bizAcctLinkInfo,a.bizAcctLinkInfo=l.newBuffer(l.base64.length(e.bizAcctLinkInfo)),0):e.bizAcctLinkInfo.length>=0&&(a.bizAcctLinkInfo=e.bizAcctLinkInfo)),a},t.toObject=function(e,a){a||(a={});var A={};return e.vnameCert!=null&&e.hasOwnProperty("vnameCert")&&(A.vnameCert=p.proto.VerifiedNameCertificate.toObject(e.vnameCert,a),a.oneofs&&(A._vnameCert="vnameCert")),e.bizAcctLinkInfo!=null&&e.hasOwnProperty("bizAcctLinkInfo")&&(A.bizAcctLinkInfo=a.bytes===String?l.base64.encode(e.bizAcctLinkInfo,0,e.bizAcctLinkInfo.length):a.bytes===Array?Array.prototype.slice.call(e.bizAcctLinkInfo):e.bizAcctLinkInfo,a.oneofs&&(A._bizAcctLinkInfo="bizAcctLinkInfo")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BizAccountPayload"},t})(),n.BizIdentityInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.vlevel=e.int32();break}case 2:{s.vnameCert=p.proto.VerifiedNameCertificate.decode(e,e.uint32());break}case 3:{s.signed=e.bool();break}case 4:{s.revoked=e.bool();break}case 5:{s.hostStorage=e.int32();break}case 6:{s.actualActors=e.int32();break}case 7:{s.privacyModeTs=e.uint64();break}case 8:{s.featureControls=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BizIdentityInfo)return e;var a=new p.proto.BizIdentityInfo;switch(e.vlevel){default:if(typeof e.vlevel=="number"){a.vlevel=e.vlevel;break}break;case"UNKNOWN":case 0:a.vlevel=0;break;case"LOW":case 1:a.vlevel=1;break;case"HIGH":case 2:a.vlevel=2;break}if(e.vnameCert!=null){if(typeof e.vnameCert!="object")throw TypeError(".proto.BizIdentityInfo.vnameCert: object expected");a.vnameCert=p.proto.VerifiedNameCertificate.fromObject(e.vnameCert)}switch(e.signed!=null&&(a.signed=!!e.signed),e.revoked!=null&&(a.revoked=!!e.revoked),e.hostStorage){default:if(typeof e.hostStorage=="number"){a.hostStorage=e.hostStorage;break}break;case"ON_PREMISE":case 0:a.hostStorage=0;break;case"FACEBOOK":case 1:a.hostStorage=1;break}switch(e.actualActors){default:if(typeof e.actualActors=="number"){a.actualActors=e.actualActors;break}break;case"SELF":case 0:a.actualActors=0;break;case"BSP":case 1:a.actualActors=1;break}return e.privacyModeTs!=null&&(l.Long?(a.privacyModeTs=l.Long.fromValue(e.privacyModeTs)).unsigned=!0:typeof e.privacyModeTs=="string"?a.privacyModeTs=parseInt(e.privacyModeTs,10):typeof e.privacyModeTs=="number"?a.privacyModeTs=e.privacyModeTs:typeof e.privacyModeTs=="object"&&(a.privacyModeTs=new l.LongBits(e.privacyModeTs.low>>>0,e.privacyModeTs.high>>>0).toNumber(!0))),e.featureControls!=null&&(l.Long?(a.featureControls=l.Long.fromValue(e.featureControls)).unsigned=!0:typeof e.featureControls=="string"?a.featureControls=parseInt(e.featureControls,10):typeof e.featureControls=="number"?a.featureControls=e.featureControls:typeof e.featureControls=="object"&&(a.featureControls=new l.LongBits(e.featureControls.low>>>0,e.featureControls.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};return e.vlevel!=null&&e.hasOwnProperty("vlevel")&&(A.vlevel=a.enums===String?p.proto.BizIdentityInfo.VerifiedLevelValue[e.vlevel]===void 0?e.vlevel:p.proto.BizIdentityInfo.VerifiedLevelValue[e.vlevel]:e.vlevel,a.oneofs&&(A._vlevel="vlevel")),e.vnameCert!=null&&e.hasOwnProperty("vnameCert")&&(A.vnameCert=p.proto.VerifiedNameCertificate.toObject(e.vnameCert,a),a.oneofs&&(A._vnameCert="vnameCert")),e.signed!=null&&e.hasOwnProperty("signed")&&(A.signed=e.signed,a.oneofs&&(A._signed="signed")),e.revoked!=null&&e.hasOwnProperty("revoked")&&(A.revoked=e.revoked,a.oneofs&&(A._revoked="revoked")),e.hostStorage!=null&&e.hasOwnProperty("hostStorage")&&(A.hostStorage=a.enums===String?p.proto.BizIdentityInfo.HostStorageType[e.hostStorage]===void 0?e.hostStorage:p.proto.BizIdentityInfo.HostStorageType[e.hostStorage]:e.hostStorage,a.oneofs&&(A._hostStorage="hostStorage")),e.actualActors!=null&&e.hasOwnProperty("actualActors")&&(A.actualActors=a.enums===String?p.proto.BizIdentityInfo.ActualActorsType[e.actualActors]===void 0?e.actualActors:p.proto.BizIdentityInfo.ActualActorsType[e.actualActors]:e.actualActors,a.oneofs&&(A._actualActors="actualActors")),e.privacyModeTs!=null&&e.hasOwnProperty("privacyModeTs")&&(typeof e.privacyModeTs=="number"?A.privacyModeTs=a.longs===String?String(e.privacyModeTs):e.privacyModeTs:A.privacyModeTs=a.longs===String?se(e.privacyModeTs,!0):a.longs===Number?ge(e.privacyModeTs,!0):e.privacyModeTs,a.oneofs&&(A._privacyModeTs="privacyModeTs")),e.featureControls!=null&&e.hasOwnProperty("featureControls")&&(typeof e.featureControls=="number"?A.featureControls=a.longs===String?String(e.featureControls):e.featureControls:A.featureControls=a.longs===String?se(e.featureControls,!0):a.longs===Number?ge(e.featureControls,!0):e.featureControls,a.oneofs&&(A._featureControls="featureControls")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BizIdentityInfo"},t.ActualActorsType=(function(){let i={},e=Object.create(i);return e[i[0]="SELF"]=0,e[i[1]="BSP"]=1,e})(),t.HostStorageType=(function(){let i={},e=Object.create(i);return e[i[0]="ON_PREMISE"]=0,e[i[1]="FACEBOOK"]=1,e})(),t.VerifiedLevelValue=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="LOW"]=1,e[i[2]="HIGH"]=2,e})(),t})(),n.BotAgeCollectionMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.ageCollectionEligible=e.bool();break}case 2:{s.shouldTriggerAgeCollectionOnClient=e.bool();break}case 3:{s.ageCollectionType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotAgeCollectionMetadata)return e;var a=new p.proto.BotAgeCollectionMetadata;switch(e.ageCollectionEligible!=null&&(a.ageCollectionEligible=!!e.ageCollectionEligible),e.shouldTriggerAgeCollectionOnClient!=null&&(a.shouldTriggerAgeCollectionOnClient=!!e.shouldTriggerAgeCollectionOnClient),e.ageCollectionType){default:if(typeof e.ageCollectionType=="number"){a.ageCollectionType=e.ageCollectionType;break}break;case"O18_BINARY":case 0:a.ageCollectionType=0;break;case"WAFFLE":case 1:a.ageCollectionType=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.ageCollectionEligible!=null&&e.hasOwnProperty("ageCollectionEligible")&&(A.ageCollectionEligible=e.ageCollectionEligible,a.oneofs&&(A._ageCollectionEligible="ageCollectionEligible")),e.shouldTriggerAgeCollectionOnClient!=null&&e.hasOwnProperty("shouldTriggerAgeCollectionOnClient")&&(A.shouldTriggerAgeCollectionOnClient=e.shouldTriggerAgeCollectionOnClient,a.oneofs&&(A._shouldTriggerAgeCollectionOnClient="shouldTriggerAgeCollectionOnClient")),e.ageCollectionType!=null&&e.hasOwnProperty("ageCollectionType")&&(A.ageCollectionType=a.enums===String?p.proto.BotAgeCollectionMetadata.AgeCollectionType[e.ageCollectionType]===void 0?e.ageCollectionType:p.proto.BotAgeCollectionMetadata.AgeCollectionType[e.ageCollectionType]:e.ageCollectionType,a.oneofs&&(A._ageCollectionType="ageCollectionType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotAgeCollectionMetadata"},t.AgeCollectionType=(function(){let i={},e=Object.create(i);return e[i[0]="O18_BINARY"]=0,e[i[1]="WAFFLE"]=1,e})(),t})(),n.BotAvatarMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.sentiment=e.uint32();break}case 2:{s.behaviorGraph=e.string();break}case 3:{s.action=e.uint32();break}case 4:{s.intensity=e.uint32();break}case 5:{s.wordCount=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotAvatarMetadata)return e;var a=new p.proto.BotAvatarMetadata;return e.sentiment!=null&&(a.sentiment=e.sentiment>>>0),e.behaviorGraph!=null&&(a.behaviorGraph=String(e.behaviorGraph)),e.action!=null&&(a.action=e.action>>>0),e.intensity!=null&&(a.intensity=e.intensity>>>0),e.wordCount!=null&&(a.wordCount=e.wordCount>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.sentiment!=null&&e.hasOwnProperty("sentiment")&&(A.sentiment=e.sentiment,a.oneofs&&(A._sentiment="sentiment")),e.behaviorGraph!=null&&e.hasOwnProperty("behaviorGraph")&&(A.behaviorGraph=e.behaviorGraph,a.oneofs&&(A._behaviorGraph="behaviorGraph")),e.action!=null&&e.hasOwnProperty("action")&&(A.action=e.action,a.oneofs&&(A._action="action")),e.intensity!=null&&e.hasOwnProperty("intensity")&&(A.intensity=e.intensity,a.oneofs&&(A._intensity="intensity")),e.wordCount!=null&&e.hasOwnProperty("wordCount")&&(A.wordCount=e.wordCount,a.oneofs&&(A._wordCount="wordCount")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotAvatarMetadata"},t})(),n.BotCapabilityMetadata=(function(){function t(o){if(this.capabilities=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{if(r.capabilities&&r.capabilities.length||(r.capabilities=[]),(s&7)===2)for(var g=i.uint32()+i.pos;i.pos>>3){case 1:{s.messageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.kind=e.int32();break}case 3:{s.text=e.string();break}case 4:{s.kindNegative=e.uint64();break}case 5:{s.kindPositive=e.uint64();break}case 6:{s.kindReport=e.int32();break}case 7:{s.sideBySideSurveyMetadata=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotFeedbackMessage)return e;var a=new p.proto.BotFeedbackMessage;if(e.messageKey!=null){if(typeof e.messageKey!="object")throw TypeError(".proto.BotFeedbackMessage.messageKey: object expected");a.messageKey=p.proto.MessageKey.fromObject(e.messageKey)}switch(e.kind){default:if(typeof e.kind=="number"){a.kind=e.kind;break}break;case"BOT_FEEDBACK_POSITIVE":case 0:a.kind=0;break;case"BOT_FEEDBACK_NEGATIVE_GENERIC":case 1:a.kind=1;break;case"BOT_FEEDBACK_NEGATIVE_HELPFUL":case 2:a.kind=2;break;case"BOT_FEEDBACK_NEGATIVE_INTERESTING":case 3:a.kind=3;break;case"BOT_FEEDBACK_NEGATIVE_ACCURATE":case 4:a.kind=4;break;case"BOT_FEEDBACK_NEGATIVE_SAFE":case 5:a.kind=5;break;case"BOT_FEEDBACK_NEGATIVE_OTHER":case 6:a.kind=6;break;case"BOT_FEEDBACK_NEGATIVE_REFUSED":case 7:a.kind=7;break;case"BOT_FEEDBACK_NEGATIVE_NOT_VISUALLY_APPEALING":case 8:a.kind=8;break;case"BOT_FEEDBACK_NEGATIVE_NOT_RELEVANT_TO_TEXT":case 9:a.kind=9;break;case"BOT_FEEDBACK_NEGATIVE_PERSONALIZED":case 10:a.kind=10;break;case"BOT_FEEDBACK_NEGATIVE_CLARITY":case 11:a.kind=11;break;case"BOT_FEEDBACK_NEGATIVE_DOESNT_LOOK_LIKE_THE_PERSON":case 12:a.kind=12;break;case"BOT_FEEDBACK_NEGATIVE_HALLUCINATION_INTERNAL_ONLY":case 13:a.kind=13;break;case"BOT_FEEDBACK_NEGATIVE":case 14:a.kind=14;break}switch(e.text!=null&&(a.text=String(e.text)),e.kindNegative!=null&&(l.Long?(a.kindNegative=l.Long.fromValue(e.kindNegative)).unsigned=!0:typeof e.kindNegative=="string"?a.kindNegative=parseInt(e.kindNegative,10):typeof e.kindNegative=="number"?a.kindNegative=e.kindNegative:typeof e.kindNegative=="object"&&(a.kindNegative=new l.LongBits(e.kindNegative.low>>>0,e.kindNegative.high>>>0).toNumber(!0))),e.kindPositive!=null&&(l.Long?(a.kindPositive=l.Long.fromValue(e.kindPositive)).unsigned=!0:typeof e.kindPositive=="string"?a.kindPositive=parseInt(e.kindPositive,10):typeof e.kindPositive=="number"?a.kindPositive=e.kindPositive:typeof e.kindPositive=="object"&&(a.kindPositive=new l.LongBits(e.kindPositive.low>>>0,e.kindPositive.high>>>0).toNumber(!0))),e.kindReport){default:if(typeof e.kindReport=="number"){a.kindReport=e.kindReport;break}break;case"NONE":case 0:a.kindReport=0;break;case"GENERIC":case 1:a.kindReport=1;break}if(e.sideBySideSurveyMetadata!=null){if(typeof e.sideBySideSurveyMetadata!="object")throw TypeError(".proto.BotFeedbackMessage.sideBySideSurveyMetadata: object expected");a.sideBySideSurveyMetadata=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.fromObject(e.sideBySideSurveyMetadata)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.messageKey!=null&&e.hasOwnProperty("messageKey")&&(A.messageKey=p.proto.MessageKey.toObject(e.messageKey,a),a.oneofs&&(A._messageKey="messageKey")),e.kind!=null&&e.hasOwnProperty("kind")&&(A.kind=a.enums===String?p.proto.BotFeedbackMessage.BotFeedbackKind[e.kind]===void 0?e.kind:p.proto.BotFeedbackMessage.BotFeedbackKind[e.kind]:e.kind,a.oneofs&&(A._kind="kind")),e.text!=null&&e.hasOwnProperty("text")&&(A.text=e.text,a.oneofs&&(A._text="text")),e.kindNegative!=null&&e.hasOwnProperty("kindNegative")&&(typeof e.kindNegative=="number"?A.kindNegative=a.longs===String?String(e.kindNegative):e.kindNegative:A.kindNegative=a.longs===String?se(e.kindNegative,!0):a.longs===Number?ge(e.kindNegative,!0):e.kindNegative,a.oneofs&&(A._kindNegative="kindNegative")),e.kindPositive!=null&&e.hasOwnProperty("kindPositive")&&(typeof e.kindPositive=="number"?A.kindPositive=a.longs===String?String(e.kindPositive):e.kindPositive:A.kindPositive=a.longs===String?se(e.kindPositive,!0):a.longs===Number?ge(e.kindPositive,!0):e.kindPositive,a.oneofs&&(A._kindPositive="kindPositive")),e.kindReport!=null&&e.hasOwnProperty("kindReport")&&(A.kindReport=a.enums===String?p.proto.BotFeedbackMessage.ReportKind[e.kindReport]===void 0?e.kindReport:p.proto.BotFeedbackMessage.ReportKind[e.kindReport]:e.kindReport,a.oneofs&&(A._kindReport="kindReport")),e.sideBySideSurveyMetadata!=null&&e.hasOwnProperty("sideBySideSurveyMetadata")&&(A.sideBySideSurveyMetadata=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.toObject(e.sideBySideSurveyMetadata,a),a.oneofs&&(A._sideBySideSurveyMetadata="sideBySideSurveyMetadata")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotFeedbackMessage"},t.BotFeedbackKind=(function(){let i={},e=Object.create(i);return e[i[0]="BOT_FEEDBACK_POSITIVE"]=0,e[i[1]="BOT_FEEDBACK_NEGATIVE_GENERIC"]=1,e[i[2]="BOT_FEEDBACK_NEGATIVE_HELPFUL"]=2,e[i[3]="BOT_FEEDBACK_NEGATIVE_INTERESTING"]=3,e[i[4]="BOT_FEEDBACK_NEGATIVE_ACCURATE"]=4,e[i[5]="BOT_FEEDBACK_NEGATIVE_SAFE"]=5,e[i[6]="BOT_FEEDBACK_NEGATIVE_OTHER"]=6,e[i[7]="BOT_FEEDBACK_NEGATIVE_REFUSED"]=7,e[i[8]="BOT_FEEDBACK_NEGATIVE_NOT_VISUALLY_APPEALING"]=8,e[i[9]="BOT_FEEDBACK_NEGATIVE_NOT_RELEVANT_TO_TEXT"]=9,e[i[10]="BOT_FEEDBACK_NEGATIVE_PERSONALIZED"]=10,e[i[11]="BOT_FEEDBACK_NEGATIVE_CLARITY"]=11,e[i[12]="BOT_FEEDBACK_NEGATIVE_DOESNT_LOOK_LIKE_THE_PERSON"]=12,e[i[13]="BOT_FEEDBACK_NEGATIVE_HALLUCINATION_INTERNAL_ONLY"]=13,e[i[14]="BOT_FEEDBACK_NEGATIVE"]=14,e})(),t.BotFeedbackKindMultipleNegative=(function(){let i={},e=Object.create(i);return e[i[1]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_GENERIC"]=1,e[i[2]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_HELPFUL"]=2,e[i[4]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_INTERESTING"]=4,e[i[8]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_ACCURATE"]=8,e[i[16]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_SAFE"]=16,e[i[32]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_OTHER"]=32,e[i[64]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_REFUSED"]=64,e[i[128]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_NOT_VISUALLY_APPEALING"]=128,e[i[256]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_NOT_RELEVANT_TO_TEXT"]=256,e})(),t.BotFeedbackKindMultiplePositive=(function(){let i={},e=Object.create(i);return e[i[1]="BOT_FEEDBACK_MULTIPLE_POSITIVE_GENERIC"]=1,e})(),t.ReportKind=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="GENERIC"]=1,e})(),t.SideBySideSurveyMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.selectedRequestId=A.string();break}case 2:{c.surveyId=A.uint32();break}case 3:{c.simonSessionFbid=A.string();break}case 4:{c.responseOtid=A.string();break}case 5:{c.responseTimestampMsString=A.string();break}case 6:{c.isSelectedResponsePrimary=A.bool();break}case 7:{c.messageIdToEdit=A.string();break}case 8:{c.analyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData.decode(A,A.uint32());break}case 9:{c.metaAiAnalyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata)return A;var r=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata;if(A.selectedRequestId!=null&&(r.selectedRequestId=String(A.selectedRequestId)),A.surveyId!=null&&(r.surveyId=A.surveyId>>>0),A.simonSessionFbid!=null&&(r.simonSessionFbid=String(A.simonSessionFbid)),A.responseOtid!=null&&(r.responseOtid=String(A.responseOtid)),A.responseTimestampMsString!=null&&(r.responseTimestampMsString=String(A.responseTimestampMsString)),A.isSelectedResponsePrimary!=null&&(r.isSelectedResponsePrimary=!!A.isSelectedResponsePrimary),A.messageIdToEdit!=null&&(r.messageIdToEdit=String(A.messageIdToEdit)),A.analyticsData!=null){if(typeof A.analyticsData!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.analyticsData: object expected");r.analyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData.fromObject(A.analyticsData)}if(A.metaAiAnalyticsData!=null){if(typeof A.metaAiAnalyticsData!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.metaAiAnalyticsData: object expected");r.metaAiAnalyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.fromObject(A.metaAiAnalyticsData)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.selectedRequestId!=null&&A.hasOwnProperty("selectedRequestId")&&(s.selectedRequestId=A.selectedRequestId,r.oneofs&&(s._selectedRequestId="selectedRequestId")),A.surveyId!=null&&A.hasOwnProperty("surveyId")&&(s.surveyId=A.surveyId,r.oneofs&&(s._surveyId="surveyId")),A.simonSessionFbid!=null&&A.hasOwnProperty("simonSessionFbid")&&(s.simonSessionFbid=A.simonSessionFbid,r.oneofs&&(s._simonSessionFbid="simonSessionFbid")),A.responseOtid!=null&&A.hasOwnProperty("responseOtid")&&(s.responseOtid=A.responseOtid,r.oneofs&&(s._responseOtid="responseOtid")),A.responseTimestampMsString!=null&&A.hasOwnProperty("responseTimestampMsString")&&(s.responseTimestampMsString=A.responseTimestampMsString,r.oneofs&&(s._responseTimestampMsString="responseTimestampMsString")),A.isSelectedResponsePrimary!=null&&A.hasOwnProperty("isSelectedResponsePrimary")&&(s.isSelectedResponsePrimary=A.isSelectedResponsePrimary,r.oneofs&&(s._isSelectedResponsePrimary="isSelectedResponsePrimary")),A.messageIdToEdit!=null&&A.hasOwnProperty("messageIdToEdit")&&(s.messageIdToEdit=A.messageIdToEdit,r.oneofs&&(s._messageIdToEdit="messageIdToEdit")),A.analyticsData!=null&&A.hasOwnProperty("analyticsData")&&(s.analyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData.toObject(A.analyticsData,r),r.oneofs&&(s._analyticsData="analyticsData")),A.metaAiAnalyticsData!=null&&A.hasOwnProperty("metaAiAnalyticsData")&&(s.metaAiAnalyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.toObject(A.metaAiAnalyticsData,r),r.oneofs&&(s._metaAiAnalyticsData="metaAiAnalyticsData")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata"},i.SideBySideSurveyAnalyticsData=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.tessaEvent=s.string();break}case 2:{d.tessaSessionFbid=s.string();break}case 3:{d.simonSessionFbid=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData)return s;var g=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData;return s.tessaEvent!=null&&(g.tessaEvent=String(s.tessaEvent)),s.tessaSessionFbid!=null&&(g.tessaSessionFbid=String(s.tessaSessionFbid)),s.simonSessionFbid!=null&&(g.simonSessionFbid=String(s.simonSessionFbid)),g},a.toObject=function(s,g){g||(g={});var c={};return s.tessaEvent!=null&&s.hasOwnProperty("tessaEvent")&&(c.tessaEvent=s.tessaEvent,g.oneofs&&(c._tessaEvent="tessaEvent")),s.tessaSessionFbid!=null&&s.hasOwnProperty("tessaSessionFbid")&&(c.tessaSessionFbid=s.tessaSessionFbid,g.oneofs&&(c._tessaSessionFbid="tessaSessionFbid")),s.simonSessionFbid!=null&&s.hasOwnProperty("simonSessionFbid")&&(c.simonSessionFbid=s.simonSessionFbid,g.oneofs&&(c._simonSessionFbid="simonSessionFbid")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData"},a})(),i.SidebySideSurveyMetaAiAnalyticsData=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.surveyId=s.uint32();break}case 2:{d.primaryResponseId=s.string();break}case 3:{d.testArmName=s.string();break}case 4:{d.timestampMsString=s.string();break}case 5:{d.ctaImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData.decode(s,s.uint32());break}case 6:{d.ctaClickEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData.decode(s,s.uint32());break}case 7:{d.cardImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData.decode(s,s.uint32());break}case 8:{d.responseEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData.decode(s,s.uint32());break}case 9:{d.abandonEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData)return s;var g=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData;if(s.surveyId!=null&&(g.surveyId=s.surveyId>>>0),s.primaryResponseId!=null&&(g.primaryResponseId=String(s.primaryResponseId)),s.testArmName!=null&&(g.testArmName=String(s.testArmName)),s.timestampMsString!=null&&(g.timestampMsString=String(s.timestampMsString)),s.ctaImpressionEvent!=null){if(typeof s.ctaImpressionEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.ctaImpressionEvent: object expected");g.ctaImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData.fromObject(s.ctaImpressionEvent)}if(s.ctaClickEvent!=null){if(typeof s.ctaClickEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.ctaClickEvent: object expected");g.ctaClickEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData.fromObject(s.ctaClickEvent)}if(s.cardImpressionEvent!=null){if(typeof s.cardImpressionEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.cardImpressionEvent: object expected");g.cardImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData.fromObject(s.cardImpressionEvent)}if(s.responseEvent!=null){if(typeof s.responseEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.responseEvent: object expected");g.responseEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData.fromObject(s.responseEvent)}if(s.abandonEvent!=null){if(typeof s.abandonEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.abandonEvent: object expected");g.abandonEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData.fromObject(s.abandonEvent)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.surveyId!=null&&s.hasOwnProperty("surveyId")&&(c.surveyId=s.surveyId,g.oneofs&&(c._surveyId="surveyId")),s.primaryResponseId!=null&&s.hasOwnProperty("primaryResponseId")&&(c.primaryResponseId=s.primaryResponseId,g.oneofs&&(c._primaryResponseId="primaryResponseId")),s.testArmName!=null&&s.hasOwnProperty("testArmName")&&(c.testArmName=s.testArmName,g.oneofs&&(c._testArmName="testArmName")),s.timestampMsString!=null&&s.hasOwnProperty("timestampMsString")&&(c.timestampMsString=s.timestampMsString,g.oneofs&&(c._timestampMsString="timestampMsString")),s.ctaImpressionEvent!=null&&s.hasOwnProperty("ctaImpressionEvent")&&(c.ctaImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData.toObject(s.ctaImpressionEvent,g),g.oneofs&&(c._ctaImpressionEvent="ctaImpressionEvent")),s.ctaClickEvent!=null&&s.hasOwnProperty("ctaClickEvent")&&(c.ctaClickEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData.toObject(s.ctaClickEvent,g),g.oneofs&&(c._ctaClickEvent="ctaClickEvent")),s.cardImpressionEvent!=null&&s.hasOwnProperty("cardImpressionEvent")&&(c.cardImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData.toObject(s.cardImpressionEvent,g),g.oneofs&&(c._cardImpressionEvent="cardImpressionEvent")),s.responseEvent!=null&&s.hasOwnProperty("responseEvent")&&(c.responseEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData.toObject(s.responseEvent,g),g.oneofs&&(c._responseEvent="responseEvent")),s.abandonEvent!=null&&s.hasOwnProperty("abandonEvent")&&(c.abandonEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData.toObject(s.abandonEvent,g),g.oneofs&&(c._abandonEvent="abandonEvent")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData"},a.SideBySideSurveyAbandonEventData=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.abandonDwellTimeMsString=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData)return c;var I=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData;return c.abandonDwellTimeMsString!=null&&(I.abandonDwellTimeMsString=String(c.abandonDwellTimeMsString)),I},r.toObject=function(c,I){I||(I={});var d={};return c.abandonDwellTimeMsString!=null&&c.hasOwnProperty("abandonDwellTimeMsString")&&(d.abandonDwellTimeMsString=c.abandonDwellTimeMsString,I.oneofs&&(d._abandonDwellTimeMsString="abandonDwellTimeMsString")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData"},r})(),a.SideBySideSurveyCTAClickEventData=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.isSurveyExpired=c.bool();break}case 2:{f.clickDwellTimeMsString=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData)return c;var I=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData;return c.isSurveyExpired!=null&&(I.isSurveyExpired=!!c.isSurveyExpired),c.clickDwellTimeMsString!=null&&(I.clickDwellTimeMsString=String(c.clickDwellTimeMsString)),I},r.toObject=function(c,I){I||(I={});var d={};return c.isSurveyExpired!=null&&c.hasOwnProperty("isSurveyExpired")&&(d.isSurveyExpired=c.isSurveyExpired,I.oneofs&&(d._isSurveyExpired="isSurveyExpired")),c.clickDwellTimeMsString!=null&&c.hasOwnProperty("clickDwellTimeMsString")&&(d.clickDwellTimeMsString=c.clickDwellTimeMsString,I.oneofs&&(d._clickDwellTimeMsString="clickDwellTimeMsString")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData"},r})(),a.SideBySideSurveyCTAImpressionEventData=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.isSurveyExpired=c.bool();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData)return c;var I=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData;return c.isSurveyExpired!=null&&(I.isSurveyExpired=!!c.isSurveyExpired),I},r.toObject=function(c,I){I||(I={});var d={};return c.isSurveyExpired!=null&&c.hasOwnProperty("isSurveyExpired")&&(d.isSurveyExpired=c.isSurveyExpired,I.oneofs&&(d._isSurveyExpired="isSurveyExpired")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData"},r})(),a.SideBySideSurveyCardImpressionEventData=(function(){function r(s){if(s)for(var g=Object.keys(s),c=0;c>>3){default:g.skipType(f&7);break}}return B},r.fromObject=function(g){return g instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData?g:new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData},r.toObject=function(){return{}},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(g){return g===void 0&&(g="type.googleapis.com"),g+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData"},r})(),a.SideBySideSurveyResponseEventData=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.responseDwellTimeMsString=c.string();break}case 2:{f.selectedResponseId=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData)return c;var I=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData;return c.responseDwellTimeMsString!=null&&(I.responseDwellTimeMsString=String(c.responseDwellTimeMsString)),c.selectedResponseId!=null&&(I.selectedResponseId=String(c.selectedResponseId)),I},r.toObject=function(c,I){I||(I={});var d={};return c.responseDwellTimeMsString!=null&&c.hasOwnProperty("responseDwellTimeMsString")&&(d.responseDwellTimeMsString=c.responseDwellTimeMsString,I.oneofs&&(d._responseDwellTimeMsString="responseDwellTimeMsString")),c.selectedResponseId!=null&&c.hasOwnProperty("selectedResponseId")&&(d.selectedResponseId=c.selectedResponseId,I.oneofs&&(d._selectedResponseId="selectedResponseId")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData"},r})(),a})(),i})(),t})(),n.BotImagineMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.imagineType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotImagineMetadata)return e;var a=new p.proto.BotImagineMetadata;switch(e.imagineType){default:if(typeof e.imagineType=="number"){a.imagineType=e.imagineType;break}break;case"UNKNOWN":case 0:a.imagineType=0;break;case"IMAGINE":case 1:a.imagineType=1;break;case"MEMU":case 2:a.imagineType=2;break;case"FLASH":case 3:a.imagineType=3;break;case"EDIT":case 4:a.imagineType=4;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.imagineType!=null&&e.hasOwnProperty("imagineType")&&(A.imagineType=a.enums===String?p.proto.BotImagineMetadata.ImagineType[e.imagineType]===void 0?e.imagineType:p.proto.BotImagineMetadata.ImagineType[e.imagineType]:e.imagineType,a.oneofs&&(A._imagineType="imagineType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotImagineMetadata"},t.ImagineType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="IMAGINE"]=1,e[i[2]="MEMU"]=2,e[i[3]="FLASH"]=3,e[i[4]="EDIT"]=4,e})(),t})(),n.BotLinkedAccount=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotLinkedAccount)return e;var a=new p.proto.BotLinkedAccount;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"BOT_LINKED_ACCOUNT_TYPE_1P":case 0:a.type=0;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.BotLinkedAccount.BotLinkedAccountType[e.type]===void 0?e.type:p.proto.BotLinkedAccount.BotLinkedAccountType[e.type]:e.type,a.oneofs&&(A._type="type")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotLinkedAccount"},t.BotLinkedAccountType=(function(){let i={},e=Object.create(i);return e[i[0]="BOT_LINKED_ACCOUNT_TYPE_1P"]=0,e})(),t})(),n.BotLinkedAccountsMetadata=(function(){function t(i){if(this.accounts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.accounts&&s.accounts.length||(s.accounts=[]),s.accounts.push(p.proto.BotLinkedAccount.decode(e,e.uint32()));break}case 2:{s.acAuthTokens=e.bytes();break}case 3:{s.acErrorCode=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotLinkedAccountsMetadata)return e;var a=new p.proto.BotLinkedAccountsMetadata;if(e.accounts){if(!Array.isArray(e.accounts))throw TypeError(".proto.BotLinkedAccountsMetadata.accounts: array expected");a.accounts=[];for(var A=0;A=0&&(a.acAuthTokens=e.acAuthTokens)),e.acErrorCode!=null&&(a.acErrorCode=e.acErrorCode|0),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.accounts=[]),e.accounts&&e.accounts.length){A.accounts=[];for(var r=0;r>>3){case 1:{s.fileSha256=e.string();break}case 2:{s.mediaKey=e.string();break}case 3:{s.fileEncSha256=e.string();break}case 4:{s.directPath=e.string();break}case 5:{s.mediaKeyTimestamp=e.int64();break}case 6:{s.mimetype=e.string();break}case 7:{s.orientationType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMediaMetadata)return e;var a=new p.proto.BotMediaMetadata;switch(e.fileSha256!=null&&(a.fileSha256=String(e.fileSha256)),e.mediaKey!=null&&(a.mediaKey=String(e.mediaKey)),e.fileEncSha256!=null&&(a.fileEncSha256=String(e.fileEncSha256)),e.directPath!=null&&(a.directPath=String(e.directPath)),e.mediaKeyTimestamp!=null&&(l.Long?(a.mediaKeyTimestamp=l.Long.fromValue(e.mediaKeyTimestamp)).unsigned=!1:typeof e.mediaKeyTimestamp=="string"?a.mediaKeyTimestamp=parseInt(e.mediaKeyTimestamp,10):typeof e.mediaKeyTimestamp=="number"?a.mediaKeyTimestamp=e.mediaKeyTimestamp:typeof e.mediaKeyTimestamp=="object"&&(a.mediaKeyTimestamp=new l.LongBits(e.mediaKeyTimestamp.low>>>0,e.mediaKeyTimestamp.high>>>0).toNumber())),e.mimetype!=null&&(a.mimetype=String(e.mimetype)),e.orientationType){default:if(typeof e.orientationType=="number"){a.orientationType=e.orientationType;break}break;case"CENTER":case 1:a.orientationType=1;break;case"LEFT":case 2:a.orientationType=2;break;case"RIGHT":case 3:a.orientationType=3;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.fileSha256!=null&&e.hasOwnProperty("fileSha256")&&(A.fileSha256=e.fileSha256,a.oneofs&&(A._fileSha256="fileSha256")),e.mediaKey!=null&&e.hasOwnProperty("mediaKey")&&(A.mediaKey=e.mediaKey,a.oneofs&&(A._mediaKey="mediaKey")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.mediaKeyTimestamp!=null&&e.hasOwnProperty("mediaKeyTimestamp")&&(typeof e.mediaKeyTimestamp=="number"?A.mediaKeyTimestamp=a.longs===String?String(e.mediaKeyTimestamp):e.mediaKeyTimestamp:A.mediaKeyTimestamp=a.longs===String?se(e.mediaKeyTimestamp):a.longs===Number?ge(e.mediaKeyTimestamp):e.mediaKeyTimestamp,a.oneofs&&(A._mediaKeyTimestamp="mediaKeyTimestamp")),e.mimetype!=null&&e.hasOwnProperty("mimetype")&&(A.mimetype=e.mimetype,a.oneofs&&(A._mimetype="mimetype")),e.orientationType!=null&&e.hasOwnProperty("orientationType")&&(A.orientationType=a.enums===String?p.proto.BotMediaMetadata.OrientationType[e.orientationType]===void 0?e.orientationType:p.proto.BotMediaMetadata.OrientationType[e.orientationType]:e.orientationType,a.oneofs&&(A._orientationType="orientationType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMediaMetadata"},t.OrientationType=(function(){let i={},e=Object.create(i);return e[i[1]="CENTER"]=1,e[i[2]="LEFT"]=2,e[i[3]="RIGHT"]=3,e})(),t})(),n.BotMemoryFact=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.fact=e.string();break}case 2:{s.factId=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMemoryFact)return e;var a=new p.proto.BotMemoryFact;return e.fact!=null&&(a.fact=String(e.fact)),e.factId!=null&&(a.factId=String(e.factId)),a},t.toObject=function(e,a){a||(a={});var A={};return e.fact!=null&&e.hasOwnProperty("fact")&&(A.fact=e.fact,a.oneofs&&(A._fact="fact")),e.factId!=null&&e.hasOwnProperty("factId")&&(A.factId=e.factId,a.oneofs&&(A._factId="factId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMemoryFact"},t})(),n.BotMemoryMetadata=(function(){function t(i){if(this.addedFacts=[],this.removedFacts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.addedFacts&&s.addedFacts.length||(s.addedFacts=[]),s.addedFacts.push(p.proto.BotMemoryFact.decode(e,e.uint32()));break}case 2:{s.removedFacts&&s.removedFacts.length||(s.removedFacts=[]),s.removedFacts.push(p.proto.BotMemoryFact.decode(e,e.uint32()));break}case 3:{s.disclaimer=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMemoryMetadata)return e;var a=new p.proto.BotMemoryMetadata;if(e.addedFacts){if(!Array.isArray(e.addedFacts))throw TypeError(".proto.BotMemoryMetadata.addedFacts: array expected");a.addedFacts=[];for(var A=0;A>>3){case 1:{r.faceImages&&r.faceImages.length||(r.faceImages=[]),r.faceImages.push(p.proto.BotMediaMetadata.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotMemuMetadata)return i;var e=new p.proto.BotMemuMetadata;if(i.faceImages){if(!Array.isArray(i.faceImages))throw TypeError(".proto.BotMemuMetadata.faceImages: array expected");e.faceImages=[];for(var a=0;a>>3){case 1:{s.type=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMessageOrigin)return e;var a=new p.proto.BotMessageOrigin;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"BOT_MESSAGE_ORIGIN_TYPE_AI_INITIATED":case 0:a.type=0;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.BotMessageOrigin.BotMessageOriginType[e.type]===void 0?e.type:p.proto.BotMessageOrigin.BotMessageOriginType[e.type]:e.type,a.oneofs&&(A._type="type")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMessageOrigin"},t.BotMessageOriginType=(function(){let i={},e=Object.create(i);return e[i[0]="BOT_MESSAGE_ORIGIN_TYPE_AI_INITIATED"]=0,e})(),t})(),n.BotMessageOriginMetadata=(function(){function t(o){if(this.origins=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.origins&&r.origins.length||(r.origins=[]),r.origins.push(p.proto.BotMessageOrigin.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotMessageOriginMetadata)return i;var e=new p.proto.BotMessageOriginMetadata;if(i.origins){if(!Array.isArray(i.origins))throw TypeError(".proto.BotMessageOriginMetadata.origins: array expected");e.origins=[];for(var a=0;a>>3){case 1:{s.botEntryPointOrigin=e.int32();break}case 2:{s.forwardScore=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMessageSharingInfo)return e;var a=new p.proto.BotMessageSharingInfo;switch(e.botEntryPointOrigin){default:if(typeof e.botEntryPointOrigin=="number"){a.botEntryPointOrigin=e.botEntryPointOrigin;break}break;case"UNDEFINED_ENTRY_POINT":case 0:a.botEntryPointOrigin=0;break;case"FAVICON":case 1:a.botEntryPointOrigin=1;break;case"CHATLIST":case 2:a.botEntryPointOrigin=2;break;case"AISEARCH_NULL_STATE_PAPER_PLANE":case 3:a.botEntryPointOrigin=3;break;case"AISEARCH_NULL_STATE_SUGGESTION":case 4:a.botEntryPointOrigin=4;break;case"AISEARCH_TYPE_AHEAD_SUGGESTION":case 5:a.botEntryPointOrigin=5;break;case"AISEARCH_TYPE_AHEAD_PAPER_PLANE":case 6:a.botEntryPointOrigin=6;break;case"AISEARCH_TYPE_AHEAD_RESULT_CHATLIST":case 7:a.botEntryPointOrigin=7;break;case"AISEARCH_TYPE_AHEAD_RESULT_MESSAGES":case 8:a.botEntryPointOrigin=8;break;case"AIVOICE_SEARCH_BAR":case 9:a.botEntryPointOrigin=9;break;case"AIVOICE_FAVICON":case 10:a.botEntryPointOrigin=10;break;case"AISTUDIO":case 11:a.botEntryPointOrigin=11;break;case"DEEPLINK":case 12:a.botEntryPointOrigin=12;break;case"NOTIFICATION":case 13:a.botEntryPointOrigin=13;break;case"PROFILE_MESSAGE_BUTTON":case 14:a.botEntryPointOrigin=14;break;case"FORWARD":case 15:a.botEntryPointOrigin=15;break;case"APP_SHORTCUT":case 16:a.botEntryPointOrigin=16;break;case"FF_FAMILY":case 17:a.botEntryPointOrigin=17;break;case"AI_TAB":case 18:a.botEntryPointOrigin=18;break;case"AI_HOME":case 19:a.botEntryPointOrigin=19;break;case"AI_DEEPLINK_IMMERSIVE":case 20:a.botEntryPointOrigin=20;break;case"AI_DEEPLINK":case 21:a.botEntryPointOrigin=21;break;case"META_AI_CHAT_SHORTCUT_AI_STUDIO":case 22:a.botEntryPointOrigin=22;break;case"UGC_CHAT_SHORTCUT_AI_STUDIO":case 23:a.botEntryPointOrigin=23;break;case"NEW_CHAT_AI_STUDIO":case 24:a.botEntryPointOrigin=24;break;case"AIVOICE_FAVICON_CALL_HISTORY":case 25:a.botEntryPointOrigin=25;break;case"ASK_META_AI_CONTEXT_MENU":case 26:a.botEntryPointOrigin=26;break;case"ASK_META_AI_CONTEXT_MENU_1ON1":case 27:a.botEntryPointOrigin=27;break;case"ASK_META_AI_CONTEXT_MENU_GROUP":case 28:a.botEntryPointOrigin=28;break;case"INVOKE_META_AI_1ON1":case 29:a.botEntryPointOrigin=29;break;case"INVOKE_META_AI_GROUP":case 30:a.botEntryPointOrigin=30;break;case"META_AI_FORWARD":case 31:a.botEntryPointOrigin=31;break;case"NEW_CHAT_AI_CONTACT":case 32:a.botEntryPointOrigin=32;break;case"MESSAGE_QUICK_ACTION_1_ON_1_CHAT":case 33:a.botEntryPointOrigin=33;break;case"MESSAGE_QUICK_ACTION_GROUP_CHAT":case 34:a.botEntryPointOrigin=34;break;case"ATTACHMENT_TRAY_1_ON_1_CHAT":case 35:a.botEntryPointOrigin=35;break;case"ATTACHMENT_TRAY_GROUP_CHAT":case 36:a.botEntryPointOrigin=36;break;case"ASK_META_AI_MEDIA_VIEWER_1ON1":case 37:a.botEntryPointOrigin=37;break;case"ASK_META_AI_MEDIA_VIEWER_GROUP":case 38:a.botEntryPointOrigin=38;break}return e.forwardScore!=null&&(a.forwardScore=e.forwardScore>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.botEntryPointOrigin!=null&&e.hasOwnProperty("botEntryPointOrigin")&&(A.botEntryPointOrigin=a.enums===String?p.proto.BotMetricsEntryPoint[e.botEntryPointOrigin]===void 0?e.botEntryPointOrigin:p.proto.BotMetricsEntryPoint[e.botEntryPointOrigin]:e.botEntryPointOrigin,a.oneofs&&(A._botEntryPointOrigin="botEntryPointOrigin")),e.forwardScore!=null&&e.hasOwnProperty("forwardScore")&&(A.forwardScore=e.forwardScore,a.oneofs&&(A._forwardScore="forwardScore")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMessageSharingInfo"},t})(),n.BotMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.avatarMetadata=p.proto.BotAvatarMetadata.decode(e,e.uint32());break}case 2:{s.personaId=e.string();break}case 3:{s.pluginMetadata=p.proto.BotPluginMetadata.decode(e,e.uint32());break}case 4:{s.suggestedPromptMetadata=p.proto.BotSuggestedPromptMetadata.decode(e,e.uint32());break}case 5:{s.invokerJid=e.string();break}case 6:{s.sessionMetadata=p.proto.BotSessionMetadata.decode(e,e.uint32());break}case 7:{s.memuMetadata=p.proto.BotMemuMetadata.decode(e,e.uint32());break}case 8:{s.timezone=e.string();break}case 9:{s.reminderMetadata=p.proto.BotReminderMetadata.decode(e,e.uint32());break}case 10:{s.modelMetadata=p.proto.BotModelMetadata.decode(e,e.uint32());break}case 11:{s.messageDisclaimerText=e.string();break}case 12:{s.progressIndicatorMetadata=p.proto.BotProgressIndicatorMetadata.decode(e,e.uint32());break}case 13:{s.capabilityMetadata=p.proto.BotCapabilityMetadata.decode(e,e.uint32());break}case 14:{s.imagineMetadata=p.proto.BotImagineMetadata.decode(e,e.uint32());break}case 15:{s.memoryMetadata=p.proto.BotMemoryMetadata.decode(e,e.uint32());break}case 16:{s.renderingMetadata=p.proto.BotRenderingMetadata.decode(e,e.uint32());break}case 17:{s.botMetricsMetadata=p.proto.BotMetricsMetadata.decode(e,e.uint32());break}case 18:{s.botLinkedAccountsMetadata=p.proto.BotLinkedAccountsMetadata.decode(e,e.uint32());break}case 19:{s.richResponseSourcesMetadata=p.proto.BotSourcesMetadata.decode(e,e.uint32());break}case 20:{s.aiConversationContext=e.bytes();break}case 21:{s.botPromotionMessageMetadata=p.proto.BotPromotionMessageMetadata.decode(e,e.uint32());break}case 22:{s.botModeSelectionMetadata=p.proto.BotModeSelectionMetadata.decode(e,e.uint32());break}case 23:{s.botQuotaMetadata=p.proto.BotQuotaMetadata.decode(e,e.uint32());break}case 24:{s.botAgeCollectionMetadata=p.proto.BotAgeCollectionMetadata.decode(e,e.uint32());break}case 25:{s.conversationStarterPromptId=e.string();break}case 26:{s.botResponseId=e.string();break}case 27:{s.verificationMetadata=p.proto.BotSignatureVerificationMetadata.decode(e,e.uint32());break}case 28:{s.unifiedResponseMutation=p.proto.BotUnifiedResponseMutation.decode(e,e.uint32());break}case 29:{s.botMessageOriginMetadata=p.proto.BotMessageOriginMetadata.decode(e,e.uint32());break}case 30:{s.inThreadSurveyMetadata=p.proto.InThreadSurveyMetadata.decode(e,e.uint32());break}case 31:{s.botThreadInfo=p.proto.AIThreadInfo.decode(e,e.uint32());break}case 32:{s.regenerateMetadata=p.proto.AIRegenerateMetadata.decode(e,e.uint32());break}case 33:{s.sessionTransparencyMetadata=p.proto.SessionTransparencyMetadata.decode(e,e.uint32());break}case 999:{s.internalMetadata=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMetadata)return e;var a=new p.proto.BotMetadata;if(e.avatarMetadata!=null){if(typeof e.avatarMetadata!="object")throw TypeError(".proto.BotMetadata.avatarMetadata: object expected");a.avatarMetadata=p.proto.BotAvatarMetadata.fromObject(e.avatarMetadata)}if(e.personaId!=null&&(a.personaId=String(e.personaId)),e.pluginMetadata!=null){if(typeof e.pluginMetadata!="object")throw TypeError(".proto.BotMetadata.pluginMetadata: object expected");a.pluginMetadata=p.proto.BotPluginMetadata.fromObject(e.pluginMetadata)}if(e.suggestedPromptMetadata!=null){if(typeof e.suggestedPromptMetadata!="object")throw TypeError(".proto.BotMetadata.suggestedPromptMetadata: object expected");a.suggestedPromptMetadata=p.proto.BotSuggestedPromptMetadata.fromObject(e.suggestedPromptMetadata)}if(e.invokerJid!=null&&(a.invokerJid=String(e.invokerJid)),e.sessionMetadata!=null){if(typeof e.sessionMetadata!="object")throw TypeError(".proto.BotMetadata.sessionMetadata: object expected");a.sessionMetadata=p.proto.BotSessionMetadata.fromObject(e.sessionMetadata)}if(e.memuMetadata!=null){if(typeof e.memuMetadata!="object")throw TypeError(".proto.BotMetadata.memuMetadata: object expected");a.memuMetadata=p.proto.BotMemuMetadata.fromObject(e.memuMetadata)}if(e.timezone!=null&&(a.timezone=String(e.timezone)),e.reminderMetadata!=null){if(typeof e.reminderMetadata!="object")throw TypeError(".proto.BotMetadata.reminderMetadata: object expected");a.reminderMetadata=p.proto.BotReminderMetadata.fromObject(e.reminderMetadata)}if(e.modelMetadata!=null){if(typeof e.modelMetadata!="object")throw TypeError(".proto.BotMetadata.modelMetadata: object expected");a.modelMetadata=p.proto.BotModelMetadata.fromObject(e.modelMetadata)}if(e.messageDisclaimerText!=null&&(a.messageDisclaimerText=String(e.messageDisclaimerText)),e.progressIndicatorMetadata!=null){if(typeof e.progressIndicatorMetadata!="object")throw TypeError(".proto.BotMetadata.progressIndicatorMetadata: object expected");a.progressIndicatorMetadata=p.proto.BotProgressIndicatorMetadata.fromObject(e.progressIndicatorMetadata)}if(e.capabilityMetadata!=null){if(typeof e.capabilityMetadata!="object")throw TypeError(".proto.BotMetadata.capabilityMetadata: object expected");a.capabilityMetadata=p.proto.BotCapabilityMetadata.fromObject(e.capabilityMetadata)}if(e.imagineMetadata!=null){if(typeof e.imagineMetadata!="object")throw TypeError(".proto.BotMetadata.imagineMetadata: object expected");a.imagineMetadata=p.proto.BotImagineMetadata.fromObject(e.imagineMetadata)}if(e.memoryMetadata!=null){if(typeof e.memoryMetadata!="object")throw TypeError(".proto.BotMetadata.memoryMetadata: object expected");a.memoryMetadata=p.proto.BotMemoryMetadata.fromObject(e.memoryMetadata)}if(e.renderingMetadata!=null){if(typeof e.renderingMetadata!="object")throw TypeError(".proto.BotMetadata.renderingMetadata: object expected");a.renderingMetadata=p.proto.BotRenderingMetadata.fromObject(e.renderingMetadata)}if(e.botMetricsMetadata!=null){if(typeof e.botMetricsMetadata!="object")throw TypeError(".proto.BotMetadata.botMetricsMetadata: object expected");a.botMetricsMetadata=p.proto.BotMetricsMetadata.fromObject(e.botMetricsMetadata)}if(e.botLinkedAccountsMetadata!=null){if(typeof e.botLinkedAccountsMetadata!="object")throw TypeError(".proto.BotMetadata.botLinkedAccountsMetadata: object expected");a.botLinkedAccountsMetadata=p.proto.BotLinkedAccountsMetadata.fromObject(e.botLinkedAccountsMetadata)}if(e.richResponseSourcesMetadata!=null){if(typeof e.richResponseSourcesMetadata!="object")throw TypeError(".proto.BotMetadata.richResponseSourcesMetadata: object expected");a.richResponseSourcesMetadata=p.proto.BotSourcesMetadata.fromObject(e.richResponseSourcesMetadata)}if(e.aiConversationContext!=null&&(typeof e.aiConversationContext=="string"?l.base64.decode(e.aiConversationContext,a.aiConversationContext=l.newBuffer(l.base64.length(e.aiConversationContext)),0):e.aiConversationContext.length>=0&&(a.aiConversationContext=e.aiConversationContext)),e.botPromotionMessageMetadata!=null){if(typeof e.botPromotionMessageMetadata!="object")throw TypeError(".proto.BotMetadata.botPromotionMessageMetadata: object expected");a.botPromotionMessageMetadata=p.proto.BotPromotionMessageMetadata.fromObject(e.botPromotionMessageMetadata)}if(e.botModeSelectionMetadata!=null){if(typeof e.botModeSelectionMetadata!="object")throw TypeError(".proto.BotMetadata.botModeSelectionMetadata: object expected");a.botModeSelectionMetadata=p.proto.BotModeSelectionMetadata.fromObject(e.botModeSelectionMetadata)}if(e.botQuotaMetadata!=null){if(typeof e.botQuotaMetadata!="object")throw TypeError(".proto.BotMetadata.botQuotaMetadata: object expected");a.botQuotaMetadata=p.proto.BotQuotaMetadata.fromObject(e.botQuotaMetadata)}if(e.botAgeCollectionMetadata!=null){if(typeof e.botAgeCollectionMetadata!="object")throw TypeError(".proto.BotMetadata.botAgeCollectionMetadata: object expected");a.botAgeCollectionMetadata=p.proto.BotAgeCollectionMetadata.fromObject(e.botAgeCollectionMetadata)}if(e.conversationStarterPromptId!=null&&(a.conversationStarterPromptId=String(e.conversationStarterPromptId)),e.botResponseId!=null&&(a.botResponseId=String(e.botResponseId)),e.verificationMetadata!=null){if(typeof e.verificationMetadata!="object")throw TypeError(".proto.BotMetadata.verificationMetadata: object expected");a.verificationMetadata=p.proto.BotSignatureVerificationMetadata.fromObject(e.verificationMetadata)}if(e.unifiedResponseMutation!=null){if(typeof e.unifiedResponseMutation!="object")throw TypeError(".proto.BotMetadata.unifiedResponseMutation: object expected");a.unifiedResponseMutation=p.proto.BotUnifiedResponseMutation.fromObject(e.unifiedResponseMutation)}if(e.botMessageOriginMetadata!=null){if(typeof e.botMessageOriginMetadata!="object")throw TypeError(".proto.BotMetadata.botMessageOriginMetadata: object expected");a.botMessageOriginMetadata=p.proto.BotMessageOriginMetadata.fromObject(e.botMessageOriginMetadata)}if(e.inThreadSurveyMetadata!=null){if(typeof e.inThreadSurveyMetadata!="object")throw TypeError(".proto.BotMetadata.inThreadSurveyMetadata: object expected");a.inThreadSurveyMetadata=p.proto.InThreadSurveyMetadata.fromObject(e.inThreadSurveyMetadata)}if(e.botThreadInfo!=null){if(typeof e.botThreadInfo!="object")throw TypeError(".proto.BotMetadata.botThreadInfo: object expected");a.botThreadInfo=p.proto.AIThreadInfo.fromObject(e.botThreadInfo)}if(e.regenerateMetadata!=null){if(typeof e.regenerateMetadata!="object")throw TypeError(".proto.BotMetadata.regenerateMetadata: object expected");a.regenerateMetadata=p.proto.AIRegenerateMetadata.fromObject(e.regenerateMetadata)}if(e.sessionTransparencyMetadata!=null){if(typeof e.sessionTransparencyMetadata!="object")throw TypeError(".proto.BotMetadata.sessionTransparencyMetadata: object expected");a.sessionTransparencyMetadata=p.proto.SessionTransparencyMetadata.fromObject(e.sessionTransparencyMetadata)}return e.internalMetadata!=null&&(typeof e.internalMetadata=="string"?l.base64.decode(e.internalMetadata,a.internalMetadata=l.newBuffer(l.base64.length(e.internalMetadata)),0):e.internalMetadata.length>=0&&(a.internalMetadata=e.internalMetadata)),a},t.toObject=function(e,a){a||(a={});var A={};return e.avatarMetadata!=null&&e.hasOwnProperty("avatarMetadata")&&(A.avatarMetadata=p.proto.BotAvatarMetadata.toObject(e.avatarMetadata,a),a.oneofs&&(A._avatarMetadata="avatarMetadata")),e.personaId!=null&&e.hasOwnProperty("personaId")&&(A.personaId=e.personaId,a.oneofs&&(A._personaId="personaId")),e.pluginMetadata!=null&&e.hasOwnProperty("pluginMetadata")&&(A.pluginMetadata=p.proto.BotPluginMetadata.toObject(e.pluginMetadata,a),a.oneofs&&(A._pluginMetadata="pluginMetadata")),e.suggestedPromptMetadata!=null&&e.hasOwnProperty("suggestedPromptMetadata")&&(A.suggestedPromptMetadata=p.proto.BotSuggestedPromptMetadata.toObject(e.suggestedPromptMetadata,a),a.oneofs&&(A._suggestedPromptMetadata="suggestedPromptMetadata")),e.invokerJid!=null&&e.hasOwnProperty("invokerJid")&&(A.invokerJid=e.invokerJid,a.oneofs&&(A._invokerJid="invokerJid")),e.sessionMetadata!=null&&e.hasOwnProperty("sessionMetadata")&&(A.sessionMetadata=p.proto.BotSessionMetadata.toObject(e.sessionMetadata,a),a.oneofs&&(A._sessionMetadata="sessionMetadata")),e.memuMetadata!=null&&e.hasOwnProperty("memuMetadata")&&(A.memuMetadata=p.proto.BotMemuMetadata.toObject(e.memuMetadata,a),a.oneofs&&(A._memuMetadata="memuMetadata")),e.timezone!=null&&e.hasOwnProperty("timezone")&&(A.timezone=e.timezone,a.oneofs&&(A._timezone="timezone")),e.reminderMetadata!=null&&e.hasOwnProperty("reminderMetadata")&&(A.reminderMetadata=p.proto.BotReminderMetadata.toObject(e.reminderMetadata,a),a.oneofs&&(A._reminderMetadata="reminderMetadata")),e.modelMetadata!=null&&e.hasOwnProperty("modelMetadata")&&(A.modelMetadata=p.proto.BotModelMetadata.toObject(e.modelMetadata,a),a.oneofs&&(A._modelMetadata="modelMetadata")),e.messageDisclaimerText!=null&&e.hasOwnProperty("messageDisclaimerText")&&(A.messageDisclaimerText=e.messageDisclaimerText,a.oneofs&&(A._messageDisclaimerText="messageDisclaimerText")),e.progressIndicatorMetadata!=null&&e.hasOwnProperty("progressIndicatorMetadata")&&(A.progressIndicatorMetadata=p.proto.BotProgressIndicatorMetadata.toObject(e.progressIndicatorMetadata,a),a.oneofs&&(A._progressIndicatorMetadata="progressIndicatorMetadata")),e.capabilityMetadata!=null&&e.hasOwnProperty("capabilityMetadata")&&(A.capabilityMetadata=p.proto.BotCapabilityMetadata.toObject(e.capabilityMetadata,a),a.oneofs&&(A._capabilityMetadata="capabilityMetadata")),e.imagineMetadata!=null&&e.hasOwnProperty("imagineMetadata")&&(A.imagineMetadata=p.proto.BotImagineMetadata.toObject(e.imagineMetadata,a),a.oneofs&&(A._imagineMetadata="imagineMetadata")),e.memoryMetadata!=null&&e.hasOwnProperty("memoryMetadata")&&(A.memoryMetadata=p.proto.BotMemoryMetadata.toObject(e.memoryMetadata,a),a.oneofs&&(A._memoryMetadata="memoryMetadata")),e.renderingMetadata!=null&&e.hasOwnProperty("renderingMetadata")&&(A.renderingMetadata=p.proto.BotRenderingMetadata.toObject(e.renderingMetadata,a),a.oneofs&&(A._renderingMetadata="renderingMetadata")),e.botMetricsMetadata!=null&&e.hasOwnProperty("botMetricsMetadata")&&(A.botMetricsMetadata=p.proto.BotMetricsMetadata.toObject(e.botMetricsMetadata,a),a.oneofs&&(A._botMetricsMetadata="botMetricsMetadata")),e.botLinkedAccountsMetadata!=null&&e.hasOwnProperty("botLinkedAccountsMetadata")&&(A.botLinkedAccountsMetadata=p.proto.BotLinkedAccountsMetadata.toObject(e.botLinkedAccountsMetadata,a),a.oneofs&&(A._botLinkedAccountsMetadata="botLinkedAccountsMetadata")),e.richResponseSourcesMetadata!=null&&e.hasOwnProperty("richResponseSourcesMetadata")&&(A.richResponseSourcesMetadata=p.proto.BotSourcesMetadata.toObject(e.richResponseSourcesMetadata,a),a.oneofs&&(A._richResponseSourcesMetadata="richResponseSourcesMetadata")),e.aiConversationContext!=null&&e.hasOwnProperty("aiConversationContext")&&(A.aiConversationContext=a.bytes===String?l.base64.encode(e.aiConversationContext,0,e.aiConversationContext.length):a.bytes===Array?Array.prototype.slice.call(e.aiConversationContext):e.aiConversationContext,a.oneofs&&(A._aiConversationContext="aiConversationContext")),e.botPromotionMessageMetadata!=null&&e.hasOwnProperty("botPromotionMessageMetadata")&&(A.botPromotionMessageMetadata=p.proto.BotPromotionMessageMetadata.toObject(e.botPromotionMessageMetadata,a),a.oneofs&&(A._botPromotionMessageMetadata="botPromotionMessageMetadata")),e.botModeSelectionMetadata!=null&&e.hasOwnProperty("botModeSelectionMetadata")&&(A.botModeSelectionMetadata=p.proto.BotModeSelectionMetadata.toObject(e.botModeSelectionMetadata,a),a.oneofs&&(A._botModeSelectionMetadata="botModeSelectionMetadata")),e.botQuotaMetadata!=null&&e.hasOwnProperty("botQuotaMetadata")&&(A.botQuotaMetadata=p.proto.BotQuotaMetadata.toObject(e.botQuotaMetadata,a),a.oneofs&&(A._botQuotaMetadata="botQuotaMetadata")),e.botAgeCollectionMetadata!=null&&e.hasOwnProperty("botAgeCollectionMetadata")&&(A.botAgeCollectionMetadata=p.proto.BotAgeCollectionMetadata.toObject(e.botAgeCollectionMetadata,a),a.oneofs&&(A._botAgeCollectionMetadata="botAgeCollectionMetadata")),e.conversationStarterPromptId!=null&&e.hasOwnProperty("conversationStarterPromptId")&&(A.conversationStarterPromptId=e.conversationStarterPromptId,a.oneofs&&(A._conversationStarterPromptId="conversationStarterPromptId")),e.botResponseId!=null&&e.hasOwnProperty("botResponseId")&&(A.botResponseId=e.botResponseId,a.oneofs&&(A._botResponseId="botResponseId")),e.verificationMetadata!=null&&e.hasOwnProperty("verificationMetadata")&&(A.verificationMetadata=p.proto.BotSignatureVerificationMetadata.toObject(e.verificationMetadata,a),a.oneofs&&(A._verificationMetadata="verificationMetadata")),e.unifiedResponseMutation!=null&&e.hasOwnProperty("unifiedResponseMutation")&&(A.unifiedResponseMutation=p.proto.BotUnifiedResponseMutation.toObject(e.unifiedResponseMutation,a),a.oneofs&&(A._unifiedResponseMutation="unifiedResponseMutation")),e.botMessageOriginMetadata!=null&&e.hasOwnProperty("botMessageOriginMetadata")&&(A.botMessageOriginMetadata=p.proto.BotMessageOriginMetadata.toObject(e.botMessageOriginMetadata,a),a.oneofs&&(A._botMessageOriginMetadata="botMessageOriginMetadata")),e.inThreadSurveyMetadata!=null&&e.hasOwnProperty("inThreadSurveyMetadata")&&(A.inThreadSurveyMetadata=p.proto.InThreadSurveyMetadata.toObject(e.inThreadSurveyMetadata,a),a.oneofs&&(A._inThreadSurveyMetadata="inThreadSurveyMetadata")),e.botThreadInfo!=null&&e.hasOwnProperty("botThreadInfo")&&(A.botThreadInfo=p.proto.AIThreadInfo.toObject(e.botThreadInfo,a),a.oneofs&&(A._botThreadInfo="botThreadInfo")),e.regenerateMetadata!=null&&e.hasOwnProperty("regenerateMetadata")&&(A.regenerateMetadata=p.proto.AIRegenerateMetadata.toObject(e.regenerateMetadata,a),a.oneofs&&(A._regenerateMetadata="regenerateMetadata")),e.sessionTransparencyMetadata!=null&&e.hasOwnProperty("sessionTransparencyMetadata")&&(A.sessionTransparencyMetadata=p.proto.SessionTransparencyMetadata.toObject(e.sessionTransparencyMetadata,a),a.oneofs&&(A._sessionTransparencyMetadata="sessionTransparencyMetadata")),e.internalMetadata!=null&&e.hasOwnProperty("internalMetadata")&&(A.internalMetadata=a.bytes===String?l.base64.encode(e.internalMetadata,0,e.internalMetadata.length):a.bytes===Array?Array.prototype.slice.call(e.internalMetadata):e.internalMetadata,a.oneofs&&(A._internalMetadata="internalMetadata")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMetadata"},t})(),n.BotMetricsEntryPoint=(function(){let t={},o=Object.create(t);return o[t[0]="UNDEFINED_ENTRY_POINT"]=0,o[t[1]="FAVICON"]=1,o[t[2]="CHATLIST"]=2,o[t[3]="AISEARCH_NULL_STATE_PAPER_PLANE"]=3,o[t[4]="AISEARCH_NULL_STATE_SUGGESTION"]=4,o[t[5]="AISEARCH_TYPE_AHEAD_SUGGESTION"]=5,o[t[6]="AISEARCH_TYPE_AHEAD_PAPER_PLANE"]=6,o[t[7]="AISEARCH_TYPE_AHEAD_RESULT_CHATLIST"]=7,o[t[8]="AISEARCH_TYPE_AHEAD_RESULT_MESSAGES"]=8,o[t[9]="AIVOICE_SEARCH_BAR"]=9,o[t[10]="AIVOICE_FAVICON"]=10,o[t[11]="AISTUDIO"]=11,o[t[12]="DEEPLINK"]=12,o[t[13]="NOTIFICATION"]=13,o[t[14]="PROFILE_MESSAGE_BUTTON"]=14,o[t[15]="FORWARD"]=15,o[t[16]="APP_SHORTCUT"]=16,o[t[17]="FF_FAMILY"]=17,o[t[18]="AI_TAB"]=18,o[t[19]="AI_HOME"]=19,o[t[20]="AI_DEEPLINK_IMMERSIVE"]=20,o[t[21]="AI_DEEPLINK"]=21,o[t[22]="META_AI_CHAT_SHORTCUT_AI_STUDIO"]=22,o[t[23]="UGC_CHAT_SHORTCUT_AI_STUDIO"]=23,o[t[24]="NEW_CHAT_AI_STUDIO"]=24,o[t[25]="AIVOICE_FAVICON_CALL_HISTORY"]=25,o[t[26]="ASK_META_AI_CONTEXT_MENU"]=26,o[t[27]="ASK_META_AI_CONTEXT_MENU_1ON1"]=27,o[t[28]="ASK_META_AI_CONTEXT_MENU_GROUP"]=28,o[t[29]="INVOKE_META_AI_1ON1"]=29,o[t[30]="INVOKE_META_AI_GROUP"]=30,o[t[31]="META_AI_FORWARD"]=31,o[t[32]="NEW_CHAT_AI_CONTACT"]=32,o[t[33]="MESSAGE_QUICK_ACTION_1_ON_1_CHAT"]=33,o[t[34]="MESSAGE_QUICK_ACTION_GROUP_CHAT"]=34,o[t[35]="ATTACHMENT_TRAY_1_ON_1_CHAT"]=35,o[t[36]="ATTACHMENT_TRAY_GROUP_CHAT"]=36,o[t[37]="ASK_META_AI_MEDIA_VIEWER_1ON1"]=37,o[t[38]="ASK_META_AI_MEDIA_VIEWER_GROUP"]=38,o})(),n.BotMetricsMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.destinationId=e.string();break}case 2:{s.destinationEntryPoint=e.int32();break}case 3:{s.threadOrigin=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMetricsMetadata)return e;var a=new p.proto.BotMetricsMetadata;switch(e.destinationId!=null&&(a.destinationId=String(e.destinationId)),e.destinationEntryPoint){default:if(typeof e.destinationEntryPoint=="number"){a.destinationEntryPoint=e.destinationEntryPoint;break}break;case"UNDEFINED_ENTRY_POINT":case 0:a.destinationEntryPoint=0;break;case"FAVICON":case 1:a.destinationEntryPoint=1;break;case"CHATLIST":case 2:a.destinationEntryPoint=2;break;case"AISEARCH_NULL_STATE_PAPER_PLANE":case 3:a.destinationEntryPoint=3;break;case"AISEARCH_NULL_STATE_SUGGESTION":case 4:a.destinationEntryPoint=4;break;case"AISEARCH_TYPE_AHEAD_SUGGESTION":case 5:a.destinationEntryPoint=5;break;case"AISEARCH_TYPE_AHEAD_PAPER_PLANE":case 6:a.destinationEntryPoint=6;break;case"AISEARCH_TYPE_AHEAD_RESULT_CHATLIST":case 7:a.destinationEntryPoint=7;break;case"AISEARCH_TYPE_AHEAD_RESULT_MESSAGES":case 8:a.destinationEntryPoint=8;break;case"AIVOICE_SEARCH_BAR":case 9:a.destinationEntryPoint=9;break;case"AIVOICE_FAVICON":case 10:a.destinationEntryPoint=10;break;case"AISTUDIO":case 11:a.destinationEntryPoint=11;break;case"DEEPLINK":case 12:a.destinationEntryPoint=12;break;case"NOTIFICATION":case 13:a.destinationEntryPoint=13;break;case"PROFILE_MESSAGE_BUTTON":case 14:a.destinationEntryPoint=14;break;case"FORWARD":case 15:a.destinationEntryPoint=15;break;case"APP_SHORTCUT":case 16:a.destinationEntryPoint=16;break;case"FF_FAMILY":case 17:a.destinationEntryPoint=17;break;case"AI_TAB":case 18:a.destinationEntryPoint=18;break;case"AI_HOME":case 19:a.destinationEntryPoint=19;break;case"AI_DEEPLINK_IMMERSIVE":case 20:a.destinationEntryPoint=20;break;case"AI_DEEPLINK":case 21:a.destinationEntryPoint=21;break;case"META_AI_CHAT_SHORTCUT_AI_STUDIO":case 22:a.destinationEntryPoint=22;break;case"UGC_CHAT_SHORTCUT_AI_STUDIO":case 23:a.destinationEntryPoint=23;break;case"NEW_CHAT_AI_STUDIO":case 24:a.destinationEntryPoint=24;break;case"AIVOICE_FAVICON_CALL_HISTORY":case 25:a.destinationEntryPoint=25;break;case"ASK_META_AI_CONTEXT_MENU":case 26:a.destinationEntryPoint=26;break;case"ASK_META_AI_CONTEXT_MENU_1ON1":case 27:a.destinationEntryPoint=27;break;case"ASK_META_AI_CONTEXT_MENU_GROUP":case 28:a.destinationEntryPoint=28;break;case"INVOKE_META_AI_1ON1":case 29:a.destinationEntryPoint=29;break;case"INVOKE_META_AI_GROUP":case 30:a.destinationEntryPoint=30;break;case"META_AI_FORWARD":case 31:a.destinationEntryPoint=31;break;case"NEW_CHAT_AI_CONTACT":case 32:a.destinationEntryPoint=32;break;case"MESSAGE_QUICK_ACTION_1_ON_1_CHAT":case 33:a.destinationEntryPoint=33;break;case"MESSAGE_QUICK_ACTION_GROUP_CHAT":case 34:a.destinationEntryPoint=34;break;case"ATTACHMENT_TRAY_1_ON_1_CHAT":case 35:a.destinationEntryPoint=35;break;case"ATTACHMENT_TRAY_GROUP_CHAT":case 36:a.destinationEntryPoint=36;break;case"ASK_META_AI_MEDIA_VIEWER_1ON1":case 37:a.destinationEntryPoint=37;break;case"ASK_META_AI_MEDIA_VIEWER_GROUP":case 38:a.destinationEntryPoint=38;break}switch(e.threadOrigin){default:if(typeof e.threadOrigin=="number"){a.threadOrigin=e.threadOrigin;break}break;case"AI_TAB_THREAD":case 1:a.threadOrigin=1;break;case"AI_HOME_THREAD":case 2:a.threadOrigin=2;break;case"AI_DEEPLINK_IMMERSIVE_THREAD":case 3:a.threadOrigin=3;break;case"AI_DEEPLINK_THREAD":case 4:a.threadOrigin=4;break;case"ASK_META_AI_CONTEXT_MENU_THREAD":case 5:a.threadOrigin=5;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.destinationId!=null&&e.hasOwnProperty("destinationId")&&(A.destinationId=e.destinationId,a.oneofs&&(A._destinationId="destinationId")),e.destinationEntryPoint!=null&&e.hasOwnProperty("destinationEntryPoint")&&(A.destinationEntryPoint=a.enums===String?p.proto.BotMetricsEntryPoint[e.destinationEntryPoint]===void 0?e.destinationEntryPoint:p.proto.BotMetricsEntryPoint[e.destinationEntryPoint]:e.destinationEntryPoint,a.oneofs&&(A._destinationEntryPoint="destinationEntryPoint")),e.threadOrigin!=null&&e.hasOwnProperty("threadOrigin")&&(A.threadOrigin=a.enums===String?p.proto.BotMetricsThreadEntryPoint[e.threadOrigin]===void 0?e.threadOrigin:p.proto.BotMetricsThreadEntryPoint[e.threadOrigin]:e.threadOrigin,a.oneofs&&(A._threadOrigin="threadOrigin")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMetricsMetadata"},t})(),n.BotMetricsThreadEntryPoint=(function(){let t={},o=Object.create(t);return o[t[1]="AI_TAB_THREAD"]=1,o[t[2]="AI_HOME_THREAD"]=2,o[t[3]="AI_DEEPLINK_IMMERSIVE_THREAD"]=3,o[t[4]="AI_DEEPLINK_THREAD"]=4,o[t[5]="ASK_META_AI_CONTEXT_MENU_THREAD"]=5,o})(),n.BotModeSelectionMetadata=(function(){function t(o){if(this.mode=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{if(r.mode&&r.mode.length||(r.mode=[]),(s&7)===2)for(var g=i.uint32()+i.pos;i.pos>>3){case 1:{s.modelType=e.int32();break}case 2:{s.premiumModelStatus=e.int32();break}case 3:{s.modelNameOverride=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotModelMetadata)return e;var a=new p.proto.BotModelMetadata;switch(e.modelType){default:if(typeof e.modelType=="number"){a.modelType=e.modelType;break}break;case"UNKNOWN_TYPE":case 0:a.modelType=0;break;case"LLAMA_PROD":case 1:a.modelType=1;break;case"LLAMA_PROD_PREMIUM":case 2:a.modelType=2;break}switch(e.premiumModelStatus){default:if(typeof e.premiumModelStatus=="number"){a.premiumModelStatus=e.premiumModelStatus;break}break;case"UNKNOWN_STATUS":case 0:a.premiumModelStatus=0;break;case"AVAILABLE":case 1:a.premiumModelStatus=1;break;case"QUOTA_EXCEED_LIMIT":case 2:a.premiumModelStatus=2;break}return e.modelNameOverride!=null&&(a.modelNameOverride=String(e.modelNameOverride)),a},t.toObject=function(e,a){a||(a={});var A={};return e.modelType!=null&&e.hasOwnProperty("modelType")&&(A.modelType=a.enums===String?p.proto.BotModelMetadata.ModelType[e.modelType]===void 0?e.modelType:p.proto.BotModelMetadata.ModelType[e.modelType]:e.modelType,a.oneofs&&(A._modelType="modelType")),e.premiumModelStatus!=null&&e.hasOwnProperty("premiumModelStatus")&&(A.premiumModelStatus=a.enums===String?p.proto.BotModelMetadata.PremiumModelStatus[e.premiumModelStatus]===void 0?e.premiumModelStatus:p.proto.BotModelMetadata.PremiumModelStatus[e.premiumModelStatus]:e.premiumModelStatus,a.oneofs&&(A._premiumModelStatus="premiumModelStatus")),e.modelNameOverride!=null&&e.hasOwnProperty("modelNameOverride")&&(A.modelNameOverride=e.modelNameOverride,a.oneofs&&(A._modelNameOverride="modelNameOverride")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotModelMetadata"},t.ModelType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_TYPE"]=0,e[i[1]="LLAMA_PROD"]=1,e[i[2]="LLAMA_PROD_PREMIUM"]=2,e})(),t.PremiumModelStatus=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_STATUS"]=0,e[i[1]="AVAILABLE"]=1,e[i[2]="QUOTA_EXCEED_LIMIT"]=2,e})(),t})(),n.BotPluginMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.provider=e.int32();break}case 2:{s.pluginType=e.int32();break}case 3:{s.thumbnailCdnUrl=e.string();break}case 4:{s.profilePhotoCdnUrl=e.string();break}case 5:{s.searchProviderUrl=e.string();break}case 6:{s.referenceIndex=e.uint32();break}case 7:{s.expectedLinksCount=e.uint32();break}case 9:{s.searchQuery=e.string();break}case 10:{s.parentPluginMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 11:{s.deprecatedField=e.int32();break}case 12:{s.parentPluginType=e.int32();break}case 13:{s.faviconCdnUrl=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotPluginMetadata)return e;var a=new p.proto.BotPluginMetadata;switch(e.provider){default:if(typeof e.provider=="number"){a.provider=e.provider;break}break;case"UNKNOWN":case 0:a.provider=0;break;case"BING":case 1:a.provider=1;break;case"GOOGLE":case 2:a.provider=2;break;case"SUPPORT":case 3:a.provider=3;break}switch(e.pluginType){default:if(typeof e.pluginType=="number"){a.pluginType=e.pluginType;break}break;case"UNKNOWN_PLUGIN":case 0:a.pluginType=0;break;case"REELS":case 1:a.pluginType=1;break;case"SEARCH":case 2:a.pluginType=2;break}if(e.thumbnailCdnUrl!=null&&(a.thumbnailCdnUrl=String(e.thumbnailCdnUrl)),e.profilePhotoCdnUrl!=null&&(a.profilePhotoCdnUrl=String(e.profilePhotoCdnUrl)),e.searchProviderUrl!=null&&(a.searchProviderUrl=String(e.searchProviderUrl)),e.referenceIndex!=null&&(a.referenceIndex=e.referenceIndex>>>0),e.expectedLinksCount!=null&&(a.expectedLinksCount=e.expectedLinksCount>>>0),e.searchQuery!=null&&(a.searchQuery=String(e.searchQuery)),e.parentPluginMessageKey!=null){if(typeof e.parentPluginMessageKey!="object")throw TypeError(".proto.BotPluginMetadata.parentPluginMessageKey: object expected");a.parentPluginMessageKey=p.proto.MessageKey.fromObject(e.parentPluginMessageKey)}switch(e.deprecatedField){default:if(typeof e.deprecatedField=="number"){a.deprecatedField=e.deprecatedField;break}break;case"UNKNOWN_PLUGIN":case 0:a.deprecatedField=0;break;case"REELS":case 1:a.deprecatedField=1;break;case"SEARCH":case 2:a.deprecatedField=2;break}switch(e.parentPluginType){default:if(typeof e.parentPluginType=="number"){a.parentPluginType=e.parentPluginType;break}break;case"UNKNOWN_PLUGIN":case 0:a.parentPluginType=0;break;case"REELS":case 1:a.parentPluginType=1;break;case"SEARCH":case 2:a.parentPluginType=2;break}return e.faviconCdnUrl!=null&&(a.faviconCdnUrl=String(e.faviconCdnUrl)),a},t.toObject=function(e,a){a||(a={});var A={};return e.provider!=null&&e.hasOwnProperty("provider")&&(A.provider=a.enums===String?p.proto.BotPluginMetadata.SearchProvider[e.provider]===void 0?e.provider:p.proto.BotPluginMetadata.SearchProvider[e.provider]:e.provider,a.oneofs&&(A._provider="provider")),e.pluginType!=null&&e.hasOwnProperty("pluginType")&&(A.pluginType=a.enums===String?p.proto.BotPluginMetadata.PluginType[e.pluginType]===void 0?e.pluginType:p.proto.BotPluginMetadata.PluginType[e.pluginType]:e.pluginType,a.oneofs&&(A._pluginType="pluginType")),e.thumbnailCdnUrl!=null&&e.hasOwnProperty("thumbnailCdnUrl")&&(A.thumbnailCdnUrl=e.thumbnailCdnUrl,a.oneofs&&(A._thumbnailCdnUrl="thumbnailCdnUrl")),e.profilePhotoCdnUrl!=null&&e.hasOwnProperty("profilePhotoCdnUrl")&&(A.profilePhotoCdnUrl=e.profilePhotoCdnUrl,a.oneofs&&(A._profilePhotoCdnUrl="profilePhotoCdnUrl")),e.searchProviderUrl!=null&&e.hasOwnProperty("searchProviderUrl")&&(A.searchProviderUrl=e.searchProviderUrl,a.oneofs&&(A._searchProviderUrl="searchProviderUrl")),e.referenceIndex!=null&&e.hasOwnProperty("referenceIndex")&&(A.referenceIndex=e.referenceIndex,a.oneofs&&(A._referenceIndex="referenceIndex")),e.expectedLinksCount!=null&&e.hasOwnProperty("expectedLinksCount")&&(A.expectedLinksCount=e.expectedLinksCount,a.oneofs&&(A._expectedLinksCount="expectedLinksCount")),e.searchQuery!=null&&e.hasOwnProperty("searchQuery")&&(A.searchQuery=e.searchQuery,a.oneofs&&(A._searchQuery="searchQuery")),e.parentPluginMessageKey!=null&&e.hasOwnProperty("parentPluginMessageKey")&&(A.parentPluginMessageKey=p.proto.MessageKey.toObject(e.parentPluginMessageKey,a),a.oneofs&&(A._parentPluginMessageKey="parentPluginMessageKey")),e.deprecatedField!=null&&e.hasOwnProperty("deprecatedField")&&(A.deprecatedField=a.enums===String?p.proto.BotPluginMetadata.PluginType[e.deprecatedField]===void 0?e.deprecatedField:p.proto.BotPluginMetadata.PluginType[e.deprecatedField]:e.deprecatedField,a.oneofs&&(A._deprecatedField="deprecatedField")),e.parentPluginType!=null&&e.hasOwnProperty("parentPluginType")&&(A.parentPluginType=a.enums===String?p.proto.BotPluginMetadata.PluginType[e.parentPluginType]===void 0?e.parentPluginType:p.proto.BotPluginMetadata.PluginType[e.parentPluginType]:e.parentPluginType,a.oneofs&&(A._parentPluginType="parentPluginType")),e.faviconCdnUrl!=null&&e.hasOwnProperty("faviconCdnUrl")&&(A.faviconCdnUrl=e.faviconCdnUrl,a.oneofs&&(A._faviconCdnUrl="faviconCdnUrl")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotPluginMetadata"},t.PluginType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_PLUGIN"]=0,e[i[1]="REELS"]=1,e[i[2]="SEARCH"]=2,e})(),t.SearchProvider=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="BING"]=1,e[i[2]="GOOGLE"]=2,e[i[3]="SUPPORT"]=3,e})(),t})(),n.BotProgressIndicatorMetadata=(function(){function t(i){if(this.stepsMetadata=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.progressDescription=e.string();break}case 2:{s.stepsMetadata&&s.stepsMetadata.length||(s.stepsMetadata=[]),s.stepsMetadata.push(p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotProgressIndicatorMetadata)return e;var a=new p.proto.BotProgressIndicatorMetadata;if(e.progressDescription!=null&&(a.progressDescription=String(e.progressDescription)),e.stepsMetadata){if(!Array.isArray(e.stepsMetadata))throw TypeError(".proto.BotProgressIndicatorMetadata.stepsMetadata: array expected");a.stepsMetadata=[];for(var A=0;A>>3){case 1:{c.statusTitle=A.string();break}case 2:{c.statusBody=A.string();break}case 3:{c.sourcesMetadata&&c.sourcesMetadata.length||(c.sourcesMetadata=[]),c.sourcesMetadata.push(p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata.decode(A,A.uint32()));break}case 4:{c.status=A.int32();break}case 5:{c.isReasoning=A.bool();break}case 6:{c.isEnhancedSearch=A.bool();break}case 7:{c.sections&&c.sections.length||(c.sections=[]),c.sections.push(p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata)return A;var r=new p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata;if(A.statusTitle!=null&&(r.statusTitle=String(A.statusTitle)),A.statusBody!=null&&(r.statusBody=String(A.statusBody)),A.sourcesMetadata){if(!Array.isArray(A.sourcesMetadata))throw TypeError(".proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.sourcesMetadata: array expected");r.sourcesMetadata=[];for(var s=0;s>>3){case 1:{d.title=s.string();break}case 2:{d.provider=s.int32();break}case 3:{d.sourceUrl=s.string();break}case 4:{d.favIconUrl=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata)return s;var g=new p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata;switch(s.title!=null&&(g.title=String(s.title)),s.provider){default:if(typeof s.provider=="number"){g.provider=s.provider;break}break;case"UNKNOWN_PROVIDER":case 0:g.provider=0;break;case"OTHER":case 1:g.provider=1;break;case"GOOGLE":case 2:g.provider=2;break;case"BING":case 3:g.provider=3;break}return s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),s.favIconUrl!=null&&(g.favIconUrl=String(s.favIconUrl)),g},a.toObject=function(s,g){g||(g={});var c={};return s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.provider!=null&&s.hasOwnProperty("provider")&&(c.provider=g.enums===String?p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotSearchSourceProvider[s.provider]===void 0?s.provider:p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotSearchSourceProvider[s.provider]:s.provider,g.oneofs&&(c._provider="provider")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),s.favIconUrl!=null&&s.hasOwnProperty("favIconUrl")&&(c.favIconUrl=s.favIconUrl,g.oneofs&&(c._favIconUrl="favIconUrl")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata"},a})(),i.BotPlanningSearchSourcesMetadata=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.sourceTitle=s.string();break}case 2:{d.provider=s.int32();break}case 3:{d.sourceUrl=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata)return s;var g=new p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata;switch(s.sourceTitle!=null&&(g.sourceTitle=String(s.sourceTitle)),s.provider){default:if(typeof s.provider=="number"){g.provider=s.provider;break}break;case"UNKNOWN":case 0:g.provider=0;break;case"OTHER":case 1:g.provider=1;break;case"GOOGLE":case 2:g.provider=2;break;case"BING":case 3:g.provider=3;break}return s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),g},a.toObject=function(s,g){g||(g={});var c={};return s.sourceTitle!=null&&s.hasOwnProperty("sourceTitle")&&(c.sourceTitle=s.sourceTitle,g.oneofs&&(c._sourceTitle="sourceTitle")),s.provider!=null&&s.hasOwnProperty("provider")&&(c.provider=g.enums===String?p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata.BotPlanningSearchSourceProvider[s.provider]===void 0?s.provider:p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata.BotPlanningSearchSourceProvider[s.provider]:s.provider,g.oneofs&&(c._provider="provider")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata"},a.BotPlanningSearchSourceProvider=(function(){let r={},s=Object.create(r);return s[r[0]="UNKNOWN"]=0,s[r[1]="OTHER"]=1,s[r[2]="GOOGLE"]=2,s[r[3]="BING"]=3,s})(),a})(),i.BotPlanningStepSectionMetadata=(function(){function a(r){if(this.sourcesMetadata=[],r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.sectionTitle=s.string();break}case 2:{d.sectionBody=s.string();break}case 3:{d.sourcesMetadata&&d.sourcesMetadata.length||(d.sourcesMetadata=[]),d.sourcesMetadata.push(p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata.decode(s,s.uint32()));break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata)return s;var g=new p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata;if(s.sectionTitle!=null&&(g.sectionTitle=String(s.sectionTitle)),s.sectionBody!=null&&(g.sectionBody=String(s.sectionBody)),s.sourcesMetadata){if(!Array.isArray(s.sourcesMetadata))throw TypeError(".proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata.sourcesMetadata: array expected");g.sourcesMetadata=[];for(var c=0;c>>3){case 1:{s.promotionType=e.int32();break}case 2:{s.buttonTitle=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotPromotionMessageMetadata)return e;var a=new p.proto.BotPromotionMessageMetadata;switch(e.promotionType){default:if(typeof e.promotionType=="number"){a.promotionType=e.promotionType;break}break;case"UNKNOWN_TYPE":case 0:a.promotionType=0;break;case"C50":case 1:a.promotionType=1;break;case"SURVEY_PLATFORM":case 2:a.promotionType=2;break}return e.buttonTitle!=null&&(a.buttonTitle=String(e.buttonTitle)),a},t.toObject=function(e,a){a||(a={});var A={};return e.promotionType!=null&&e.hasOwnProperty("promotionType")&&(A.promotionType=a.enums===String?p.proto.BotPromotionMessageMetadata.BotPromotionType[e.promotionType]===void 0?e.promotionType:p.proto.BotPromotionMessageMetadata.BotPromotionType[e.promotionType]:e.promotionType,a.oneofs&&(A._promotionType="promotionType")),e.buttonTitle!=null&&e.hasOwnProperty("buttonTitle")&&(A.buttonTitle=e.buttonTitle,a.oneofs&&(A._buttonTitle="buttonTitle")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotPromotionMessageMetadata"},t.BotPromotionType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_TYPE"]=0,e[i[1]="C50"]=1,e[i[2]="SURVEY_PLATFORM"]=2,e})(),t})(),n.BotPromptSuggestion=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.prompt=e.string();break}case 2:{s.promptId=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotPromptSuggestion)return e;var a=new p.proto.BotPromptSuggestion;return e.prompt!=null&&(a.prompt=String(e.prompt)),e.promptId!=null&&(a.promptId=String(e.promptId)),a},t.toObject=function(e,a){a||(a={});var A={};return e.prompt!=null&&e.hasOwnProperty("prompt")&&(A.prompt=e.prompt,a.oneofs&&(A._prompt="prompt")),e.promptId!=null&&e.hasOwnProperty("promptId")&&(A.promptId=e.promptId,a.oneofs&&(A._promptId="promptId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotPromptSuggestion"},t})(),n.BotPromptSuggestions=(function(){function t(o){if(this.suggestions=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.suggestions&&r.suggestions.length||(r.suggestions=[]),r.suggestions.push(p.proto.BotPromptSuggestion.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotPromptSuggestions)return i;var e=new p.proto.BotPromptSuggestions;if(i.suggestions){if(!Array.isArray(i.suggestions))throw TypeError(".proto.BotPromptSuggestions.suggestions: array expected");e.suggestions=[];for(var a=0;a>>3){case 1:{r.botFeatureQuotaMetadata&&r.botFeatureQuotaMetadata.length||(r.botFeatureQuotaMetadata=[]),r.botFeatureQuotaMetadata.push(p.proto.BotQuotaMetadata.BotFeatureQuotaMetadata.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotQuotaMetadata)return i;var e=new p.proto.BotQuotaMetadata;if(i.botFeatureQuotaMetadata){if(!Array.isArray(i.botFeatureQuotaMetadata))throw TypeError(".proto.BotQuotaMetadata.botFeatureQuotaMetadata: array expected");e.botFeatureQuotaMetadata=[];for(var a=0;a>>3){case 1:{g.featureType=a.int32();break}case 2:{g.remainingQuota=a.uint32();break}case 3:{g.expirationTimestamp=a.uint64();break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof p.proto.BotQuotaMetadata.BotFeatureQuotaMetadata)return a;var A=new p.proto.BotQuotaMetadata.BotFeatureQuotaMetadata;switch(a.featureType){default:if(typeof a.featureType=="number"){A.featureType=a.featureType;break}break;case"UNKNOWN_FEATURE":case 0:A.featureType=0;break;case"REASONING_FEATURE":case 1:A.featureType=1;break}return a.remainingQuota!=null&&(A.remainingQuota=a.remainingQuota>>>0),a.expirationTimestamp!=null&&(l.Long?(A.expirationTimestamp=l.Long.fromValue(a.expirationTimestamp)).unsigned=!0:typeof a.expirationTimestamp=="string"?A.expirationTimestamp=parseInt(a.expirationTimestamp,10):typeof a.expirationTimestamp=="number"?A.expirationTimestamp=a.expirationTimestamp:typeof a.expirationTimestamp=="object"&&(A.expirationTimestamp=new l.LongBits(a.expirationTimestamp.low>>>0,a.expirationTimestamp.high>>>0).toNumber(!0))),A},o.toObject=function(a,A){A||(A={});var r={};return a.featureType!=null&&a.hasOwnProperty("featureType")&&(r.featureType=A.enums===String?p.proto.BotQuotaMetadata.BotFeatureQuotaMetadata.BotFeatureType[a.featureType]===void 0?a.featureType:p.proto.BotQuotaMetadata.BotFeatureQuotaMetadata.BotFeatureType[a.featureType]:a.featureType,A.oneofs&&(r._featureType="featureType")),a.remainingQuota!=null&&a.hasOwnProperty("remainingQuota")&&(r.remainingQuota=a.remainingQuota,A.oneofs&&(r._remainingQuota="remainingQuota")),a.expirationTimestamp!=null&&a.hasOwnProperty("expirationTimestamp")&&(typeof a.expirationTimestamp=="number"?r.expirationTimestamp=A.longs===String?String(a.expirationTimestamp):a.expirationTimestamp:r.expirationTimestamp=A.longs===String?se(a.expirationTimestamp,!0):A.longs===Number?ge(a.expirationTimestamp,!0):a.expirationTimestamp,A.oneofs&&(r._expirationTimestamp="expirationTimestamp")),r},o.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.BotQuotaMetadata.BotFeatureQuotaMetadata"},o.BotFeatureType=(function(){let e={},a=Object.create(e);return a[e[0]="UNKNOWN_FEATURE"]=0,a[e[1]="REASONING_FEATURE"]=1,a})(),o})(),t})(),n.BotReminderMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.requestMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.action=e.int32();break}case 3:{s.name=e.string();break}case 4:{s.nextTriggerTimestamp=e.uint64();break}case 5:{s.frequency=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotReminderMetadata)return e;var a=new p.proto.BotReminderMetadata;if(e.requestMessageKey!=null){if(typeof e.requestMessageKey!="object")throw TypeError(".proto.BotReminderMetadata.requestMessageKey: object expected");a.requestMessageKey=p.proto.MessageKey.fromObject(e.requestMessageKey)}switch(e.action){default:if(typeof e.action=="number"){a.action=e.action;break}break;case"NOTIFY":case 1:a.action=1;break;case"CREATE":case 2:a.action=2;break;case"DELETE":case 3:a.action=3;break;case"UPDATE":case 4:a.action=4;break}switch(e.name!=null&&(a.name=String(e.name)),e.nextTriggerTimestamp!=null&&(l.Long?(a.nextTriggerTimestamp=l.Long.fromValue(e.nextTriggerTimestamp)).unsigned=!0:typeof e.nextTriggerTimestamp=="string"?a.nextTriggerTimestamp=parseInt(e.nextTriggerTimestamp,10):typeof e.nextTriggerTimestamp=="number"?a.nextTriggerTimestamp=e.nextTriggerTimestamp:typeof e.nextTriggerTimestamp=="object"&&(a.nextTriggerTimestamp=new l.LongBits(e.nextTriggerTimestamp.low>>>0,e.nextTriggerTimestamp.high>>>0).toNumber(!0))),e.frequency){default:if(typeof e.frequency=="number"){a.frequency=e.frequency;break}break;case"ONCE":case 1:a.frequency=1;break;case"DAILY":case 2:a.frequency=2;break;case"WEEKLY":case 3:a.frequency=3;break;case"BIWEEKLY":case 4:a.frequency=4;break;case"MONTHLY":case 5:a.frequency=5;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.requestMessageKey!=null&&e.hasOwnProperty("requestMessageKey")&&(A.requestMessageKey=p.proto.MessageKey.toObject(e.requestMessageKey,a),a.oneofs&&(A._requestMessageKey="requestMessageKey")),e.action!=null&&e.hasOwnProperty("action")&&(A.action=a.enums===String?p.proto.BotReminderMetadata.ReminderAction[e.action]===void 0?e.action:p.proto.BotReminderMetadata.ReminderAction[e.action]:e.action,a.oneofs&&(A._action="action")),e.name!=null&&e.hasOwnProperty("name")&&(A.name=e.name,a.oneofs&&(A._name="name")),e.nextTriggerTimestamp!=null&&e.hasOwnProperty("nextTriggerTimestamp")&&(typeof e.nextTriggerTimestamp=="number"?A.nextTriggerTimestamp=a.longs===String?String(e.nextTriggerTimestamp):e.nextTriggerTimestamp:A.nextTriggerTimestamp=a.longs===String?se(e.nextTriggerTimestamp,!0):a.longs===Number?ge(e.nextTriggerTimestamp,!0):e.nextTriggerTimestamp,a.oneofs&&(A._nextTriggerTimestamp="nextTriggerTimestamp")),e.frequency!=null&&e.hasOwnProperty("frequency")&&(A.frequency=a.enums===String?p.proto.BotReminderMetadata.ReminderFrequency[e.frequency]===void 0?e.frequency:p.proto.BotReminderMetadata.ReminderFrequency[e.frequency]:e.frequency,a.oneofs&&(A._frequency="frequency")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotReminderMetadata"},t.ReminderAction=(function(){let i={},e=Object.create(i);return e[i[1]="NOTIFY"]=1,e[i[2]="CREATE"]=2,e[i[3]="DELETE"]=3,e[i[4]="UPDATE"]=4,e})(),t.ReminderFrequency=(function(){let i={},e=Object.create(i);return e[i[1]="ONCE"]=1,e[i[2]="DAILY"]=2,e[i[3]="WEEKLY"]=3,e[i[4]="BIWEEKLY"]=4,e[i[5]="MONTHLY"]=5,e})(),t})(),n.BotRenderingMetadata=(function(){function t(o){if(this.keywords=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.keywords&&r.keywords.length||(r.keywords=[]),r.keywords.push(p.proto.BotRenderingMetadata.Keyword.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotRenderingMetadata)return i;var e=new p.proto.BotRenderingMetadata;if(i.keywords){if(!Array.isArray(i.keywords))throw TypeError(".proto.BotRenderingMetadata.keywords: array expected");e.keywords=[];for(var a=0;a>>3){case 1:{g.value=a.string();break}case 2:{g.associatedPrompts&&g.associatedPrompts.length||(g.associatedPrompts=[]),g.associatedPrompts.push(a.string());break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof p.proto.BotRenderingMetadata.Keyword)return a;var A=new p.proto.BotRenderingMetadata.Keyword;if(a.value!=null&&(A.value=String(a.value)),a.associatedPrompts){if(!Array.isArray(a.associatedPrompts))throw TypeError(".proto.BotRenderingMetadata.Keyword.associatedPrompts: array expected");A.associatedPrompts=[];for(var r=0;r>>3){case 1:{s.sessionId=e.string();break}case 2:{s.sessionSource=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotSessionMetadata)return e;var a=new p.proto.BotSessionMetadata;switch(e.sessionId!=null&&(a.sessionId=String(e.sessionId)),e.sessionSource){default:if(typeof e.sessionSource=="number"){a.sessionSource=e.sessionSource;break}break;case"NONE":case 0:a.sessionSource=0;break;case"NULL_STATE":case 1:a.sessionSource=1;break;case"TYPEAHEAD":case 2:a.sessionSource=2;break;case"USER_INPUT":case 3:a.sessionSource=3;break;case"EMU_FLASH":case 4:a.sessionSource=4;break;case"EMU_FLASH_FOLLOWUP":case 5:a.sessionSource=5;break;case"VOICE":case 6:a.sessionSource=6;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.sessionId!=null&&e.hasOwnProperty("sessionId")&&(A.sessionId=e.sessionId,a.oneofs&&(A._sessionId="sessionId")),e.sessionSource!=null&&e.hasOwnProperty("sessionSource")&&(A.sessionSource=a.enums===String?p.proto.BotSessionSource[e.sessionSource]===void 0?e.sessionSource:p.proto.BotSessionSource[e.sessionSource]:e.sessionSource,a.oneofs&&(A._sessionSource="sessionSource")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotSessionMetadata"},t})(),n.BotSessionSource=(function(){let t={},o=Object.create(t);return o[t[0]="NONE"]=0,o[t[1]="NULL_STATE"]=1,o[t[2]="TYPEAHEAD"]=2,o[t[3]="USER_INPUT"]=3,o[t[4]="EMU_FLASH"]=4,o[t[5]="EMU_FLASH_FOLLOWUP"]=5,o[t[6]="VOICE"]=6,o})(),n.BotSignatureVerificationMetadata=(function(){function t(o){if(this.proofs=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.proofs&&r.proofs.length||(r.proofs=[]),r.proofs.push(p.proto.BotSignatureVerificationUseCaseProof.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotSignatureVerificationMetadata)return i;var e=new p.proto.BotSignatureVerificationMetadata;if(i.proofs){if(!Array.isArray(i.proofs))throw TypeError(".proto.BotSignatureVerificationMetadata.proofs: array expected");e.proofs=[];for(var a=0;a>>3){case 1:{s.version=e.int32();break}case 2:{s.useCase=e.int32();break}case 3:{s.signature=e.bytes();break}case 4:{s.certificateChain&&s.certificateChain.length||(s.certificateChain=[]),s.certificateChain.push(e.bytes());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotSignatureVerificationUseCaseProof)return e;var a=new p.proto.BotSignatureVerificationUseCaseProof;switch(e.version!=null&&(a.version=e.version|0),e.useCase){default:if(typeof e.useCase=="number"){a.useCase=e.useCase;break}break;case"UNSPECIFIED":case 0:a.useCase=0;break;case"WA_BOT_MSG":case 1:a.useCase=1;break}if(e.signature!=null&&(typeof e.signature=="string"?l.base64.decode(e.signature,a.signature=l.newBuffer(l.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),e.certificateChain){if(!Array.isArray(e.certificateChain))throw TypeError(".proto.BotSignatureVerificationUseCaseProof.certificateChain: array expected");a.certificateChain=[];for(var A=0;A=0&&(a.certificateChain[A]=e.certificateChain[A])}return a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.certificateChain=[]),e.version!=null&&e.hasOwnProperty("version")&&(A.version=e.version,a.oneofs&&(A._version="version")),e.useCase!=null&&e.hasOwnProperty("useCase")&&(A.useCase=a.enums===String?p.proto.BotSignatureVerificationUseCaseProof.BotSignatureUseCase[e.useCase]===void 0?e.useCase:p.proto.BotSignatureVerificationUseCaseProof.BotSignatureUseCase[e.useCase]:e.useCase,a.oneofs&&(A._useCase="useCase")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?l.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),e.certificateChain&&e.certificateChain.length){A.certificateChain=[];for(var r=0;r>>3){case 1:{r.sources&&r.sources.length||(r.sources=[]),r.sources.push(p.proto.BotSourcesMetadata.BotSourceItem.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotSourcesMetadata)return i;var e=new p.proto.BotSourcesMetadata;if(i.sources){if(!Array.isArray(i.sources))throw TypeError(".proto.BotSourcesMetadata.sources: array expected");e.sources=[];for(var a=0;a>>3){case 1:{g.provider=a.int32();break}case 2:{g.thumbnailCdnUrl=a.string();break}case 3:{g.sourceProviderUrl=a.string();break}case 4:{g.sourceQuery=a.string();break}case 5:{g.faviconCdnUrl=a.string();break}case 6:{g.citationNumber=a.uint32();break}case 7:{g.sourceTitle=a.string();break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof p.proto.BotSourcesMetadata.BotSourceItem)return a;var A=new p.proto.BotSourcesMetadata.BotSourceItem;switch(a.provider){default:if(typeof a.provider=="number"){A.provider=a.provider;break}break;case"UNKNOWN":case 0:A.provider=0;break;case"BING":case 1:A.provider=1;break;case"GOOGLE":case 2:A.provider=2;break;case"SUPPORT":case 3:A.provider=3;break;case"OTHER":case 4:A.provider=4;break}return a.thumbnailCdnUrl!=null&&(A.thumbnailCdnUrl=String(a.thumbnailCdnUrl)),a.sourceProviderUrl!=null&&(A.sourceProviderUrl=String(a.sourceProviderUrl)),a.sourceQuery!=null&&(A.sourceQuery=String(a.sourceQuery)),a.faviconCdnUrl!=null&&(A.faviconCdnUrl=String(a.faviconCdnUrl)),a.citationNumber!=null&&(A.citationNumber=a.citationNumber>>>0),a.sourceTitle!=null&&(A.sourceTitle=String(a.sourceTitle)),A},o.toObject=function(a,A){A||(A={});var r={};return a.provider!=null&&a.hasOwnProperty("provider")&&(r.provider=A.enums===String?p.proto.BotSourcesMetadata.BotSourceItem.SourceProvider[a.provider]===void 0?a.provider:p.proto.BotSourcesMetadata.BotSourceItem.SourceProvider[a.provider]:a.provider,A.oneofs&&(r._provider="provider")),a.thumbnailCdnUrl!=null&&a.hasOwnProperty("thumbnailCdnUrl")&&(r.thumbnailCdnUrl=a.thumbnailCdnUrl,A.oneofs&&(r._thumbnailCdnUrl="thumbnailCdnUrl")),a.sourceProviderUrl!=null&&a.hasOwnProperty("sourceProviderUrl")&&(r.sourceProviderUrl=a.sourceProviderUrl,A.oneofs&&(r._sourceProviderUrl="sourceProviderUrl")),a.sourceQuery!=null&&a.hasOwnProperty("sourceQuery")&&(r.sourceQuery=a.sourceQuery,A.oneofs&&(r._sourceQuery="sourceQuery")),a.faviconCdnUrl!=null&&a.hasOwnProperty("faviconCdnUrl")&&(r.faviconCdnUrl=a.faviconCdnUrl,A.oneofs&&(r._faviconCdnUrl="faviconCdnUrl")),a.citationNumber!=null&&a.hasOwnProperty("citationNumber")&&(r.citationNumber=a.citationNumber,A.oneofs&&(r._citationNumber="citationNumber")),a.sourceTitle!=null&&a.hasOwnProperty("sourceTitle")&&(r.sourceTitle=a.sourceTitle,A.oneofs&&(r._sourceTitle="sourceTitle")),r},o.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.BotSourcesMetadata.BotSourceItem"},o.SourceProvider=(function(){let e={},a=Object.create(e);return a[e[0]="UNKNOWN"]=0,a[e[1]="BING"]=1,a[e[2]="GOOGLE"]=2,a[e[3]="SUPPORT"]=3,a[e[4]="OTHER"]=4,a})(),o})(),t})(),n.BotSuggestedPromptMetadata=(function(){function t(i){if(this.suggestedPrompts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.suggestedPrompts&&s.suggestedPrompts.length||(s.suggestedPrompts=[]),s.suggestedPrompts.push(e.string());break}case 2:{s.selectedPromptIndex=e.uint32();break}case 3:{s.promptSuggestions=p.proto.BotPromptSuggestions.decode(e,e.uint32());break}case 4:{s.selectedPromptId=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotSuggestedPromptMetadata)return e;var a=new p.proto.BotSuggestedPromptMetadata;if(e.suggestedPrompts){if(!Array.isArray(e.suggestedPrompts))throw TypeError(".proto.BotSuggestedPromptMetadata.suggestedPrompts: array expected");a.suggestedPrompts=[];for(var A=0;A>>0),e.promptSuggestions!=null){if(typeof e.promptSuggestions!="object")throw TypeError(".proto.BotSuggestedPromptMetadata.promptSuggestions: object expected");a.promptSuggestions=p.proto.BotPromptSuggestions.fromObject(e.promptSuggestions)}return e.selectedPromptId!=null&&(a.selectedPromptId=String(e.selectedPromptId)),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.suggestedPrompts=[]),e.suggestedPrompts&&e.suggestedPrompts.length){A.suggestedPrompts=[];for(var r=0;r>>3){case 1:{s.sbsMetadata=p.proto.BotUnifiedResponseMutation.SideBySideMetadata.decode(e,e.uint32());break}case 2:{s.mediaDetailsMetadataList&&s.mediaDetailsMetadataList.length||(s.mediaDetailsMetadataList=[]),s.mediaDetailsMetadataList.push(p.proto.BotUnifiedResponseMutation.MediaDetailsMetadata.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotUnifiedResponseMutation)return e;var a=new p.proto.BotUnifiedResponseMutation;if(e.sbsMetadata!=null){if(typeof e.sbsMetadata!="object")throw TypeError(".proto.BotUnifiedResponseMutation.sbsMetadata: object expected");a.sbsMetadata=p.proto.BotUnifiedResponseMutation.SideBySideMetadata.fromObject(e.sbsMetadata)}if(e.mediaDetailsMetadataList){if(!Array.isArray(e.mediaDetailsMetadataList))throw TypeError(".proto.BotUnifiedResponseMutation.mediaDetailsMetadataList: array expected");a.mediaDetailsMetadataList=[];for(var A=0;A>>3){case 1:{c.id=A.string();break}case 2:{c.highResMedia=p.proto.BotMediaMetadata.decode(A,A.uint32());break}case 3:{c.previewMedia=p.proto.BotMediaMetadata.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.BotUnifiedResponseMutation.MediaDetailsMetadata)return A;var r=new p.proto.BotUnifiedResponseMutation.MediaDetailsMetadata;if(A.id!=null&&(r.id=String(A.id)),A.highResMedia!=null){if(typeof A.highResMedia!="object")throw TypeError(".proto.BotUnifiedResponseMutation.MediaDetailsMetadata.highResMedia: object expected");r.highResMedia=p.proto.BotMediaMetadata.fromObject(A.highResMedia)}if(A.previewMedia!=null){if(typeof A.previewMedia!="object")throw TypeError(".proto.BotUnifiedResponseMutation.MediaDetailsMetadata.previewMedia: object expected");r.previewMedia=p.proto.BotMediaMetadata.fromObject(A.previewMedia)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,r.oneofs&&(s._id="id")),A.highResMedia!=null&&A.hasOwnProperty("highResMedia")&&(s.highResMedia=p.proto.BotMediaMetadata.toObject(A.highResMedia,r),r.oneofs&&(s._highResMedia="highResMedia")),A.previewMedia!=null&&A.hasOwnProperty("previewMedia")&&(s.previewMedia=p.proto.BotMediaMetadata.toObject(A.previewMedia,r),r.oneofs&&(s._previewMedia="previewMedia")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.BotUnifiedResponseMutation.MediaDetailsMetadata"},i})(),t.SideBySideMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.primaryResponseId=A.string();break}case 2:{c.surveyCtaHasRendered=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.BotUnifiedResponseMutation.SideBySideMetadata)return A;var r=new p.proto.BotUnifiedResponseMutation.SideBySideMetadata;return A.primaryResponseId!=null&&(r.primaryResponseId=String(A.primaryResponseId)),A.surveyCtaHasRendered!=null&&(r.surveyCtaHasRendered=!!A.surveyCtaHasRendered),r},i.toObject=function(A,r){r||(r={});var s={};return A.primaryResponseId!=null&&A.hasOwnProperty("primaryResponseId")&&(s.primaryResponseId=A.primaryResponseId,r.oneofs&&(s._primaryResponseId="primaryResponseId")),A.surveyCtaHasRendered!=null&&A.hasOwnProperty("surveyCtaHasRendered")&&(s.surveyCtaHasRendered=A.surveyCtaHasRendered,r.oneofs&&(s._surveyCtaHasRendered="surveyCtaHasRendered")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.BotUnifiedResponseMutation.SideBySideMetadata"},i})(),t})(),n.CallLogRecord=(function(){function t(i){if(this.participants=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.callResult=e.int32();break}case 2:{s.isDndMode=e.bool();break}case 3:{s.silenceReason=e.int32();break}case 4:{s.duration=e.int64();break}case 5:{s.startTime=e.int64();break}case 6:{s.isIncoming=e.bool();break}case 7:{s.isVideo=e.bool();break}case 8:{s.isCallLink=e.bool();break}case 9:{s.callLinkToken=e.string();break}case 10:{s.scheduledCallId=e.string();break}case 11:{s.callId=e.string();break}case 12:{s.callCreatorJid=e.string();break}case 13:{s.groupJid=e.string();break}case 14:{s.participants&&s.participants.length||(s.participants=[]),s.participants.push(p.proto.CallLogRecord.ParticipantInfo.decode(e,e.uint32()));break}case 15:{s.callType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.CallLogRecord)return e;var a=new p.proto.CallLogRecord;switch(e.callResult){default:if(typeof e.callResult=="number"){a.callResult=e.callResult;break}break;case"CONNECTED":case 0:a.callResult=0;break;case"REJECTED":case 1:a.callResult=1;break;case"CANCELLED":case 2:a.callResult=2;break;case"ACCEPTEDELSEWHERE":case 3:a.callResult=3;break;case"MISSED":case 4:a.callResult=4;break;case"INVALID":case 5:a.callResult=5;break;case"UNAVAILABLE":case 6:a.callResult=6;break;case"UPCOMING":case 7:a.callResult=7;break;case"FAILED":case 8:a.callResult=8;break;case"ABANDONED":case 9:a.callResult=9;break;case"ONGOING":case 10:a.callResult=10;break}switch(e.isDndMode!=null&&(a.isDndMode=!!e.isDndMode),e.silenceReason){default:if(typeof e.silenceReason=="number"){a.silenceReason=e.silenceReason;break}break;case"NONE":case 0:a.silenceReason=0;break;case"SCHEDULED":case 1:a.silenceReason=1;break;case"PRIVACY":case 2:a.silenceReason=2;break;case"LIGHTWEIGHT":case 3:a.silenceReason=3;break}if(e.duration!=null&&(l.Long?(a.duration=l.Long.fromValue(e.duration)).unsigned=!1:typeof e.duration=="string"?a.duration=parseInt(e.duration,10):typeof e.duration=="number"?a.duration=e.duration:typeof e.duration=="object"&&(a.duration=new l.LongBits(e.duration.low>>>0,e.duration.high>>>0).toNumber())),e.startTime!=null&&(l.Long?(a.startTime=l.Long.fromValue(e.startTime)).unsigned=!1:typeof e.startTime=="string"?a.startTime=parseInt(e.startTime,10):typeof e.startTime=="number"?a.startTime=e.startTime:typeof e.startTime=="object"&&(a.startTime=new l.LongBits(e.startTime.low>>>0,e.startTime.high>>>0).toNumber())),e.isIncoming!=null&&(a.isIncoming=!!e.isIncoming),e.isVideo!=null&&(a.isVideo=!!e.isVideo),e.isCallLink!=null&&(a.isCallLink=!!e.isCallLink),e.callLinkToken!=null&&(a.callLinkToken=String(e.callLinkToken)),e.scheduledCallId!=null&&(a.scheduledCallId=String(e.scheduledCallId)),e.callId!=null&&(a.callId=String(e.callId)),e.callCreatorJid!=null&&(a.callCreatorJid=String(e.callCreatorJid)),e.groupJid!=null&&(a.groupJid=String(e.groupJid)),e.participants){if(!Array.isArray(e.participants))throw TypeError(".proto.CallLogRecord.participants: array expected");a.participants=[];for(var A=0;A>>3){case 1:{c.userJid=A.string();break}case 2:{c.callResult=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.CallLogRecord.ParticipantInfo)return A;var r=new p.proto.CallLogRecord.ParticipantInfo;switch(A.userJid!=null&&(r.userJid=String(A.userJid)),A.callResult){default:if(typeof A.callResult=="number"){r.callResult=A.callResult;break}break;case"CONNECTED":case 0:r.callResult=0;break;case"REJECTED":case 1:r.callResult=1;break;case"CANCELLED":case 2:r.callResult=2;break;case"ACCEPTEDELSEWHERE":case 3:r.callResult=3;break;case"MISSED":case 4:r.callResult=4;break;case"INVALID":case 5:r.callResult=5;break;case"UNAVAILABLE":case 6:r.callResult=6;break;case"UPCOMING":case 7:r.callResult=7;break;case"FAILED":case 8:r.callResult=8;break;case"ABANDONED":case 9:r.callResult=9;break;case"ONGOING":case 10:r.callResult=10;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.userJid!=null&&A.hasOwnProperty("userJid")&&(s.userJid=A.userJid,r.oneofs&&(s._userJid="userJid")),A.callResult!=null&&A.hasOwnProperty("callResult")&&(s.callResult=r.enums===String?p.proto.CallLogRecord.CallResult[A.callResult]===void 0?A.callResult:p.proto.CallLogRecord.CallResult[A.callResult]:A.callResult,r.oneofs&&(s._callResult="callResult")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.CallLogRecord.ParticipantInfo"},i})(),t.SilenceReason=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="SCHEDULED"]=1,e[i[2]="PRIVACY"]=2,e[i[3]="LIGHTWEIGHT"]=3,e})(),t})(),n.CertChain=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.leaf=p.proto.CertChain.NoiseCertificate.decode(e,e.uint32());break}case 2:{s.intermediate=p.proto.CertChain.NoiseCertificate.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.CertChain)return e;var a=new p.proto.CertChain;if(e.leaf!=null){if(typeof e.leaf!="object")throw TypeError(".proto.CertChain.leaf: object expected");a.leaf=p.proto.CertChain.NoiseCertificate.fromObject(e.leaf)}if(e.intermediate!=null){if(typeof e.intermediate!="object")throw TypeError(".proto.CertChain.intermediate: object expected");a.intermediate=p.proto.CertChain.NoiseCertificate.fromObject(e.intermediate)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.leaf!=null&&e.hasOwnProperty("leaf")&&(A.leaf=p.proto.CertChain.NoiseCertificate.toObject(e.leaf,a),a.oneofs&&(A._leaf="leaf")),e.intermediate!=null&&e.hasOwnProperty("intermediate")&&(A.intermediate=p.proto.CertChain.NoiseCertificate.toObject(e.intermediate,a),a.oneofs&&(A._intermediate="intermediate")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CertChain"},t.NoiseCertificate=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.details=A.bytes();break}case 2:{c.signature=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.CertChain.NoiseCertificate)return A;var r=new p.proto.CertChain.NoiseCertificate;return A.details!=null&&(typeof A.details=="string"?l.base64.decode(A.details,r.details=l.newBuffer(l.base64.length(A.details)),0):A.details.length>=0&&(r.details=A.details)),A.signature!=null&&(typeof A.signature=="string"?l.base64.decode(A.signature,r.signature=l.newBuffer(l.base64.length(A.signature)),0):A.signature.length>=0&&(r.signature=A.signature)),r},i.toObject=function(A,r){r||(r={});var s={};return A.details!=null&&A.hasOwnProperty("details")&&(s.details=r.bytes===String?l.base64.encode(A.details,0,A.details.length):r.bytes===Array?Array.prototype.slice.call(A.details):A.details,r.oneofs&&(s._details="details")),A.signature!=null&&A.hasOwnProperty("signature")&&(s.signature=r.bytes===String?l.base64.encode(A.signature,0,A.signature.length):r.bytes===Array?Array.prototype.slice.call(A.signature):A.signature,r.oneofs&&(s._signature="signature")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.CertChain.NoiseCertificate"},i.Details=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.serial=s.uint32();break}case 2:{d.issuerSerial=s.uint32();break}case 3:{d.key=s.bytes();break}case 4:{d.notBefore=s.uint64();break}case 5:{d.notAfter=s.uint64();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.CertChain.NoiseCertificate.Details)return s;var g=new p.proto.CertChain.NoiseCertificate.Details;return s.serial!=null&&(g.serial=s.serial>>>0),s.issuerSerial!=null&&(g.issuerSerial=s.issuerSerial>>>0),s.key!=null&&(typeof s.key=="string"?l.base64.decode(s.key,g.key=l.newBuffer(l.base64.length(s.key)),0):s.key.length>=0&&(g.key=s.key)),s.notBefore!=null&&(l.Long?(g.notBefore=l.Long.fromValue(s.notBefore)).unsigned=!0:typeof s.notBefore=="string"?g.notBefore=parseInt(s.notBefore,10):typeof s.notBefore=="number"?g.notBefore=s.notBefore:typeof s.notBefore=="object"&&(g.notBefore=new l.LongBits(s.notBefore.low>>>0,s.notBefore.high>>>0).toNumber(!0))),s.notAfter!=null&&(l.Long?(g.notAfter=l.Long.fromValue(s.notAfter)).unsigned=!0:typeof s.notAfter=="string"?g.notAfter=parseInt(s.notAfter,10):typeof s.notAfter=="number"?g.notAfter=s.notAfter:typeof s.notAfter=="object"&&(g.notAfter=new l.LongBits(s.notAfter.low>>>0,s.notAfter.high>>>0).toNumber(!0))),g},a.toObject=function(s,g){g||(g={});var c={};return s.serial!=null&&s.hasOwnProperty("serial")&&(c.serial=s.serial,g.oneofs&&(c._serial="serial")),s.issuerSerial!=null&&s.hasOwnProperty("issuerSerial")&&(c.issuerSerial=s.issuerSerial,g.oneofs&&(c._issuerSerial="issuerSerial")),s.key!=null&&s.hasOwnProperty("key")&&(c.key=g.bytes===String?l.base64.encode(s.key,0,s.key.length):g.bytes===Array?Array.prototype.slice.call(s.key):s.key,g.oneofs&&(c._key="key")),s.notBefore!=null&&s.hasOwnProperty("notBefore")&&(typeof s.notBefore=="number"?c.notBefore=g.longs===String?String(s.notBefore):s.notBefore:c.notBefore=g.longs===String?se(s.notBefore,!0):g.longs===Number?ge(s.notBefore,!0):s.notBefore,g.oneofs&&(c._notBefore="notBefore")),s.notAfter!=null&&s.hasOwnProperty("notAfter")&&(typeof s.notAfter=="number"?c.notAfter=g.longs===String?String(s.notAfter):s.notAfter:c.notAfter=g.longs===String?se(s.notAfter,!0):g.longs===Number?ge(s.notAfter,!0):s.notAfter,g.oneofs&&(c._notAfter="notAfter")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.CertChain.NoiseCertificate.Details"},a})(),i})(),t})(),n.ChatLockSettings=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.hideLockedChats=e.bool();break}case 2:{s.secretCode=p.proto.UserPassword.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ChatLockSettings)return e;var a=new p.proto.ChatLockSettings;if(e.hideLockedChats!=null&&(a.hideLockedChats=!!e.hideLockedChats),e.secretCode!=null){if(typeof e.secretCode!="object")throw TypeError(".proto.ChatLockSettings.secretCode: object expected");a.secretCode=p.proto.UserPassword.fromObject(e.secretCode)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.hideLockedChats!=null&&e.hasOwnProperty("hideLockedChats")&&(A.hideLockedChats=e.hideLockedChats,a.oneofs&&(A._hideLockedChats="hideLockedChats")),e.secretCode!=null&&e.hasOwnProperty("secretCode")&&(A.secretCode=p.proto.UserPassword.toObject(e.secretCode,a),a.oneofs&&(A._secretCode="secretCode")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ChatLockSettings"},t})(),n.ChatRowOpaqueData=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.draftMessage=p.proto.ChatRowOpaqueData.DraftMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ChatRowOpaqueData)return e;var a=new p.proto.ChatRowOpaqueData;if(e.draftMessage!=null){if(typeof e.draftMessage!="object")throw TypeError(".proto.ChatRowOpaqueData.draftMessage: object expected");a.draftMessage=p.proto.ChatRowOpaqueData.DraftMessage.fromObject(e.draftMessage)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.draftMessage!=null&&e.hasOwnProperty("draftMessage")&&(A.draftMessage=p.proto.ChatRowOpaqueData.DraftMessage.toObject(e.draftMessage,a),a.oneofs&&(A._draftMessage="draftMessage")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ChatRowOpaqueData"},t.DraftMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.text=A.string();break}case 2:{c.omittedUrl=A.string();break}case 3:{c.ctwaContextLinkData=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData.decode(A,A.uint32());break}case 4:{c.ctwaContext=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.decode(A,A.uint32());break}case 5:{c.timestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ChatRowOpaqueData.DraftMessage)return A;var r=new p.proto.ChatRowOpaqueData.DraftMessage;if(A.text!=null&&(r.text=String(A.text)),A.omittedUrl!=null&&(r.omittedUrl=String(A.omittedUrl)),A.ctwaContextLinkData!=null){if(typeof A.ctwaContextLinkData!="object")throw TypeError(".proto.ChatRowOpaqueData.DraftMessage.ctwaContextLinkData: object expected");r.ctwaContextLinkData=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData.fromObject(A.ctwaContextLinkData)}if(A.ctwaContext!=null){if(typeof A.ctwaContext!="object")throw TypeError(".proto.ChatRowOpaqueData.DraftMessage.ctwaContext: object expected");r.ctwaContext=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.fromObject(A.ctwaContext)}return A.timestamp!=null&&(l.Long?(r.timestamp=l.Long.fromValue(A.timestamp)).unsigned=!1:typeof A.timestamp=="string"?r.timestamp=parseInt(A.timestamp,10):typeof A.timestamp=="number"?r.timestamp=A.timestamp:typeof A.timestamp=="object"&&(r.timestamp=new l.LongBits(A.timestamp.low>>>0,A.timestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),A.omittedUrl!=null&&A.hasOwnProperty("omittedUrl")&&(s.omittedUrl=A.omittedUrl,r.oneofs&&(s._omittedUrl="omittedUrl")),A.ctwaContextLinkData!=null&&A.hasOwnProperty("ctwaContextLinkData")&&(s.ctwaContextLinkData=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData.toObject(A.ctwaContextLinkData,r),r.oneofs&&(s._ctwaContextLinkData="ctwaContextLinkData")),A.ctwaContext!=null&&A.hasOwnProperty("ctwaContext")&&(s.ctwaContext=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.toObject(A.ctwaContext,r),r.oneofs&&(s._ctwaContext="ctwaContext")),A.timestamp!=null&&A.hasOwnProperty("timestamp")&&(typeof A.timestamp=="number"?s.timestamp=r.longs===String?String(A.timestamp):A.timestamp:s.timestamp=r.longs===String?se(A.timestamp):r.longs===Number?ge(A.timestamp):A.timestamp,r.oneofs&&(s._timestamp="timestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ChatRowOpaqueData.DraftMessage"},i.CtwaContextData=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.conversionSource=s.string();break}case 2:{d.conversionData=s.bytes();break}case 3:{d.sourceUrl=s.string();break}case 4:{d.sourceId=s.string();break}case 5:{d.sourceType=s.string();break}case 6:{d.title=s.string();break}case 7:{d.description=s.string();break}case 8:{d.thumbnail=s.string();break}case 9:{d.thumbnailUrl=s.string();break}case 10:{d.mediaType=s.int32();break}case 11:{d.mediaUrl=s.string();break}case 12:{d.isSuspiciousLink=s.bool();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData)return s;var g=new p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData;switch(s.conversionSource!=null&&(g.conversionSource=String(s.conversionSource)),s.conversionData!=null&&(typeof s.conversionData=="string"?l.base64.decode(s.conversionData,g.conversionData=l.newBuffer(l.base64.length(s.conversionData)),0):s.conversionData.length>=0&&(g.conversionData=s.conversionData)),s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),s.sourceId!=null&&(g.sourceId=String(s.sourceId)),s.sourceType!=null&&(g.sourceType=String(s.sourceType)),s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),s.thumbnail!=null&&(g.thumbnail=String(s.thumbnail)),s.thumbnailUrl!=null&&(g.thumbnailUrl=String(s.thumbnailUrl)),s.mediaType){default:if(typeof s.mediaType=="number"){g.mediaType=s.mediaType;break}break;case"NONE":case 0:g.mediaType=0;break;case"IMAGE":case 1:g.mediaType=1;break;case"VIDEO":case 2:g.mediaType=2;break}return s.mediaUrl!=null&&(g.mediaUrl=String(s.mediaUrl)),s.isSuspiciousLink!=null&&(g.isSuspiciousLink=!!s.isSuspiciousLink),g},a.toObject=function(s,g){g||(g={});var c={};return s.conversionSource!=null&&s.hasOwnProperty("conversionSource")&&(c.conversionSource=s.conversionSource,g.oneofs&&(c._conversionSource="conversionSource")),s.conversionData!=null&&s.hasOwnProperty("conversionData")&&(c.conversionData=g.bytes===String?l.base64.encode(s.conversionData,0,s.conversionData.length):g.bytes===Array?Array.prototype.slice.call(s.conversionData):s.conversionData,g.oneofs&&(c._conversionData="conversionData")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),s.sourceId!=null&&s.hasOwnProperty("sourceId")&&(c.sourceId=s.sourceId,g.oneofs&&(c._sourceId="sourceId")),s.sourceType!=null&&s.hasOwnProperty("sourceType")&&(c.sourceType=s.sourceType,g.oneofs&&(c._sourceType="sourceType")),s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),s.thumbnail!=null&&s.hasOwnProperty("thumbnail")&&(c.thumbnail=s.thumbnail,g.oneofs&&(c._thumbnail="thumbnail")),s.thumbnailUrl!=null&&s.hasOwnProperty("thumbnailUrl")&&(c.thumbnailUrl=s.thumbnailUrl,g.oneofs&&(c._thumbnailUrl="thumbnailUrl")),s.mediaType!=null&&s.hasOwnProperty("mediaType")&&(c.mediaType=g.enums===String?p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.ContextInfoExternalAdReplyInfoMediaType[s.mediaType]===void 0?s.mediaType:p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.ContextInfoExternalAdReplyInfoMediaType[s.mediaType]:s.mediaType,g.oneofs&&(c._mediaType="mediaType")),s.mediaUrl!=null&&s.hasOwnProperty("mediaUrl")&&(c.mediaUrl=s.mediaUrl,g.oneofs&&(c._mediaUrl="mediaUrl")),s.isSuspiciousLink!=null&&s.hasOwnProperty("isSuspiciousLink")&&(c.isSuspiciousLink=s.isSuspiciousLink,g.oneofs&&(c._isSuspiciousLink="isSuspiciousLink")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ChatRowOpaqueData.DraftMessage.CtwaContextData"},a.ContextInfoExternalAdReplyInfoMediaType=(function(){let r={},s=Object.create(r);return s[r[0]="NONE"]=0,s[r[1]="IMAGE"]=1,s[r[2]="VIDEO"]=2,s})(),a})(),i.CtwaContextLinkData=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.context=s.string();break}case 2:{d.sourceUrl=s.string();break}case 3:{d.icebreaker=s.string();break}case 4:{d.phone=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData)return s;var g=new p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData;return s.context!=null&&(g.context=String(s.context)),s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),s.icebreaker!=null&&(g.icebreaker=String(s.icebreaker)),s.phone!=null&&(g.phone=String(s.phone)),g},a.toObject=function(s,g){g||(g={});var c={};return s.context!=null&&s.hasOwnProperty("context")&&(c.context=s.context,g.oneofs&&(c._context="context")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),s.icebreaker!=null&&s.hasOwnProperty("icebreaker")&&(c.icebreaker=s.icebreaker,g.oneofs&&(c._icebreaker="icebreaker")),s.phone!=null&&s.hasOwnProperty("phone")&&(c.phone=s.phone,g.oneofs&&(c._phone="phone")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData"},a})(),i})(),t})(),n.Citation=(function(){function t(o){if(o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.title=i.string();break}case 2:{r.subtitle=i.string();break}case 3:{r.cmsId=i.string();break}case 4:{r.imageUrl=i.string();break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.Citation)return i;var e=new p.proto.Citation;return i.title!=null&&(e.title=String(i.title)),i.subtitle!=null&&(e.subtitle=String(i.subtitle)),i.cmsId!=null&&(e.cmsId=String(i.cmsId)),i.imageUrl!=null&&(e.imageUrl=String(i.imageUrl)),e},t.toObject=function(i,e){e||(e={});var a={};return e.defaults&&(a.title="",a.subtitle="",a.cmsId="",a.imageUrl=""),i.title!=null&&i.hasOwnProperty("title")&&(a.title=i.title),i.subtitle!=null&&i.hasOwnProperty("subtitle")&&(a.subtitle=i.subtitle),i.cmsId!=null&&i.hasOwnProperty("cmsId")&&(a.cmsId=i.cmsId),i.imageUrl!=null&&i.hasOwnProperty("imageUrl")&&(a.imageUrl=i.imageUrl),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(i){return i===void 0&&(i="type.googleapis.com"),i+"/proto.Citation"},t})(),n.ClientPairingProps=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.isChatDbLidMigrated=e.bool();break}case 2:{s.isSyncdPureLidSession=e.bool();break}case 3:{s.isSyncdSnapshotRecoveryEnabled=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ClientPairingProps)return e;var a=new p.proto.ClientPairingProps;return e.isChatDbLidMigrated!=null&&(a.isChatDbLidMigrated=!!e.isChatDbLidMigrated),e.isSyncdPureLidSession!=null&&(a.isSyncdPureLidSession=!!e.isSyncdPureLidSession),e.isSyncdSnapshotRecoveryEnabled!=null&&(a.isSyncdSnapshotRecoveryEnabled=!!e.isSyncdSnapshotRecoveryEnabled),a},t.toObject=function(e,a){a||(a={});var A={};return e.isChatDbLidMigrated!=null&&e.hasOwnProperty("isChatDbLidMigrated")&&(A.isChatDbLidMigrated=e.isChatDbLidMigrated,a.oneofs&&(A._isChatDbLidMigrated="isChatDbLidMigrated")),e.isSyncdPureLidSession!=null&&e.hasOwnProperty("isSyncdPureLidSession")&&(A.isSyncdPureLidSession=e.isSyncdPureLidSession,a.oneofs&&(A._isSyncdPureLidSession="isSyncdPureLidSession")),e.isSyncdSnapshotRecoveryEnabled!=null&&e.hasOwnProperty("isSyncdSnapshotRecoveryEnabled")&&(A.isSyncdSnapshotRecoveryEnabled=e.isSyncdSnapshotRecoveryEnabled,a.oneofs&&(A._isSyncdSnapshotRecoveryEnabled="isSyncdSnapshotRecoveryEnabled")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ClientPairingProps"},t})(),n.ClientPayload=(function(){function t(i){if(this.shards=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.username=e.uint64();break}case 3:{s.passive=e.bool();break}case 5:{s.userAgent=p.proto.ClientPayload.UserAgent.decode(e,e.uint32());break}case 6:{s.webInfo=p.proto.ClientPayload.WebInfo.decode(e,e.uint32());break}case 7:{s.pushName=e.string();break}case 9:{s.sessionId=e.sfixed32();break}case 10:{s.shortConnect=e.bool();break}case 12:{s.connectType=e.int32();break}case 13:{s.connectReason=e.int32();break}case 14:{if(s.shards&&s.shards.length||(s.shards=[]),(g&7)===2)for(var c=e.uint32()+e.pos;e.pos>>0,e.username.high>>>0).toNumber(!0))),e.passive!=null&&(a.passive=!!e.passive),e.userAgent!=null){if(typeof e.userAgent!="object")throw TypeError(".proto.ClientPayload.userAgent: object expected");a.userAgent=p.proto.ClientPayload.UserAgent.fromObject(e.userAgent)}if(e.webInfo!=null){if(typeof e.webInfo!="object")throw TypeError(".proto.ClientPayload.webInfo: object expected");a.webInfo=p.proto.ClientPayload.WebInfo.fromObject(e.webInfo)}switch(e.pushName!=null&&(a.pushName=String(e.pushName)),e.sessionId!=null&&(a.sessionId=e.sessionId|0),e.shortConnect!=null&&(a.shortConnect=!!e.shortConnect),e.connectType){default:if(typeof e.connectType=="number"){a.connectType=e.connectType;break}break;case"CELLULAR_UNKNOWN":case 0:a.connectType=0;break;case"WIFI_UNKNOWN":case 1:a.connectType=1;break;case"CELLULAR_EDGE":case 100:a.connectType=100;break;case"CELLULAR_IDEN":case 101:a.connectType=101;break;case"CELLULAR_UMTS":case 102:a.connectType=102;break;case"CELLULAR_EVDO":case 103:a.connectType=103;break;case"CELLULAR_GPRS":case 104:a.connectType=104;break;case"CELLULAR_HSDPA":case 105:a.connectType=105;break;case"CELLULAR_HSUPA":case 106:a.connectType=106;break;case"CELLULAR_HSPA":case 107:a.connectType=107;break;case"CELLULAR_CDMA":case 108:a.connectType=108;break;case"CELLULAR_1XRTT":case 109:a.connectType=109;break;case"CELLULAR_EHRPD":case 110:a.connectType=110;break;case"CELLULAR_LTE":case 111:a.connectType=111;break;case"CELLULAR_HSPAP":case 112:a.connectType=112;break}switch(e.connectReason){default:if(typeof e.connectReason=="number"){a.connectReason=e.connectReason;break}break;case"PUSH":case 0:a.connectReason=0;break;case"USER_ACTIVATED":case 1:a.connectReason=1;break;case"SCHEDULED":case 2:a.connectReason=2;break;case"ERROR_RECONNECT":case 3:a.connectReason=3;break;case"NETWORK_SWITCH":case 4:a.connectReason=4;break;case"PING_RECONNECT":case 5:a.connectReason=5;break;case"UNKNOWN":case 6:a.connectReason=6;break}if(e.shards){if(!Array.isArray(e.shards))throw TypeError(".proto.ClientPayload.shards: array expected");a.shards=[];for(var A=0;A>>0),e.device!=null&&(a.device=e.device>>>0),e.devicePairingData!=null){if(typeof e.devicePairingData!="object")throw TypeError(".proto.ClientPayload.devicePairingData: object expected");a.devicePairingData=p.proto.ClientPayload.DevicePairingRegistrationData.fromObject(e.devicePairingData)}switch(e.product){default:if(typeof e.product=="number"){a.product=e.product;break}break;case"WHATSAPP":case 0:a.product=0;break;case"MESSENGER":case 1:a.product=1;break;case"INTEROP":case 2:a.product=2;break;case"INTEROP_MSGR":case 3:a.product=3;break;case"WHATSAPP_LID":case 4:a.product=4;break}switch(e.fbCat!=null&&(typeof e.fbCat=="string"?l.base64.decode(e.fbCat,a.fbCat=l.newBuffer(l.base64.length(e.fbCat)),0):e.fbCat.length>=0&&(a.fbCat=e.fbCat)),e.fbUserAgent!=null&&(typeof e.fbUserAgent=="string"?l.base64.decode(e.fbUserAgent,a.fbUserAgent=l.newBuffer(l.base64.length(e.fbUserAgent)),0):e.fbUserAgent.length>=0&&(a.fbUserAgent=e.fbUserAgent)),e.oc!=null&&(a.oc=!!e.oc),e.lc!=null&&(a.lc=e.lc|0),e.iosAppExtension){default:if(typeof e.iosAppExtension=="number"){a.iosAppExtension=e.iosAppExtension;break}break;case"SHARE_EXTENSION":case 0:a.iosAppExtension=0;break;case"SERVICE_EXTENSION":case 1:a.iosAppExtension=1;break;case"INTENTS_EXTENSION":case 2:a.iosAppExtension=2;break}if(e.fbAppId!=null&&(l.Long?(a.fbAppId=l.Long.fromValue(e.fbAppId)).unsigned=!0:typeof e.fbAppId=="string"?a.fbAppId=parseInt(e.fbAppId,10):typeof e.fbAppId=="number"?a.fbAppId=e.fbAppId:typeof e.fbAppId=="object"&&(a.fbAppId=new l.LongBits(e.fbAppId.low>>>0,e.fbAppId.high>>>0).toNumber(!0))),e.fbDeviceId!=null&&(typeof e.fbDeviceId=="string"?l.base64.decode(e.fbDeviceId,a.fbDeviceId=l.newBuffer(l.base64.length(e.fbDeviceId)),0):e.fbDeviceId.length>=0&&(a.fbDeviceId=e.fbDeviceId)),e.pull!=null&&(a.pull=!!e.pull),e.paddingBytes!=null&&(typeof e.paddingBytes=="string"?l.base64.decode(e.paddingBytes,a.paddingBytes=l.newBuffer(l.base64.length(e.paddingBytes)),0):e.paddingBytes.length>=0&&(a.paddingBytes=e.paddingBytes)),e.yearClass!=null&&(a.yearClass=e.yearClass|0),e.memClass!=null&&(a.memClass=e.memClass|0),e.interopData!=null){if(typeof e.interopData!="object")throw TypeError(".proto.ClientPayload.interopData: object expected");a.interopData=p.proto.ClientPayload.InteropData.fromObject(e.interopData)}switch(e.trafficAnonymization){default:if(typeof e.trafficAnonymization=="number"){a.trafficAnonymization=e.trafficAnonymization;break}break;case"OFF":case 0:a.trafficAnonymization=0;break;case"STANDARD":case 1:a.trafficAnonymization=1;break}switch(e.lidDbMigrated!=null&&(a.lidDbMigrated=!!e.lidDbMigrated),e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"DEFAULT":case 0:a.accountType=0;break;case"GUEST":case 1:a.accountType=1;break}return e.connectionSequenceInfo!=null&&(a.connectionSequenceInfo=e.connectionSequenceInfo|0),e.paaLink!=null&&(a.paaLink=!!e.paaLink),e.preacksCount!=null&&(a.preacksCount=e.preacksCount|0),e.processingQueueSize!=null&&(a.processingQueueSize=e.processingQueueSize|0),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.shards=[]),e.username!=null&&e.hasOwnProperty("username")&&(typeof e.username=="number"?A.username=a.longs===String?String(e.username):e.username:A.username=a.longs===String?se(e.username,!0):a.longs===Number?ge(e.username,!0):e.username,a.oneofs&&(A._username="username")),e.passive!=null&&e.hasOwnProperty("passive")&&(A.passive=e.passive,a.oneofs&&(A._passive="passive")),e.userAgent!=null&&e.hasOwnProperty("userAgent")&&(A.userAgent=p.proto.ClientPayload.UserAgent.toObject(e.userAgent,a),a.oneofs&&(A._userAgent="userAgent")),e.webInfo!=null&&e.hasOwnProperty("webInfo")&&(A.webInfo=p.proto.ClientPayload.WebInfo.toObject(e.webInfo,a),a.oneofs&&(A._webInfo="webInfo")),e.pushName!=null&&e.hasOwnProperty("pushName")&&(A.pushName=e.pushName,a.oneofs&&(A._pushName="pushName")),e.sessionId!=null&&e.hasOwnProperty("sessionId")&&(A.sessionId=e.sessionId,a.oneofs&&(A._sessionId="sessionId")),e.shortConnect!=null&&e.hasOwnProperty("shortConnect")&&(A.shortConnect=e.shortConnect,a.oneofs&&(A._shortConnect="shortConnect")),e.connectType!=null&&e.hasOwnProperty("connectType")&&(A.connectType=a.enums===String?p.proto.ClientPayload.ConnectType[e.connectType]===void 0?e.connectType:p.proto.ClientPayload.ConnectType[e.connectType]:e.connectType,a.oneofs&&(A._connectType="connectType")),e.connectReason!=null&&e.hasOwnProperty("connectReason")&&(A.connectReason=a.enums===String?p.proto.ClientPayload.ConnectReason[e.connectReason]===void 0?e.connectReason:p.proto.ClientPayload.ConnectReason[e.connectReason]:e.connectReason,a.oneofs&&(A._connectReason="connectReason")),e.shards&&e.shards.length){A.shards=[];for(var r=0;r>>3){case 15:{c.dnsMethod=A.int32();break}case 16:{c.appCached=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ClientPayload.DNSSource)return A;var r=new p.proto.ClientPayload.DNSSource;switch(A.dnsMethod){default:if(typeof A.dnsMethod=="number"){r.dnsMethod=A.dnsMethod;break}break;case"SYSTEM":case 0:r.dnsMethod=0;break;case"GOOGLE":case 1:r.dnsMethod=1;break;case"HARDCODED":case 2:r.dnsMethod=2;break;case"OVERRIDE":case 3:r.dnsMethod=3;break;case"FALLBACK":case 4:r.dnsMethod=4;break;case"MNS":case 5:r.dnsMethod=5;break}return A.appCached!=null&&(r.appCached=!!A.appCached),r},i.toObject=function(A,r){r||(r={});var s={};return A.dnsMethod!=null&&A.hasOwnProperty("dnsMethod")&&(s.dnsMethod=r.enums===String?p.proto.ClientPayload.DNSSource.DNSResolutionMethod[A.dnsMethod]===void 0?A.dnsMethod:p.proto.ClientPayload.DNSSource.DNSResolutionMethod[A.dnsMethod]:A.dnsMethod,r.oneofs&&(s._dnsMethod="dnsMethod")),A.appCached!=null&&A.hasOwnProperty("appCached")&&(s.appCached=A.appCached,r.oneofs&&(s._appCached="appCached")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.DNSSource"},i.DNSResolutionMethod=(function(){let a={},A=Object.create(a);return A[a[0]="SYSTEM"]=0,A[a[1]="GOOGLE"]=1,A[a[2]="HARDCODED"]=2,A[a[3]="OVERRIDE"]=3,A[a[4]="FALLBACK"]=4,A[a[5]="MNS"]=5,A})(),i})(),t.DevicePairingRegistrationData=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.eRegid=A.bytes();break}case 2:{c.eKeytype=A.bytes();break}case 3:{c.eIdent=A.bytes();break}case 4:{c.eSkeyId=A.bytes();break}case 5:{c.eSkeyVal=A.bytes();break}case 6:{c.eSkeySig=A.bytes();break}case 7:{c.buildHash=A.bytes();break}case 8:{c.deviceProps=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ClientPayload.DevicePairingRegistrationData)return A;var r=new p.proto.ClientPayload.DevicePairingRegistrationData;return A.eRegid!=null&&(typeof A.eRegid=="string"?l.base64.decode(A.eRegid,r.eRegid=l.newBuffer(l.base64.length(A.eRegid)),0):A.eRegid.length>=0&&(r.eRegid=A.eRegid)),A.eKeytype!=null&&(typeof A.eKeytype=="string"?l.base64.decode(A.eKeytype,r.eKeytype=l.newBuffer(l.base64.length(A.eKeytype)),0):A.eKeytype.length>=0&&(r.eKeytype=A.eKeytype)),A.eIdent!=null&&(typeof A.eIdent=="string"?l.base64.decode(A.eIdent,r.eIdent=l.newBuffer(l.base64.length(A.eIdent)),0):A.eIdent.length>=0&&(r.eIdent=A.eIdent)),A.eSkeyId!=null&&(typeof A.eSkeyId=="string"?l.base64.decode(A.eSkeyId,r.eSkeyId=l.newBuffer(l.base64.length(A.eSkeyId)),0):A.eSkeyId.length>=0&&(r.eSkeyId=A.eSkeyId)),A.eSkeyVal!=null&&(typeof A.eSkeyVal=="string"?l.base64.decode(A.eSkeyVal,r.eSkeyVal=l.newBuffer(l.base64.length(A.eSkeyVal)),0):A.eSkeyVal.length>=0&&(r.eSkeyVal=A.eSkeyVal)),A.eSkeySig!=null&&(typeof A.eSkeySig=="string"?l.base64.decode(A.eSkeySig,r.eSkeySig=l.newBuffer(l.base64.length(A.eSkeySig)),0):A.eSkeySig.length>=0&&(r.eSkeySig=A.eSkeySig)),A.buildHash!=null&&(typeof A.buildHash=="string"?l.base64.decode(A.buildHash,r.buildHash=l.newBuffer(l.base64.length(A.buildHash)),0):A.buildHash.length>=0&&(r.buildHash=A.buildHash)),A.deviceProps!=null&&(typeof A.deviceProps=="string"?l.base64.decode(A.deviceProps,r.deviceProps=l.newBuffer(l.base64.length(A.deviceProps)),0):A.deviceProps.length>=0&&(r.deviceProps=A.deviceProps)),r},i.toObject=function(A,r){r||(r={});var s={};return A.eRegid!=null&&A.hasOwnProperty("eRegid")&&(s.eRegid=r.bytes===String?l.base64.encode(A.eRegid,0,A.eRegid.length):r.bytes===Array?Array.prototype.slice.call(A.eRegid):A.eRegid,r.oneofs&&(s._eRegid="eRegid")),A.eKeytype!=null&&A.hasOwnProperty("eKeytype")&&(s.eKeytype=r.bytes===String?l.base64.encode(A.eKeytype,0,A.eKeytype.length):r.bytes===Array?Array.prototype.slice.call(A.eKeytype):A.eKeytype,r.oneofs&&(s._eKeytype="eKeytype")),A.eIdent!=null&&A.hasOwnProperty("eIdent")&&(s.eIdent=r.bytes===String?l.base64.encode(A.eIdent,0,A.eIdent.length):r.bytes===Array?Array.prototype.slice.call(A.eIdent):A.eIdent,r.oneofs&&(s._eIdent="eIdent")),A.eSkeyId!=null&&A.hasOwnProperty("eSkeyId")&&(s.eSkeyId=r.bytes===String?l.base64.encode(A.eSkeyId,0,A.eSkeyId.length):r.bytes===Array?Array.prototype.slice.call(A.eSkeyId):A.eSkeyId,r.oneofs&&(s._eSkeyId="eSkeyId")),A.eSkeyVal!=null&&A.hasOwnProperty("eSkeyVal")&&(s.eSkeyVal=r.bytes===String?l.base64.encode(A.eSkeyVal,0,A.eSkeyVal.length):r.bytes===Array?Array.prototype.slice.call(A.eSkeyVal):A.eSkeyVal,r.oneofs&&(s._eSkeyVal="eSkeyVal")),A.eSkeySig!=null&&A.hasOwnProperty("eSkeySig")&&(s.eSkeySig=r.bytes===String?l.base64.encode(A.eSkeySig,0,A.eSkeySig.length):r.bytes===Array?Array.prototype.slice.call(A.eSkeySig):A.eSkeySig,r.oneofs&&(s._eSkeySig="eSkeySig")),A.buildHash!=null&&A.hasOwnProperty("buildHash")&&(s.buildHash=r.bytes===String?l.base64.encode(A.buildHash,0,A.buildHash.length):r.bytes===Array?Array.prototype.slice.call(A.buildHash):A.buildHash,r.oneofs&&(s._buildHash="buildHash")),A.deviceProps!=null&&A.hasOwnProperty("deviceProps")&&(s.deviceProps=r.bytes===String?l.base64.encode(A.deviceProps,0,A.deviceProps.length):r.bytes===Array?Array.prototype.slice.call(A.deviceProps):A.deviceProps,r.oneofs&&(s._deviceProps="deviceProps")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.DevicePairingRegistrationData"},i})(),t.IOSAppExtension=(function(){let i={},e=Object.create(i);return e[i[0]="SHARE_EXTENSION"]=0,e[i[1]="SERVICE_EXTENSION"]=1,e[i[2]="INTENTS_EXTENSION"]=2,e})(),t.InteropData=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.accountId=A.uint64();break}case 2:{c.token=A.bytes();break}case 3:{c.enableReadReceipts=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ClientPayload.InteropData)return A;var r=new p.proto.ClientPayload.InteropData;return A.accountId!=null&&(l.Long?(r.accountId=l.Long.fromValue(A.accountId)).unsigned=!0:typeof A.accountId=="string"?r.accountId=parseInt(A.accountId,10):typeof A.accountId=="number"?r.accountId=A.accountId:typeof A.accountId=="object"&&(r.accountId=new l.LongBits(A.accountId.low>>>0,A.accountId.high>>>0).toNumber(!0))),A.token!=null&&(typeof A.token=="string"?l.base64.decode(A.token,r.token=l.newBuffer(l.base64.length(A.token)),0):A.token.length>=0&&(r.token=A.token)),A.enableReadReceipts!=null&&(r.enableReadReceipts=!!A.enableReadReceipts),r},i.toObject=function(A,r){r||(r={});var s={};return A.accountId!=null&&A.hasOwnProperty("accountId")&&(typeof A.accountId=="number"?s.accountId=r.longs===String?String(A.accountId):A.accountId:s.accountId=r.longs===String?se(A.accountId,!0):r.longs===Number?ge(A.accountId,!0):A.accountId,r.oneofs&&(s._accountId="accountId")),A.token!=null&&A.hasOwnProperty("token")&&(s.token=r.bytes===String?l.base64.encode(A.token,0,A.token.length):r.bytes===Array?Array.prototype.slice.call(A.token):A.token,r.oneofs&&(s._token="token")),A.enableReadReceipts!=null&&A.hasOwnProperty("enableReadReceipts")&&(s.enableReadReceipts=A.enableReadReceipts,r.oneofs&&(s._enableReadReceipts="enableReadReceipts")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.InteropData"},i})(),t.Product=(function(){let i={},e=Object.create(i);return e[i[0]="WHATSAPP"]=0,e[i[1]="MESSENGER"]=1,e[i[2]="INTEROP"]=2,e[i[3]="INTEROP_MSGR"]=3,e[i[4]="WHATSAPP_LID"]=4,e})(),t.TrafficAnonymization=(function(){let i={},e=Object.create(i);return e[i[0]="OFF"]=0,e[i[1]="STANDARD"]=1,e})(),t.UserAgent=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.platform=A.int32();break}case 2:{c.appVersion=p.proto.ClientPayload.UserAgent.AppVersion.decode(A,A.uint32());break}case 3:{c.mcc=A.string();break}case 4:{c.mnc=A.string();break}case 5:{c.osVersion=A.string();break}case 6:{c.manufacturer=A.string();break}case 7:{c.device=A.string();break}case 8:{c.osBuildNumber=A.string();break}case 9:{c.phoneId=A.string();break}case 10:{c.releaseChannel=A.int32();break}case 11:{c.localeLanguageIso6391=A.string();break}case 12:{c.localeCountryIso31661Alpha2=A.string();break}case 13:{c.deviceBoard=A.string();break}case 14:{c.deviceExpId=A.string();break}case 15:{c.deviceType=A.int32();break}case 16:{c.deviceModelType=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ClientPayload.UserAgent)return A;var r=new p.proto.ClientPayload.UserAgent;switch(A.platform){default:if(typeof A.platform=="number"){r.platform=A.platform;break}break;case"ANDROID":case 0:r.platform=0;break;case"IOS":case 1:r.platform=1;break;case"WINDOWS_PHONE":case 2:r.platform=2;break;case"BLACKBERRY":case 3:r.platform=3;break;case"BLACKBERRYX":case 4:r.platform=4;break;case"S40":case 5:r.platform=5;break;case"S60":case 6:r.platform=6;break;case"PYTHON_CLIENT":case 7:r.platform=7;break;case"TIZEN":case 8:r.platform=8;break;case"ENTERPRISE":case 9:r.platform=9;break;case"SMB_ANDROID":case 10:r.platform=10;break;case"KAIOS":case 11:r.platform=11;break;case"SMB_IOS":case 12:r.platform=12;break;case"WINDOWS":case 13:r.platform=13;break;case"WEB":case 14:r.platform=14;break;case"PORTAL":case 15:r.platform=15;break;case"GREEN_ANDROID":case 16:r.platform=16;break;case"GREEN_IPHONE":case 17:r.platform=17;break;case"BLUE_ANDROID":case 18:r.platform=18;break;case"BLUE_IPHONE":case 19:r.platform=19;break;case"FBLITE_ANDROID":case 20:r.platform=20;break;case"MLITE_ANDROID":case 21:r.platform=21;break;case"IGLITE_ANDROID":case 22:r.platform=22;break;case"PAGE":case 23:r.platform=23;break;case"MACOS":case 24:r.platform=24;break;case"OCULUS_MSG":case 25:r.platform=25;break;case"OCULUS_CALL":case 26:r.platform=26;break;case"MILAN":case 27:r.platform=27;break;case"CAPI":case 28:r.platform=28;break;case"WEAROS":case 29:r.platform=29;break;case"ARDEVICE":case 30:r.platform=30;break;case"VRDEVICE":case 31:r.platform=31;break;case"BLUE_WEB":case 32:r.platform=32;break;case"IPAD":case 33:r.platform=33;break;case"TEST":case 34:r.platform=34;break;case"SMART_GLASSES":case 35:r.platform=35;break;case"BLUE_VR":case 36:r.platform=36;break;case"AR_WRIST":case 37:r.platform=37;break}if(A.appVersion!=null){if(typeof A.appVersion!="object")throw TypeError(".proto.ClientPayload.UserAgent.appVersion: object expected");r.appVersion=p.proto.ClientPayload.UserAgent.AppVersion.fromObject(A.appVersion)}switch(A.mcc!=null&&(r.mcc=String(A.mcc)),A.mnc!=null&&(r.mnc=String(A.mnc)),A.osVersion!=null&&(r.osVersion=String(A.osVersion)),A.manufacturer!=null&&(r.manufacturer=String(A.manufacturer)),A.device!=null&&(r.device=String(A.device)),A.osBuildNumber!=null&&(r.osBuildNumber=String(A.osBuildNumber)),A.phoneId!=null&&(r.phoneId=String(A.phoneId)),A.releaseChannel){default:if(typeof A.releaseChannel=="number"){r.releaseChannel=A.releaseChannel;break}break;case"RELEASE":case 0:r.releaseChannel=0;break;case"BETA":case 1:r.releaseChannel=1;break;case"ALPHA":case 2:r.releaseChannel=2;break;case"DEBUG":case 3:r.releaseChannel=3;break}switch(A.localeLanguageIso6391!=null&&(r.localeLanguageIso6391=String(A.localeLanguageIso6391)),A.localeCountryIso31661Alpha2!=null&&(r.localeCountryIso31661Alpha2=String(A.localeCountryIso31661Alpha2)),A.deviceBoard!=null&&(r.deviceBoard=String(A.deviceBoard)),A.deviceExpId!=null&&(r.deviceExpId=String(A.deviceExpId)),A.deviceType){default:if(typeof A.deviceType=="number"){r.deviceType=A.deviceType;break}break;case"PHONE":case 0:r.deviceType=0;break;case"TABLET":case 1:r.deviceType=1;break;case"DESKTOP":case 2:r.deviceType=2;break;case"WEARABLE":case 3:r.deviceType=3;break;case"VR":case 4:r.deviceType=4;break}return A.deviceModelType!=null&&(r.deviceModelType=String(A.deviceModelType)),r},i.toObject=function(A,r){r||(r={});var s={};return A.platform!=null&&A.hasOwnProperty("platform")&&(s.platform=r.enums===String?p.proto.ClientPayload.UserAgent.Platform[A.platform]===void 0?A.platform:p.proto.ClientPayload.UserAgent.Platform[A.platform]:A.platform,r.oneofs&&(s._platform="platform")),A.appVersion!=null&&A.hasOwnProperty("appVersion")&&(s.appVersion=p.proto.ClientPayload.UserAgent.AppVersion.toObject(A.appVersion,r),r.oneofs&&(s._appVersion="appVersion")),A.mcc!=null&&A.hasOwnProperty("mcc")&&(s.mcc=A.mcc,r.oneofs&&(s._mcc="mcc")),A.mnc!=null&&A.hasOwnProperty("mnc")&&(s.mnc=A.mnc,r.oneofs&&(s._mnc="mnc")),A.osVersion!=null&&A.hasOwnProperty("osVersion")&&(s.osVersion=A.osVersion,r.oneofs&&(s._osVersion="osVersion")),A.manufacturer!=null&&A.hasOwnProperty("manufacturer")&&(s.manufacturer=A.manufacturer,r.oneofs&&(s._manufacturer="manufacturer")),A.device!=null&&A.hasOwnProperty("device")&&(s.device=A.device,r.oneofs&&(s._device="device")),A.osBuildNumber!=null&&A.hasOwnProperty("osBuildNumber")&&(s.osBuildNumber=A.osBuildNumber,r.oneofs&&(s._osBuildNumber="osBuildNumber")),A.phoneId!=null&&A.hasOwnProperty("phoneId")&&(s.phoneId=A.phoneId,r.oneofs&&(s._phoneId="phoneId")),A.releaseChannel!=null&&A.hasOwnProperty("releaseChannel")&&(s.releaseChannel=r.enums===String?p.proto.ClientPayload.UserAgent.ReleaseChannel[A.releaseChannel]===void 0?A.releaseChannel:p.proto.ClientPayload.UserAgent.ReleaseChannel[A.releaseChannel]:A.releaseChannel,r.oneofs&&(s._releaseChannel="releaseChannel")),A.localeLanguageIso6391!=null&&A.hasOwnProperty("localeLanguageIso6391")&&(s.localeLanguageIso6391=A.localeLanguageIso6391,r.oneofs&&(s._localeLanguageIso6391="localeLanguageIso6391")),A.localeCountryIso31661Alpha2!=null&&A.hasOwnProperty("localeCountryIso31661Alpha2")&&(s.localeCountryIso31661Alpha2=A.localeCountryIso31661Alpha2,r.oneofs&&(s._localeCountryIso31661Alpha2="localeCountryIso31661Alpha2")),A.deviceBoard!=null&&A.hasOwnProperty("deviceBoard")&&(s.deviceBoard=A.deviceBoard,r.oneofs&&(s._deviceBoard="deviceBoard")),A.deviceExpId!=null&&A.hasOwnProperty("deviceExpId")&&(s.deviceExpId=A.deviceExpId,r.oneofs&&(s._deviceExpId="deviceExpId")),A.deviceType!=null&&A.hasOwnProperty("deviceType")&&(s.deviceType=r.enums===String?p.proto.ClientPayload.UserAgent.DeviceType[A.deviceType]===void 0?A.deviceType:p.proto.ClientPayload.UserAgent.DeviceType[A.deviceType]:A.deviceType,r.oneofs&&(s._deviceType="deviceType")),A.deviceModelType!=null&&A.hasOwnProperty("deviceModelType")&&(s.deviceModelType=A.deviceModelType,r.oneofs&&(s._deviceModelType="deviceModelType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.UserAgent"},i.AppVersion=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.primary=s.uint32();break}case 2:{d.secondary=s.uint32();break}case 3:{d.tertiary=s.uint32();break}case 4:{d.quaternary=s.uint32();break}case 5:{d.quinary=s.uint32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.ClientPayload.UserAgent.AppVersion)return s;var g=new p.proto.ClientPayload.UserAgent.AppVersion;return s.primary!=null&&(g.primary=s.primary>>>0),s.secondary!=null&&(g.secondary=s.secondary>>>0),s.tertiary!=null&&(g.tertiary=s.tertiary>>>0),s.quaternary!=null&&(g.quaternary=s.quaternary>>>0),s.quinary!=null&&(g.quinary=s.quinary>>>0),g},a.toObject=function(s,g){g||(g={});var c={};return s.primary!=null&&s.hasOwnProperty("primary")&&(c.primary=s.primary,g.oneofs&&(c._primary="primary")),s.secondary!=null&&s.hasOwnProperty("secondary")&&(c.secondary=s.secondary,g.oneofs&&(c._secondary="secondary")),s.tertiary!=null&&s.hasOwnProperty("tertiary")&&(c.tertiary=s.tertiary,g.oneofs&&(c._tertiary="tertiary")),s.quaternary!=null&&s.hasOwnProperty("quaternary")&&(c.quaternary=s.quaternary,g.oneofs&&(c._quaternary="quaternary")),s.quinary!=null&&s.hasOwnProperty("quinary")&&(c.quinary=s.quinary,g.oneofs&&(c._quinary="quinary")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ClientPayload.UserAgent.AppVersion"},a})(),i.DeviceType=(function(){let a={},A=Object.create(a);return A[a[0]="PHONE"]=0,A[a[1]="TABLET"]=1,A[a[2]="DESKTOP"]=2,A[a[3]="WEARABLE"]=3,A[a[4]="VR"]=4,A})(),i.Platform=(function(){let a={},A=Object.create(a);return A[a[0]="ANDROID"]=0,A[a[1]="IOS"]=1,A[a[2]="WINDOWS_PHONE"]=2,A[a[3]="BLACKBERRY"]=3,A[a[4]="BLACKBERRYX"]=4,A[a[5]="S40"]=5,A[a[6]="S60"]=6,A[a[7]="PYTHON_CLIENT"]=7,A[a[8]="TIZEN"]=8,A[a[9]="ENTERPRISE"]=9,A[a[10]="SMB_ANDROID"]=10,A[a[11]="KAIOS"]=11,A[a[12]="SMB_IOS"]=12,A[a[13]="WINDOWS"]=13,A[a[14]="WEB"]=14,A[a[15]="PORTAL"]=15,A[a[16]="GREEN_ANDROID"]=16,A[a[17]="GREEN_IPHONE"]=17,A[a[18]="BLUE_ANDROID"]=18,A[a[19]="BLUE_IPHONE"]=19,A[a[20]="FBLITE_ANDROID"]=20,A[a[21]="MLITE_ANDROID"]=21,A[a[22]="IGLITE_ANDROID"]=22,A[a[23]="PAGE"]=23,A[a[24]="MACOS"]=24,A[a[25]="OCULUS_MSG"]=25,A[a[26]="OCULUS_CALL"]=26,A[a[27]="MILAN"]=27,A[a[28]="CAPI"]=28,A[a[29]="WEAROS"]=29,A[a[30]="ARDEVICE"]=30,A[a[31]="VRDEVICE"]=31,A[a[32]="BLUE_WEB"]=32,A[a[33]="IPAD"]=33,A[a[34]="TEST"]=34,A[a[35]="SMART_GLASSES"]=35,A[a[36]="BLUE_VR"]=36,A[a[37]="AR_WRIST"]=37,A})(),i.ReleaseChannel=(function(){let a={},A=Object.create(a);return A[a[0]="RELEASE"]=0,A[a[1]="BETA"]=1,A[a[2]="ALPHA"]=2,A[a[3]="DEBUG"]=3,A})(),i})(),t.WebInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.refToken=A.string();break}case 2:{c.version=A.string();break}case 3:{c.webdPayload=p.proto.ClientPayload.WebInfo.WebdPayload.decode(A,A.uint32());break}case 4:{c.webSubPlatform=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ClientPayload.WebInfo)return A;var r=new p.proto.ClientPayload.WebInfo;if(A.refToken!=null&&(r.refToken=String(A.refToken)),A.version!=null&&(r.version=String(A.version)),A.webdPayload!=null){if(typeof A.webdPayload!="object")throw TypeError(".proto.ClientPayload.WebInfo.webdPayload: object expected");r.webdPayload=p.proto.ClientPayload.WebInfo.WebdPayload.fromObject(A.webdPayload)}switch(A.webSubPlatform){default:if(typeof A.webSubPlatform=="number"){r.webSubPlatform=A.webSubPlatform;break}break;case"WEB_BROWSER":case 0:r.webSubPlatform=0;break;case"APP_STORE":case 1:r.webSubPlatform=1;break;case"WIN_STORE":case 2:r.webSubPlatform=2;break;case"DARWIN":case 3:r.webSubPlatform=3;break;case"WIN32":case 4:r.webSubPlatform=4;break;case"WIN_HYBRID":case 5:r.webSubPlatform=5;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.refToken!=null&&A.hasOwnProperty("refToken")&&(s.refToken=A.refToken,r.oneofs&&(s._refToken="refToken")),A.version!=null&&A.hasOwnProperty("version")&&(s.version=A.version,r.oneofs&&(s._version="version")),A.webdPayload!=null&&A.hasOwnProperty("webdPayload")&&(s.webdPayload=p.proto.ClientPayload.WebInfo.WebdPayload.toObject(A.webdPayload,r),r.oneofs&&(s._webdPayload="webdPayload")),A.webSubPlatform!=null&&A.hasOwnProperty("webSubPlatform")&&(s.webSubPlatform=r.enums===String?p.proto.ClientPayload.WebInfo.WebSubPlatform[A.webSubPlatform]===void 0?A.webSubPlatform:p.proto.ClientPayload.WebInfo.WebSubPlatform[A.webSubPlatform]:A.webSubPlatform,r.oneofs&&(s._webSubPlatform="webSubPlatform")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.WebInfo"},i.WebSubPlatform=(function(){let a={},A=Object.create(a);return A[a[0]="WEB_BROWSER"]=0,A[a[1]="APP_STORE"]=1,A[a[2]="WIN_STORE"]=2,A[a[3]="DARWIN"]=3,A[a[4]="WIN32"]=4,A[a[5]="WIN_HYBRID"]=5,A})(),i.WebdPayload=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.usesParticipantInKey=s.bool();break}case 2:{d.supportsStarredMessages=s.bool();break}case 3:{d.supportsDocumentMessages=s.bool();break}case 4:{d.supportsUrlMessages=s.bool();break}case 5:{d.supportsMediaRetry=s.bool();break}case 6:{d.supportsE2EImage=s.bool();break}case 7:{d.supportsE2EVideo=s.bool();break}case 8:{d.supportsE2EAudio=s.bool();break}case 9:{d.supportsE2EDocument=s.bool();break}case 10:{d.documentTypes=s.string();break}case 11:{d.features=s.bytes();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.ClientPayload.WebInfo.WebdPayload)return s;var g=new p.proto.ClientPayload.WebInfo.WebdPayload;return s.usesParticipantInKey!=null&&(g.usesParticipantInKey=!!s.usesParticipantInKey),s.supportsStarredMessages!=null&&(g.supportsStarredMessages=!!s.supportsStarredMessages),s.supportsDocumentMessages!=null&&(g.supportsDocumentMessages=!!s.supportsDocumentMessages),s.supportsUrlMessages!=null&&(g.supportsUrlMessages=!!s.supportsUrlMessages),s.supportsMediaRetry!=null&&(g.supportsMediaRetry=!!s.supportsMediaRetry),s.supportsE2EImage!=null&&(g.supportsE2EImage=!!s.supportsE2EImage),s.supportsE2EVideo!=null&&(g.supportsE2EVideo=!!s.supportsE2EVideo),s.supportsE2EAudio!=null&&(g.supportsE2EAudio=!!s.supportsE2EAudio),s.supportsE2EDocument!=null&&(g.supportsE2EDocument=!!s.supportsE2EDocument),s.documentTypes!=null&&(g.documentTypes=String(s.documentTypes)),s.features!=null&&(typeof s.features=="string"?l.base64.decode(s.features,g.features=l.newBuffer(l.base64.length(s.features)),0):s.features.length>=0&&(g.features=s.features)),g},a.toObject=function(s,g){g||(g={});var c={};return s.usesParticipantInKey!=null&&s.hasOwnProperty("usesParticipantInKey")&&(c.usesParticipantInKey=s.usesParticipantInKey,g.oneofs&&(c._usesParticipantInKey="usesParticipantInKey")),s.supportsStarredMessages!=null&&s.hasOwnProperty("supportsStarredMessages")&&(c.supportsStarredMessages=s.supportsStarredMessages,g.oneofs&&(c._supportsStarredMessages="supportsStarredMessages")),s.supportsDocumentMessages!=null&&s.hasOwnProperty("supportsDocumentMessages")&&(c.supportsDocumentMessages=s.supportsDocumentMessages,g.oneofs&&(c._supportsDocumentMessages="supportsDocumentMessages")),s.supportsUrlMessages!=null&&s.hasOwnProperty("supportsUrlMessages")&&(c.supportsUrlMessages=s.supportsUrlMessages,g.oneofs&&(c._supportsUrlMessages="supportsUrlMessages")),s.supportsMediaRetry!=null&&s.hasOwnProperty("supportsMediaRetry")&&(c.supportsMediaRetry=s.supportsMediaRetry,g.oneofs&&(c._supportsMediaRetry="supportsMediaRetry")),s.supportsE2EImage!=null&&s.hasOwnProperty("supportsE2EImage")&&(c.supportsE2EImage=s.supportsE2EImage,g.oneofs&&(c._supportsE2EImage="supportsE2EImage")),s.supportsE2EVideo!=null&&s.hasOwnProperty("supportsE2EVideo")&&(c.supportsE2EVideo=s.supportsE2EVideo,g.oneofs&&(c._supportsE2EVideo="supportsE2EVideo")),s.supportsE2EAudio!=null&&s.hasOwnProperty("supportsE2EAudio")&&(c.supportsE2EAudio=s.supportsE2EAudio,g.oneofs&&(c._supportsE2EAudio="supportsE2EAudio")),s.supportsE2EDocument!=null&&s.hasOwnProperty("supportsE2EDocument")&&(c.supportsE2EDocument=s.supportsE2EDocument,g.oneofs&&(c._supportsE2EDocument="supportsE2EDocument")),s.documentTypes!=null&&s.hasOwnProperty("documentTypes")&&(c.documentTypes=s.documentTypes,g.oneofs&&(c._documentTypes="documentTypes")),s.features!=null&&s.hasOwnProperty("features")&&(c.features=g.bytes===String?l.base64.encode(s.features,0,s.features.length):g.bytes===Array?Array.prototype.slice.call(s.features):s.features,g.oneofs&&(c._features="features")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ClientPayload.WebInfo.WebdPayload"},a})(),i})(),t})(),n.CollectionName=(function(){let t={},o=Object.create(t);return o[t[0]="COLLECTION_NAME_UNKNOWN"]=0,o[t[1]="REGULAR"]=1,o[t[2]="REGULAR_LOW"]=2,o[t[3]="REGULAR_HIGH"]=3,o[t[4]="CRITICAL_BLOCK"]=4,o[t[5]="CRITICAL_UNBLOCK_LOW"]=5,o})(),n.CommentMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.commentParentKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.replyCount=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.CommentMetadata)return e;var a=new p.proto.CommentMetadata;if(e.commentParentKey!=null){if(typeof e.commentParentKey!="object")throw TypeError(".proto.CommentMetadata.commentParentKey: object expected");a.commentParentKey=p.proto.MessageKey.fromObject(e.commentParentKey)}return e.replyCount!=null&&(a.replyCount=e.replyCount>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.commentParentKey!=null&&e.hasOwnProperty("commentParentKey")&&(A.commentParentKey=p.proto.MessageKey.toObject(e.commentParentKey,a),a.oneofs&&(A._commentParentKey="commentParentKey")),e.replyCount!=null&&e.hasOwnProperty("replyCount")&&(A.replyCount=e.replyCount,a.oneofs&&(A._replyCount="replyCount")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CommentMetadata"},t})(),n.CompanionCommitment=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.hash=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.CompanionCommitment)return e;var a=new p.proto.CompanionCommitment;return e.hash!=null&&(typeof e.hash=="string"?l.base64.decode(e.hash,a.hash=l.newBuffer(l.base64.length(e.hash)),0):e.hash.length>=0&&(a.hash=e.hash)),a},t.toObject=function(e,a){a||(a={});var A={};return e.hash!=null&&e.hasOwnProperty("hash")&&(A.hash=a.bytes===String?l.base64.encode(e.hash,0,e.hash.length):a.bytes===Array?Array.prototype.slice.call(e.hash):e.hash,a.oneofs&&(A._hash="hash")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CompanionCommitment"},t})(),n.CompanionEphemeralIdentity=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.deviceType=e.int32();break}case 3:{s.ref=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.CompanionEphemeralIdentity)return e;var a=new p.proto.CompanionEphemeralIdentity;switch(e.publicKey!=null&&(typeof e.publicKey=="string"?l.base64.decode(e.publicKey,a.publicKey=l.newBuffer(l.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.deviceType){default:if(typeof e.deviceType=="number"){a.deviceType=e.deviceType;break}break;case"UNKNOWN":case 0:a.deviceType=0;break;case"CHROME":case 1:a.deviceType=1;break;case"FIREFOX":case 2:a.deviceType=2;break;case"IE":case 3:a.deviceType=3;break;case"OPERA":case 4:a.deviceType=4;break;case"SAFARI":case 5:a.deviceType=5;break;case"EDGE":case 6:a.deviceType=6;break;case"DESKTOP":case 7:a.deviceType=7;break;case"IPAD":case 8:a.deviceType=8;break;case"ANDROID_TABLET":case 9:a.deviceType=9;break;case"OHANA":case 10:a.deviceType=10;break;case"ALOHA":case 11:a.deviceType=11;break;case"CATALINA":case 12:a.deviceType=12;break;case"TCL_TV":case 13:a.deviceType=13;break;case"IOS_PHONE":case 14:a.deviceType=14;break;case"IOS_CATALYST":case 15:a.deviceType=15;break;case"ANDROID_PHONE":case 16:a.deviceType=16;break;case"ANDROID_AMBIGUOUS":case 17:a.deviceType=17;break;case"WEAR_OS":case 18:a.deviceType=18;break;case"AR_WRIST":case 19:a.deviceType=19;break;case"AR_DEVICE":case 20:a.deviceType=20;break;case"UWP":case 21:a.deviceType=21;break;case"VR":case 22:a.deviceType=22;break;case"CLOUD_API":case 23:a.deviceType=23;break;case"SMARTGLASSES":case 24:a.deviceType=24;break}return e.ref!=null&&(a.ref=String(e.ref)),a},t.toObject=function(e,a){a||(a={});var A={};return e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?l.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.deviceType!=null&&e.hasOwnProperty("deviceType")&&(A.deviceType=a.enums===String?p.proto.DeviceProps.PlatformType[e.deviceType]===void 0?e.deviceType:p.proto.DeviceProps.PlatformType[e.deviceType]:e.deviceType,a.oneofs&&(A._deviceType="deviceType")),e.ref!=null&&e.hasOwnProperty("ref")&&(A.ref=e.ref,a.oneofs&&(A._ref="ref")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CompanionEphemeralIdentity"},t})(),n.Config=(function(){function t(i){if(this.field={},i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.field===l.emptyObject&&(s.field={});var d=e.uint32()+e.pos;for(g=0,c=null;e.pos>>3){case 1:g=e.uint32();break;case 2:c=p.proto.Field.decode(e,e.uint32());break;default:e.skipType(B&7);break}}s.field[g]=c;break}case 2:{s.version=e.uint32();break}default:e.skipType(I&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Config)return e;var a=new p.proto.Config;if(e.field){if(typeof e.field!="object")throw TypeError(".proto.Config.field: object expected");a.field={};for(var A=Object.keys(e.field),r=0;r>>0),a},t.toObject=function(e,a){a||(a={});var A={};(a.objects||a.defaults)&&(A.field={});var r;if(e.field&&(r=Object.keys(e.field)).length){A.field={};for(var s=0;s>>3){case 1:{s.stanzaId=e.string();break}case 2:{s.participant=e.string();break}case 3:{s.quotedMessage=p.proto.Message.decode(e,e.uint32());break}case 4:{s.remoteJid=e.string();break}case 15:{s.mentionedJid&&s.mentionedJid.length||(s.mentionedJid=[]),s.mentionedJid.push(e.string());break}case 18:{s.conversionSource=e.string();break}case 19:{s.conversionData=e.bytes();break}case 20:{s.conversionDelaySeconds=e.uint32();break}case 21:{s.forwardingScore=e.uint32();break}case 22:{s.isForwarded=e.bool();break}case 23:{s.quotedAd=p.proto.ContextInfo.AdReplyInfo.decode(e,e.uint32());break}case 24:{s.placeholderKey=p.proto.MessageKey.decode(e,e.uint32());break}case 25:{s.expiration=e.uint32();break}case 26:{s.ephemeralSettingTimestamp=e.int64();break}case 27:{s.ephemeralSharedSecret=e.bytes();break}case 28:{s.externalAdReply=p.proto.ContextInfo.ExternalAdReplyInfo.decode(e,e.uint32());break}case 29:{s.entryPointConversionSource=e.string();break}case 30:{s.entryPointConversionApp=e.string();break}case 31:{s.entryPointConversionDelaySeconds=e.uint32();break}case 32:{s.disappearingMode=p.proto.DisappearingMode.decode(e,e.uint32());break}case 33:{s.actionLink=p.proto.ActionLink.decode(e,e.uint32());break}case 34:{s.groupSubject=e.string();break}case 35:{s.parentGroupJid=e.string();break}case 37:{s.trustBannerType=e.string();break}case 38:{s.trustBannerAction=e.uint32();break}case 39:{s.isSampled=e.bool();break}case 40:{s.groupMentions&&s.groupMentions.length||(s.groupMentions=[]),s.groupMentions.push(p.proto.GroupMention.decode(e,e.uint32()));break}case 41:{s.utm=p.proto.ContextInfo.UTMInfo.decode(e,e.uint32());break}case 43:{s.forwardedNewsletterMessageInfo=p.proto.ContextInfo.ForwardedNewsletterMessageInfo.decode(e,e.uint32());break}case 44:{s.businessMessageForwardInfo=p.proto.ContextInfo.BusinessMessageForwardInfo.decode(e,e.uint32());break}case 45:{s.smbClientCampaignId=e.string();break}case 46:{s.smbServerCampaignId=e.string();break}case 47:{s.dataSharingContext=p.proto.ContextInfo.DataSharingContext.decode(e,e.uint32());break}case 48:{s.alwaysShowAdAttribution=e.bool();break}case 49:{s.featureEligibilities=p.proto.ContextInfo.FeatureEligibilities.decode(e,e.uint32());break}case 50:{s.entryPointConversionExternalSource=e.string();break}case 51:{s.entryPointConversionExternalMedium=e.string();break}case 54:{s.ctwaSignals=e.string();break}case 55:{s.ctwaPayload=e.bytes();break}case 56:{s.forwardedAiBotMessageInfo=p.proto.ForwardedAIBotMessageInfo.decode(e,e.uint32());break}case 57:{s.statusAttributionType=e.int32();break}case 58:{s.urlTrackingMap=p.proto.UrlTrackingMap.decode(e,e.uint32());break}case 59:{s.pairedMediaType=e.int32();break}case 60:{s.rankingVersion=e.uint32();break}case 62:{s.memberLabel=p.proto.MemberLabel.decode(e,e.uint32());break}case 63:{s.isQuestion=e.bool();break}case 64:{s.statusSourceType=e.int32();break}case 65:{s.statusAttributions&&s.statusAttributions.length||(s.statusAttributions=[]),s.statusAttributions.push(p.proto.StatusAttribution.decode(e,e.uint32()));break}case 66:{s.isGroupStatus=e.bool();break}case 67:{s.forwardOrigin=e.int32();break}case 68:{s.questionReplyQuotedMessage=p.proto.ContextInfo.QuestionReplyQuotedMessage.decode(e,e.uint32());break}case 69:{s.statusAudienceMetadata=p.proto.ContextInfo.StatusAudienceMetadata.decode(e,e.uint32());break}case 70:{s.nonJidMentions=e.uint32();break}case 71:{s.quotedType=e.int32();break}case 72:{s.botMessageSharingInfo=p.proto.BotMessageSharingInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ContextInfo)return e;var a=new p.proto.ContextInfo;if(e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),e.participant!=null&&(a.participant=String(e.participant)),e.quotedMessage!=null){if(typeof e.quotedMessage!="object")throw TypeError(".proto.ContextInfo.quotedMessage: object expected");a.quotedMessage=p.proto.Message.fromObject(e.quotedMessage)}if(e.remoteJid!=null&&(a.remoteJid=String(e.remoteJid)),e.mentionedJid){if(!Array.isArray(e.mentionedJid))throw TypeError(".proto.ContextInfo.mentionedJid: array expected");a.mentionedJid=[];for(var A=0;A=0&&(a.conversionData=e.conversionData)),e.conversionDelaySeconds!=null&&(a.conversionDelaySeconds=e.conversionDelaySeconds>>>0),e.forwardingScore!=null&&(a.forwardingScore=e.forwardingScore>>>0),e.isForwarded!=null&&(a.isForwarded=!!e.isForwarded),e.quotedAd!=null){if(typeof e.quotedAd!="object")throw TypeError(".proto.ContextInfo.quotedAd: object expected");a.quotedAd=p.proto.ContextInfo.AdReplyInfo.fromObject(e.quotedAd)}if(e.placeholderKey!=null){if(typeof e.placeholderKey!="object")throw TypeError(".proto.ContextInfo.placeholderKey: object expected");a.placeholderKey=p.proto.MessageKey.fromObject(e.placeholderKey)}if(e.expiration!=null&&(a.expiration=e.expiration>>>0),e.ephemeralSettingTimestamp!=null&&(l.Long?(a.ephemeralSettingTimestamp=l.Long.fromValue(e.ephemeralSettingTimestamp)).unsigned=!1:typeof e.ephemeralSettingTimestamp=="string"?a.ephemeralSettingTimestamp=parseInt(e.ephemeralSettingTimestamp,10):typeof e.ephemeralSettingTimestamp=="number"?a.ephemeralSettingTimestamp=e.ephemeralSettingTimestamp:typeof e.ephemeralSettingTimestamp=="object"&&(a.ephemeralSettingTimestamp=new l.LongBits(e.ephemeralSettingTimestamp.low>>>0,e.ephemeralSettingTimestamp.high>>>0).toNumber())),e.ephemeralSharedSecret!=null&&(typeof e.ephemeralSharedSecret=="string"?l.base64.decode(e.ephemeralSharedSecret,a.ephemeralSharedSecret=l.newBuffer(l.base64.length(e.ephemeralSharedSecret)),0):e.ephemeralSharedSecret.length>=0&&(a.ephemeralSharedSecret=e.ephemeralSharedSecret)),e.externalAdReply!=null){if(typeof e.externalAdReply!="object")throw TypeError(".proto.ContextInfo.externalAdReply: object expected");a.externalAdReply=p.proto.ContextInfo.ExternalAdReplyInfo.fromObject(e.externalAdReply)}if(e.entryPointConversionSource!=null&&(a.entryPointConversionSource=String(e.entryPointConversionSource)),e.entryPointConversionApp!=null&&(a.entryPointConversionApp=String(e.entryPointConversionApp)),e.entryPointConversionDelaySeconds!=null&&(a.entryPointConversionDelaySeconds=e.entryPointConversionDelaySeconds>>>0),e.disappearingMode!=null){if(typeof e.disappearingMode!="object")throw TypeError(".proto.ContextInfo.disappearingMode: object expected");a.disappearingMode=p.proto.DisappearingMode.fromObject(e.disappearingMode)}if(e.actionLink!=null){if(typeof e.actionLink!="object")throw TypeError(".proto.ContextInfo.actionLink: object expected");a.actionLink=p.proto.ActionLink.fromObject(e.actionLink)}if(e.groupSubject!=null&&(a.groupSubject=String(e.groupSubject)),e.parentGroupJid!=null&&(a.parentGroupJid=String(e.parentGroupJid)),e.trustBannerType!=null&&(a.trustBannerType=String(e.trustBannerType)),e.trustBannerAction!=null&&(a.trustBannerAction=e.trustBannerAction>>>0),e.isSampled!=null&&(a.isSampled=!!e.isSampled),e.groupMentions){if(!Array.isArray(e.groupMentions))throw TypeError(".proto.ContextInfo.groupMentions: array expected");a.groupMentions=[];for(var A=0;A=0&&(a.ctwaPayload=e.ctwaPayload)),e.forwardedAiBotMessageInfo!=null){if(typeof e.forwardedAiBotMessageInfo!="object")throw TypeError(".proto.ContextInfo.forwardedAiBotMessageInfo: object expected");a.forwardedAiBotMessageInfo=p.proto.ForwardedAIBotMessageInfo.fromObject(e.forwardedAiBotMessageInfo)}switch(e.statusAttributionType){default:if(typeof e.statusAttributionType=="number"){a.statusAttributionType=e.statusAttributionType;break}break;case"NONE":case 0:a.statusAttributionType=0;break;case"RESHARED_FROM_MENTION":case 1:a.statusAttributionType=1;break;case"RESHARED_FROM_POST":case 2:a.statusAttributionType=2;break;case"RESHARED_FROM_POST_MANY_TIMES":case 3:a.statusAttributionType=3;break;case"FORWARDED_FROM_STATUS":case 4:a.statusAttributionType=4;break}if(e.urlTrackingMap!=null){if(typeof e.urlTrackingMap!="object")throw TypeError(".proto.ContextInfo.urlTrackingMap: object expected");a.urlTrackingMap=p.proto.UrlTrackingMap.fromObject(e.urlTrackingMap)}switch(e.pairedMediaType){default:if(typeof e.pairedMediaType=="number"){a.pairedMediaType=e.pairedMediaType;break}break;case"NOT_PAIRED_MEDIA":case 0:a.pairedMediaType=0;break;case"SD_VIDEO_PARENT":case 1:a.pairedMediaType=1;break;case"HD_VIDEO_CHILD":case 2:a.pairedMediaType=2;break;case"SD_IMAGE_PARENT":case 3:a.pairedMediaType=3;break;case"HD_IMAGE_CHILD":case 4:a.pairedMediaType=4;break;case"MOTION_PHOTO_PARENT":case 5:a.pairedMediaType=5;break;case"MOTION_PHOTO_CHILD":case 6:a.pairedMediaType=6;break;case"HEVC_VIDEO_PARENT":case 7:a.pairedMediaType=7;break;case"HEVC_VIDEO_CHILD":case 8:a.pairedMediaType=8;break}if(e.rankingVersion!=null&&(a.rankingVersion=e.rankingVersion>>>0),e.memberLabel!=null){if(typeof e.memberLabel!="object")throw TypeError(".proto.ContextInfo.memberLabel: object expected");a.memberLabel=p.proto.MemberLabel.fromObject(e.memberLabel)}switch(e.isQuestion!=null&&(a.isQuestion=!!e.isQuestion),e.statusSourceType){default:if(typeof e.statusSourceType=="number"){a.statusSourceType=e.statusSourceType;break}break;case"IMAGE":case 0:a.statusSourceType=0;break;case"VIDEO":case 1:a.statusSourceType=1;break;case"GIF":case 2:a.statusSourceType=2;break;case"AUDIO":case 3:a.statusSourceType=3;break;case"TEXT":case 4:a.statusSourceType=4;break;case"MUSIC_STANDALONE":case 5:a.statusSourceType=5;break}if(e.statusAttributions){if(!Array.isArray(e.statusAttributions))throw TypeError(".proto.ContextInfo.statusAttributions: array expected");a.statusAttributions=[];for(var A=0;A>>0),e.quotedType){default:if(typeof e.quotedType=="number"){a.quotedType=e.quotedType;break}break;case"EXPLICIT":case 0:a.quotedType=0;break;case"AUTO":case 1:a.quotedType=1;break}if(e.botMessageSharingInfo!=null){if(typeof e.botMessageSharingInfo!="object")throw TypeError(".proto.ContextInfo.botMessageSharingInfo: object expected");a.botMessageSharingInfo=p.proto.BotMessageSharingInfo.fromObject(e.botMessageSharingInfo)}return a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.mentionedJid=[],A.groupMentions=[],A.statusAttributions=[]),e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),e.participant!=null&&e.hasOwnProperty("participant")&&(A.participant=e.participant,a.oneofs&&(A._participant="participant")),e.quotedMessage!=null&&e.hasOwnProperty("quotedMessage")&&(A.quotedMessage=p.proto.Message.toObject(e.quotedMessage,a),a.oneofs&&(A._quotedMessage="quotedMessage")),e.remoteJid!=null&&e.hasOwnProperty("remoteJid")&&(A.remoteJid=e.remoteJid,a.oneofs&&(A._remoteJid="remoteJid")),e.mentionedJid&&e.mentionedJid.length){A.mentionedJid=[];for(var r=0;r>>3){case 1:{c.advertiserName=A.string();break}case 2:{c.mediaType=A.int32();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.caption=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.AdReplyInfo)return A;var r=new p.proto.ContextInfo.AdReplyInfo;switch(A.advertiserName!=null&&(r.advertiserName=String(A.advertiserName)),A.mediaType){default:if(typeof A.mediaType=="number"){r.mediaType=A.mediaType;break}break;case"NONE":case 0:r.mediaType=0;break;case"IMAGE":case 1:r.mediaType=1;break;case"VIDEO":case 2:r.mediaType=2;break}return A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(r.caption=String(A.caption)),r},i.toObject=function(A,r){r||(r={});var s={};return A.advertiserName!=null&&A.hasOwnProperty("advertiserName")&&(s.advertiserName=A.advertiserName,r.oneofs&&(s._advertiserName="advertiserName")),A.mediaType!=null&&A.hasOwnProperty("mediaType")&&(s.mediaType=r.enums===String?p.proto.ContextInfo.AdReplyInfo.MediaType[A.mediaType]===void 0?A.mediaType:p.proto.ContextInfo.AdReplyInfo.MediaType[A.mediaType]:A.mediaType,r.oneofs&&(s._mediaType="mediaType")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.AdReplyInfo"},i.MediaType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="IMAGE"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),t.BusinessMessageForwardInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.businessOwnerJid=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.BusinessMessageForwardInfo)return A;var r=new p.proto.ContextInfo.BusinessMessageForwardInfo;return A.businessOwnerJid!=null&&(r.businessOwnerJid=String(A.businessOwnerJid)),r},i.toObject=function(A,r){r||(r={});var s={};return A.businessOwnerJid!=null&&A.hasOwnProperty("businessOwnerJid")&&(s.businessOwnerJid=A.businessOwnerJid,r.oneofs&&(s._businessOwnerJid="businessOwnerJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.BusinessMessageForwardInfo"},i})(),t.DataSharingContext=(function(){function i(a){if(this.parameters=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.showMmDisclosure=A.bool();break}case 2:{c.encryptedSignalTokenConsented=A.string();break}case 3:{c.parameters&&c.parameters.length||(c.parameters=[]),c.parameters.push(p.proto.ContextInfo.DataSharingContext.Parameters.decode(A,A.uint32()));break}case 4:{c.dataSharingFlags=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.DataSharingContext)return A;var r=new p.proto.ContextInfo.DataSharingContext;if(A.showMmDisclosure!=null&&(r.showMmDisclosure=!!A.showMmDisclosure),A.encryptedSignalTokenConsented!=null&&(r.encryptedSignalTokenConsented=String(A.encryptedSignalTokenConsented)),A.parameters){if(!Array.isArray(A.parameters))throw TypeError(".proto.ContextInfo.DataSharingContext.parameters: array expected");r.parameters=[];for(var s=0;s>>3){case 1:{d.key=s.string();break}case 2:{d.stringData=s.string();break}case 3:{d.intData=s.int64();break}case 4:{d.floatData=s.float();break}case 5:{d.contents=p.proto.ContextInfo.DataSharingContext.Parameters.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.ContextInfo.DataSharingContext.Parameters)return s;var g=new p.proto.ContextInfo.DataSharingContext.Parameters;if(s.key!=null&&(g.key=String(s.key)),s.stringData!=null&&(g.stringData=String(s.stringData)),s.intData!=null&&(l.Long?(g.intData=l.Long.fromValue(s.intData)).unsigned=!1:typeof s.intData=="string"?g.intData=parseInt(s.intData,10):typeof s.intData=="number"?g.intData=s.intData:typeof s.intData=="object"&&(g.intData=new l.LongBits(s.intData.low>>>0,s.intData.high>>>0).toNumber())),s.floatData!=null&&(g.floatData=Number(s.floatData)),s.contents!=null){if(typeof s.contents!="object")throw TypeError(".proto.ContextInfo.DataSharingContext.Parameters.contents: object expected");g.contents=p.proto.ContextInfo.DataSharingContext.Parameters.fromObject(s.contents)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.key!=null&&s.hasOwnProperty("key")&&(c.key=s.key,g.oneofs&&(c._key="key")),s.stringData!=null&&s.hasOwnProperty("stringData")&&(c.stringData=s.stringData,g.oneofs&&(c._stringData="stringData")),s.intData!=null&&s.hasOwnProperty("intData")&&(typeof s.intData=="number"?c.intData=g.longs===String?String(s.intData):s.intData:c.intData=g.longs===String?se(s.intData):g.longs===Number?ge(s.intData):s.intData,g.oneofs&&(c._intData="intData")),s.floatData!=null&&s.hasOwnProperty("floatData")&&(c.floatData=g.json&&!isFinite(s.floatData)?String(s.floatData):s.floatData,g.oneofs&&(c._floatData="floatData")),s.contents!=null&&s.hasOwnProperty("contents")&&(c.contents=p.proto.ContextInfo.DataSharingContext.Parameters.toObject(s.contents,g),g.oneofs&&(c._contents="contents")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ContextInfo.DataSharingContext.Parameters"},a})(),i})(),t.ExternalAdReplyInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.title=A.string();break}case 2:{c.body=A.string();break}case 3:{c.mediaType=A.int32();break}case 4:{c.thumbnailUrl=A.string();break}case 5:{c.mediaUrl=A.string();break}case 6:{c.thumbnail=A.bytes();break}case 7:{c.sourceType=A.string();break}case 8:{c.sourceId=A.string();break}case 9:{c.sourceUrl=A.string();break}case 10:{c.containsAutoReply=A.bool();break}case 11:{c.renderLargerThumbnail=A.bool();break}case 12:{c.showAdAttribution=A.bool();break}case 13:{c.ctwaClid=A.string();break}case 14:{c.ref=A.string();break}case 15:{c.clickToWhatsappCall=A.bool();break}case 16:{c.adContextPreviewDismissed=A.bool();break}case 17:{c.sourceApp=A.string();break}case 18:{c.automatedGreetingMessageShown=A.bool();break}case 19:{c.greetingMessageBody=A.string();break}case 20:{c.ctaPayload=A.string();break}case 21:{c.disableNudge=A.bool();break}case 22:{c.originalImageUrl=A.string();break}case 23:{c.automatedGreetingMessageCtaType=A.string();break}case 24:{c.wtwaAdFormat=A.bool();break}case 25:{c.adType=A.int32();break}case 26:{c.wtwaWebsiteUrl=A.string();break}case 27:{c.adPreviewUrl=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.ExternalAdReplyInfo)return A;var r=new p.proto.ContextInfo.ExternalAdReplyInfo;switch(A.title!=null&&(r.title=String(A.title)),A.body!=null&&(r.body=String(A.body)),A.mediaType){default:if(typeof A.mediaType=="number"){r.mediaType=A.mediaType;break}break;case"NONE":case 0:r.mediaType=0;break;case"IMAGE":case 1:r.mediaType=1;break;case"VIDEO":case 2:r.mediaType=2;break}switch(A.thumbnailUrl!=null&&(r.thumbnailUrl=String(A.thumbnailUrl)),A.mediaUrl!=null&&(r.mediaUrl=String(A.mediaUrl)),A.thumbnail!=null&&(typeof A.thumbnail=="string"?l.base64.decode(A.thumbnail,r.thumbnail=l.newBuffer(l.base64.length(A.thumbnail)),0):A.thumbnail.length>=0&&(r.thumbnail=A.thumbnail)),A.sourceType!=null&&(r.sourceType=String(A.sourceType)),A.sourceId!=null&&(r.sourceId=String(A.sourceId)),A.sourceUrl!=null&&(r.sourceUrl=String(A.sourceUrl)),A.containsAutoReply!=null&&(r.containsAutoReply=!!A.containsAutoReply),A.renderLargerThumbnail!=null&&(r.renderLargerThumbnail=!!A.renderLargerThumbnail),A.showAdAttribution!=null&&(r.showAdAttribution=!!A.showAdAttribution),A.ctwaClid!=null&&(r.ctwaClid=String(A.ctwaClid)),A.ref!=null&&(r.ref=String(A.ref)),A.clickToWhatsappCall!=null&&(r.clickToWhatsappCall=!!A.clickToWhatsappCall),A.adContextPreviewDismissed!=null&&(r.adContextPreviewDismissed=!!A.adContextPreviewDismissed),A.sourceApp!=null&&(r.sourceApp=String(A.sourceApp)),A.automatedGreetingMessageShown!=null&&(r.automatedGreetingMessageShown=!!A.automatedGreetingMessageShown),A.greetingMessageBody!=null&&(r.greetingMessageBody=String(A.greetingMessageBody)),A.ctaPayload!=null&&(r.ctaPayload=String(A.ctaPayload)),A.disableNudge!=null&&(r.disableNudge=!!A.disableNudge),A.originalImageUrl!=null&&(r.originalImageUrl=String(A.originalImageUrl)),A.automatedGreetingMessageCtaType!=null&&(r.automatedGreetingMessageCtaType=String(A.automatedGreetingMessageCtaType)),A.wtwaAdFormat!=null&&(r.wtwaAdFormat=!!A.wtwaAdFormat),A.adType){default:if(typeof A.adType=="number"){r.adType=A.adType;break}break;case"CTWA":case 0:r.adType=0;break;case"CAWC":case 1:r.adType=1;break}return A.wtwaWebsiteUrl!=null&&(r.wtwaWebsiteUrl=String(A.wtwaWebsiteUrl)),A.adPreviewUrl!=null&&(r.adPreviewUrl=String(A.adPreviewUrl)),r},i.toObject=function(A,r){r||(r={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=A.body,r.oneofs&&(s._body="body")),A.mediaType!=null&&A.hasOwnProperty("mediaType")&&(s.mediaType=r.enums===String?p.proto.ContextInfo.ExternalAdReplyInfo.MediaType[A.mediaType]===void 0?A.mediaType:p.proto.ContextInfo.ExternalAdReplyInfo.MediaType[A.mediaType]:A.mediaType,r.oneofs&&(s._mediaType="mediaType")),A.thumbnailUrl!=null&&A.hasOwnProperty("thumbnailUrl")&&(s.thumbnailUrl=A.thumbnailUrl,r.oneofs&&(s._thumbnailUrl="thumbnailUrl")),A.mediaUrl!=null&&A.hasOwnProperty("mediaUrl")&&(s.mediaUrl=A.mediaUrl,r.oneofs&&(s._mediaUrl="mediaUrl")),A.thumbnail!=null&&A.hasOwnProperty("thumbnail")&&(s.thumbnail=r.bytes===String?l.base64.encode(A.thumbnail,0,A.thumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnail):A.thumbnail,r.oneofs&&(s._thumbnail="thumbnail")),A.sourceType!=null&&A.hasOwnProperty("sourceType")&&(s.sourceType=A.sourceType,r.oneofs&&(s._sourceType="sourceType")),A.sourceId!=null&&A.hasOwnProperty("sourceId")&&(s.sourceId=A.sourceId,r.oneofs&&(s._sourceId="sourceId")),A.sourceUrl!=null&&A.hasOwnProperty("sourceUrl")&&(s.sourceUrl=A.sourceUrl,r.oneofs&&(s._sourceUrl="sourceUrl")),A.containsAutoReply!=null&&A.hasOwnProperty("containsAutoReply")&&(s.containsAutoReply=A.containsAutoReply,r.oneofs&&(s._containsAutoReply="containsAutoReply")),A.renderLargerThumbnail!=null&&A.hasOwnProperty("renderLargerThumbnail")&&(s.renderLargerThumbnail=A.renderLargerThumbnail,r.oneofs&&(s._renderLargerThumbnail="renderLargerThumbnail")),A.showAdAttribution!=null&&A.hasOwnProperty("showAdAttribution")&&(s.showAdAttribution=A.showAdAttribution,r.oneofs&&(s._showAdAttribution="showAdAttribution")),A.ctwaClid!=null&&A.hasOwnProperty("ctwaClid")&&(s.ctwaClid=A.ctwaClid,r.oneofs&&(s._ctwaClid="ctwaClid")),A.ref!=null&&A.hasOwnProperty("ref")&&(s.ref=A.ref,r.oneofs&&(s._ref="ref")),A.clickToWhatsappCall!=null&&A.hasOwnProperty("clickToWhatsappCall")&&(s.clickToWhatsappCall=A.clickToWhatsappCall,r.oneofs&&(s._clickToWhatsappCall="clickToWhatsappCall")),A.adContextPreviewDismissed!=null&&A.hasOwnProperty("adContextPreviewDismissed")&&(s.adContextPreviewDismissed=A.adContextPreviewDismissed,r.oneofs&&(s._adContextPreviewDismissed="adContextPreviewDismissed")),A.sourceApp!=null&&A.hasOwnProperty("sourceApp")&&(s.sourceApp=A.sourceApp,r.oneofs&&(s._sourceApp="sourceApp")),A.automatedGreetingMessageShown!=null&&A.hasOwnProperty("automatedGreetingMessageShown")&&(s.automatedGreetingMessageShown=A.automatedGreetingMessageShown,r.oneofs&&(s._automatedGreetingMessageShown="automatedGreetingMessageShown")),A.greetingMessageBody!=null&&A.hasOwnProperty("greetingMessageBody")&&(s.greetingMessageBody=A.greetingMessageBody,r.oneofs&&(s._greetingMessageBody="greetingMessageBody")),A.ctaPayload!=null&&A.hasOwnProperty("ctaPayload")&&(s.ctaPayload=A.ctaPayload,r.oneofs&&(s._ctaPayload="ctaPayload")),A.disableNudge!=null&&A.hasOwnProperty("disableNudge")&&(s.disableNudge=A.disableNudge,r.oneofs&&(s._disableNudge="disableNudge")),A.originalImageUrl!=null&&A.hasOwnProperty("originalImageUrl")&&(s.originalImageUrl=A.originalImageUrl,r.oneofs&&(s._originalImageUrl="originalImageUrl")),A.automatedGreetingMessageCtaType!=null&&A.hasOwnProperty("automatedGreetingMessageCtaType")&&(s.automatedGreetingMessageCtaType=A.automatedGreetingMessageCtaType,r.oneofs&&(s._automatedGreetingMessageCtaType="automatedGreetingMessageCtaType")),A.wtwaAdFormat!=null&&A.hasOwnProperty("wtwaAdFormat")&&(s.wtwaAdFormat=A.wtwaAdFormat,r.oneofs&&(s._wtwaAdFormat="wtwaAdFormat")),A.adType!=null&&A.hasOwnProperty("adType")&&(s.adType=r.enums===String?p.proto.ContextInfo.ExternalAdReplyInfo.AdType[A.adType]===void 0?A.adType:p.proto.ContextInfo.ExternalAdReplyInfo.AdType[A.adType]:A.adType,r.oneofs&&(s._adType="adType")),A.wtwaWebsiteUrl!=null&&A.hasOwnProperty("wtwaWebsiteUrl")&&(s.wtwaWebsiteUrl=A.wtwaWebsiteUrl,r.oneofs&&(s._wtwaWebsiteUrl="wtwaWebsiteUrl")),A.adPreviewUrl!=null&&A.hasOwnProperty("adPreviewUrl")&&(s.adPreviewUrl=A.adPreviewUrl,r.oneofs&&(s._adPreviewUrl="adPreviewUrl")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.ExternalAdReplyInfo"},i.AdType=(function(){let a={},A=Object.create(a);return A[a[0]="CTWA"]=0,A[a[1]="CAWC"]=1,A})(),i.MediaType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="IMAGE"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),t.FeatureEligibilities=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.cannotBeReactedTo=A.bool();break}case 2:{c.cannotBeRanked=A.bool();break}case 3:{c.canRequestFeedback=A.bool();break}case 4:{c.canBeReshared=A.bool();break}case 5:{c.canReceiveMultiReact=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.FeatureEligibilities)return A;var r=new p.proto.ContextInfo.FeatureEligibilities;return A.cannotBeReactedTo!=null&&(r.cannotBeReactedTo=!!A.cannotBeReactedTo),A.cannotBeRanked!=null&&(r.cannotBeRanked=!!A.cannotBeRanked),A.canRequestFeedback!=null&&(r.canRequestFeedback=!!A.canRequestFeedback),A.canBeReshared!=null&&(r.canBeReshared=!!A.canBeReshared),A.canReceiveMultiReact!=null&&(r.canReceiveMultiReact=!!A.canReceiveMultiReact),r},i.toObject=function(A,r){r||(r={});var s={};return A.cannotBeReactedTo!=null&&A.hasOwnProperty("cannotBeReactedTo")&&(s.cannotBeReactedTo=A.cannotBeReactedTo,r.oneofs&&(s._cannotBeReactedTo="cannotBeReactedTo")),A.cannotBeRanked!=null&&A.hasOwnProperty("cannotBeRanked")&&(s.cannotBeRanked=A.cannotBeRanked,r.oneofs&&(s._cannotBeRanked="cannotBeRanked")),A.canRequestFeedback!=null&&A.hasOwnProperty("canRequestFeedback")&&(s.canRequestFeedback=A.canRequestFeedback,r.oneofs&&(s._canRequestFeedback="canRequestFeedback")),A.canBeReshared!=null&&A.hasOwnProperty("canBeReshared")&&(s.canBeReshared=A.canBeReshared,r.oneofs&&(s._canBeReshared="canBeReshared")),A.canReceiveMultiReact!=null&&A.hasOwnProperty("canReceiveMultiReact")&&(s.canReceiveMultiReact=A.canReceiveMultiReact,r.oneofs&&(s._canReceiveMultiReact="canReceiveMultiReact")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.FeatureEligibilities"},i})(),t.ForwardOrigin=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHAT"]=1,e[i[2]="STATUS"]=2,e[i[3]="CHANNELS"]=3,e[i[4]="META_AI"]=4,e[i[5]="UGC"]=5,e})(),t.ForwardedNewsletterMessageInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.newsletterJid=A.string();break}case 2:{c.serverMessageId=A.int32();break}case 3:{c.newsletterName=A.string();break}case 4:{c.contentType=A.int32();break}case 5:{c.accessibilityText=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.ForwardedNewsletterMessageInfo)return A;var r=new p.proto.ContextInfo.ForwardedNewsletterMessageInfo;switch(A.newsletterJid!=null&&(r.newsletterJid=String(A.newsletterJid)),A.serverMessageId!=null&&(r.serverMessageId=A.serverMessageId|0),A.newsletterName!=null&&(r.newsletterName=String(A.newsletterName)),A.contentType){default:if(typeof A.contentType=="number"){r.contentType=A.contentType;break}break;case"UPDATE":case 1:r.contentType=1;break;case"UPDATE_CARD":case 2:r.contentType=2;break;case"LINK_CARD":case 3:r.contentType=3;break}return A.accessibilityText!=null&&(r.accessibilityText=String(A.accessibilityText)),r},i.toObject=function(A,r){r||(r={});var s={};return A.newsletterJid!=null&&A.hasOwnProperty("newsletterJid")&&(s.newsletterJid=A.newsletterJid,r.oneofs&&(s._newsletterJid="newsletterJid")),A.serverMessageId!=null&&A.hasOwnProperty("serverMessageId")&&(s.serverMessageId=A.serverMessageId,r.oneofs&&(s._serverMessageId="serverMessageId")),A.newsletterName!=null&&A.hasOwnProperty("newsletterName")&&(s.newsletterName=A.newsletterName,r.oneofs&&(s._newsletterName="newsletterName")),A.contentType!=null&&A.hasOwnProperty("contentType")&&(s.contentType=r.enums===String?p.proto.ContextInfo.ForwardedNewsletterMessageInfo.ContentType[A.contentType]===void 0?A.contentType:p.proto.ContextInfo.ForwardedNewsletterMessageInfo.ContentType[A.contentType]:A.contentType,r.oneofs&&(s._contentType="contentType")),A.accessibilityText!=null&&A.hasOwnProperty("accessibilityText")&&(s.accessibilityText=A.accessibilityText,r.oneofs&&(s._accessibilityText="accessibilityText")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.ForwardedNewsletterMessageInfo"},i.ContentType=(function(){let a={},A=Object.create(a);return A[a[1]="UPDATE"]=1,A[a[2]="UPDATE_CARD"]=2,A[a[3]="LINK_CARD"]=3,A})(),i})(),t.PairedMediaType=(function(){let i={},e=Object.create(i);return e[i[0]="NOT_PAIRED_MEDIA"]=0,e[i[1]="SD_VIDEO_PARENT"]=1,e[i[2]="HD_VIDEO_CHILD"]=2,e[i[3]="SD_IMAGE_PARENT"]=3,e[i[4]="HD_IMAGE_CHILD"]=4,e[i[5]="MOTION_PHOTO_PARENT"]=5,e[i[6]="MOTION_PHOTO_CHILD"]=6,e[i[7]="HEVC_VIDEO_PARENT"]=7,e[i[8]="HEVC_VIDEO_CHILD"]=8,e})(),t.QuestionReplyQuotedMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.serverQuestionId=A.int32();break}case 2:{c.quotedQuestion=p.proto.Message.decode(A,A.uint32());break}case 3:{c.quotedResponse=p.proto.Message.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.QuestionReplyQuotedMessage)return A;var r=new p.proto.ContextInfo.QuestionReplyQuotedMessage;if(A.serverQuestionId!=null&&(r.serverQuestionId=A.serverQuestionId|0),A.quotedQuestion!=null){if(typeof A.quotedQuestion!="object")throw TypeError(".proto.ContextInfo.QuestionReplyQuotedMessage.quotedQuestion: object expected");r.quotedQuestion=p.proto.Message.fromObject(A.quotedQuestion)}if(A.quotedResponse!=null){if(typeof A.quotedResponse!="object")throw TypeError(".proto.ContextInfo.QuestionReplyQuotedMessage.quotedResponse: object expected");r.quotedResponse=p.proto.Message.fromObject(A.quotedResponse)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.serverQuestionId!=null&&A.hasOwnProperty("serverQuestionId")&&(s.serverQuestionId=A.serverQuestionId,r.oneofs&&(s._serverQuestionId="serverQuestionId")),A.quotedQuestion!=null&&A.hasOwnProperty("quotedQuestion")&&(s.quotedQuestion=p.proto.Message.toObject(A.quotedQuestion,r),r.oneofs&&(s._quotedQuestion="quotedQuestion")),A.quotedResponse!=null&&A.hasOwnProperty("quotedResponse")&&(s.quotedResponse=p.proto.Message.toObject(A.quotedResponse,r),r.oneofs&&(s._quotedResponse="quotedResponse")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.QuestionReplyQuotedMessage"},i})(),t.QuotedType=(function(){let i={},e=Object.create(i);return e[i[0]="EXPLICIT"]=0,e[i[1]="AUTO"]=1,e})(),t.StatusAttributionType=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="RESHARED_FROM_MENTION"]=1,e[i[2]="RESHARED_FROM_POST"]=2,e[i[3]="RESHARED_FROM_POST_MANY_TIMES"]=3,e[i[4]="FORWARDED_FROM_STATUS"]=4,e})(),t.StatusAudienceMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.audienceType=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.StatusAudienceMetadata)return A;var r=new p.proto.ContextInfo.StatusAudienceMetadata;switch(A.audienceType){default:if(typeof A.audienceType=="number"){r.audienceType=A.audienceType;break}break;case"UNKNOWN":case 0:r.audienceType=0;break;case"CLOSE_FRIENDS":case 1:r.audienceType=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.audienceType!=null&&A.hasOwnProperty("audienceType")&&(s.audienceType=r.enums===String?p.proto.ContextInfo.StatusAudienceMetadata.AudienceType[A.audienceType]===void 0?A.audienceType:p.proto.ContextInfo.StatusAudienceMetadata.AudienceType[A.audienceType]:A.audienceType,r.oneofs&&(s._audienceType="audienceType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.StatusAudienceMetadata"},i.AudienceType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="CLOSE_FRIENDS"]=1,A})(),i})(),t.StatusSourceType=(function(){let i={},e=Object.create(i);return e[i[0]="IMAGE"]=0,e[i[1]="VIDEO"]=1,e[i[2]="GIF"]=2,e[i[3]="AUDIO"]=3,e[i[4]="TEXT"]=4,e[i[5]="MUSIC_STANDALONE"]=5,e})(),t.UTMInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.utmSource=A.string();break}case 2:{c.utmCampaign=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.UTMInfo)return A;var r=new p.proto.ContextInfo.UTMInfo;return A.utmSource!=null&&(r.utmSource=String(A.utmSource)),A.utmCampaign!=null&&(r.utmCampaign=String(A.utmCampaign)),r},i.toObject=function(A,r){r||(r={});var s={};return A.utmSource!=null&&A.hasOwnProperty("utmSource")&&(s.utmSource=A.utmSource,r.oneofs&&(s._utmSource="utmSource")),A.utmCampaign!=null&&A.hasOwnProperty("utmCampaign")&&(s.utmCampaign=A.utmCampaign,r.oneofs&&(s._utmCampaign="utmCampaign")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.UTMInfo"},i})(),t})(),n.Conversation=(function(){function t(i){if(this.messages=[],this.participant=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.string();break}case 2:{s.messages&&s.messages.length||(s.messages=[]),s.messages.push(p.proto.HistorySyncMsg.decode(e,e.uint32()));break}case 3:{s.newJid=e.string();break}case 4:{s.oldJid=e.string();break}case 5:{s.lastMsgTimestamp=e.uint64();break}case 6:{s.unreadCount=e.uint32();break}case 7:{s.readOnly=e.bool();break}case 8:{s.endOfHistoryTransfer=e.bool();break}case 9:{s.ephemeralExpiration=e.uint32();break}case 10:{s.ephemeralSettingTimestamp=e.int64();break}case 11:{s.endOfHistoryTransferType=e.int32();break}case 12:{s.conversationTimestamp=e.uint64();break}case 13:{s.name=e.string();break}case 14:{s.pHash=e.string();break}case 15:{s.notSpam=e.bool();break}case 16:{s.archived=e.bool();break}case 17:{s.disappearingMode=p.proto.DisappearingMode.decode(e,e.uint32());break}case 18:{s.unreadMentionCount=e.uint32();break}case 19:{s.markedAsUnread=e.bool();break}case 20:{s.participant&&s.participant.length||(s.participant=[]),s.participant.push(p.proto.GroupParticipant.decode(e,e.uint32()));break}case 21:{s.tcToken=e.bytes();break}case 22:{s.tcTokenTimestamp=e.uint64();break}case 23:{s.contactPrimaryIdentityKey=e.bytes();break}case 24:{s.pinned=e.uint32();break}case 25:{s.muteEndTime=e.uint64();break}case 26:{s.wallpaper=p.proto.WallpaperSettings.decode(e,e.uint32());break}case 27:{s.mediaVisibility=e.int32();break}case 28:{s.tcTokenSenderTimestamp=e.uint64();break}case 29:{s.suspended=e.bool();break}case 30:{s.terminated=e.bool();break}case 31:{s.createdAt=e.uint64();break}case 32:{s.createdBy=e.string();break}case 33:{s.description=e.string();break}case 34:{s.support=e.bool();break}case 35:{s.isParentGroup=e.bool();break}case 37:{s.parentGroupId=e.string();break}case 36:{s.isDefaultSubgroup=e.bool();break}case 38:{s.displayName=e.string();break}case 39:{s.pnJid=e.string();break}case 40:{s.shareOwnPn=e.bool();break}case 41:{s.pnhDuplicateLidThread=e.bool();break}case 42:{s.lidJid=e.string();break}case 43:{s.username=e.string();break}case 44:{s.lidOriginType=e.string();break}case 45:{s.commentsCount=e.uint32();break}case 46:{s.locked=e.bool();break}case 47:{s.systemMessageToInsert=e.int32();break}case 48:{s.capiCreatedGroup=e.bool();break}case 49:{s.accountLid=e.string();break}case 50:{s.limitSharing=e.bool();break}case 51:{s.limitSharingSettingTimestamp=e.int64();break}case 52:{s.limitSharingTrigger=e.int32();break}case 53:{s.limitSharingInitiatedByMe=e.bool();break}case 54:{s.maibaAiThreadEnabled=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Conversation)return e;var a=new p.proto.Conversation;if(e.id!=null&&(a.id=String(e.id)),e.messages){if(!Array.isArray(e.messages))throw TypeError(".proto.Conversation.messages: array expected");a.messages=[];for(var A=0;A>>0,e.lastMsgTimestamp.high>>>0).toNumber(!0))),e.unreadCount!=null&&(a.unreadCount=e.unreadCount>>>0),e.readOnly!=null&&(a.readOnly=!!e.readOnly),e.endOfHistoryTransfer!=null&&(a.endOfHistoryTransfer=!!e.endOfHistoryTransfer),e.ephemeralExpiration!=null&&(a.ephemeralExpiration=e.ephemeralExpiration>>>0),e.ephemeralSettingTimestamp!=null&&(l.Long?(a.ephemeralSettingTimestamp=l.Long.fromValue(e.ephemeralSettingTimestamp)).unsigned=!1:typeof e.ephemeralSettingTimestamp=="string"?a.ephemeralSettingTimestamp=parseInt(e.ephemeralSettingTimestamp,10):typeof e.ephemeralSettingTimestamp=="number"?a.ephemeralSettingTimestamp=e.ephemeralSettingTimestamp:typeof e.ephemeralSettingTimestamp=="object"&&(a.ephemeralSettingTimestamp=new l.LongBits(e.ephemeralSettingTimestamp.low>>>0,e.ephemeralSettingTimestamp.high>>>0).toNumber())),e.endOfHistoryTransferType){default:if(typeof e.endOfHistoryTransferType=="number"){a.endOfHistoryTransferType=e.endOfHistoryTransferType;break}break;case"COMPLETE_BUT_MORE_MESSAGES_REMAIN_ON_PRIMARY":case 0:a.endOfHistoryTransferType=0;break;case"COMPLETE_AND_NO_MORE_MESSAGE_REMAIN_ON_PRIMARY":case 1:a.endOfHistoryTransferType=1;break;case"COMPLETE_ON_DEMAND_SYNC_BUT_MORE_MSG_REMAIN_ON_PRIMARY":case 2:a.endOfHistoryTransferType=2;break}if(e.conversationTimestamp!=null&&(l.Long?(a.conversationTimestamp=l.Long.fromValue(e.conversationTimestamp)).unsigned=!0:typeof e.conversationTimestamp=="string"?a.conversationTimestamp=parseInt(e.conversationTimestamp,10):typeof e.conversationTimestamp=="number"?a.conversationTimestamp=e.conversationTimestamp:typeof e.conversationTimestamp=="object"&&(a.conversationTimestamp=new l.LongBits(e.conversationTimestamp.low>>>0,e.conversationTimestamp.high>>>0).toNumber(!0))),e.name!=null&&(a.name=String(e.name)),e.pHash!=null&&(a.pHash=String(e.pHash)),e.notSpam!=null&&(a.notSpam=!!e.notSpam),e.archived!=null&&(a.archived=!!e.archived),e.disappearingMode!=null){if(typeof e.disappearingMode!="object")throw TypeError(".proto.Conversation.disappearingMode: object expected");a.disappearingMode=p.proto.DisappearingMode.fromObject(e.disappearingMode)}if(e.unreadMentionCount!=null&&(a.unreadMentionCount=e.unreadMentionCount>>>0),e.markedAsUnread!=null&&(a.markedAsUnread=!!e.markedAsUnread),e.participant){if(!Array.isArray(e.participant))throw TypeError(".proto.Conversation.participant: array expected");a.participant=[];for(var A=0;A=0&&(a.tcToken=e.tcToken)),e.tcTokenTimestamp!=null&&(l.Long?(a.tcTokenTimestamp=l.Long.fromValue(e.tcTokenTimestamp)).unsigned=!0:typeof e.tcTokenTimestamp=="string"?a.tcTokenTimestamp=parseInt(e.tcTokenTimestamp,10):typeof e.tcTokenTimestamp=="number"?a.tcTokenTimestamp=e.tcTokenTimestamp:typeof e.tcTokenTimestamp=="object"&&(a.tcTokenTimestamp=new l.LongBits(e.tcTokenTimestamp.low>>>0,e.tcTokenTimestamp.high>>>0).toNumber(!0))),e.contactPrimaryIdentityKey!=null&&(typeof e.contactPrimaryIdentityKey=="string"?l.base64.decode(e.contactPrimaryIdentityKey,a.contactPrimaryIdentityKey=l.newBuffer(l.base64.length(e.contactPrimaryIdentityKey)),0):e.contactPrimaryIdentityKey.length>=0&&(a.contactPrimaryIdentityKey=e.contactPrimaryIdentityKey)),e.pinned!=null&&(a.pinned=e.pinned>>>0),e.muteEndTime!=null&&(l.Long?(a.muteEndTime=l.Long.fromValue(e.muteEndTime)).unsigned=!0:typeof e.muteEndTime=="string"?a.muteEndTime=parseInt(e.muteEndTime,10):typeof e.muteEndTime=="number"?a.muteEndTime=e.muteEndTime:typeof e.muteEndTime=="object"&&(a.muteEndTime=new l.LongBits(e.muteEndTime.low>>>0,e.muteEndTime.high>>>0).toNumber(!0))),e.wallpaper!=null){if(typeof e.wallpaper!="object")throw TypeError(".proto.Conversation.wallpaper: object expected");a.wallpaper=p.proto.WallpaperSettings.fromObject(e.wallpaper)}switch(e.mediaVisibility){default:if(typeof e.mediaVisibility=="number"){a.mediaVisibility=e.mediaVisibility;break}break;case"DEFAULT":case 0:a.mediaVisibility=0;break;case"OFF":case 1:a.mediaVisibility=1;break;case"ON":case 2:a.mediaVisibility=2;break}switch(e.tcTokenSenderTimestamp!=null&&(l.Long?(a.tcTokenSenderTimestamp=l.Long.fromValue(e.tcTokenSenderTimestamp)).unsigned=!0:typeof e.tcTokenSenderTimestamp=="string"?a.tcTokenSenderTimestamp=parseInt(e.tcTokenSenderTimestamp,10):typeof e.tcTokenSenderTimestamp=="number"?a.tcTokenSenderTimestamp=e.tcTokenSenderTimestamp:typeof e.tcTokenSenderTimestamp=="object"&&(a.tcTokenSenderTimestamp=new l.LongBits(e.tcTokenSenderTimestamp.low>>>0,e.tcTokenSenderTimestamp.high>>>0).toNumber(!0))),e.suspended!=null&&(a.suspended=!!e.suspended),e.terminated!=null&&(a.terminated=!!e.terminated),e.createdAt!=null&&(l.Long?(a.createdAt=l.Long.fromValue(e.createdAt)).unsigned=!0:typeof e.createdAt=="string"?a.createdAt=parseInt(e.createdAt,10):typeof e.createdAt=="number"?a.createdAt=e.createdAt:typeof e.createdAt=="object"&&(a.createdAt=new l.LongBits(e.createdAt.low>>>0,e.createdAt.high>>>0).toNumber(!0))),e.createdBy!=null&&(a.createdBy=String(e.createdBy)),e.description!=null&&(a.description=String(e.description)),e.support!=null&&(a.support=!!e.support),e.isParentGroup!=null&&(a.isParentGroup=!!e.isParentGroup),e.parentGroupId!=null&&(a.parentGroupId=String(e.parentGroupId)),e.isDefaultSubgroup!=null&&(a.isDefaultSubgroup=!!e.isDefaultSubgroup),e.displayName!=null&&(a.displayName=String(e.displayName)),e.pnJid!=null&&(a.pnJid=String(e.pnJid)),e.shareOwnPn!=null&&(a.shareOwnPn=!!e.shareOwnPn),e.pnhDuplicateLidThread!=null&&(a.pnhDuplicateLidThread=!!e.pnhDuplicateLidThread),e.lidJid!=null&&(a.lidJid=String(e.lidJid)),e.username!=null&&(a.username=String(e.username)),e.lidOriginType!=null&&(a.lidOriginType=String(e.lidOriginType)),e.commentsCount!=null&&(a.commentsCount=e.commentsCount>>>0),e.locked!=null&&(a.locked=!!e.locked),e.systemMessageToInsert){default:if(typeof e.systemMessageToInsert=="number"){a.systemMessageToInsert=e.systemMessageToInsert;break}break;case"E2EE_MSG":case 1:a.systemMessageToInsert=1;break;case"NE2EE_SELF":case 2:a.systemMessageToInsert=2;break;case"NE2EE_OTHER":case 3:a.systemMessageToInsert=3;break}switch(e.capiCreatedGroup!=null&&(a.capiCreatedGroup=!!e.capiCreatedGroup),e.accountLid!=null&&(a.accountLid=String(e.accountLid)),e.limitSharing!=null&&(a.limitSharing=!!e.limitSharing),e.limitSharingSettingTimestamp!=null&&(l.Long?(a.limitSharingSettingTimestamp=l.Long.fromValue(e.limitSharingSettingTimestamp)).unsigned=!1:typeof e.limitSharingSettingTimestamp=="string"?a.limitSharingSettingTimestamp=parseInt(e.limitSharingSettingTimestamp,10):typeof e.limitSharingSettingTimestamp=="number"?a.limitSharingSettingTimestamp=e.limitSharingSettingTimestamp:typeof e.limitSharingSettingTimestamp=="object"&&(a.limitSharingSettingTimestamp=new l.LongBits(e.limitSharingSettingTimestamp.low>>>0,e.limitSharingSettingTimestamp.high>>>0).toNumber())),e.limitSharingTrigger){default:if(typeof e.limitSharingTrigger=="number"){a.limitSharingTrigger=e.limitSharingTrigger;break}break;case"UNKNOWN":case 0:a.limitSharingTrigger=0;break;case"CHAT_SETTING":case 1:a.limitSharingTrigger=1;break;case"BIZ_SUPPORTS_FB_HOSTING":case 2:a.limitSharingTrigger=2;break;case"UNKNOWN_GROUP":case 3:a.limitSharingTrigger=3;break}return e.limitSharingInitiatedByMe!=null&&(a.limitSharingInitiatedByMe=!!e.limitSharingInitiatedByMe),e.maibaAiThreadEnabled!=null&&(a.maibaAiThreadEnabled=!!e.maibaAiThreadEnabled),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.messages=[],A.participant=[]),a.defaults&&(A.id=""),e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id),e.messages&&e.messages.length){A.messages=[];for(var r=0;r>>3){case 1:{s.chatLockSupportLevel=e.int32();break}case 2:{s.lidMigration=p.proto.DeviceCapabilities.LIDMigration.decode(e,e.uint32());break}case 3:{s.businessBroadcast=p.proto.DeviceCapabilities.BusinessBroadcast.decode(e,e.uint32());break}case 4:{s.userHasAvatar=p.proto.DeviceCapabilities.UserHasAvatar.decode(e,e.uint32());break}case 5:{s.memberNameTagPrimarySupport=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.DeviceCapabilities)return e;var a=new p.proto.DeviceCapabilities;switch(e.chatLockSupportLevel){default:if(typeof e.chatLockSupportLevel=="number"){a.chatLockSupportLevel=e.chatLockSupportLevel;break}break;case"NONE":case 0:a.chatLockSupportLevel=0;break;case"MINIMAL":case 1:a.chatLockSupportLevel=1;break;case"FULL":case 2:a.chatLockSupportLevel=2;break}if(e.lidMigration!=null){if(typeof e.lidMigration!="object")throw TypeError(".proto.DeviceCapabilities.lidMigration: object expected");a.lidMigration=p.proto.DeviceCapabilities.LIDMigration.fromObject(e.lidMigration)}if(e.businessBroadcast!=null){if(typeof e.businessBroadcast!="object")throw TypeError(".proto.DeviceCapabilities.businessBroadcast: object expected");a.businessBroadcast=p.proto.DeviceCapabilities.BusinessBroadcast.fromObject(e.businessBroadcast)}if(e.userHasAvatar!=null){if(typeof e.userHasAvatar!="object")throw TypeError(".proto.DeviceCapabilities.userHasAvatar: object expected");a.userHasAvatar=p.proto.DeviceCapabilities.UserHasAvatar.fromObject(e.userHasAvatar)}switch(e.memberNameTagPrimarySupport){default:if(typeof e.memberNameTagPrimarySupport=="number"){a.memberNameTagPrimarySupport=e.memberNameTagPrimarySupport;break}break;case"DISABLED":case 0:a.memberNameTagPrimarySupport=0;break;case"RECEIVER_ENABLED":case 1:a.memberNameTagPrimarySupport=1;break;case"SENDER_ENABLED":case 2:a.memberNameTagPrimarySupport=2;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.chatLockSupportLevel!=null&&e.hasOwnProperty("chatLockSupportLevel")&&(A.chatLockSupportLevel=a.enums===String?p.proto.DeviceCapabilities.ChatLockSupportLevel[e.chatLockSupportLevel]===void 0?e.chatLockSupportLevel:p.proto.DeviceCapabilities.ChatLockSupportLevel[e.chatLockSupportLevel]:e.chatLockSupportLevel,a.oneofs&&(A._chatLockSupportLevel="chatLockSupportLevel")),e.lidMigration!=null&&e.hasOwnProperty("lidMigration")&&(A.lidMigration=p.proto.DeviceCapabilities.LIDMigration.toObject(e.lidMigration,a),a.oneofs&&(A._lidMigration="lidMigration")),e.businessBroadcast!=null&&e.hasOwnProperty("businessBroadcast")&&(A.businessBroadcast=p.proto.DeviceCapabilities.BusinessBroadcast.toObject(e.businessBroadcast,a),a.oneofs&&(A._businessBroadcast="businessBroadcast")),e.userHasAvatar!=null&&e.hasOwnProperty("userHasAvatar")&&(A.userHasAvatar=p.proto.DeviceCapabilities.UserHasAvatar.toObject(e.userHasAvatar,a),a.oneofs&&(A._userHasAvatar="userHasAvatar")),e.memberNameTagPrimarySupport!=null&&e.hasOwnProperty("memberNameTagPrimarySupport")&&(A.memberNameTagPrimarySupport=a.enums===String?p.proto.DeviceCapabilities.MemberNameTagPrimarySupport[e.memberNameTagPrimarySupport]===void 0?e.memberNameTagPrimarySupport:p.proto.DeviceCapabilities.MemberNameTagPrimarySupport[e.memberNameTagPrimarySupport]:e.memberNameTagPrimarySupport,a.oneofs&&(A._memberNameTagPrimarySupport="memberNameTagPrimarySupport")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DeviceCapabilities"},t.BusinessBroadcast=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.importListEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.DeviceCapabilities.BusinessBroadcast)return A;var r=new p.proto.DeviceCapabilities.BusinessBroadcast;return A.importListEnabled!=null&&(r.importListEnabled=!!A.importListEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.importListEnabled!=null&&A.hasOwnProperty("importListEnabled")&&(s.importListEnabled=A.importListEnabled,r.oneofs&&(s._importListEnabled="importListEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceCapabilities.BusinessBroadcast"},i})(),t.ChatLockSupportLevel=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="MINIMAL"]=1,e[i[2]="FULL"]=2,e})(),t.LIDMigration=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.chatDbMigrationTimestamp=A.uint64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.DeviceCapabilities.LIDMigration)return A;var r=new p.proto.DeviceCapabilities.LIDMigration;return A.chatDbMigrationTimestamp!=null&&(l.Long?(r.chatDbMigrationTimestamp=l.Long.fromValue(A.chatDbMigrationTimestamp)).unsigned=!0:typeof A.chatDbMigrationTimestamp=="string"?r.chatDbMigrationTimestamp=parseInt(A.chatDbMigrationTimestamp,10):typeof A.chatDbMigrationTimestamp=="number"?r.chatDbMigrationTimestamp=A.chatDbMigrationTimestamp:typeof A.chatDbMigrationTimestamp=="object"&&(r.chatDbMigrationTimestamp=new l.LongBits(A.chatDbMigrationTimestamp.low>>>0,A.chatDbMigrationTimestamp.high>>>0).toNumber(!0))),r},i.toObject=function(A,r){r||(r={});var s={};return A.chatDbMigrationTimestamp!=null&&A.hasOwnProperty("chatDbMigrationTimestamp")&&(typeof A.chatDbMigrationTimestamp=="number"?s.chatDbMigrationTimestamp=r.longs===String?String(A.chatDbMigrationTimestamp):A.chatDbMigrationTimestamp:s.chatDbMigrationTimestamp=r.longs===String?se(A.chatDbMigrationTimestamp,!0):r.longs===Number?ge(A.chatDbMigrationTimestamp,!0):A.chatDbMigrationTimestamp,r.oneofs&&(s._chatDbMigrationTimestamp="chatDbMigrationTimestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceCapabilities.LIDMigration"},i})(),t.MemberNameTagPrimarySupport=(function(){let i={},e=Object.create(i);return e[i[0]="DISABLED"]=0,e[i[1]="RECEIVER_ENABLED"]=1,e[i[2]="SENDER_ENABLED"]=2,e})(),t.UserHasAvatar=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.userHasAvatar=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.DeviceCapabilities.UserHasAvatar)return A;var r=new p.proto.DeviceCapabilities.UserHasAvatar;return A.userHasAvatar!=null&&(r.userHasAvatar=!!A.userHasAvatar),r},i.toObject=function(A,r){r||(r={});var s={};return A.userHasAvatar!=null&&A.hasOwnProperty("userHasAvatar")&&(s.userHasAvatar=A.userHasAvatar,r.oneofs&&(s._userHasAvatar="userHasAvatar")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceCapabilities.UserHasAvatar"},i})(),t})(),n.DeviceConsistencyCodeMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.generation=e.uint32();break}case 2:{s.signature=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.DeviceConsistencyCodeMessage)return e;var a=new p.proto.DeviceConsistencyCodeMessage;return e.generation!=null&&(a.generation=e.generation>>>0),e.signature!=null&&(typeof e.signature=="string"?l.base64.decode(e.signature,a.signature=l.newBuffer(l.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),a},t.toObject=function(e,a){a||(a={});var A={};return e.generation!=null&&e.hasOwnProperty("generation")&&(A.generation=e.generation,a.oneofs&&(A._generation="generation")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?l.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DeviceConsistencyCodeMessage"},t})(),n.DeviceListMetadata=(function(){function t(i){if(this.senderKeyIndexes=[],this.recipientKeyIndexes=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.senderKeyHash=e.bytes();break}case 2:{s.senderTimestamp=e.uint64();break}case 3:{if(s.senderKeyIndexes&&s.senderKeyIndexes.length||(s.senderKeyIndexes=[]),(g&7)===2)for(var c=e.uint32()+e.pos;e.pos=0&&(a.senderKeyHash=e.senderKeyHash)),e.senderTimestamp!=null&&(l.Long?(a.senderTimestamp=l.Long.fromValue(e.senderTimestamp)).unsigned=!0:typeof e.senderTimestamp=="string"?a.senderTimestamp=parseInt(e.senderTimestamp,10):typeof e.senderTimestamp=="number"?a.senderTimestamp=e.senderTimestamp:typeof e.senderTimestamp=="object"&&(a.senderTimestamp=new l.LongBits(e.senderTimestamp.low>>>0,e.senderTimestamp.high>>>0).toNumber(!0))),e.senderKeyIndexes){if(!Array.isArray(e.senderKeyIndexes))throw TypeError(".proto.DeviceListMetadata.senderKeyIndexes: array expected");a.senderKeyIndexes=[];for(var A=0;A>>0}switch(e.senderAccountType){default:if(typeof e.senderAccountType=="number"){a.senderAccountType=e.senderAccountType;break}break;case"E2EE":case 0:a.senderAccountType=0;break;case"HOSTED":case 1:a.senderAccountType=1;break}switch(e.receiverAccountType){default:if(typeof e.receiverAccountType=="number"){a.receiverAccountType=e.receiverAccountType;break}break;case"E2EE":case 0:a.receiverAccountType=0;break;case"HOSTED":case 1:a.receiverAccountType=1;break}if(e.recipientKeyHash!=null&&(typeof e.recipientKeyHash=="string"?l.base64.decode(e.recipientKeyHash,a.recipientKeyHash=l.newBuffer(l.base64.length(e.recipientKeyHash)),0):e.recipientKeyHash.length>=0&&(a.recipientKeyHash=e.recipientKeyHash)),e.recipientTimestamp!=null&&(l.Long?(a.recipientTimestamp=l.Long.fromValue(e.recipientTimestamp)).unsigned=!0:typeof e.recipientTimestamp=="string"?a.recipientTimestamp=parseInt(e.recipientTimestamp,10):typeof e.recipientTimestamp=="number"?a.recipientTimestamp=e.recipientTimestamp:typeof e.recipientTimestamp=="object"&&(a.recipientTimestamp=new l.LongBits(e.recipientTimestamp.low>>>0,e.recipientTimestamp.high>>>0).toNumber(!0))),e.recipientKeyIndexes){if(!Array.isArray(e.recipientKeyIndexes))throw TypeError(".proto.DeviceListMetadata.recipientKeyIndexes: array expected");a.recipientKeyIndexes=[];for(var A=0;A>>0}return a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.senderKeyIndexes=[],A.recipientKeyIndexes=[]),e.senderKeyHash!=null&&e.hasOwnProperty("senderKeyHash")&&(A.senderKeyHash=a.bytes===String?l.base64.encode(e.senderKeyHash,0,e.senderKeyHash.length):a.bytes===Array?Array.prototype.slice.call(e.senderKeyHash):e.senderKeyHash,a.oneofs&&(A._senderKeyHash="senderKeyHash")),e.senderTimestamp!=null&&e.hasOwnProperty("senderTimestamp")&&(typeof e.senderTimestamp=="number"?A.senderTimestamp=a.longs===String?String(e.senderTimestamp):e.senderTimestamp:A.senderTimestamp=a.longs===String?se(e.senderTimestamp,!0):a.longs===Number?ge(e.senderTimestamp,!0):e.senderTimestamp,a.oneofs&&(A._senderTimestamp="senderTimestamp")),e.senderKeyIndexes&&e.senderKeyIndexes.length){A.senderKeyIndexes=[];for(var r=0;r>>3){case 1:{s.os=e.string();break}case 2:{s.version=p.proto.DeviceProps.AppVersion.decode(e,e.uint32());break}case 3:{s.platformType=e.int32();break}case 4:{s.requireFullSync=e.bool();break}case 5:{s.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.DeviceProps)return e;var a=new p.proto.DeviceProps;if(e.os!=null&&(a.os=String(e.os)),e.version!=null){if(typeof e.version!="object")throw TypeError(".proto.DeviceProps.version: object expected");a.version=p.proto.DeviceProps.AppVersion.fromObject(e.version)}switch(e.platformType){default:if(typeof e.platformType=="number"){a.platformType=e.platformType;break}break;case"UNKNOWN":case 0:a.platformType=0;break;case"CHROME":case 1:a.platformType=1;break;case"FIREFOX":case 2:a.platformType=2;break;case"IE":case 3:a.platformType=3;break;case"OPERA":case 4:a.platformType=4;break;case"SAFARI":case 5:a.platformType=5;break;case"EDGE":case 6:a.platformType=6;break;case"DESKTOP":case 7:a.platformType=7;break;case"IPAD":case 8:a.platformType=8;break;case"ANDROID_TABLET":case 9:a.platformType=9;break;case"OHANA":case 10:a.platformType=10;break;case"ALOHA":case 11:a.platformType=11;break;case"CATALINA":case 12:a.platformType=12;break;case"TCL_TV":case 13:a.platformType=13;break;case"IOS_PHONE":case 14:a.platformType=14;break;case"IOS_CATALYST":case 15:a.platformType=15;break;case"ANDROID_PHONE":case 16:a.platformType=16;break;case"ANDROID_AMBIGUOUS":case 17:a.platformType=17;break;case"WEAR_OS":case 18:a.platformType=18;break;case"AR_WRIST":case 19:a.platformType=19;break;case"AR_DEVICE":case 20:a.platformType=20;break;case"UWP":case 21:a.platformType=21;break;case"VR":case 22:a.platformType=22;break;case"CLOUD_API":case 23:a.platformType=23;break;case"SMARTGLASSES":case 24:a.platformType=24;break}if(e.requireFullSync!=null&&(a.requireFullSync=!!e.requireFullSync),e.historySyncConfig!=null){if(typeof e.historySyncConfig!="object")throw TypeError(".proto.DeviceProps.historySyncConfig: object expected");a.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.fromObject(e.historySyncConfig)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.os!=null&&e.hasOwnProperty("os")&&(A.os=e.os,a.oneofs&&(A._os="os")),e.version!=null&&e.hasOwnProperty("version")&&(A.version=p.proto.DeviceProps.AppVersion.toObject(e.version,a),a.oneofs&&(A._version="version")),e.platformType!=null&&e.hasOwnProperty("platformType")&&(A.platformType=a.enums===String?p.proto.DeviceProps.PlatformType[e.platformType]===void 0?e.platformType:p.proto.DeviceProps.PlatformType[e.platformType]:e.platformType,a.oneofs&&(A._platformType="platformType")),e.requireFullSync!=null&&e.hasOwnProperty("requireFullSync")&&(A.requireFullSync=e.requireFullSync,a.oneofs&&(A._requireFullSync="requireFullSync")),e.historySyncConfig!=null&&e.hasOwnProperty("historySyncConfig")&&(A.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.toObject(e.historySyncConfig,a),a.oneofs&&(A._historySyncConfig="historySyncConfig")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DeviceProps"},t.AppVersion=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.primary=A.uint32();break}case 2:{c.secondary=A.uint32();break}case 3:{c.tertiary=A.uint32();break}case 4:{c.quaternary=A.uint32();break}case 5:{c.quinary=A.uint32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.DeviceProps.AppVersion)return A;var r=new p.proto.DeviceProps.AppVersion;return A.primary!=null&&(r.primary=A.primary>>>0),A.secondary!=null&&(r.secondary=A.secondary>>>0),A.tertiary!=null&&(r.tertiary=A.tertiary>>>0),A.quaternary!=null&&(r.quaternary=A.quaternary>>>0),A.quinary!=null&&(r.quinary=A.quinary>>>0),r},i.toObject=function(A,r){r||(r={});var s={};return A.primary!=null&&A.hasOwnProperty("primary")&&(s.primary=A.primary,r.oneofs&&(s._primary="primary")),A.secondary!=null&&A.hasOwnProperty("secondary")&&(s.secondary=A.secondary,r.oneofs&&(s._secondary="secondary")),A.tertiary!=null&&A.hasOwnProperty("tertiary")&&(s.tertiary=A.tertiary,r.oneofs&&(s._tertiary="tertiary")),A.quaternary!=null&&A.hasOwnProperty("quaternary")&&(s.quaternary=A.quaternary,r.oneofs&&(s._quaternary="quaternary")),A.quinary!=null&&A.hasOwnProperty("quinary")&&(s.quinary=A.quinary,r.oneofs&&(s._quinary="quinary")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceProps.AppVersion"},i})(),t.HistorySyncConfig=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.fullSyncDaysLimit=A.uint32();break}case 2:{c.fullSyncSizeMbLimit=A.uint32();break}case 3:{c.storageQuotaMb=A.uint32();break}case 4:{c.inlineInitialPayloadInE2EeMsg=A.bool();break}case 5:{c.recentSyncDaysLimit=A.uint32();break}case 6:{c.supportCallLogHistory=A.bool();break}case 7:{c.supportBotUserAgentChatHistory=A.bool();break}case 8:{c.supportCagReactionsAndPolls=A.bool();break}case 9:{c.supportBizHostedMsg=A.bool();break}case 10:{c.supportRecentSyncChunkMessageCountTuning=A.bool();break}case 11:{c.supportHostedGroupMsg=A.bool();break}case 12:{c.supportFbidBotChatHistory=A.bool();break}case 13:{c.supportAddOnHistorySyncMigration=A.bool();break}case 14:{c.supportMessageAssociation=A.bool();break}case 15:{c.supportGroupHistory=A.bool();break}case 16:{c.onDemandReady=A.bool();break}case 17:{c.supportGuestChat=A.bool();break}case 18:{c.completeOnDemandReady=A.bool();break}case 19:{c.thumbnailSyncDaysLimit=A.uint32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.DeviceProps.HistorySyncConfig)return A;var r=new p.proto.DeviceProps.HistorySyncConfig;return A.fullSyncDaysLimit!=null&&(r.fullSyncDaysLimit=A.fullSyncDaysLimit>>>0),A.fullSyncSizeMbLimit!=null&&(r.fullSyncSizeMbLimit=A.fullSyncSizeMbLimit>>>0),A.storageQuotaMb!=null&&(r.storageQuotaMb=A.storageQuotaMb>>>0),A.inlineInitialPayloadInE2EeMsg!=null&&(r.inlineInitialPayloadInE2EeMsg=!!A.inlineInitialPayloadInE2EeMsg),A.recentSyncDaysLimit!=null&&(r.recentSyncDaysLimit=A.recentSyncDaysLimit>>>0),A.supportCallLogHistory!=null&&(r.supportCallLogHistory=!!A.supportCallLogHistory),A.supportBotUserAgentChatHistory!=null&&(r.supportBotUserAgentChatHistory=!!A.supportBotUserAgentChatHistory),A.supportCagReactionsAndPolls!=null&&(r.supportCagReactionsAndPolls=!!A.supportCagReactionsAndPolls),A.supportBizHostedMsg!=null&&(r.supportBizHostedMsg=!!A.supportBizHostedMsg),A.supportRecentSyncChunkMessageCountTuning!=null&&(r.supportRecentSyncChunkMessageCountTuning=!!A.supportRecentSyncChunkMessageCountTuning),A.supportHostedGroupMsg!=null&&(r.supportHostedGroupMsg=!!A.supportHostedGroupMsg),A.supportFbidBotChatHistory!=null&&(r.supportFbidBotChatHistory=!!A.supportFbidBotChatHistory),A.supportAddOnHistorySyncMigration!=null&&(r.supportAddOnHistorySyncMigration=!!A.supportAddOnHistorySyncMigration),A.supportMessageAssociation!=null&&(r.supportMessageAssociation=!!A.supportMessageAssociation),A.supportGroupHistory!=null&&(r.supportGroupHistory=!!A.supportGroupHistory),A.onDemandReady!=null&&(r.onDemandReady=!!A.onDemandReady),A.supportGuestChat!=null&&(r.supportGuestChat=!!A.supportGuestChat),A.completeOnDemandReady!=null&&(r.completeOnDemandReady=!!A.completeOnDemandReady),A.thumbnailSyncDaysLimit!=null&&(r.thumbnailSyncDaysLimit=A.thumbnailSyncDaysLimit>>>0),r},i.toObject=function(A,r){r||(r={});var s={};return A.fullSyncDaysLimit!=null&&A.hasOwnProperty("fullSyncDaysLimit")&&(s.fullSyncDaysLimit=A.fullSyncDaysLimit,r.oneofs&&(s._fullSyncDaysLimit="fullSyncDaysLimit")),A.fullSyncSizeMbLimit!=null&&A.hasOwnProperty("fullSyncSizeMbLimit")&&(s.fullSyncSizeMbLimit=A.fullSyncSizeMbLimit,r.oneofs&&(s._fullSyncSizeMbLimit="fullSyncSizeMbLimit")),A.storageQuotaMb!=null&&A.hasOwnProperty("storageQuotaMb")&&(s.storageQuotaMb=A.storageQuotaMb,r.oneofs&&(s._storageQuotaMb="storageQuotaMb")),A.inlineInitialPayloadInE2EeMsg!=null&&A.hasOwnProperty("inlineInitialPayloadInE2EeMsg")&&(s.inlineInitialPayloadInE2EeMsg=A.inlineInitialPayloadInE2EeMsg,r.oneofs&&(s._inlineInitialPayloadInE2EeMsg="inlineInitialPayloadInE2EeMsg")),A.recentSyncDaysLimit!=null&&A.hasOwnProperty("recentSyncDaysLimit")&&(s.recentSyncDaysLimit=A.recentSyncDaysLimit,r.oneofs&&(s._recentSyncDaysLimit="recentSyncDaysLimit")),A.supportCallLogHistory!=null&&A.hasOwnProperty("supportCallLogHistory")&&(s.supportCallLogHistory=A.supportCallLogHistory,r.oneofs&&(s._supportCallLogHistory="supportCallLogHistory")),A.supportBotUserAgentChatHistory!=null&&A.hasOwnProperty("supportBotUserAgentChatHistory")&&(s.supportBotUserAgentChatHistory=A.supportBotUserAgentChatHistory,r.oneofs&&(s._supportBotUserAgentChatHistory="supportBotUserAgentChatHistory")),A.supportCagReactionsAndPolls!=null&&A.hasOwnProperty("supportCagReactionsAndPolls")&&(s.supportCagReactionsAndPolls=A.supportCagReactionsAndPolls,r.oneofs&&(s._supportCagReactionsAndPolls="supportCagReactionsAndPolls")),A.supportBizHostedMsg!=null&&A.hasOwnProperty("supportBizHostedMsg")&&(s.supportBizHostedMsg=A.supportBizHostedMsg,r.oneofs&&(s._supportBizHostedMsg="supportBizHostedMsg")),A.supportRecentSyncChunkMessageCountTuning!=null&&A.hasOwnProperty("supportRecentSyncChunkMessageCountTuning")&&(s.supportRecentSyncChunkMessageCountTuning=A.supportRecentSyncChunkMessageCountTuning,r.oneofs&&(s._supportRecentSyncChunkMessageCountTuning="supportRecentSyncChunkMessageCountTuning")),A.supportHostedGroupMsg!=null&&A.hasOwnProperty("supportHostedGroupMsg")&&(s.supportHostedGroupMsg=A.supportHostedGroupMsg,r.oneofs&&(s._supportHostedGroupMsg="supportHostedGroupMsg")),A.supportFbidBotChatHistory!=null&&A.hasOwnProperty("supportFbidBotChatHistory")&&(s.supportFbidBotChatHistory=A.supportFbidBotChatHistory,r.oneofs&&(s._supportFbidBotChatHistory="supportFbidBotChatHistory")),A.supportAddOnHistorySyncMigration!=null&&A.hasOwnProperty("supportAddOnHistorySyncMigration")&&(s.supportAddOnHistorySyncMigration=A.supportAddOnHistorySyncMigration,r.oneofs&&(s._supportAddOnHistorySyncMigration="supportAddOnHistorySyncMigration")),A.supportMessageAssociation!=null&&A.hasOwnProperty("supportMessageAssociation")&&(s.supportMessageAssociation=A.supportMessageAssociation,r.oneofs&&(s._supportMessageAssociation="supportMessageAssociation")),A.supportGroupHistory!=null&&A.hasOwnProperty("supportGroupHistory")&&(s.supportGroupHistory=A.supportGroupHistory,r.oneofs&&(s._supportGroupHistory="supportGroupHistory")),A.onDemandReady!=null&&A.hasOwnProperty("onDemandReady")&&(s.onDemandReady=A.onDemandReady,r.oneofs&&(s._onDemandReady="onDemandReady")),A.supportGuestChat!=null&&A.hasOwnProperty("supportGuestChat")&&(s.supportGuestChat=A.supportGuestChat,r.oneofs&&(s._supportGuestChat="supportGuestChat")),A.completeOnDemandReady!=null&&A.hasOwnProperty("completeOnDemandReady")&&(s.completeOnDemandReady=A.completeOnDemandReady,r.oneofs&&(s._completeOnDemandReady="completeOnDemandReady")),A.thumbnailSyncDaysLimit!=null&&A.hasOwnProperty("thumbnailSyncDaysLimit")&&(s.thumbnailSyncDaysLimit=A.thumbnailSyncDaysLimit,r.oneofs&&(s._thumbnailSyncDaysLimit="thumbnailSyncDaysLimit")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceProps.HistorySyncConfig"},i})(),t.PlatformType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHROME"]=1,e[i[2]="FIREFOX"]=2,e[i[3]="IE"]=3,e[i[4]="OPERA"]=4,e[i[5]="SAFARI"]=5,e[i[6]="EDGE"]=6,e[i[7]="DESKTOP"]=7,e[i[8]="IPAD"]=8,e[i[9]="ANDROID_TABLET"]=9,e[i[10]="OHANA"]=10,e[i[11]="ALOHA"]=11,e[i[12]="CATALINA"]=12,e[i[13]="TCL_TV"]=13,e[i[14]="IOS_PHONE"]=14,e[i[15]="IOS_CATALYST"]=15,e[i[16]="ANDROID_PHONE"]=16,e[i[17]="ANDROID_AMBIGUOUS"]=17,e[i[18]="WEAR_OS"]=18,e[i[19]="AR_WRIST"]=19,e[i[20]="AR_DEVICE"]=20,e[i[21]="UWP"]=21,e[i[22]="VR"]=22,e[i[23]="CLOUD_API"]=23,e[i[24]="SMARTGLASSES"]=24,e})(),t})(),n.DisappearingMode=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.initiator=e.int32();break}case 2:{s.trigger=e.int32();break}case 3:{s.initiatorDeviceJid=e.string();break}case 4:{s.initiatedByMe=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.DisappearingMode)return e;var a=new p.proto.DisappearingMode;switch(e.initiator){default:if(typeof e.initiator=="number"){a.initiator=e.initiator;break}break;case"CHANGED_IN_CHAT":case 0:a.initiator=0;break;case"INITIATED_BY_ME":case 1:a.initiator=1;break;case"INITIATED_BY_OTHER":case 2:a.initiator=2;break;case"BIZ_UPGRADE_FB_HOSTING":case 3:a.initiator=3;break}switch(e.trigger){default:if(typeof e.trigger=="number"){a.trigger=e.trigger;break}break;case"UNKNOWN":case 0:a.trigger=0;break;case"CHAT_SETTING":case 1:a.trigger=1;break;case"ACCOUNT_SETTING":case 2:a.trigger=2;break;case"BULK_CHANGE":case 3:a.trigger=3;break;case"BIZ_SUPPORTS_FB_HOSTING":case 4:a.trigger=4;break;case"UNKNOWN_GROUPS":case 5:a.trigger=5;break}return e.initiatorDeviceJid!=null&&(a.initiatorDeviceJid=String(e.initiatorDeviceJid)),e.initiatedByMe!=null&&(a.initiatedByMe=!!e.initiatedByMe),a},t.toObject=function(e,a){a||(a={});var A={};return e.initiator!=null&&e.hasOwnProperty("initiator")&&(A.initiator=a.enums===String?p.proto.DisappearingMode.Initiator[e.initiator]===void 0?e.initiator:p.proto.DisappearingMode.Initiator[e.initiator]:e.initiator,a.oneofs&&(A._initiator="initiator")),e.trigger!=null&&e.hasOwnProperty("trigger")&&(A.trigger=a.enums===String?p.proto.DisappearingMode.Trigger[e.trigger]===void 0?e.trigger:p.proto.DisappearingMode.Trigger[e.trigger]:e.trigger,a.oneofs&&(A._trigger="trigger")),e.initiatorDeviceJid!=null&&e.hasOwnProperty("initiatorDeviceJid")&&(A.initiatorDeviceJid=e.initiatorDeviceJid,a.oneofs&&(A._initiatorDeviceJid="initiatorDeviceJid")),e.initiatedByMe!=null&&e.hasOwnProperty("initiatedByMe")&&(A.initiatedByMe=e.initiatedByMe,a.oneofs&&(A._initiatedByMe="initiatedByMe")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DisappearingMode"},t.Initiator=(function(){let i={},e=Object.create(i);return e[i[0]="CHANGED_IN_CHAT"]=0,e[i[1]="INITIATED_BY_ME"]=1,e[i[2]="INITIATED_BY_OTHER"]=2,e[i[3]="BIZ_UPGRADE_FB_HOSTING"]=3,e})(),t.Trigger=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHAT_SETTING"]=1,e[i[2]="ACCOUNT_SETTING"]=2,e[i[3]="BULK_CHANGE"]=3,e[i[4]="BIZ_SUPPORTS_FB_HOSTING"]=4,e[i[5]="UNKNOWN_GROUPS"]=5,e})(),t})(),n.EmbeddedContent=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.embeddedMessage=p.proto.EmbeddedMessage.decode(e,e.uint32());break}case 2:{s.embeddedMusic=p.proto.EmbeddedMusic.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EmbeddedContent)return e;var a=new p.proto.EmbeddedContent;if(e.embeddedMessage!=null){if(typeof e.embeddedMessage!="object")throw TypeError(".proto.EmbeddedContent.embeddedMessage: object expected");a.embeddedMessage=p.proto.EmbeddedMessage.fromObject(e.embeddedMessage)}if(e.embeddedMusic!=null){if(typeof e.embeddedMusic!="object")throw TypeError(".proto.EmbeddedContent.embeddedMusic: object expected");a.embeddedMusic=p.proto.EmbeddedMusic.fromObject(e.embeddedMusic)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.embeddedMessage!=null&&e.hasOwnProperty("embeddedMessage")&&(A.embeddedMessage=p.proto.EmbeddedMessage.toObject(e.embeddedMessage,a),a.oneofs&&(A.content="embeddedMessage")),e.embeddedMusic!=null&&e.hasOwnProperty("embeddedMusic")&&(A.embeddedMusic=p.proto.EmbeddedMusic.toObject(e.embeddedMusic,a),a.oneofs&&(A.content="embeddedMusic")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EmbeddedContent"},t})(),n.EmbeddedMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.stanzaId=e.string();break}case 2:{s.message=p.proto.Message.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EmbeddedMessage)return e;var a=new p.proto.EmbeddedMessage;if(e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.EmbeddedMessage.message: object expected");a.message=p.proto.Message.fromObject(e.message)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=p.proto.Message.toObject(e.message,a),a.oneofs&&(A._message="message")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EmbeddedMessage"},t})(),n.EmbeddedMusic=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.musicContentMediaId=e.string();break}case 2:{s.songId=e.string();break}case 3:{s.author=e.string();break}case 4:{s.title=e.string();break}case 5:{s.artworkDirectPath=e.string();break}case 6:{s.artworkSha256=e.bytes();break}case 7:{s.artworkEncSha256=e.bytes();break}case 8:{s.artistAttribution=e.string();break}case 9:{s.countryBlocklist=e.bytes();break}case 10:{s.isExplicit=e.bool();break}case 11:{s.artworkMediaKey=e.bytes();break}case 12:{s.musicSongStartTimeInMs=e.int64();break}case 13:{s.derivedContentStartTimeInMs=e.int64();break}case 14:{s.overlapDurationInMs=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EmbeddedMusic)return e;var a=new p.proto.EmbeddedMusic;return e.musicContentMediaId!=null&&(a.musicContentMediaId=String(e.musicContentMediaId)),e.songId!=null&&(a.songId=String(e.songId)),e.author!=null&&(a.author=String(e.author)),e.title!=null&&(a.title=String(e.title)),e.artworkDirectPath!=null&&(a.artworkDirectPath=String(e.artworkDirectPath)),e.artworkSha256!=null&&(typeof e.artworkSha256=="string"?l.base64.decode(e.artworkSha256,a.artworkSha256=l.newBuffer(l.base64.length(e.artworkSha256)),0):e.artworkSha256.length>=0&&(a.artworkSha256=e.artworkSha256)),e.artworkEncSha256!=null&&(typeof e.artworkEncSha256=="string"?l.base64.decode(e.artworkEncSha256,a.artworkEncSha256=l.newBuffer(l.base64.length(e.artworkEncSha256)),0):e.artworkEncSha256.length>=0&&(a.artworkEncSha256=e.artworkEncSha256)),e.artistAttribution!=null&&(a.artistAttribution=String(e.artistAttribution)),e.countryBlocklist!=null&&(typeof e.countryBlocklist=="string"?l.base64.decode(e.countryBlocklist,a.countryBlocklist=l.newBuffer(l.base64.length(e.countryBlocklist)),0):e.countryBlocklist.length>=0&&(a.countryBlocklist=e.countryBlocklist)),e.isExplicit!=null&&(a.isExplicit=!!e.isExplicit),e.artworkMediaKey!=null&&(typeof e.artworkMediaKey=="string"?l.base64.decode(e.artworkMediaKey,a.artworkMediaKey=l.newBuffer(l.base64.length(e.artworkMediaKey)),0):e.artworkMediaKey.length>=0&&(a.artworkMediaKey=e.artworkMediaKey)),e.musicSongStartTimeInMs!=null&&(l.Long?(a.musicSongStartTimeInMs=l.Long.fromValue(e.musicSongStartTimeInMs)).unsigned=!1:typeof e.musicSongStartTimeInMs=="string"?a.musicSongStartTimeInMs=parseInt(e.musicSongStartTimeInMs,10):typeof e.musicSongStartTimeInMs=="number"?a.musicSongStartTimeInMs=e.musicSongStartTimeInMs:typeof e.musicSongStartTimeInMs=="object"&&(a.musicSongStartTimeInMs=new l.LongBits(e.musicSongStartTimeInMs.low>>>0,e.musicSongStartTimeInMs.high>>>0).toNumber())),e.derivedContentStartTimeInMs!=null&&(l.Long?(a.derivedContentStartTimeInMs=l.Long.fromValue(e.derivedContentStartTimeInMs)).unsigned=!1:typeof e.derivedContentStartTimeInMs=="string"?a.derivedContentStartTimeInMs=parseInt(e.derivedContentStartTimeInMs,10):typeof e.derivedContentStartTimeInMs=="number"?a.derivedContentStartTimeInMs=e.derivedContentStartTimeInMs:typeof e.derivedContentStartTimeInMs=="object"&&(a.derivedContentStartTimeInMs=new l.LongBits(e.derivedContentStartTimeInMs.low>>>0,e.derivedContentStartTimeInMs.high>>>0).toNumber())),e.overlapDurationInMs!=null&&(l.Long?(a.overlapDurationInMs=l.Long.fromValue(e.overlapDurationInMs)).unsigned=!1:typeof e.overlapDurationInMs=="string"?a.overlapDurationInMs=parseInt(e.overlapDurationInMs,10):typeof e.overlapDurationInMs=="number"?a.overlapDurationInMs=e.overlapDurationInMs:typeof e.overlapDurationInMs=="object"&&(a.overlapDurationInMs=new l.LongBits(e.overlapDurationInMs.low>>>0,e.overlapDurationInMs.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.musicContentMediaId!=null&&e.hasOwnProperty("musicContentMediaId")&&(A.musicContentMediaId=e.musicContentMediaId,a.oneofs&&(A._musicContentMediaId="musicContentMediaId")),e.songId!=null&&e.hasOwnProperty("songId")&&(A.songId=e.songId,a.oneofs&&(A._songId="songId")),e.author!=null&&e.hasOwnProperty("author")&&(A.author=e.author,a.oneofs&&(A._author="author")),e.title!=null&&e.hasOwnProperty("title")&&(A.title=e.title,a.oneofs&&(A._title="title")),e.artworkDirectPath!=null&&e.hasOwnProperty("artworkDirectPath")&&(A.artworkDirectPath=e.artworkDirectPath,a.oneofs&&(A._artworkDirectPath="artworkDirectPath")),e.artworkSha256!=null&&e.hasOwnProperty("artworkSha256")&&(A.artworkSha256=a.bytes===String?l.base64.encode(e.artworkSha256,0,e.artworkSha256.length):a.bytes===Array?Array.prototype.slice.call(e.artworkSha256):e.artworkSha256,a.oneofs&&(A._artworkSha256="artworkSha256")),e.artworkEncSha256!=null&&e.hasOwnProperty("artworkEncSha256")&&(A.artworkEncSha256=a.bytes===String?l.base64.encode(e.artworkEncSha256,0,e.artworkEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.artworkEncSha256):e.artworkEncSha256,a.oneofs&&(A._artworkEncSha256="artworkEncSha256")),e.artistAttribution!=null&&e.hasOwnProperty("artistAttribution")&&(A.artistAttribution=e.artistAttribution,a.oneofs&&(A._artistAttribution="artistAttribution")),e.countryBlocklist!=null&&e.hasOwnProperty("countryBlocklist")&&(A.countryBlocklist=a.bytes===String?l.base64.encode(e.countryBlocklist,0,e.countryBlocklist.length):a.bytes===Array?Array.prototype.slice.call(e.countryBlocklist):e.countryBlocklist,a.oneofs&&(A._countryBlocklist="countryBlocklist")),e.isExplicit!=null&&e.hasOwnProperty("isExplicit")&&(A.isExplicit=e.isExplicit,a.oneofs&&(A._isExplicit="isExplicit")),e.artworkMediaKey!=null&&e.hasOwnProperty("artworkMediaKey")&&(A.artworkMediaKey=a.bytes===String?l.base64.encode(e.artworkMediaKey,0,e.artworkMediaKey.length):a.bytes===Array?Array.prototype.slice.call(e.artworkMediaKey):e.artworkMediaKey,a.oneofs&&(A._artworkMediaKey="artworkMediaKey")),e.musicSongStartTimeInMs!=null&&e.hasOwnProperty("musicSongStartTimeInMs")&&(typeof e.musicSongStartTimeInMs=="number"?A.musicSongStartTimeInMs=a.longs===String?String(e.musicSongStartTimeInMs):e.musicSongStartTimeInMs:A.musicSongStartTimeInMs=a.longs===String?se(e.musicSongStartTimeInMs):a.longs===Number?ge(e.musicSongStartTimeInMs):e.musicSongStartTimeInMs,a.oneofs&&(A._musicSongStartTimeInMs="musicSongStartTimeInMs")),e.derivedContentStartTimeInMs!=null&&e.hasOwnProperty("derivedContentStartTimeInMs")&&(typeof e.derivedContentStartTimeInMs=="number"?A.derivedContentStartTimeInMs=a.longs===String?String(e.derivedContentStartTimeInMs):e.derivedContentStartTimeInMs:A.derivedContentStartTimeInMs=a.longs===String?se(e.derivedContentStartTimeInMs):a.longs===Number?ge(e.derivedContentStartTimeInMs):e.derivedContentStartTimeInMs,a.oneofs&&(A._derivedContentStartTimeInMs="derivedContentStartTimeInMs")),e.overlapDurationInMs!=null&&e.hasOwnProperty("overlapDurationInMs")&&(typeof e.overlapDurationInMs=="number"?A.overlapDurationInMs=a.longs===String?String(e.overlapDurationInMs):e.overlapDurationInMs:A.overlapDurationInMs=a.longs===String?se(e.overlapDurationInMs):a.longs===Number?ge(e.overlapDurationInMs):e.overlapDurationInMs,a.oneofs&&(A._overlapDurationInMs="overlapDurationInMs")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EmbeddedMusic"},t})(),n.EncryptedPairingRequest=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encryptedPayload=e.bytes();break}case 2:{s.iv=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EncryptedPairingRequest)return e;var a=new p.proto.EncryptedPairingRequest;return e.encryptedPayload!=null&&(typeof e.encryptedPayload=="string"?l.base64.decode(e.encryptedPayload,a.encryptedPayload=l.newBuffer(l.base64.length(e.encryptedPayload)),0):e.encryptedPayload.length>=0&&(a.encryptedPayload=e.encryptedPayload)),e.iv!=null&&(typeof e.iv=="string"?l.base64.decode(e.iv,a.iv=l.newBuffer(l.base64.length(e.iv)),0):e.iv.length>=0&&(a.iv=e.iv)),a},t.toObject=function(e,a){a||(a={});var A={};return e.encryptedPayload!=null&&e.hasOwnProperty("encryptedPayload")&&(A.encryptedPayload=a.bytes===String?l.base64.encode(e.encryptedPayload,0,e.encryptedPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encryptedPayload):e.encryptedPayload,a.oneofs&&(A._encryptedPayload="encryptedPayload")),e.iv!=null&&e.hasOwnProperty("iv")&&(A.iv=a.bytes===String?l.base64.encode(e.iv,0,e.iv.length):a.bytes===Array?Array.prototype.slice.call(e.iv):e.iv,a.oneofs&&(A._iv="iv")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EncryptedPairingRequest"},t})(),n.EphemeralSetting=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.duration=e.sfixed32();break}case 2:{s.timestamp=e.sfixed64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EphemeralSetting)return e;var a=new p.proto.EphemeralSetting;return e.duration!=null&&(a.duration=e.duration|0),e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.duration!=null&&e.hasOwnProperty("duration")&&(A.duration=e.duration,a.oneofs&&(A._duration="duration")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp):a.longs===Number?ge(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EphemeralSetting"},t})(),n.EventAdditionalMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.isStale=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EventAdditionalMetadata)return e;var a=new p.proto.EventAdditionalMetadata;return e.isStale!=null&&(a.isStale=!!e.isStale),a},t.toObject=function(e,a){a||(a={});var A={};return e.isStale!=null&&e.hasOwnProperty("isStale")&&(A.isStale=e.isStale,a.oneofs&&(A._isStale="isStale")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EventAdditionalMetadata"},t})(),n.EventResponse=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.eventResponseMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.timestampMs=e.int64();break}case 3:{s.eventResponseMessage=p.proto.Message.EventResponseMessage.decode(e,e.uint32());break}case 4:{s.unread=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EventResponse)return e;var a=new p.proto.EventResponse;if(e.eventResponseMessageKey!=null){if(typeof e.eventResponseMessageKey!="object")throw TypeError(".proto.EventResponse.eventResponseMessageKey: object expected");a.eventResponseMessageKey=p.proto.MessageKey.fromObject(e.eventResponseMessageKey)}if(e.timestampMs!=null&&(l.Long?(a.timestampMs=l.Long.fromValue(e.timestampMs)).unsigned=!1:typeof e.timestampMs=="string"?a.timestampMs=parseInt(e.timestampMs,10):typeof e.timestampMs=="number"?a.timestampMs=e.timestampMs:typeof e.timestampMs=="object"&&(a.timestampMs=new l.LongBits(e.timestampMs.low>>>0,e.timestampMs.high>>>0).toNumber())),e.eventResponseMessage!=null){if(typeof e.eventResponseMessage!="object")throw TypeError(".proto.EventResponse.eventResponseMessage: object expected");a.eventResponseMessage=p.proto.Message.EventResponseMessage.fromObject(e.eventResponseMessage)}return e.unread!=null&&(a.unread=!!e.unread),a},t.toObject=function(e,a){a||(a={});var A={};return e.eventResponseMessageKey!=null&&e.hasOwnProperty("eventResponseMessageKey")&&(A.eventResponseMessageKey=p.proto.MessageKey.toObject(e.eventResponseMessageKey,a),a.oneofs&&(A._eventResponseMessageKey="eventResponseMessageKey")),e.timestampMs!=null&&e.hasOwnProperty("timestampMs")&&(typeof e.timestampMs=="number"?A.timestampMs=a.longs===String?String(e.timestampMs):e.timestampMs:A.timestampMs=a.longs===String?se(e.timestampMs):a.longs===Number?ge(e.timestampMs):e.timestampMs,a.oneofs&&(A._timestampMs="timestampMs")),e.eventResponseMessage!=null&&e.hasOwnProperty("eventResponseMessage")&&(A.eventResponseMessage=p.proto.Message.EventResponseMessage.toObject(e.eventResponseMessage,a),a.oneofs&&(A._eventResponseMessage="eventResponseMessage")),e.unread!=null&&e.hasOwnProperty("unread")&&(A.unread=e.unread,a.oneofs&&(A._unread="unread")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EventResponse"},t})(),n.ExitCode=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.code=e.uint64();break}case 2:{s.text=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ExitCode)return e;var a=new p.proto.ExitCode;return e.code!=null&&(l.Long?(a.code=l.Long.fromValue(e.code)).unsigned=!0:typeof e.code=="string"?a.code=parseInt(e.code,10):typeof e.code=="number"?a.code=e.code:typeof e.code=="object"&&(a.code=new l.LongBits(e.code.low>>>0,e.code.high>>>0).toNumber(!0))),e.text!=null&&(a.text=String(e.text)),a},t.toObject=function(e,a){a||(a={});var A={};return e.code!=null&&e.hasOwnProperty("code")&&(typeof e.code=="number"?A.code=a.longs===String?String(e.code):e.code:A.code=a.longs===String?se(e.code,!0):a.longs===Number?ge(e.code,!0):e.code,a.oneofs&&(A._code="code")),e.text!=null&&e.hasOwnProperty("text")&&(A.text=e.text,a.oneofs&&(A._text="text")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ExitCode"},t})(),n.ExternalBlobReference=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.mediaKey=e.bytes();break}case 2:{s.directPath=e.string();break}case 3:{s.handle=e.string();break}case 4:{s.fileSizeBytes=e.uint64();break}case 5:{s.fileSha256=e.bytes();break}case 6:{s.fileEncSha256=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ExternalBlobReference)return e;var a=new p.proto.ExternalBlobReference;return e.mediaKey!=null&&(typeof e.mediaKey=="string"?l.base64.decode(e.mediaKey,a.mediaKey=l.newBuffer(l.base64.length(e.mediaKey)),0):e.mediaKey.length>=0&&(a.mediaKey=e.mediaKey)),e.directPath!=null&&(a.directPath=String(e.directPath)),e.handle!=null&&(a.handle=String(e.handle)),e.fileSizeBytes!=null&&(l.Long?(a.fileSizeBytes=l.Long.fromValue(e.fileSizeBytes)).unsigned=!0:typeof e.fileSizeBytes=="string"?a.fileSizeBytes=parseInt(e.fileSizeBytes,10):typeof e.fileSizeBytes=="number"?a.fileSizeBytes=e.fileSizeBytes:typeof e.fileSizeBytes=="object"&&(a.fileSizeBytes=new l.LongBits(e.fileSizeBytes.low>>>0,e.fileSizeBytes.high>>>0).toNumber(!0))),e.fileSha256!=null&&(typeof e.fileSha256=="string"?l.base64.decode(e.fileSha256,a.fileSha256=l.newBuffer(l.base64.length(e.fileSha256)),0):e.fileSha256.length>=0&&(a.fileSha256=e.fileSha256)),e.fileEncSha256!=null&&(typeof e.fileEncSha256=="string"?l.base64.decode(e.fileEncSha256,a.fileEncSha256=l.newBuffer(l.base64.length(e.fileEncSha256)),0):e.fileEncSha256.length>=0&&(a.fileEncSha256=e.fileEncSha256)),a},t.toObject=function(e,a){a||(a={});var A={};return e.mediaKey!=null&&e.hasOwnProperty("mediaKey")&&(A.mediaKey=a.bytes===String?l.base64.encode(e.mediaKey,0,e.mediaKey.length):a.bytes===Array?Array.prototype.slice.call(e.mediaKey):e.mediaKey,a.oneofs&&(A._mediaKey="mediaKey")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.handle!=null&&e.hasOwnProperty("handle")&&(A.handle=e.handle,a.oneofs&&(A._handle="handle")),e.fileSizeBytes!=null&&e.hasOwnProperty("fileSizeBytes")&&(typeof e.fileSizeBytes=="number"?A.fileSizeBytes=a.longs===String?String(e.fileSizeBytes):e.fileSizeBytes:A.fileSizeBytes=a.longs===String?se(e.fileSizeBytes,!0):a.longs===Number?ge(e.fileSizeBytes,!0):e.fileSizeBytes,a.oneofs&&(A._fileSizeBytes="fileSizeBytes")),e.fileSha256!=null&&e.hasOwnProperty("fileSha256")&&(A.fileSha256=a.bytes===String?l.base64.encode(e.fileSha256,0,e.fileSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileSha256):e.fileSha256,a.oneofs&&(A._fileSha256="fileSha256")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=a.bytes===String?l.base64.encode(e.fileEncSha256,0,e.fileEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileEncSha256):e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ExternalBlobReference"},t})(),n.Field=(function(){function t(i){if(this.subfield={},i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.minVersion=e.uint32();break}case 2:{s.maxVersion=e.uint32();break}case 3:{s.notReportableMinVersion=e.uint32();break}case 4:{s.isMessage=e.bool();break}case 5:{s.subfield===l.emptyObject&&(s.subfield={});var d=e.uint32()+e.pos;for(g=0,c=null;e.pos>>3){case 1:g=e.uint32();break;case 2:c=p.proto.Field.decode(e,e.uint32());break;default:e.skipType(B&7);break}}s.subfield[g]=c;break}default:e.skipType(I&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Field)return e;var a=new p.proto.Field;if(e.minVersion!=null&&(a.minVersion=e.minVersion>>>0),e.maxVersion!=null&&(a.maxVersion=e.maxVersion>>>0),e.notReportableMinVersion!=null&&(a.notReportableMinVersion=e.notReportableMinVersion>>>0),e.isMessage!=null&&(a.isMessage=!!e.isMessage),e.subfield){if(typeof e.subfield!="object")throw TypeError(".proto.Field.subfield: object expected");a.subfield={};for(var A=Object.keys(e.subfield),r=0;r>>3){case 1:{s.botName=e.string();break}case 2:{s.botJid=e.string();break}case 3:{s.creatorName=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ForwardedAIBotMessageInfo)return e;var a=new p.proto.ForwardedAIBotMessageInfo;return e.botName!=null&&(a.botName=String(e.botName)),e.botJid!=null&&(a.botJid=String(e.botJid)),e.creatorName!=null&&(a.creatorName=String(e.creatorName)),a},t.toObject=function(e,a){a||(a={});var A={};return e.botName!=null&&e.hasOwnProperty("botName")&&(A.botName=e.botName,a.oneofs&&(A._botName="botName")),e.botJid!=null&&e.hasOwnProperty("botJid")&&(A.botJid=e.botJid,a.oneofs&&(A._botJid="botJid")),e.creatorName!=null&&e.hasOwnProperty("creatorName")&&(A.creatorName=e.creatorName,a.oneofs&&(A._creatorName="creatorName")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ForwardedAIBotMessageInfo"},t})(),n.GlobalSettings=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lightThemeWallpaper=p.proto.WallpaperSettings.decode(e,e.uint32());break}case 2:{s.mediaVisibility=e.int32();break}case 3:{s.darkThemeWallpaper=p.proto.WallpaperSettings.decode(e,e.uint32());break}case 4:{s.autoDownloadWiFi=p.proto.AutoDownloadSettings.decode(e,e.uint32());break}case 5:{s.autoDownloadCellular=p.proto.AutoDownloadSettings.decode(e,e.uint32());break}case 6:{s.autoDownloadRoaming=p.proto.AutoDownloadSettings.decode(e,e.uint32());break}case 7:{s.showIndividualNotificationsPreview=e.bool();break}case 8:{s.showGroupNotificationsPreview=e.bool();break}case 9:{s.disappearingModeDuration=e.int32();break}case 10:{s.disappearingModeTimestamp=e.int64();break}case 11:{s.avatarUserSettings=p.proto.AvatarUserSettings.decode(e,e.uint32());break}case 12:{s.fontSize=e.int32();break}case 13:{s.securityNotifications=e.bool();break}case 14:{s.autoUnarchiveChats=e.bool();break}case 15:{s.videoQualityMode=e.int32();break}case 16:{s.photoQualityMode=e.int32();break}case 17:{s.individualNotificationSettings=p.proto.NotificationSettings.decode(e,e.uint32());break}case 18:{s.groupNotificationSettings=p.proto.NotificationSettings.decode(e,e.uint32());break}case 19:{s.chatLockSettings=p.proto.ChatLockSettings.decode(e,e.uint32());break}case 20:{s.chatDbLidMigrationTimestamp=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.GlobalSettings)return e;var a=new p.proto.GlobalSettings;if(e.lightThemeWallpaper!=null){if(typeof e.lightThemeWallpaper!="object")throw TypeError(".proto.GlobalSettings.lightThemeWallpaper: object expected");a.lightThemeWallpaper=p.proto.WallpaperSettings.fromObject(e.lightThemeWallpaper)}switch(e.mediaVisibility){default:if(typeof e.mediaVisibility=="number"){a.mediaVisibility=e.mediaVisibility;break}break;case"DEFAULT":case 0:a.mediaVisibility=0;break;case"OFF":case 1:a.mediaVisibility=1;break;case"ON":case 2:a.mediaVisibility=2;break}if(e.darkThemeWallpaper!=null){if(typeof e.darkThemeWallpaper!="object")throw TypeError(".proto.GlobalSettings.darkThemeWallpaper: object expected");a.darkThemeWallpaper=p.proto.WallpaperSettings.fromObject(e.darkThemeWallpaper)}if(e.autoDownloadWiFi!=null){if(typeof e.autoDownloadWiFi!="object")throw TypeError(".proto.GlobalSettings.autoDownloadWiFi: object expected");a.autoDownloadWiFi=p.proto.AutoDownloadSettings.fromObject(e.autoDownloadWiFi)}if(e.autoDownloadCellular!=null){if(typeof e.autoDownloadCellular!="object")throw TypeError(".proto.GlobalSettings.autoDownloadCellular: object expected");a.autoDownloadCellular=p.proto.AutoDownloadSettings.fromObject(e.autoDownloadCellular)}if(e.autoDownloadRoaming!=null){if(typeof e.autoDownloadRoaming!="object")throw TypeError(".proto.GlobalSettings.autoDownloadRoaming: object expected");a.autoDownloadRoaming=p.proto.AutoDownloadSettings.fromObject(e.autoDownloadRoaming)}if(e.showIndividualNotificationsPreview!=null&&(a.showIndividualNotificationsPreview=!!e.showIndividualNotificationsPreview),e.showGroupNotificationsPreview!=null&&(a.showGroupNotificationsPreview=!!e.showGroupNotificationsPreview),e.disappearingModeDuration!=null&&(a.disappearingModeDuration=e.disappearingModeDuration|0),e.disappearingModeTimestamp!=null&&(l.Long?(a.disappearingModeTimestamp=l.Long.fromValue(e.disappearingModeTimestamp)).unsigned=!1:typeof e.disappearingModeTimestamp=="string"?a.disappearingModeTimestamp=parseInt(e.disappearingModeTimestamp,10):typeof e.disappearingModeTimestamp=="number"?a.disappearingModeTimestamp=e.disappearingModeTimestamp:typeof e.disappearingModeTimestamp=="object"&&(a.disappearingModeTimestamp=new l.LongBits(e.disappearingModeTimestamp.low>>>0,e.disappearingModeTimestamp.high>>>0).toNumber())),e.avatarUserSettings!=null){if(typeof e.avatarUserSettings!="object")throw TypeError(".proto.GlobalSettings.avatarUserSettings: object expected");a.avatarUserSettings=p.proto.AvatarUserSettings.fromObject(e.avatarUserSettings)}if(e.fontSize!=null&&(a.fontSize=e.fontSize|0),e.securityNotifications!=null&&(a.securityNotifications=!!e.securityNotifications),e.autoUnarchiveChats!=null&&(a.autoUnarchiveChats=!!e.autoUnarchiveChats),e.videoQualityMode!=null&&(a.videoQualityMode=e.videoQualityMode|0),e.photoQualityMode!=null&&(a.photoQualityMode=e.photoQualityMode|0),e.individualNotificationSettings!=null){if(typeof e.individualNotificationSettings!="object")throw TypeError(".proto.GlobalSettings.individualNotificationSettings: object expected");a.individualNotificationSettings=p.proto.NotificationSettings.fromObject(e.individualNotificationSettings)}if(e.groupNotificationSettings!=null){if(typeof e.groupNotificationSettings!="object")throw TypeError(".proto.GlobalSettings.groupNotificationSettings: object expected");a.groupNotificationSettings=p.proto.NotificationSettings.fromObject(e.groupNotificationSettings)}if(e.chatLockSettings!=null){if(typeof e.chatLockSettings!="object")throw TypeError(".proto.GlobalSettings.chatLockSettings: object expected");a.chatLockSettings=p.proto.ChatLockSettings.fromObject(e.chatLockSettings)}return e.chatDbLidMigrationTimestamp!=null&&(l.Long?(a.chatDbLidMigrationTimestamp=l.Long.fromValue(e.chatDbLidMigrationTimestamp)).unsigned=!1:typeof e.chatDbLidMigrationTimestamp=="string"?a.chatDbLidMigrationTimestamp=parseInt(e.chatDbLidMigrationTimestamp,10):typeof e.chatDbLidMigrationTimestamp=="number"?a.chatDbLidMigrationTimestamp=e.chatDbLidMigrationTimestamp:typeof e.chatDbLidMigrationTimestamp=="object"&&(a.chatDbLidMigrationTimestamp=new l.LongBits(e.chatDbLidMigrationTimestamp.low>>>0,e.chatDbLidMigrationTimestamp.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.lightThemeWallpaper!=null&&e.hasOwnProperty("lightThemeWallpaper")&&(A.lightThemeWallpaper=p.proto.WallpaperSettings.toObject(e.lightThemeWallpaper,a),a.oneofs&&(A._lightThemeWallpaper="lightThemeWallpaper")),e.mediaVisibility!=null&&e.hasOwnProperty("mediaVisibility")&&(A.mediaVisibility=a.enums===String?p.proto.MediaVisibility[e.mediaVisibility]===void 0?e.mediaVisibility:p.proto.MediaVisibility[e.mediaVisibility]:e.mediaVisibility,a.oneofs&&(A._mediaVisibility="mediaVisibility")),e.darkThemeWallpaper!=null&&e.hasOwnProperty("darkThemeWallpaper")&&(A.darkThemeWallpaper=p.proto.WallpaperSettings.toObject(e.darkThemeWallpaper,a),a.oneofs&&(A._darkThemeWallpaper="darkThemeWallpaper")),e.autoDownloadWiFi!=null&&e.hasOwnProperty("autoDownloadWiFi")&&(A.autoDownloadWiFi=p.proto.AutoDownloadSettings.toObject(e.autoDownloadWiFi,a),a.oneofs&&(A._autoDownloadWiFi="autoDownloadWiFi")),e.autoDownloadCellular!=null&&e.hasOwnProperty("autoDownloadCellular")&&(A.autoDownloadCellular=p.proto.AutoDownloadSettings.toObject(e.autoDownloadCellular,a),a.oneofs&&(A._autoDownloadCellular="autoDownloadCellular")),e.autoDownloadRoaming!=null&&e.hasOwnProperty("autoDownloadRoaming")&&(A.autoDownloadRoaming=p.proto.AutoDownloadSettings.toObject(e.autoDownloadRoaming,a),a.oneofs&&(A._autoDownloadRoaming="autoDownloadRoaming")),e.showIndividualNotificationsPreview!=null&&e.hasOwnProperty("showIndividualNotificationsPreview")&&(A.showIndividualNotificationsPreview=e.showIndividualNotificationsPreview,a.oneofs&&(A._showIndividualNotificationsPreview="showIndividualNotificationsPreview")),e.showGroupNotificationsPreview!=null&&e.hasOwnProperty("showGroupNotificationsPreview")&&(A.showGroupNotificationsPreview=e.showGroupNotificationsPreview,a.oneofs&&(A._showGroupNotificationsPreview="showGroupNotificationsPreview")),e.disappearingModeDuration!=null&&e.hasOwnProperty("disappearingModeDuration")&&(A.disappearingModeDuration=e.disappearingModeDuration,a.oneofs&&(A._disappearingModeDuration="disappearingModeDuration")),e.disappearingModeTimestamp!=null&&e.hasOwnProperty("disappearingModeTimestamp")&&(typeof e.disappearingModeTimestamp=="number"?A.disappearingModeTimestamp=a.longs===String?String(e.disappearingModeTimestamp):e.disappearingModeTimestamp:A.disappearingModeTimestamp=a.longs===String?se(e.disappearingModeTimestamp):a.longs===Number?ge(e.disappearingModeTimestamp):e.disappearingModeTimestamp,a.oneofs&&(A._disappearingModeTimestamp="disappearingModeTimestamp")),e.avatarUserSettings!=null&&e.hasOwnProperty("avatarUserSettings")&&(A.avatarUserSettings=p.proto.AvatarUserSettings.toObject(e.avatarUserSettings,a),a.oneofs&&(A._avatarUserSettings="avatarUserSettings")),e.fontSize!=null&&e.hasOwnProperty("fontSize")&&(A.fontSize=e.fontSize,a.oneofs&&(A._fontSize="fontSize")),e.securityNotifications!=null&&e.hasOwnProperty("securityNotifications")&&(A.securityNotifications=e.securityNotifications,a.oneofs&&(A._securityNotifications="securityNotifications")),e.autoUnarchiveChats!=null&&e.hasOwnProperty("autoUnarchiveChats")&&(A.autoUnarchiveChats=e.autoUnarchiveChats,a.oneofs&&(A._autoUnarchiveChats="autoUnarchiveChats")),e.videoQualityMode!=null&&e.hasOwnProperty("videoQualityMode")&&(A.videoQualityMode=e.videoQualityMode,a.oneofs&&(A._videoQualityMode="videoQualityMode")),e.photoQualityMode!=null&&e.hasOwnProperty("photoQualityMode")&&(A.photoQualityMode=e.photoQualityMode,a.oneofs&&(A._photoQualityMode="photoQualityMode")),e.individualNotificationSettings!=null&&e.hasOwnProperty("individualNotificationSettings")&&(A.individualNotificationSettings=p.proto.NotificationSettings.toObject(e.individualNotificationSettings,a),a.oneofs&&(A._individualNotificationSettings="individualNotificationSettings")),e.groupNotificationSettings!=null&&e.hasOwnProperty("groupNotificationSettings")&&(A.groupNotificationSettings=p.proto.NotificationSettings.toObject(e.groupNotificationSettings,a),a.oneofs&&(A._groupNotificationSettings="groupNotificationSettings")),e.chatLockSettings!=null&&e.hasOwnProperty("chatLockSettings")&&(A.chatLockSettings=p.proto.ChatLockSettings.toObject(e.chatLockSettings,a),a.oneofs&&(A._chatLockSettings="chatLockSettings")),e.chatDbLidMigrationTimestamp!=null&&e.hasOwnProperty("chatDbLidMigrationTimestamp")&&(typeof e.chatDbLidMigrationTimestamp=="number"?A.chatDbLidMigrationTimestamp=a.longs===String?String(e.chatDbLidMigrationTimestamp):e.chatDbLidMigrationTimestamp:A.chatDbLidMigrationTimestamp=a.longs===String?se(e.chatDbLidMigrationTimestamp):a.longs===Number?ge(e.chatDbLidMigrationTimestamp):e.chatDbLidMigrationTimestamp,a.oneofs&&(A._chatDbLidMigrationTimestamp="chatDbLidMigrationTimestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GlobalSettings"},t})(),n.GroupHistoryBundleInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.deprecatedMessageHistoryBundle=p.proto.Message.MessageHistoryBundle.decode(e,e.uint32());break}case 2:{s.processState=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.GroupHistoryBundleInfo)return e;var a=new p.proto.GroupHistoryBundleInfo;if(e.deprecatedMessageHistoryBundle!=null){if(typeof e.deprecatedMessageHistoryBundle!="object")throw TypeError(".proto.GroupHistoryBundleInfo.deprecatedMessageHistoryBundle: object expected");a.deprecatedMessageHistoryBundle=p.proto.Message.MessageHistoryBundle.fromObject(e.deprecatedMessageHistoryBundle)}switch(e.processState){default:if(typeof e.processState=="number"){a.processState=e.processState;break}break;case"NOT_INJECTED":case 0:a.processState=0;break;case"INJECTED":case 1:a.processState=1;break;case"INJECTED_PARTIAL":case 2:a.processState=2;break;case"INJECTION_FAILED":case 3:a.processState=3;break;case"INJECTION_FAILED_NO_RETRY":case 4:a.processState=4;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.deprecatedMessageHistoryBundle!=null&&e.hasOwnProperty("deprecatedMessageHistoryBundle")&&(A.deprecatedMessageHistoryBundle=p.proto.Message.MessageHistoryBundle.toObject(e.deprecatedMessageHistoryBundle,a),a.oneofs&&(A._deprecatedMessageHistoryBundle="deprecatedMessageHistoryBundle")),e.processState!=null&&e.hasOwnProperty("processState")&&(A.processState=a.enums===String?p.proto.GroupHistoryBundleInfo.ProcessState[e.processState]===void 0?e.processState:p.proto.GroupHistoryBundleInfo.ProcessState[e.processState]:e.processState,a.oneofs&&(A._processState="processState")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupHistoryBundleInfo"},t.ProcessState=(function(){let i={},e=Object.create(i);return e[i[0]="NOT_INJECTED"]=0,e[i[1]="INJECTED"]=1,e[i[2]="INJECTED_PARTIAL"]=2,e[i[3]="INJECTION_FAILED"]=3,e[i[4]="INJECTION_FAILED_NO_RETRY"]=4,e})(),t})(),n.GroupHistoryIndividualMessageInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.bundleMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.editedAfterReceivedAsHistory=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.GroupHistoryIndividualMessageInfo)return e;var a=new p.proto.GroupHistoryIndividualMessageInfo;if(e.bundleMessageKey!=null){if(typeof e.bundleMessageKey!="object")throw TypeError(".proto.GroupHistoryIndividualMessageInfo.bundleMessageKey: object expected");a.bundleMessageKey=p.proto.MessageKey.fromObject(e.bundleMessageKey)}return e.editedAfterReceivedAsHistory!=null&&(a.editedAfterReceivedAsHistory=!!e.editedAfterReceivedAsHistory),a},t.toObject=function(e,a){a||(a={});var A={};return e.bundleMessageKey!=null&&e.hasOwnProperty("bundleMessageKey")&&(A.bundleMessageKey=p.proto.MessageKey.toObject(e.bundleMessageKey,a),a.oneofs&&(A._bundleMessageKey="bundleMessageKey")),e.editedAfterReceivedAsHistory!=null&&e.hasOwnProperty("editedAfterReceivedAsHistory")&&(A.editedAfterReceivedAsHistory=e.editedAfterReceivedAsHistory,a.oneofs&&(A._editedAfterReceivedAsHistory="editedAfterReceivedAsHistory")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupHistoryIndividualMessageInfo"},t})(),n.GroupMention=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.groupJid=e.string();break}case 2:{s.groupSubject=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.GroupMention)return e;var a=new p.proto.GroupMention;return e.groupJid!=null&&(a.groupJid=String(e.groupJid)),e.groupSubject!=null&&(a.groupSubject=String(e.groupSubject)),a},t.toObject=function(e,a){a||(a={});var A={};return e.groupJid!=null&&e.hasOwnProperty("groupJid")&&(A.groupJid=e.groupJid,a.oneofs&&(A._groupJid="groupJid")),e.groupSubject!=null&&e.hasOwnProperty("groupSubject")&&(A.groupSubject=e.groupSubject,a.oneofs&&(A._groupSubject="groupSubject")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupMention"},t})(),n.GroupParticipant=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.userJid=e.string();break}case 2:{s.rank=e.int32();break}case 3:{s.memberLabel=p.proto.MemberLabel.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.GroupParticipant)return e;var a=new p.proto.GroupParticipant;switch(e.userJid!=null&&(a.userJid=String(e.userJid)),e.rank){default:if(typeof e.rank=="number"){a.rank=e.rank;break}break;case"REGULAR":case 0:a.rank=0;break;case"ADMIN":case 1:a.rank=1;break;case"SUPERADMIN":case 2:a.rank=2;break}if(e.memberLabel!=null){if(typeof e.memberLabel!="object")throw TypeError(".proto.GroupParticipant.memberLabel: object expected");a.memberLabel=p.proto.MemberLabel.fromObject(e.memberLabel)}return a},t.toObject=function(e,a){a||(a={});var A={};return a.defaults&&(A.userJid=""),e.userJid!=null&&e.hasOwnProperty("userJid")&&(A.userJid=e.userJid),e.rank!=null&&e.hasOwnProperty("rank")&&(A.rank=a.enums===String?p.proto.GroupParticipant.Rank[e.rank]===void 0?e.rank:p.proto.GroupParticipant.Rank[e.rank]:e.rank,a.oneofs&&(A._rank="rank")),e.memberLabel!=null&&e.hasOwnProperty("memberLabel")&&(A.memberLabel=p.proto.MemberLabel.toObject(e.memberLabel,a),a.oneofs&&(A._memberLabel="memberLabel")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupParticipant"},t.Rank=(function(){let i={},e=Object.create(i);return e[i[0]="REGULAR"]=0,e[i[1]="ADMIN"]=1,e[i[2]="SUPERADMIN"]=2,e})(),t})(),n.HandshakeMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 2:{s.clientHello=p.proto.HandshakeMessage.ClientHello.decode(e,e.uint32());break}case 3:{s.serverHello=p.proto.HandshakeMessage.ServerHello.decode(e,e.uint32());break}case 4:{s.clientFinish=p.proto.HandshakeMessage.ClientFinish.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.HandshakeMessage)return e;var a=new p.proto.HandshakeMessage;if(e.clientHello!=null){if(typeof e.clientHello!="object")throw TypeError(".proto.HandshakeMessage.clientHello: object expected");a.clientHello=p.proto.HandshakeMessage.ClientHello.fromObject(e.clientHello)}if(e.serverHello!=null){if(typeof e.serverHello!="object")throw TypeError(".proto.HandshakeMessage.serverHello: object expected");a.serverHello=p.proto.HandshakeMessage.ServerHello.fromObject(e.serverHello)}if(e.clientFinish!=null){if(typeof e.clientFinish!="object")throw TypeError(".proto.HandshakeMessage.clientFinish: object expected");a.clientFinish=p.proto.HandshakeMessage.ClientFinish.fromObject(e.clientFinish)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.clientHello!=null&&e.hasOwnProperty("clientHello")&&(A.clientHello=p.proto.HandshakeMessage.ClientHello.toObject(e.clientHello,a),a.oneofs&&(A._clientHello="clientHello")),e.serverHello!=null&&e.hasOwnProperty("serverHello")&&(A.serverHello=p.proto.HandshakeMessage.ServerHello.toObject(e.serverHello,a),a.oneofs&&(A._serverHello="serverHello")),e.clientFinish!=null&&e.hasOwnProperty("clientFinish")&&(A.clientFinish=p.proto.HandshakeMessage.ClientFinish.toObject(e.clientFinish,a),a.oneofs&&(A._clientFinish="clientFinish")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.HandshakeMessage"},t.ClientFinish=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.static=A.bytes();break}case 2:{c.payload=A.bytes();break}case 3:{c.extendedCiphertext=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HandshakeMessage.ClientFinish)return A;var r=new p.proto.HandshakeMessage.ClientFinish;return A.static!=null&&(typeof A.static=="string"?l.base64.decode(A.static,r.static=l.newBuffer(l.base64.length(A.static)),0):A.static.length>=0&&(r.static=A.static)),A.payload!=null&&(typeof A.payload=="string"?l.base64.decode(A.payload,r.payload=l.newBuffer(l.base64.length(A.payload)),0):A.payload.length>=0&&(r.payload=A.payload)),A.extendedCiphertext!=null&&(typeof A.extendedCiphertext=="string"?l.base64.decode(A.extendedCiphertext,r.extendedCiphertext=l.newBuffer(l.base64.length(A.extendedCiphertext)),0):A.extendedCiphertext.length>=0&&(r.extendedCiphertext=A.extendedCiphertext)),r},i.toObject=function(A,r){r||(r={});var s={};return A.static!=null&&A.hasOwnProperty("static")&&(s.static=r.bytes===String?l.base64.encode(A.static,0,A.static.length):r.bytes===Array?Array.prototype.slice.call(A.static):A.static,r.oneofs&&(s._static="static")),A.payload!=null&&A.hasOwnProperty("payload")&&(s.payload=r.bytes===String?l.base64.encode(A.payload,0,A.payload.length):r.bytes===Array?Array.prototype.slice.call(A.payload):A.payload,r.oneofs&&(s._payload="payload")),A.extendedCiphertext!=null&&A.hasOwnProperty("extendedCiphertext")&&(s.extendedCiphertext=r.bytes===String?l.base64.encode(A.extendedCiphertext,0,A.extendedCiphertext.length):r.bytes===Array?Array.prototype.slice.call(A.extendedCiphertext):A.extendedCiphertext,r.oneofs&&(s._extendedCiphertext="extendedCiphertext")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HandshakeMessage.ClientFinish"},i})(),t.ClientHello=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.ephemeral=A.bytes();break}case 2:{c.static=A.bytes();break}case 3:{c.payload=A.bytes();break}case 4:{c.useExtended=A.bool();break}case 5:{c.extendedCiphertext=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HandshakeMessage.ClientHello)return A;var r=new p.proto.HandshakeMessage.ClientHello;return A.ephemeral!=null&&(typeof A.ephemeral=="string"?l.base64.decode(A.ephemeral,r.ephemeral=l.newBuffer(l.base64.length(A.ephemeral)),0):A.ephemeral.length>=0&&(r.ephemeral=A.ephemeral)),A.static!=null&&(typeof A.static=="string"?l.base64.decode(A.static,r.static=l.newBuffer(l.base64.length(A.static)),0):A.static.length>=0&&(r.static=A.static)),A.payload!=null&&(typeof A.payload=="string"?l.base64.decode(A.payload,r.payload=l.newBuffer(l.base64.length(A.payload)),0):A.payload.length>=0&&(r.payload=A.payload)),A.useExtended!=null&&(r.useExtended=!!A.useExtended),A.extendedCiphertext!=null&&(typeof A.extendedCiphertext=="string"?l.base64.decode(A.extendedCiphertext,r.extendedCiphertext=l.newBuffer(l.base64.length(A.extendedCiphertext)),0):A.extendedCiphertext.length>=0&&(r.extendedCiphertext=A.extendedCiphertext)),r},i.toObject=function(A,r){r||(r={});var s={};return A.ephemeral!=null&&A.hasOwnProperty("ephemeral")&&(s.ephemeral=r.bytes===String?l.base64.encode(A.ephemeral,0,A.ephemeral.length):r.bytes===Array?Array.prototype.slice.call(A.ephemeral):A.ephemeral,r.oneofs&&(s._ephemeral="ephemeral")),A.static!=null&&A.hasOwnProperty("static")&&(s.static=r.bytes===String?l.base64.encode(A.static,0,A.static.length):r.bytes===Array?Array.prototype.slice.call(A.static):A.static,r.oneofs&&(s._static="static")),A.payload!=null&&A.hasOwnProperty("payload")&&(s.payload=r.bytes===String?l.base64.encode(A.payload,0,A.payload.length):r.bytes===Array?Array.prototype.slice.call(A.payload):A.payload,r.oneofs&&(s._payload="payload")),A.useExtended!=null&&A.hasOwnProperty("useExtended")&&(s.useExtended=A.useExtended,r.oneofs&&(s._useExtended="useExtended")),A.extendedCiphertext!=null&&A.hasOwnProperty("extendedCiphertext")&&(s.extendedCiphertext=r.bytes===String?l.base64.encode(A.extendedCiphertext,0,A.extendedCiphertext.length):r.bytes===Array?Array.prototype.slice.call(A.extendedCiphertext):A.extendedCiphertext,r.oneofs&&(s._extendedCiphertext="extendedCiphertext")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HandshakeMessage.ClientHello"},i})(),t.ServerHello=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.ephemeral=A.bytes();break}case 2:{c.static=A.bytes();break}case 3:{c.payload=A.bytes();break}case 4:{c.extendedStatic=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HandshakeMessage.ServerHello)return A;var r=new p.proto.HandshakeMessage.ServerHello;return A.ephemeral!=null&&(typeof A.ephemeral=="string"?l.base64.decode(A.ephemeral,r.ephemeral=l.newBuffer(l.base64.length(A.ephemeral)),0):A.ephemeral.length>=0&&(r.ephemeral=A.ephemeral)),A.static!=null&&(typeof A.static=="string"?l.base64.decode(A.static,r.static=l.newBuffer(l.base64.length(A.static)),0):A.static.length>=0&&(r.static=A.static)),A.payload!=null&&(typeof A.payload=="string"?l.base64.decode(A.payload,r.payload=l.newBuffer(l.base64.length(A.payload)),0):A.payload.length>=0&&(r.payload=A.payload)),A.extendedStatic!=null&&(typeof A.extendedStatic=="string"?l.base64.decode(A.extendedStatic,r.extendedStatic=l.newBuffer(l.base64.length(A.extendedStatic)),0):A.extendedStatic.length>=0&&(r.extendedStatic=A.extendedStatic)),r},i.toObject=function(A,r){r||(r={});var s={};return A.ephemeral!=null&&A.hasOwnProperty("ephemeral")&&(s.ephemeral=r.bytes===String?l.base64.encode(A.ephemeral,0,A.ephemeral.length):r.bytes===Array?Array.prototype.slice.call(A.ephemeral):A.ephemeral,r.oneofs&&(s._ephemeral="ephemeral")),A.static!=null&&A.hasOwnProperty("static")&&(s.static=r.bytes===String?l.base64.encode(A.static,0,A.static.length):r.bytes===Array?Array.prototype.slice.call(A.static):A.static,r.oneofs&&(s._static="static")),A.payload!=null&&A.hasOwnProperty("payload")&&(s.payload=r.bytes===String?l.base64.encode(A.payload,0,A.payload.length):r.bytes===Array?Array.prototype.slice.call(A.payload):A.payload,r.oneofs&&(s._payload="payload")),A.extendedStatic!=null&&A.hasOwnProperty("extendedStatic")&&(s.extendedStatic=r.bytes===String?l.base64.encode(A.extendedStatic,0,A.extendedStatic.length):r.bytes===Array?Array.prototype.slice.call(A.extendedStatic):A.extendedStatic,r.oneofs&&(s._extendedStatic="extendedStatic")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HandshakeMessage.ServerHello"},i})(),t})(),n.HistorySync=(function(){function t(i){if(this.conversations=[],this.statusV3Messages=[],this.pushnames=[],this.recentStickers=[],this.pastParticipants=[],this.callLogRecords=[],this.phoneNumberToLidMappings=[],this.accounts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.syncType=e.int32();break}case 2:{s.conversations&&s.conversations.length||(s.conversations=[]),s.conversations.push(p.proto.Conversation.decode(e,e.uint32()));break}case 3:{s.statusV3Messages&&s.statusV3Messages.length||(s.statusV3Messages=[]),s.statusV3Messages.push(p.proto.WebMessageInfo.decode(e,e.uint32()));break}case 5:{s.chunkOrder=e.uint32();break}case 6:{s.progress=e.uint32();break}case 7:{s.pushnames&&s.pushnames.length||(s.pushnames=[]),s.pushnames.push(p.proto.Pushname.decode(e,e.uint32()));break}case 8:{s.globalSettings=p.proto.GlobalSettings.decode(e,e.uint32());break}case 9:{s.threadIdUserSecret=e.bytes();break}case 10:{s.threadDsTimeframeOffset=e.uint32();break}case 11:{s.recentStickers&&s.recentStickers.length||(s.recentStickers=[]),s.recentStickers.push(p.proto.StickerMetadata.decode(e,e.uint32()));break}case 12:{s.pastParticipants&&s.pastParticipants.length||(s.pastParticipants=[]),s.pastParticipants.push(p.proto.PastParticipants.decode(e,e.uint32()));break}case 13:{s.callLogRecords&&s.callLogRecords.length||(s.callLogRecords=[]),s.callLogRecords.push(p.proto.CallLogRecord.decode(e,e.uint32()));break}case 14:{s.aiWaitListState=e.int32();break}case 15:{s.phoneNumberToLidMappings&&s.phoneNumberToLidMappings.length||(s.phoneNumberToLidMappings=[]),s.phoneNumberToLidMappings.push(p.proto.PhoneNumberToLIDMapping.decode(e,e.uint32()));break}case 16:{s.companionMetaNonce=e.string();break}case 17:{s.shareableChatIdentifierEncryptionKey=e.bytes();break}case 18:{s.accounts&&s.accounts.length||(s.accounts=[]),s.accounts.push(p.proto.Account.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.HistorySync)return e;var a=new p.proto.HistorySync;switch(e.syncType){default:if(typeof e.syncType=="number"){a.syncType=e.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:a.syncType=0;break;case"INITIAL_STATUS_V3":case 1:a.syncType=1;break;case"FULL":case 2:a.syncType=2;break;case"RECENT":case 3:a.syncType=3;break;case"PUSH_NAME":case 4:a.syncType=4;break;case"NON_BLOCKING_DATA":case 5:a.syncType=5;break;case"ON_DEMAND":case 6:a.syncType=6;break}if(e.conversations){if(!Array.isArray(e.conversations))throw TypeError(".proto.HistorySync.conversations: array expected");a.conversations=[];for(var A=0;A>>0),e.progress!=null&&(a.progress=e.progress>>>0),e.pushnames){if(!Array.isArray(e.pushnames))throw TypeError(".proto.HistorySync.pushnames: array expected");a.pushnames=[];for(var A=0;A=0&&(a.threadIdUserSecret=e.threadIdUserSecret)),e.threadDsTimeframeOffset!=null&&(a.threadDsTimeframeOffset=e.threadDsTimeframeOffset>>>0),e.recentStickers){if(!Array.isArray(e.recentStickers))throw TypeError(".proto.HistorySync.recentStickers: array expected");a.recentStickers=[];for(var A=0;A=0&&(a.shareableChatIdentifierEncryptionKey=e.shareableChatIdentifierEncryptionKey)),e.accounts){if(!Array.isArray(e.accounts))throw TypeError(".proto.HistorySync.accounts: array expected");a.accounts=[];for(var A=0;A>>3){case 1:{s.message=p.proto.WebMessageInfo.decode(e,e.uint32());break}case 2:{s.msgOrderId=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.HistorySyncMsg)return e;var a=new p.proto.HistorySyncMsg;if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.HistorySyncMsg.message: object expected");a.message=p.proto.WebMessageInfo.fromObject(e.message)}return e.msgOrderId!=null&&(l.Long?(a.msgOrderId=l.Long.fromValue(e.msgOrderId)).unsigned=!0:typeof e.msgOrderId=="string"?a.msgOrderId=parseInt(e.msgOrderId,10):typeof e.msgOrderId=="number"?a.msgOrderId=e.msgOrderId:typeof e.msgOrderId=="object"&&(a.msgOrderId=new l.LongBits(e.msgOrderId.low>>>0,e.msgOrderId.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};return e.message!=null&&e.hasOwnProperty("message")&&(A.message=p.proto.WebMessageInfo.toObject(e.message,a),a.oneofs&&(A._message="message")),e.msgOrderId!=null&&e.hasOwnProperty("msgOrderId")&&(typeof e.msgOrderId=="number"?A.msgOrderId=a.longs===String?String(e.msgOrderId):e.msgOrderId:A.msgOrderId=a.longs===String?se(e.msgOrderId,!0):a.longs===Number?ge(e.msgOrderId,!0):e.msgOrderId,a.oneofs&&(A._msgOrderId="msgOrderId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.HistorySyncMsg"},t})(),n.HydratedTemplateButton=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 4:{s.index=e.uint32();break}case 1:{s.quickReplyButton=p.proto.HydratedTemplateButton.HydratedQuickReplyButton.decode(e,e.uint32());break}case 2:{s.urlButton=p.proto.HydratedTemplateButton.HydratedURLButton.decode(e,e.uint32());break}case 3:{s.callButton=p.proto.HydratedTemplateButton.HydratedCallButton.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.HydratedTemplateButton)return e;var a=new p.proto.HydratedTemplateButton;if(e.index!=null&&(a.index=e.index>>>0),e.quickReplyButton!=null){if(typeof e.quickReplyButton!="object")throw TypeError(".proto.HydratedTemplateButton.quickReplyButton: object expected");a.quickReplyButton=p.proto.HydratedTemplateButton.HydratedQuickReplyButton.fromObject(e.quickReplyButton)}if(e.urlButton!=null){if(typeof e.urlButton!="object")throw TypeError(".proto.HydratedTemplateButton.urlButton: object expected");a.urlButton=p.proto.HydratedTemplateButton.HydratedURLButton.fromObject(e.urlButton)}if(e.callButton!=null){if(typeof e.callButton!="object")throw TypeError(".proto.HydratedTemplateButton.callButton: object expected");a.callButton=p.proto.HydratedTemplateButton.HydratedCallButton.fromObject(e.callButton)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.quickReplyButton!=null&&e.hasOwnProperty("quickReplyButton")&&(A.quickReplyButton=p.proto.HydratedTemplateButton.HydratedQuickReplyButton.toObject(e.quickReplyButton,a),a.oneofs&&(A.hydratedButton="quickReplyButton")),e.urlButton!=null&&e.hasOwnProperty("urlButton")&&(A.urlButton=p.proto.HydratedTemplateButton.HydratedURLButton.toObject(e.urlButton,a),a.oneofs&&(A.hydratedButton="urlButton")),e.callButton!=null&&e.hasOwnProperty("callButton")&&(A.callButton=p.proto.HydratedTemplateButton.HydratedCallButton.toObject(e.callButton,a),a.oneofs&&(A.hydratedButton="callButton")),e.index!=null&&e.hasOwnProperty("index")&&(A.index=e.index,a.oneofs&&(A._index="index")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.HydratedTemplateButton"},t.HydratedCallButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=A.string();break}case 2:{c.phoneNumber=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HydratedTemplateButton.HydratedCallButton)return A;var r=new p.proto.HydratedTemplateButton.HydratedCallButton;return A.displayText!=null&&(r.displayText=String(A.displayText)),A.phoneNumber!=null&&(r.phoneNumber=String(A.phoneNumber)),r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=A.displayText,r.oneofs&&(s._displayText="displayText")),A.phoneNumber!=null&&A.hasOwnProperty("phoneNumber")&&(s.phoneNumber=A.phoneNumber,r.oneofs&&(s._phoneNumber="phoneNumber")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HydratedTemplateButton.HydratedCallButton"},i})(),t.HydratedQuickReplyButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=A.string();break}case 2:{c.id=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HydratedTemplateButton.HydratedQuickReplyButton)return A;var r=new p.proto.HydratedTemplateButton.HydratedQuickReplyButton;return A.displayText!=null&&(r.displayText=String(A.displayText)),A.id!=null&&(r.id=String(A.id)),r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=A.displayText,r.oneofs&&(s._displayText="displayText")),A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,r.oneofs&&(s._id="id")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HydratedTemplateButton.HydratedQuickReplyButton"},i})(),t.HydratedURLButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=A.string();break}case 2:{c.url=A.string();break}case 3:{c.consentedUsersUrl=A.string();break}case 4:{c.webviewPresentation=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HydratedTemplateButton.HydratedURLButton)return A;var r=new p.proto.HydratedTemplateButton.HydratedURLButton;switch(A.displayText!=null&&(r.displayText=String(A.displayText)),A.url!=null&&(r.url=String(A.url)),A.consentedUsersUrl!=null&&(r.consentedUsersUrl=String(A.consentedUsersUrl)),A.webviewPresentation){default:if(typeof A.webviewPresentation=="number"){r.webviewPresentation=A.webviewPresentation;break}break;case"FULL":case 1:r.webviewPresentation=1;break;case"TALL":case 2:r.webviewPresentation=2;break;case"COMPACT":case 3:r.webviewPresentation=3;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=A.displayText,r.oneofs&&(s._displayText="displayText")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.consentedUsersUrl!=null&&A.hasOwnProperty("consentedUsersUrl")&&(s.consentedUsersUrl=A.consentedUsersUrl,r.oneofs&&(s._consentedUsersUrl="consentedUsersUrl")),A.webviewPresentation!=null&&A.hasOwnProperty("webviewPresentation")&&(s.webviewPresentation=r.enums===String?p.proto.HydratedTemplateButton.HydratedURLButton.WebviewPresentationType[A.webviewPresentation]===void 0?A.webviewPresentation:p.proto.HydratedTemplateButton.HydratedURLButton.WebviewPresentationType[A.webviewPresentation]:A.webviewPresentation,r.oneofs&&(s._webviewPresentation="webviewPresentation")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HydratedTemplateButton.HydratedURLButton"},i.WebviewPresentationType=(function(){let a={},A=Object.create(a);return A[a[1]="FULL"]=1,A[a[2]="TALL"]=2,A[a[3]="COMPACT"]=3,A})(),i})(),t})(),n.IdentityKeyPairStructure=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.privateKey=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.IdentityKeyPairStructure)return e;var a=new p.proto.IdentityKeyPairStructure;return e.publicKey!=null&&(typeof e.publicKey=="string"?l.base64.decode(e.publicKey,a.publicKey=l.newBuffer(l.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.privateKey!=null&&(typeof e.privateKey=="string"?l.base64.decode(e.privateKey,a.privateKey=l.newBuffer(l.base64.length(e.privateKey)),0):e.privateKey.length>=0&&(a.privateKey=e.privateKey)),a},t.toObject=function(e,a){a||(a={});var A={};return e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?l.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.privateKey!=null&&e.hasOwnProperty("privateKey")&&(A.privateKey=a.bytes===String?l.base64.encode(e.privateKey,0,e.privateKey.length):a.bytes===Array?Array.prototype.slice.call(e.privateKey):e.privateKey,a.oneofs&&(A._privateKey="privateKey")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.IdentityKeyPairStructure"},t})(),n.InThreadSurveyMetadata=(function(){function t(i){if(this.questions=[],this.privacyStatementParts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.tessaSessionId=e.string();break}case 2:{s.simonSessionId=e.string();break}case 3:{s.simonSurveyId=e.string();break}case 4:{s.tessaRootId=e.string();break}case 5:{s.requestId=e.string();break}case 6:{s.tessaEvent=e.string();break}case 7:{s.invitationHeaderText=e.string();break}case 8:{s.invitationBodyText=e.string();break}case 9:{s.invitationCtaText=e.string();break}case 10:{s.invitationCtaUrl=e.string();break}case 11:{s.surveyTitle=e.string();break}case 12:{s.questions&&s.questions.length||(s.questions=[]),s.questions.push(p.proto.InThreadSurveyMetadata.InThreadSurveyQuestion.decode(e,e.uint32()));break}case 13:{s.surveyContinueButtonText=e.string();break}case 14:{s.surveySubmitButtonText=e.string();break}case 15:{s.privacyStatementFull=e.string();break}case 16:{s.privacyStatementParts&&s.privacyStatementParts.length||(s.privacyStatementParts=[]),s.privacyStatementParts.push(p.proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart.decode(e,e.uint32()));break}case 17:{s.feedbackToastText=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.InThreadSurveyMetadata)return e;var a=new p.proto.InThreadSurveyMetadata;if(e.tessaSessionId!=null&&(a.tessaSessionId=String(e.tessaSessionId)),e.simonSessionId!=null&&(a.simonSessionId=String(e.simonSessionId)),e.simonSurveyId!=null&&(a.simonSurveyId=String(e.simonSurveyId)),e.tessaRootId!=null&&(a.tessaRootId=String(e.tessaRootId)),e.requestId!=null&&(a.requestId=String(e.requestId)),e.tessaEvent!=null&&(a.tessaEvent=String(e.tessaEvent)),e.invitationHeaderText!=null&&(a.invitationHeaderText=String(e.invitationHeaderText)),e.invitationBodyText!=null&&(a.invitationBodyText=String(e.invitationBodyText)),e.invitationCtaText!=null&&(a.invitationCtaText=String(e.invitationCtaText)),e.invitationCtaUrl!=null&&(a.invitationCtaUrl=String(e.invitationCtaUrl)),e.surveyTitle!=null&&(a.surveyTitle=String(e.surveyTitle)),e.questions){if(!Array.isArray(e.questions))throw TypeError(".proto.InThreadSurveyMetadata.questions: array expected");a.questions=[];for(var A=0;A>>3){case 1:{c.stringValue=A.string();break}case 2:{c.numericValue=A.uint32();break}case 3:{c.textTranslated=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.InThreadSurveyMetadata.InThreadSurveyOption)return A;var r=new p.proto.InThreadSurveyMetadata.InThreadSurveyOption;return A.stringValue!=null&&(r.stringValue=String(A.stringValue)),A.numericValue!=null&&(r.numericValue=A.numericValue>>>0),A.textTranslated!=null&&(r.textTranslated=String(A.textTranslated)),r},i.toObject=function(A,r){r||(r={});var s={};return A.stringValue!=null&&A.hasOwnProperty("stringValue")&&(s.stringValue=A.stringValue,r.oneofs&&(s._stringValue="stringValue")),A.numericValue!=null&&A.hasOwnProperty("numericValue")&&(s.numericValue=A.numericValue,r.oneofs&&(s._numericValue="numericValue")),A.textTranslated!=null&&A.hasOwnProperty("textTranslated")&&(s.textTranslated=A.textTranslated,r.oneofs&&(s._textTranslated="textTranslated")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.InThreadSurveyMetadata.InThreadSurveyOption"},i})(),t.InThreadSurveyPrivacyStatementPart=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.text=A.string();break}case 2:{c.url=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart)return A;var r=new p.proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart;return A.text!=null&&(r.text=String(A.text)),A.url!=null&&(r.url=String(A.url)),r},i.toObject=function(A,r){r||(r={});var s={};return A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart"},i})(),t.InThreadSurveyQuestion=(function(){function i(a){if(this.questionOptions=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.questionText=A.string();break}case 2:{c.questionId=A.string();break}case 3:{c.questionOptions&&c.questionOptions.length||(c.questionOptions=[]),c.questionOptions.push(p.proto.InThreadSurveyMetadata.InThreadSurveyOption.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.InThreadSurveyMetadata.InThreadSurveyQuestion)return A;var r=new p.proto.InThreadSurveyMetadata.InThreadSurveyQuestion;if(A.questionText!=null&&(r.questionText=String(A.questionText)),A.questionId!=null&&(r.questionId=String(A.questionId)),A.questionOptions){if(!Array.isArray(A.questionOptions))throw TypeError(".proto.InThreadSurveyMetadata.InThreadSurveyQuestion.questionOptions: array expected");r.questionOptions=[];for(var s=0;s>>3){case 1:{s.polygonVertices&&s.polygonVertices.length||(s.polygonVertices=[]),s.polygonVertices.push(p.proto.Point.decode(e,e.uint32()));break}case 4:{s.shouldSkipConfirmation=e.bool();break}case 5:{s.embeddedContent=p.proto.EmbeddedContent.decode(e,e.uint32());break}case 8:{s.statusLinkType=e.int32();break}case 2:{s.location=p.proto.Location.decode(e,e.uint32());break}case 3:{s.newsletter=p.proto.ContextInfo.ForwardedNewsletterMessageInfo.decode(e,e.uint32());break}case 6:{s.embeddedAction=e.bool();break}case 7:{s.tapAction=p.proto.TapLinkAction.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.InteractiveAnnotation)return e;var a=new p.proto.InteractiveAnnotation;if(e.polygonVertices){if(!Array.isArray(e.polygonVertices))throw TypeError(".proto.InteractiveAnnotation.polygonVertices: array expected");a.polygonVertices=[];for(var A=0;A>>3){case 1:{s.isGalaxyFlowCompleted=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.InteractiveMessageAdditionalMetadata)return e;var a=new p.proto.InteractiveMessageAdditionalMetadata;return e.isGalaxyFlowCompleted!=null&&(a.isGalaxyFlowCompleted=!!e.isGalaxyFlowCompleted),a},t.toObject=function(e,a){a||(a={});var A={};return e.isGalaxyFlowCompleted!=null&&e.hasOwnProperty("isGalaxyFlowCompleted")&&(A.isGalaxyFlowCompleted=e.isGalaxyFlowCompleted,a.oneofs&&(A._isGalaxyFlowCompleted="isGalaxyFlowCompleted")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.InteractiveMessageAdditionalMetadata"},t})(),n.KeepInChat=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.keepType=e.int32();break}case 2:{s.serverTimestamp=e.int64();break}case 3:{s.key=p.proto.MessageKey.decode(e,e.uint32());break}case 4:{s.deviceJid=e.string();break}case 5:{s.clientTimestampMs=e.int64();break}case 6:{s.serverTimestampMs=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.KeepInChat)return e;var a=new p.proto.KeepInChat;switch(e.keepType){default:if(typeof e.keepType=="number"){a.keepType=e.keepType;break}break;case"UNKNOWN":case 0:a.keepType=0;break;case"KEEP_FOR_ALL":case 1:a.keepType=1;break;case"UNDO_KEEP_FOR_ALL":case 2:a.keepType=2;break}if(e.serverTimestamp!=null&&(l.Long?(a.serverTimestamp=l.Long.fromValue(e.serverTimestamp)).unsigned=!1:typeof e.serverTimestamp=="string"?a.serverTimestamp=parseInt(e.serverTimestamp,10):typeof e.serverTimestamp=="number"?a.serverTimestamp=e.serverTimestamp:typeof e.serverTimestamp=="object"&&(a.serverTimestamp=new l.LongBits(e.serverTimestamp.low>>>0,e.serverTimestamp.high>>>0).toNumber())),e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.KeepInChat.key: object expected");a.key=p.proto.MessageKey.fromObject(e.key)}return e.deviceJid!=null&&(a.deviceJid=String(e.deviceJid)),e.clientTimestampMs!=null&&(l.Long?(a.clientTimestampMs=l.Long.fromValue(e.clientTimestampMs)).unsigned=!1:typeof e.clientTimestampMs=="string"?a.clientTimestampMs=parseInt(e.clientTimestampMs,10):typeof e.clientTimestampMs=="number"?a.clientTimestampMs=e.clientTimestampMs:typeof e.clientTimestampMs=="object"&&(a.clientTimestampMs=new l.LongBits(e.clientTimestampMs.low>>>0,e.clientTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(l.Long?(a.serverTimestampMs=l.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new l.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.keepType!=null&&e.hasOwnProperty("keepType")&&(A.keepType=a.enums===String?p.proto.KeepType[e.keepType]===void 0?e.keepType:p.proto.KeepType[e.keepType]:e.keepType,a.oneofs&&(A._keepType="keepType")),e.serverTimestamp!=null&&e.hasOwnProperty("serverTimestamp")&&(typeof e.serverTimestamp=="number"?A.serverTimestamp=a.longs===String?String(e.serverTimestamp):e.serverTimestamp:A.serverTimestamp=a.longs===String?se(e.serverTimestamp):a.longs===Number?ge(e.serverTimestamp):e.serverTimestamp,a.oneofs&&(A._serverTimestamp="serverTimestamp")),e.key!=null&&e.hasOwnProperty("key")&&(A.key=p.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.deviceJid!=null&&e.hasOwnProperty("deviceJid")&&(A.deviceJid=e.deviceJid,a.oneofs&&(A._deviceJid="deviceJid")),e.clientTimestampMs!=null&&e.hasOwnProperty("clientTimestampMs")&&(typeof e.clientTimestampMs=="number"?A.clientTimestampMs=a.longs===String?String(e.clientTimestampMs):e.clientTimestampMs:A.clientTimestampMs=a.longs===String?se(e.clientTimestampMs):a.longs===Number?ge(e.clientTimestampMs):e.clientTimestampMs,a.oneofs&&(A._clientTimestampMs="clientTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?se(e.serverTimestampMs):a.longs===Number?ge(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.KeepInChat"},t})(),n.KeepType=(function(){let t={},o=Object.create(t);return o[t[0]="UNKNOWN"]=0,o[t[1]="KEEP_FOR_ALL"]=1,o[t[2]="UNDO_KEEP_FOR_ALL"]=2,o})(),n.KeyExchangeMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.baseKey=e.bytes();break}case 3:{s.ratchetKey=e.bytes();break}case 4:{s.identityKey=e.bytes();break}case 5:{s.baseKeySignature=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.KeyExchangeMessage)return e;var a=new p.proto.KeyExchangeMessage;return e.id!=null&&(a.id=e.id>>>0),e.baseKey!=null&&(typeof e.baseKey=="string"?l.base64.decode(e.baseKey,a.baseKey=l.newBuffer(l.base64.length(e.baseKey)),0):e.baseKey.length>=0&&(a.baseKey=e.baseKey)),e.ratchetKey!=null&&(typeof e.ratchetKey=="string"?l.base64.decode(e.ratchetKey,a.ratchetKey=l.newBuffer(l.base64.length(e.ratchetKey)),0):e.ratchetKey.length>=0&&(a.ratchetKey=e.ratchetKey)),e.identityKey!=null&&(typeof e.identityKey=="string"?l.base64.decode(e.identityKey,a.identityKey=l.newBuffer(l.base64.length(e.identityKey)),0):e.identityKey.length>=0&&(a.identityKey=e.identityKey)),e.baseKeySignature!=null&&(typeof e.baseKeySignature=="string"?l.base64.decode(e.baseKeySignature,a.baseKeySignature=l.newBuffer(l.base64.length(e.baseKeySignature)),0):e.baseKeySignature.length>=0&&(a.baseKeySignature=e.baseKeySignature)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.baseKey!=null&&e.hasOwnProperty("baseKey")&&(A.baseKey=a.bytes===String?l.base64.encode(e.baseKey,0,e.baseKey.length):a.bytes===Array?Array.prototype.slice.call(e.baseKey):e.baseKey,a.oneofs&&(A._baseKey="baseKey")),e.ratchetKey!=null&&e.hasOwnProperty("ratchetKey")&&(A.ratchetKey=a.bytes===String?l.base64.encode(e.ratchetKey,0,e.ratchetKey.length):a.bytes===Array?Array.prototype.slice.call(e.ratchetKey):e.ratchetKey,a.oneofs&&(A._ratchetKey="ratchetKey")),e.identityKey!=null&&e.hasOwnProperty("identityKey")&&(A.identityKey=a.bytes===String?l.base64.encode(e.identityKey,0,e.identityKey.length):a.bytes===Array?Array.prototype.slice.call(e.identityKey):e.identityKey,a.oneofs&&(A._identityKey="identityKey")),e.baseKeySignature!=null&&e.hasOwnProperty("baseKeySignature")&&(A.baseKeySignature=a.bytes===String?l.base64.encode(e.baseKeySignature,0,e.baseKeySignature.length):a.bytes===Array?Array.prototype.slice.call(e.baseKeySignature):e.baseKeySignature,a.oneofs&&(A._baseKeySignature="baseKeySignature")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.KeyExchangeMessage"},t})(),n.KeyId=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.KeyId)return e;var a=new p.proto.KeyId;return e.id!=null&&(typeof e.id=="string"?l.base64.decode(e.id,a.id=l.newBuffer(l.base64.length(e.id)),0):e.id.length>=0&&(a.id=e.id)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=a.bytes===String?l.base64.encode(e.id,0,e.id.length):a.bytes===Array?Array.prototype.slice.call(e.id):e.id,a.oneofs&&(A._id="id")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.KeyId"},t})(),n.LIDMigrationMapping=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pn=e.uint64();break}case 2:{s.assignedLid=e.uint64();break}case 3:{s.latestLid=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LIDMigrationMapping)return e;var a=new p.proto.LIDMigrationMapping;return e.pn!=null&&(l.Long?(a.pn=l.Long.fromValue(e.pn)).unsigned=!0:typeof e.pn=="string"?a.pn=parseInt(e.pn,10):typeof e.pn=="number"?a.pn=e.pn:typeof e.pn=="object"&&(a.pn=new l.LongBits(e.pn.low>>>0,e.pn.high>>>0).toNumber(!0))),e.assignedLid!=null&&(l.Long?(a.assignedLid=l.Long.fromValue(e.assignedLid)).unsigned=!0:typeof e.assignedLid=="string"?a.assignedLid=parseInt(e.assignedLid,10):typeof e.assignedLid=="number"?a.assignedLid=e.assignedLid:typeof e.assignedLid=="object"&&(a.assignedLid=new l.LongBits(e.assignedLid.low>>>0,e.assignedLid.high>>>0).toNumber(!0))),e.latestLid!=null&&(l.Long?(a.latestLid=l.Long.fromValue(e.latestLid)).unsigned=!0:typeof e.latestLid=="string"?a.latestLid=parseInt(e.latestLid,10):typeof e.latestLid=="number"?a.latestLid=e.latestLid:typeof e.latestLid=="object"&&(a.latestLid=new l.LongBits(e.latestLid.low>>>0,e.latestLid.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};if(a.defaults){if(l.Long){var r=new l.Long(0,0,!0);A.pn=a.longs===String?r.toString():a.longs===Number?r.toNumber():r}else A.pn=a.longs===String?"0":0;if(l.Long){var r=new l.Long(0,0,!0);A.assignedLid=a.longs===String?r.toString():a.longs===Number?r.toNumber():r}else A.assignedLid=a.longs===String?"0":0}return e.pn!=null&&e.hasOwnProperty("pn")&&(typeof e.pn=="number"?A.pn=a.longs===String?String(e.pn):e.pn:A.pn=a.longs===String?se(e.pn,!0):a.longs===Number?ge(e.pn,!0):e.pn),e.assignedLid!=null&&e.hasOwnProperty("assignedLid")&&(typeof e.assignedLid=="number"?A.assignedLid=a.longs===String?String(e.assignedLid):e.assignedLid:A.assignedLid=a.longs===String?se(e.assignedLid,!0):a.longs===Number?ge(e.assignedLid,!0):e.assignedLid),e.latestLid!=null&&e.hasOwnProperty("latestLid")&&(typeof e.latestLid=="number"?A.latestLid=a.longs===String?String(e.latestLid):e.latestLid:A.latestLid=a.longs===String?se(e.latestLid,!0):a.longs===Number?ge(e.latestLid,!0):e.latestLid,a.oneofs&&(A._latestLid="latestLid")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LIDMigrationMapping"},t})(),n.LIDMigrationMappingSyncMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encodedMappingPayload=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LIDMigrationMappingSyncMessage)return e;var a=new p.proto.LIDMigrationMappingSyncMessage;return e.encodedMappingPayload!=null&&(typeof e.encodedMappingPayload=="string"?l.base64.decode(e.encodedMappingPayload,a.encodedMappingPayload=l.newBuffer(l.base64.length(e.encodedMappingPayload)),0):e.encodedMappingPayload.length>=0&&(a.encodedMappingPayload=e.encodedMappingPayload)),a},t.toObject=function(e,a){a||(a={});var A={};return e.encodedMappingPayload!=null&&e.hasOwnProperty("encodedMappingPayload")&&(A.encodedMappingPayload=a.bytes===String?l.base64.encode(e.encodedMappingPayload,0,e.encodedMappingPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encodedMappingPayload):e.encodedMappingPayload,a.oneofs&&(A._encodedMappingPayload="encodedMappingPayload")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LIDMigrationMappingSyncMessage"},t})(),n.LIDMigrationMappingSyncPayload=(function(){function t(i){if(this.pnToLidMappings=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pnToLidMappings&&s.pnToLidMappings.length||(s.pnToLidMappings=[]),s.pnToLidMappings.push(p.proto.LIDMigrationMapping.decode(e,e.uint32()));break}case 2:{s.chatDbMigrationTimestamp=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LIDMigrationMappingSyncPayload)return e;var a=new p.proto.LIDMigrationMappingSyncPayload;if(e.pnToLidMappings){if(!Array.isArray(e.pnToLidMappings))throw TypeError(".proto.LIDMigrationMappingSyncPayload.pnToLidMappings: array expected");a.pnToLidMappings=[];for(var A=0;A>>0,e.chatDbMigrationTimestamp.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.pnToLidMappings=[]),e.pnToLidMappings&&e.pnToLidMappings.length){A.pnToLidMappings=[];for(var r=0;r>>3){case 1:{s.eventResponseMessage=p.proto.Message.EventResponseMessage.decode(e,e.uint32());break}case 2:{s.pollVote=p.proto.Message.PollVoteMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LegacyMessage)return e;var a=new p.proto.LegacyMessage;if(e.eventResponseMessage!=null){if(typeof e.eventResponseMessage!="object")throw TypeError(".proto.LegacyMessage.eventResponseMessage: object expected");a.eventResponseMessage=p.proto.Message.EventResponseMessage.fromObject(e.eventResponseMessage)}if(e.pollVote!=null){if(typeof e.pollVote!="object")throw TypeError(".proto.LegacyMessage.pollVote: object expected");a.pollVote=p.proto.Message.PollVoteMessage.fromObject(e.pollVote)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.eventResponseMessage!=null&&e.hasOwnProperty("eventResponseMessage")&&(A.eventResponseMessage=p.proto.Message.EventResponseMessage.toObject(e.eventResponseMessage,a),a.oneofs&&(A._eventResponseMessage="eventResponseMessage")),e.pollVote!=null&&e.hasOwnProperty("pollVote")&&(A.pollVote=p.proto.Message.PollVoteMessage.toObject(e.pollVote,a),a.oneofs&&(A._pollVote="pollVote")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LegacyMessage"},t})(),n.LimitSharing=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.sharingLimited=e.bool();break}case 2:{s.trigger=e.int32();break}case 3:{s.limitSharingSettingTimestamp=e.int64();break}case 4:{s.initiatedByMe=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LimitSharing)return e;var a=new p.proto.LimitSharing;switch(e.sharingLimited!=null&&(a.sharingLimited=!!e.sharingLimited),e.trigger){default:if(typeof e.trigger=="number"){a.trigger=e.trigger;break}break;case"UNKNOWN":case 0:a.trigger=0;break;case"CHAT_SETTING":case 1:a.trigger=1;break;case"BIZ_SUPPORTS_FB_HOSTING":case 2:a.trigger=2;break;case"UNKNOWN_GROUP":case 3:a.trigger=3;break}return e.limitSharingSettingTimestamp!=null&&(l.Long?(a.limitSharingSettingTimestamp=l.Long.fromValue(e.limitSharingSettingTimestamp)).unsigned=!1:typeof e.limitSharingSettingTimestamp=="string"?a.limitSharingSettingTimestamp=parseInt(e.limitSharingSettingTimestamp,10):typeof e.limitSharingSettingTimestamp=="number"?a.limitSharingSettingTimestamp=e.limitSharingSettingTimestamp:typeof e.limitSharingSettingTimestamp=="object"&&(a.limitSharingSettingTimestamp=new l.LongBits(e.limitSharingSettingTimestamp.low>>>0,e.limitSharingSettingTimestamp.high>>>0).toNumber())),e.initiatedByMe!=null&&(a.initiatedByMe=!!e.initiatedByMe),a},t.toObject=function(e,a){a||(a={});var A={};return e.sharingLimited!=null&&e.hasOwnProperty("sharingLimited")&&(A.sharingLimited=e.sharingLimited,a.oneofs&&(A._sharingLimited="sharingLimited")),e.trigger!=null&&e.hasOwnProperty("trigger")&&(A.trigger=a.enums===String?p.proto.LimitSharing.TriggerType[e.trigger]===void 0?e.trigger:p.proto.LimitSharing.TriggerType[e.trigger]:e.trigger,a.oneofs&&(A._trigger="trigger")),e.limitSharingSettingTimestamp!=null&&e.hasOwnProperty("limitSharingSettingTimestamp")&&(typeof e.limitSharingSettingTimestamp=="number"?A.limitSharingSettingTimestamp=a.longs===String?String(e.limitSharingSettingTimestamp):e.limitSharingSettingTimestamp:A.limitSharingSettingTimestamp=a.longs===String?se(e.limitSharingSettingTimestamp):a.longs===Number?ge(e.limitSharingSettingTimestamp):e.limitSharingSettingTimestamp,a.oneofs&&(A._limitSharingSettingTimestamp="limitSharingSettingTimestamp")),e.initiatedByMe!=null&&e.hasOwnProperty("initiatedByMe")&&(A.initiatedByMe=e.initiatedByMe,a.oneofs&&(A._initiatedByMe="initiatedByMe")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LimitSharing"},t.TriggerType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHAT_SETTING"]=1,e[i[2]="BIZ_SUPPORTS_FB_HOSTING"]=2,e[i[3]="UNKNOWN_GROUP"]=3,e})(),t})(),n.LocalizedName=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lg=e.string();break}case 2:{s.lc=e.string();break}case 3:{s.verifiedName=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LocalizedName)return e;var a=new p.proto.LocalizedName;return e.lg!=null&&(a.lg=String(e.lg)),e.lc!=null&&(a.lc=String(e.lc)),e.verifiedName!=null&&(a.verifiedName=String(e.verifiedName)),a},t.toObject=function(e,a){a||(a={});var A={};return e.lg!=null&&e.hasOwnProperty("lg")&&(A.lg=e.lg,a.oneofs&&(A._lg="lg")),e.lc!=null&&e.hasOwnProperty("lc")&&(A.lc=e.lc,a.oneofs&&(A._lc="lc")),e.verifiedName!=null&&e.hasOwnProperty("verifiedName")&&(A.verifiedName=e.verifiedName,a.oneofs&&(A._verifiedName="verifiedName")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LocalizedName"},t})(),n.Location=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.degreesLatitude=e.double();break}case 2:{s.degreesLongitude=e.double();break}case 3:{s.name=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Location)return e;var a=new p.proto.Location;return e.degreesLatitude!=null&&(a.degreesLatitude=Number(e.degreesLatitude)),e.degreesLongitude!=null&&(a.degreesLongitude=Number(e.degreesLongitude)),e.name!=null&&(a.name=String(e.name)),a},t.toObject=function(e,a){a||(a={});var A={};return e.degreesLatitude!=null&&e.hasOwnProperty("degreesLatitude")&&(A.degreesLatitude=a.json&&!isFinite(e.degreesLatitude)?String(e.degreesLatitude):e.degreesLatitude,a.oneofs&&(A._degreesLatitude="degreesLatitude")),e.degreesLongitude!=null&&e.hasOwnProperty("degreesLongitude")&&(A.degreesLongitude=a.json&&!isFinite(e.degreesLongitude)?String(e.degreesLongitude):e.degreesLongitude,a.oneofs&&(A._degreesLongitude="degreesLongitude")),e.name!=null&&e.hasOwnProperty("name")&&(A.name=e.name,a.oneofs&&(A._name="name")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Location"},t})(),n.MediaData=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.localPath=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MediaData)return e;var a=new p.proto.MediaData;return e.localPath!=null&&(a.localPath=String(e.localPath)),a},t.toObject=function(e,a){a||(a={});var A={};return e.localPath!=null&&e.hasOwnProperty("localPath")&&(A.localPath=e.localPath,a.oneofs&&(A._localPath="localPath")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MediaData"},t})(),n.MediaNotifyMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.expressPathUrl=e.string();break}case 2:{s.fileEncSha256=e.bytes();break}case 3:{s.fileLength=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MediaNotifyMessage)return e;var a=new p.proto.MediaNotifyMessage;return e.expressPathUrl!=null&&(a.expressPathUrl=String(e.expressPathUrl)),e.fileEncSha256!=null&&(typeof e.fileEncSha256=="string"?l.base64.decode(e.fileEncSha256,a.fileEncSha256=l.newBuffer(l.base64.length(e.fileEncSha256)),0):e.fileEncSha256.length>=0&&(a.fileEncSha256=e.fileEncSha256)),e.fileLength!=null&&(l.Long?(a.fileLength=l.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new l.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};return e.expressPathUrl!=null&&e.hasOwnProperty("expressPathUrl")&&(A.expressPathUrl=e.expressPathUrl,a.oneofs&&(A._expressPathUrl="expressPathUrl")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=a.bytes===String?l.base64.encode(e.fileEncSha256,0,e.fileEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileEncSha256):e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),e.fileLength!=null&&e.hasOwnProperty("fileLength")&&(typeof e.fileLength=="number"?A.fileLength=a.longs===String?String(e.fileLength):e.fileLength:A.fileLength=a.longs===String?se(e.fileLength,!0):a.longs===Number?ge(e.fileLength,!0):e.fileLength,a.oneofs&&(A._fileLength="fileLength")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MediaNotifyMessage"},t})(),n.MediaRetryNotification=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.stanzaId=e.string();break}case 2:{s.directPath=e.string();break}case 3:{s.result=e.int32();break}case 4:{s.messageSecret=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MediaRetryNotification)return e;var a=new p.proto.MediaRetryNotification;switch(e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),e.directPath!=null&&(a.directPath=String(e.directPath)),e.result){default:if(typeof e.result=="number"){a.result=e.result;break}break;case"GENERAL_ERROR":case 0:a.result=0;break;case"SUCCESS":case 1:a.result=1;break;case"NOT_FOUND":case 2:a.result=2;break;case"DECRYPTION_ERROR":case 3:a.result=3;break}return e.messageSecret!=null&&(typeof e.messageSecret=="string"?l.base64.decode(e.messageSecret,a.messageSecret=l.newBuffer(l.base64.length(e.messageSecret)),0):e.messageSecret.length>=0&&(a.messageSecret=e.messageSecret)),a},t.toObject=function(e,a){a||(a={});var A={};return e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.result!=null&&e.hasOwnProperty("result")&&(A.result=a.enums===String?p.proto.MediaRetryNotification.ResultType[e.result]===void 0?e.result:p.proto.MediaRetryNotification.ResultType[e.result]:e.result,a.oneofs&&(A._result="result")),e.messageSecret!=null&&e.hasOwnProperty("messageSecret")&&(A.messageSecret=a.bytes===String?l.base64.encode(e.messageSecret,0,e.messageSecret.length):a.bytes===Array?Array.prototype.slice.call(e.messageSecret):e.messageSecret,a.oneofs&&(A._messageSecret="messageSecret")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MediaRetryNotification"},t.ResultType=(function(){let i={},e=Object.create(i);return e[i[0]="GENERAL_ERROR"]=0,e[i[1]="SUCCESS"]=1,e[i[2]="NOT_FOUND"]=2,e[i[3]="DECRYPTION_ERROR"]=3,e})(),t})(),n.MediaVisibility=(function(){let t={},o=Object.create(t);return o[t[0]="DEFAULT"]=0,o[t[1]="OFF"]=1,o[t[2]="ON"]=2,o})(),n.MemberLabel=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.label=e.string();break}case 2:{s.labelTimestamp=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MemberLabel)return e;var a=new p.proto.MemberLabel;return e.label!=null&&(a.label=String(e.label)),e.labelTimestamp!=null&&(l.Long?(a.labelTimestamp=l.Long.fromValue(e.labelTimestamp)).unsigned=!1:typeof e.labelTimestamp=="string"?a.labelTimestamp=parseInt(e.labelTimestamp,10):typeof e.labelTimestamp=="number"?a.labelTimestamp=e.labelTimestamp:typeof e.labelTimestamp=="object"&&(a.labelTimestamp=new l.LongBits(e.labelTimestamp.low>>>0,e.labelTimestamp.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.label!=null&&e.hasOwnProperty("label")&&(A.label=e.label,a.oneofs&&(A._label="label")),e.labelTimestamp!=null&&e.hasOwnProperty("labelTimestamp")&&(typeof e.labelTimestamp=="number"?A.labelTimestamp=a.longs===String?String(e.labelTimestamp):e.labelTimestamp:A.labelTimestamp=a.longs===String?se(e.labelTimestamp):a.longs===Number?ge(e.labelTimestamp):e.labelTimestamp,a.oneofs&&(A._labelTimestamp="labelTimestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MemberLabel"},t})(),n.Message=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.conversation=e.string();break}case 2:{s.senderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.decode(e,e.uint32());break}case 3:{s.imageMessage=p.proto.Message.ImageMessage.decode(e,e.uint32());break}case 4:{s.contactMessage=p.proto.Message.ContactMessage.decode(e,e.uint32());break}case 5:{s.locationMessage=p.proto.Message.LocationMessage.decode(e,e.uint32());break}case 6:{s.extendedTextMessage=p.proto.Message.ExtendedTextMessage.decode(e,e.uint32());break}case 7:{s.documentMessage=p.proto.Message.DocumentMessage.decode(e,e.uint32());break}case 8:{s.audioMessage=p.proto.Message.AudioMessage.decode(e,e.uint32());break}case 9:{s.videoMessage=p.proto.Message.VideoMessage.decode(e,e.uint32());break}case 10:{s.call=p.proto.Message.Call.decode(e,e.uint32());break}case 11:{s.chat=p.proto.Message.Chat.decode(e,e.uint32());break}case 12:{s.protocolMessage=p.proto.Message.ProtocolMessage.decode(e,e.uint32());break}case 13:{s.contactsArrayMessage=p.proto.Message.ContactsArrayMessage.decode(e,e.uint32());break}case 14:{s.highlyStructuredMessage=p.proto.Message.HighlyStructuredMessage.decode(e,e.uint32());break}case 15:{s.fastRatchetKeySenderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.decode(e,e.uint32());break}case 16:{s.sendPaymentMessage=p.proto.Message.SendPaymentMessage.decode(e,e.uint32());break}case 18:{s.liveLocationMessage=p.proto.Message.LiveLocationMessage.decode(e,e.uint32());break}case 22:{s.requestPaymentMessage=p.proto.Message.RequestPaymentMessage.decode(e,e.uint32());break}case 23:{s.declinePaymentRequestMessage=p.proto.Message.DeclinePaymentRequestMessage.decode(e,e.uint32());break}case 24:{s.cancelPaymentRequestMessage=p.proto.Message.CancelPaymentRequestMessage.decode(e,e.uint32());break}case 25:{s.templateMessage=p.proto.Message.TemplateMessage.decode(e,e.uint32());break}case 26:{s.stickerMessage=p.proto.Message.StickerMessage.decode(e,e.uint32());break}case 28:{s.groupInviteMessage=p.proto.Message.GroupInviteMessage.decode(e,e.uint32());break}case 29:{s.templateButtonReplyMessage=p.proto.Message.TemplateButtonReplyMessage.decode(e,e.uint32());break}case 30:{s.productMessage=p.proto.Message.ProductMessage.decode(e,e.uint32());break}case 31:{s.deviceSentMessage=p.proto.Message.DeviceSentMessage.decode(e,e.uint32());break}case 35:{s.messageContextInfo=p.proto.MessageContextInfo.decode(e,e.uint32());break}case 36:{s.listMessage=p.proto.Message.ListMessage.decode(e,e.uint32());break}case 37:{s.viewOnceMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 38:{s.orderMessage=p.proto.Message.OrderMessage.decode(e,e.uint32());break}case 39:{s.listResponseMessage=p.proto.Message.ListResponseMessage.decode(e,e.uint32());break}case 40:{s.ephemeralMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 41:{s.invoiceMessage=p.proto.Message.InvoiceMessage.decode(e,e.uint32());break}case 42:{s.buttonsMessage=p.proto.Message.ButtonsMessage.decode(e,e.uint32());break}case 43:{s.buttonsResponseMessage=p.proto.Message.ButtonsResponseMessage.decode(e,e.uint32());break}case 44:{s.paymentInviteMessage=p.proto.Message.PaymentInviteMessage.decode(e,e.uint32());break}case 45:{s.interactiveMessage=p.proto.Message.InteractiveMessage.decode(e,e.uint32());break}case 46:{s.reactionMessage=p.proto.Message.ReactionMessage.decode(e,e.uint32());break}case 47:{s.stickerSyncRmrMessage=p.proto.Message.StickerSyncRMRMessage.decode(e,e.uint32());break}case 48:{s.interactiveResponseMessage=p.proto.Message.InteractiveResponseMessage.decode(e,e.uint32());break}case 49:{s.pollCreationMessage=p.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 50:{s.pollUpdateMessage=p.proto.Message.PollUpdateMessage.decode(e,e.uint32());break}case 51:{s.keepInChatMessage=p.proto.Message.KeepInChatMessage.decode(e,e.uint32());break}case 53:{s.documentWithCaptionMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 54:{s.requestPhoneNumberMessage=p.proto.Message.RequestPhoneNumberMessage.decode(e,e.uint32());break}case 55:{s.viewOnceMessageV2=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 56:{s.encReactionMessage=p.proto.Message.EncReactionMessage.decode(e,e.uint32());break}case 58:{s.editedMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 59:{s.viewOnceMessageV2Extension=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 60:{s.pollCreationMessageV2=p.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 61:{s.scheduledCallCreationMessage=p.proto.Message.ScheduledCallCreationMessage.decode(e,e.uint32());break}case 62:{s.groupMentionedMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 63:{s.pinInChatMessage=p.proto.Message.PinInChatMessage.decode(e,e.uint32());break}case 64:{s.pollCreationMessageV3=p.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 65:{s.scheduledCallEditMessage=p.proto.Message.ScheduledCallEditMessage.decode(e,e.uint32());break}case 66:{s.ptvMessage=p.proto.Message.VideoMessage.decode(e,e.uint32());break}case 67:{s.botInvokeMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 69:{s.callLogMesssage=p.proto.Message.CallLogMessage.decode(e,e.uint32());break}case 70:{s.messageHistoryBundle=p.proto.Message.MessageHistoryBundle.decode(e,e.uint32());break}case 71:{s.encCommentMessage=p.proto.Message.EncCommentMessage.decode(e,e.uint32());break}case 72:{s.bcallMessage=p.proto.Message.BCallMessage.decode(e,e.uint32());break}case 74:{s.lottieStickerMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 75:{s.eventMessage=p.proto.Message.EventMessage.decode(e,e.uint32());break}case 76:{s.encEventResponseMessage=p.proto.Message.EncEventResponseMessage.decode(e,e.uint32());break}case 77:{s.commentMessage=p.proto.Message.CommentMessage.decode(e,e.uint32());break}case 78:{s.newsletterAdminInviteMessage=p.proto.Message.NewsletterAdminInviteMessage.decode(e,e.uint32());break}case 80:{s.placeholderMessage=p.proto.Message.PlaceholderMessage.decode(e,e.uint32());break}case 82:{s.secretEncryptedMessage=p.proto.Message.SecretEncryptedMessage.decode(e,e.uint32());break}case 83:{s.albumMessage=p.proto.Message.AlbumMessage.decode(e,e.uint32());break}case 85:{s.eventCoverImage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 86:{s.stickerPackMessage=p.proto.Message.StickerPackMessage.decode(e,e.uint32());break}case 87:{s.statusMentionMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 88:{s.pollResultSnapshotMessage=p.proto.Message.PollResultSnapshotMessage.decode(e,e.uint32());break}case 90:{s.pollCreationOptionImageMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 91:{s.associatedChildMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 92:{s.groupStatusMentionMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 93:{s.pollCreationMessageV4=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 95:{s.statusAddYours=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 96:{s.groupStatusMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 97:{s.richResponseMessage=p.proto.AIRichResponseMessage.decode(e,e.uint32());break}case 98:{s.statusNotificationMessage=p.proto.Message.StatusNotificationMessage.decode(e,e.uint32());break}case 99:{s.limitSharingMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 100:{s.botTaskMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 101:{s.questionMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 102:{s.messageHistoryNotice=p.proto.Message.MessageHistoryNotice.decode(e,e.uint32());break}case 103:{s.groupStatusMessageV2=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 104:{s.botForwardedMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 105:{s.statusQuestionAnswerMessage=p.proto.Message.StatusQuestionAnswerMessage.decode(e,e.uint32());break}case 106:{s.questionReplyMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 107:{s.questionResponseMessage=p.proto.Message.QuestionResponseMessage.decode(e,e.uint32());break}case 109:{s.statusQuotedMessage=p.proto.Message.StatusQuotedMessage.decode(e,e.uint32());break}case 110:{s.statusStickerInteractionMessage=p.proto.Message.StatusStickerInteractionMessage.decode(e,e.uint32());break}case 111:{s.pollCreationMessageV5=p.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 113:{s.newsletterFollowerInviteMessageV2=p.proto.Message.NewsletterFollowerInviteMessage.decode(e,e.uint32());break}case 114:{s.pollResultSnapshotMessageV3=p.proto.Message.PollResultSnapshotMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Message)return e;var a=new p.proto.Message;if(e.conversation!=null&&(a.conversation=String(e.conversation)),e.senderKeyDistributionMessage!=null){if(typeof e.senderKeyDistributionMessage!="object")throw TypeError(".proto.Message.senderKeyDistributionMessage: object expected");a.senderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.fromObject(e.senderKeyDistributionMessage)}if(e.imageMessage!=null){if(typeof e.imageMessage!="object")throw TypeError(".proto.Message.imageMessage: object expected");a.imageMessage=p.proto.Message.ImageMessage.fromObject(e.imageMessage)}if(e.contactMessage!=null){if(typeof e.contactMessage!="object")throw TypeError(".proto.Message.contactMessage: object expected");a.contactMessage=p.proto.Message.ContactMessage.fromObject(e.contactMessage)}if(e.locationMessage!=null){if(typeof e.locationMessage!="object")throw TypeError(".proto.Message.locationMessage: object expected");a.locationMessage=p.proto.Message.LocationMessage.fromObject(e.locationMessage)}if(e.extendedTextMessage!=null){if(typeof e.extendedTextMessage!="object")throw TypeError(".proto.Message.extendedTextMessage: object expected");a.extendedTextMessage=p.proto.Message.ExtendedTextMessage.fromObject(e.extendedTextMessage)}if(e.documentMessage!=null){if(typeof e.documentMessage!="object")throw TypeError(".proto.Message.documentMessage: object expected");a.documentMessage=p.proto.Message.DocumentMessage.fromObject(e.documentMessage)}if(e.audioMessage!=null){if(typeof e.audioMessage!="object")throw TypeError(".proto.Message.audioMessage: object expected");a.audioMessage=p.proto.Message.AudioMessage.fromObject(e.audioMessage)}if(e.videoMessage!=null){if(typeof e.videoMessage!="object")throw TypeError(".proto.Message.videoMessage: object expected");a.videoMessage=p.proto.Message.VideoMessage.fromObject(e.videoMessage)}if(e.call!=null){if(typeof e.call!="object")throw TypeError(".proto.Message.call: object expected");a.call=p.proto.Message.Call.fromObject(e.call)}if(e.chat!=null){if(typeof e.chat!="object")throw TypeError(".proto.Message.chat: object expected");a.chat=p.proto.Message.Chat.fromObject(e.chat)}if(e.protocolMessage!=null){if(typeof e.protocolMessage!="object")throw TypeError(".proto.Message.protocolMessage: object expected");a.protocolMessage=p.proto.Message.ProtocolMessage.fromObject(e.protocolMessage)}if(e.contactsArrayMessage!=null){if(typeof e.contactsArrayMessage!="object")throw TypeError(".proto.Message.contactsArrayMessage: object expected");a.contactsArrayMessage=p.proto.Message.ContactsArrayMessage.fromObject(e.contactsArrayMessage)}if(e.highlyStructuredMessage!=null){if(typeof e.highlyStructuredMessage!="object")throw TypeError(".proto.Message.highlyStructuredMessage: object expected");a.highlyStructuredMessage=p.proto.Message.HighlyStructuredMessage.fromObject(e.highlyStructuredMessage)}if(e.fastRatchetKeySenderKeyDistributionMessage!=null){if(typeof e.fastRatchetKeySenderKeyDistributionMessage!="object")throw TypeError(".proto.Message.fastRatchetKeySenderKeyDistributionMessage: object expected");a.fastRatchetKeySenderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.fromObject(e.fastRatchetKeySenderKeyDistributionMessage)}if(e.sendPaymentMessage!=null){if(typeof e.sendPaymentMessage!="object")throw TypeError(".proto.Message.sendPaymentMessage: object expected");a.sendPaymentMessage=p.proto.Message.SendPaymentMessage.fromObject(e.sendPaymentMessage)}if(e.liveLocationMessage!=null){if(typeof e.liveLocationMessage!="object")throw TypeError(".proto.Message.liveLocationMessage: object expected");a.liveLocationMessage=p.proto.Message.LiveLocationMessage.fromObject(e.liveLocationMessage)}if(e.requestPaymentMessage!=null){if(typeof e.requestPaymentMessage!="object")throw TypeError(".proto.Message.requestPaymentMessage: object expected");a.requestPaymentMessage=p.proto.Message.RequestPaymentMessage.fromObject(e.requestPaymentMessage)}if(e.declinePaymentRequestMessage!=null){if(typeof e.declinePaymentRequestMessage!="object")throw TypeError(".proto.Message.declinePaymentRequestMessage: object expected");a.declinePaymentRequestMessage=p.proto.Message.DeclinePaymentRequestMessage.fromObject(e.declinePaymentRequestMessage)}if(e.cancelPaymentRequestMessage!=null){if(typeof e.cancelPaymentRequestMessage!="object")throw TypeError(".proto.Message.cancelPaymentRequestMessage: object expected");a.cancelPaymentRequestMessage=p.proto.Message.CancelPaymentRequestMessage.fromObject(e.cancelPaymentRequestMessage)}if(e.templateMessage!=null){if(typeof e.templateMessage!="object")throw TypeError(".proto.Message.templateMessage: object expected");a.templateMessage=p.proto.Message.TemplateMessage.fromObject(e.templateMessage)}if(e.stickerMessage!=null){if(typeof e.stickerMessage!="object")throw TypeError(".proto.Message.stickerMessage: object expected");a.stickerMessage=p.proto.Message.StickerMessage.fromObject(e.stickerMessage)}if(e.groupInviteMessage!=null){if(typeof e.groupInviteMessage!="object")throw TypeError(".proto.Message.groupInviteMessage: object expected");a.groupInviteMessage=p.proto.Message.GroupInviteMessage.fromObject(e.groupInviteMessage)}if(e.templateButtonReplyMessage!=null){if(typeof e.templateButtonReplyMessage!="object")throw TypeError(".proto.Message.templateButtonReplyMessage: object expected");a.templateButtonReplyMessage=p.proto.Message.TemplateButtonReplyMessage.fromObject(e.templateButtonReplyMessage)}if(e.productMessage!=null){if(typeof e.productMessage!="object")throw TypeError(".proto.Message.productMessage: object expected");a.productMessage=p.proto.Message.ProductMessage.fromObject(e.productMessage)}if(e.deviceSentMessage!=null){if(typeof e.deviceSentMessage!="object")throw TypeError(".proto.Message.deviceSentMessage: object expected");a.deviceSentMessage=p.proto.Message.DeviceSentMessage.fromObject(e.deviceSentMessage)}if(e.messageContextInfo!=null){if(typeof e.messageContextInfo!="object")throw TypeError(".proto.Message.messageContextInfo: object expected");a.messageContextInfo=p.proto.MessageContextInfo.fromObject(e.messageContextInfo)}if(e.listMessage!=null){if(typeof e.listMessage!="object")throw TypeError(".proto.Message.listMessage: object expected");a.listMessage=p.proto.Message.ListMessage.fromObject(e.listMessage)}if(e.viewOnceMessage!=null){if(typeof e.viewOnceMessage!="object")throw TypeError(".proto.Message.viewOnceMessage: object expected");a.viewOnceMessage=p.proto.Message.FutureProofMessage.fromObject(e.viewOnceMessage)}if(e.orderMessage!=null){if(typeof e.orderMessage!="object")throw TypeError(".proto.Message.orderMessage: object expected");a.orderMessage=p.proto.Message.OrderMessage.fromObject(e.orderMessage)}if(e.listResponseMessage!=null){if(typeof e.listResponseMessage!="object")throw TypeError(".proto.Message.listResponseMessage: object expected");a.listResponseMessage=p.proto.Message.ListResponseMessage.fromObject(e.listResponseMessage)}if(e.ephemeralMessage!=null){if(typeof e.ephemeralMessage!="object")throw TypeError(".proto.Message.ephemeralMessage: object expected");a.ephemeralMessage=p.proto.Message.FutureProofMessage.fromObject(e.ephemeralMessage)}if(e.invoiceMessage!=null){if(typeof e.invoiceMessage!="object")throw TypeError(".proto.Message.invoiceMessage: object expected");a.invoiceMessage=p.proto.Message.InvoiceMessage.fromObject(e.invoiceMessage)}if(e.buttonsMessage!=null){if(typeof e.buttonsMessage!="object")throw TypeError(".proto.Message.buttonsMessage: object expected");a.buttonsMessage=p.proto.Message.ButtonsMessage.fromObject(e.buttonsMessage)}if(e.buttonsResponseMessage!=null){if(typeof e.buttonsResponseMessage!="object")throw TypeError(".proto.Message.buttonsResponseMessage: object expected");a.buttonsResponseMessage=p.proto.Message.ButtonsResponseMessage.fromObject(e.buttonsResponseMessage)}if(e.paymentInviteMessage!=null){if(typeof e.paymentInviteMessage!="object")throw TypeError(".proto.Message.paymentInviteMessage: object expected");a.paymentInviteMessage=p.proto.Message.PaymentInviteMessage.fromObject(e.paymentInviteMessage)}if(e.interactiveMessage!=null){if(typeof e.interactiveMessage!="object")throw TypeError(".proto.Message.interactiveMessage: object expected");a.interactiveMessage=p.proto.Message.InteractiveMessage.fromObject(e.interactiveMessage)}if(e.reactionMessage!=null){if(typeof e.reactionMessage!="object")throw TypeError(".proto.Message.reactionMessage: object expected");a.reactionMessage=p.proto.Message.ReactionMessage.fromObject(e.reactionMessage)}if(e.stickerSyncRmrMessage!=null){if(typeof e.stickerSyncRmrMessage!="object")throw TypeError(".proto.Message.stickerSyncRmrMessage: object expected");a.stickerSyncRmrMessage=p.proto.Message.StickerSyncRMRMessage.fromObject(e.stickerSyncRmrMessage)}if(e.interactiveResponseMessage!=null){if(typeof e.interactiveResponseMessage!="object")throw TypeError(".proto.Message.interactiveResponseMessage: object expected");a.interactiveResponseMessage=p.proto.Message.InteractiveResponseMessage.fromObject(e.interactiveResponseMessage)}if(e.pollCreationMessage!=null){if(typeof e.pollCreationMessage!="object")throw TypeError(".proto.Message.pollCreationMessage: object expected");a.pollCreationMessage=p.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessage)}if(e.pollUpdateMessage!=null){if(typeof e.pollUpdateMessage!="object")throw TypeError(".proto.Message.pollUpdateMessage: object expected");a.pollUpdateMessage=p.proto.Message.PollUpdateMessage.fromObject(e.pollUpdateMessage)}if(e.keepInChatMessage!=null){if(typeof e.keepInChatMessage!="object")throw TypeError(".proto.Message.keepInChatMessage: object expected");a.keepInChatMessage=p.proto.Message.KeepInChatMessage.fromObject(e.keepInChatMessage)}if(e.documentWithCaptionMessage!=null){if(typeof e.documentWithCaptionMessage!="object")throw TypeError(".proto.Message.documentWithCaptionMessage: object expected");a.documentWithCaptionMessage=p.proto.Message.FutureProofMessage.fromObject(e.documentWithCaptionMessage)}if(e.requestPhoneNumberMessage!=null){if(typeof e.requestPhoneNumberMessage!="object")throw TypeError(".proto.Message.requestPhoneNumberMessage: object expected");a.requestPhoneNumberMessage=p.proto.Message.RequestPhoneNumberMessage.fromObject(e.requestPhoneNumberMessage)}if(e.viewOnceMessageV2!=null){if(typeof e.viewOnceMessageV2!="object")throw TypeError(".proto.Message.viewOnceMessageV2: object expected");a.viewOnceMessageV2=p.proto.Message.FutureProofMessage.fromObject(e.viewOnceMessageV2)}if(e.encReactionMessage!=null){if(typeof e.encReactionMessage!="object")throw TypeError(".proto.Message.encReactionMessage: object expected");a.encReactionMessage=p.proto.Message.EncReactionMessage.fromObject(e.encReactionMessage)}if(e.editedMessage!=null){if(typeof e.editedMessage!="object")throw TypeError(".proto.Message.editedMessage: object expected");a.editedMessage=p.proto.Message.FutureProofMessage.fromObject(e.editedMessage)}if(e.viewOnceMessageV2Extension!=null){if(typeof e.viewOnceMessageV2Extension!="object")throw TypeError(".proto.Message.viewOnceMessageV2Extension: object expected");a.viewOnceMessageV2Extension=p.proto.Message.FutureProofMessage.fromObject(e.viewOnceMessageV2Extension)}if(e.pollCreationMessageV2!=null){if(typeof e.pollCreationMessageV2!="object")throw TypeError(".proto.Message.pollCreationMessageV2: object expected");a.pollCreationMessageV2=p.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessageV2)}if(e.scheduledCallCreationMessage!=null){if(typeof e.scheduledCallCreationMessage!="object")throw TypeError(".proto.Message.scheduledCallCreationMessage: object expected");a.scheduledCallCreationMessage=p.proto.Message.ScheduledCallCreationMessage.fromObject(e.scheduledCallCreationMessage)}if(e.groupMentionedMessage!=null){if(typeof e.groupMentionedMessage!="object")throw TypeError(".proto.Message.groupMentionedMessage: object expected");a.groupMentionedMessage=p.proto.Message.FutureProofMessage.fromObject(e.groupMentionedMessage)}if(e.pinInChatMessage!=null){if(typeof e.pinInChatMessage!="object")throw TypeError(".proto.Message.pinInChatMessage: object expected");a.pinInChatMessage=p.proto.Message.PinInChatMessage.fromObject(e.pinInChatMessage)}if(e.pollCreationMessageV3!=null){if(typeof e.pollCreationMessageV3!="object")throw TypeError(".proto.Message.pollCreationMessageV3: object expected");a.pollCreationMessageV3=p.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessageV3)}if(e.scheduledCallEditMessage!=null){if(typeof e.scheduledCallEditMessage!="object")throw TypeError(".proto.Message.scheduledCallEditMessage: object expected");a.scheduledCallEditMessage=p.proto.Message.ScheduledCallEditMessage.fromObject(e.scheduledCallEditMessage)}if(e.ptvMessage!=null){if(typeof e.ptvMessage!="object")throw TypeError(".proto.Message.ptvMessage: object expected");a.ptvMessage=p.proto.Message.VideoMessage.fromObject(e.ptvMessage)}if(e.botInvokeMessage!=null){if(typeof e.botInvokeMessage!="object")throw TypeError(".proto.Message.botInvokeMessage: object expected");a.botInvokeMessage=p.proto.Message.FutureProofMessage.fromObject(e.botInvokeMessage)}if(e.callLogMesssage!=null){if(typeof e.callLogMesssage!="object")throw TypeError(".proto.Message.callLogMesssage: object expected");a.callLogMesssage=p.proto.Message.CallLogMessage.fromObject(e.callLogMesssage)}if(e.messageHistoryBundle!=null){if(typeof e.messageHistoryBundle!="object")throw TypeError(".proto.Message.messageHistoryBundle: object expected");a.messageHistoryBundle=p.proto.Message.MessageHistoryBundle.fromObject(e.messageHistoryBundle)}if(e.encCommentMessage!=null){if(typeof e.encCommentMessage!="object")throw TypeError(".proto.Message.encCommentMessage: object expected");a.encCommentMessage=p.proto.Message.EncCommentMessage.fromObject(e.encCommentMessage)}if(e.bcallMessage!=null){if(typeof e.bcallMessage!="object")throw TypeError(".proto.Message.bcallMessage: object expected");a.bcallMessage=p.proto.Message.BCallMessage.fromObject(e.bcallMessage)}if(e.lottieStickerMessage!=null){if(typeof e.lottieStickerMessage!="object")throw TypeError(".proto.Message.lottieStickerMessage: object expected");a.lottieStickerMessage=p.proto.Message.FutureProofMessage.fromObject(e.lottieStickerMessage)}if(e.eventMessage!=null){if(typeof e.eventMessage!="object")throw TypeError(".proto.Message.eventMessage: object expected");a.eventMessage=p.proto.Message.EventMessage.fromObject(e.eventMessage)}if(e.encEventResponseMessage!=null){if(typeof e.encEventResponseMessage!="object")throw TypeError(".proto.Message.encEventResponseMessage: object expected");a.encEventResponseMessage=p.proto.Message.EncEventResponseMessage.fromObject(e.encEventResponseMessage)}if(e.commentMessage!=null){if(typeof e.commentMessage!="object")throw TypeError(".proto.Message.commentMessage: object expected");a.commentMessage=p.proto.Message.CommentMessage.fromObject(e.commentMessage)}if(e.newsletterAdminInviteMessage!=null){if(typeof e.newsletterAdminInviteMessage!="object")throw TypeError(".proto.Message.newsletterAdminInviteMessage: object expected");a.newsletterAdminInviteMessage=p.proto.Message.NewsletterAdminInviteMessage.fromObject(e.newsletterAdminInviteMessage)}if(e.placeholderMessage!=null){if(typeof e.placeholderMessage!="object")throw TypeError(".proto.Message.placeholderMessage: object expected");a.placeholderMessage=p.proto.Message.PlaceholderMessage.fromObject(e.placeholderMessage)}if(e.secretEncryptedMessage!=null){if(typeof e.secretEncryptedMessage!="object")throw TypeError(".proto.Message.secretEncryptedMessage: object expected");a.secretEncryptedMessage=p.proto.Message.SecretEncryptedMessage.fromObject(e.secretEncryptedMessage)}if(e.albumMessage!=null){if(typeof e.albumMessage!="object")throw TypeError(".proto.Message.albumMessage: object expected");a.albumMessage=p.proto.Message.AlbumMessage.fromObject(e.albumMessage)}if(e.eventCoverImage!=null){if(typeof e.eventCoverImage!="object")throw TypeError(".proto.Message.eventCoverImage: object expected");a.eventCoverImage=p.proto.Message.FutureProofMessage.fromObject(e.eventCoverImage)}if(e.stickerPackMessage!=null){if(typeof e.stickerPackMessage!="object")throw TypeError(".proto.Message.stickerPackMessage: object expected");a.stickerPackMessage=p.proto.Message.StickerPackMessage.fromObject(e.stickerPackMessage)}if(e.statusMentionMessage!=null){if(typeof e.statusMentionMessage!="object")throw TypeError(".proto.Message.statusMentionMessage: object expected");a.statusMentionMessage=p.proto.Message.FutureProofMessage.fromObject(e.statusMentionMessage)}if(e.pollResultSnapshotMessage!=null){if(typeof e.pollResultSnapshotMessage!="object")throw TypeError(".proto.Message.pollResultSnapshotMessage: object expected");a.pollResultSnapshotMessage=p.proto.Message.PollResultSnapshotMessage.fromObject(e.pollResultSnapshotMessage)}if(e.pollCreationOptionImageMessage!=null){if(typeof e.pollCreationOptionImageMessage!="object")throw TypeError(".proto.Message.pollCreationOptionImageMessage: object expected");a.pollCreationOptionImageMessage=p.proto.Message.FutureProofMessage.fromObject(e.pollCreationOptionImageMessage)}if(e.associatedChildMessage!=null){if(typeof e.associatedChildMessage!="object")throw TypeError(".proto.Message.associatedChildMessage: object expected");a.associatedChildMessage=p.proto.Message.FutureProofMessage.fromObject(e.associatedChildMessage)}if(e.groupStatusMentionMessage!=null){if(typeof e.groupStatusMentionMessage!="object")throw TypeError(".proto.Message.groupStatusMentionMessage: object expected");a.groupStatusMentionMessage=p.proto.Message.FutureProofMessage.fromObject(e.groupStatusMentionMessage)}if(e.pollCreationMessageV4!=null){if(typeof e.pollCreationMessageV4!="object")throw TypeError(".proto.Message.pollCreationMessageV4: object expected");a.pollCreationMessageV4=p.proto.Message.FutureProofMessage.fromObject(e.pollCreationMessageV4)}if(e.statusAddYours!=null){if(typeof e.statusAddYours!="object")throw TypeError(".proto.Message.statusAddYours: object expected");a.statusAddYours=p.proto.Message.FutureProofMessage.fromObject(e.statusAddYours)}if(e.groupStatusMessage!=null){if(typeof e.groupStatusMessage!="object")throw TypeError(".proto.Message.groupStatusMessage: object expected");a.groupStatusMessage=p.proto.Message.FutureProofMessage.fromObject(e.groupStatusMessage)}if(e.richResponseMessage!=null){if(typeof e.richResponseMessage!="object")throw TypeError(".proto.Message.richResponseMessage: object expected");a.richResponseMessage=p.proto.AIRichResponseMessage.fromObject(e.richResponseMessage)}if(e.statusNotificationMessage!=null){if(typeof e.statusNotificationMessage!="object")throw TypeError(".proto.Message.statusNotificationMessage: object expected");a.statusNotificationMessage=p.proto.Message.StatusNotificationMessage.fromObject(e.statusNotificationMessage)}if(e.limitSharingMessage!=null){if(typeof e.limitSharingMessage!="object")throw TypeError(".proto.Message.limitSharingMessage: object expected");a.limitSharingMessage=p.proto.Message.FutureProofMessage.fromObject(e.limitSharingMessage)}if(e.botTaskMessage!=null){if(typeof e.botTaskMessage!="object")throw TypeError(".proto.Message.botTaskMessage: object expected");a.botTaskMessage=p.proto.Message.FutureProofMessage.fromObject(e.botTaskMessage)}if(e.questionMessage!=null){if(typeof e.questionMessage!="object")throw TypeError(".proto.Message.questionMessage: object expected");a.questionMessage=p.proto.Message.FutureProofMessage.fromObject(e.questionMessage)}if(e.messageHistoryNotice!=null){if(typeof e.messageHistoryNotice!="object")throw TypeError(".proto.Message.messageHistoryNotice: object expected");a.messageHistoryNotice=p.proto.Message.MessageHistoryNotice.fromObject(e.messageHistoryNotice)}if(e.groupStatusMessageV2!=null){if(typeof e.groupStatusMessageV2!="object")throw TypeError(".proto.Message.groupStatusMessageV2: object expected");a.groupStatusMessageV2=p.proto.Message.FutureProofMessage.fromObject(e.groupStatusMessageV2)}if(e.botForwardedMessage!=null){if(typeof e.botForwardedMessage!="object")throw TypeError(".proto.Message.botForwardedMessage: object expected");a.botForwardedMessage=p.proto.Message.FutureProofMessage.fromObject(e.botForwardedMessage)}if(e.statusQuestionAnswerMessage!=null){if(typeof e.statusQuestionAnswerMessage!="object")throw TypeError(".proto.Message.statusQuestionAnswerMessage: object expected");a.statusQuestionAnswerMessage=p.proto.Message.StatusQuestionAnswerMessage.fromObject(e.statusQuestionAnswerMessage)}if(e.questionReplyMessage!=null){if(typeof e.questionReplyMessage!="object")throw TypeError(".proto.Message.questionReplyMessage: object expected");a.questionReplyMessage=p.proto.Message.FutureProofMessage.fromObject(e.questionReplyMessage)}if(e.questionResponseMessage!=null){if(typeof e.questionResponseMessage!="object")throw TypeError(".proto.Message.questionResponseMessage: object expected");a.questionResponseMessage=p.proto.Message.QuestionResponseMessage.fromObject(e.questionResponseMessage)}if(e.statusQuotedMessage!=null){if(typeof e.statusQuotedMessage!="object")throw TypeError(".proto.Message.statusQuotedMessage: object expected");a.statusQuotedMessage=p.proto.Message.StatusQuotedMessage.fromObject(e.statusQuotedMessage)}if(e.statusStickerInteractionMessage!=null){if(typeof e.statusStickerInteractionMessage!="object")throw TypeError(".proto.Message.statusStickerInteractionMessage: object expected");a.statusStickerInteractionMessage=p.proto.Message.StatusStickerInteractionMessage.fromObject(e.statusStickerInteractionMessage)}if(e.pollCreationMessageV5!=null){if(typeof e.pollCreationMessageV5!="object")throw TypeError(".proto.Message.pollCreationMessageV5: object expected");a.pollCreationMessageV5=p.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessageV5)}if(e.newsletterFollowerInviteMessageV2!=null){if(typeof e.newsletterFollowerInviteMessageV2!="object")throw TypeError(".proto.Message.newsletterFollowerInviteMessageV2: object expected");a.newsletterFollowerInviteMessageV2=p.proto.Message.NewsletterFollowerInviteMessage.fromObject(e.newsletterFollowerInviteMessageV2)}if(e.pollResultSnapshotMessageV3!=null){if(typeof e.pollResultSnapshotMessageV3!="object")throw TypeError(".proto.Message.pollResultSnapshotMessageV3: object expected");a.pollResultSnapshotMessageV3=p.proto.Message.PollResultSnapshotMessage.fromObject(e.pollResultSnapshotMessageV3)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.conversation!=null&&e.hasOwnProperty("conversation")&&(A.conversation=e.conversation,a.oneofs&&(A._conversation="conversation")),e.senderKeyDistributionMessage!=null&&e.hasOwnProperty("senderKeyDistributionMessage")&&(A.senderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.toObject(e.senderKeyDistributionMessage,a),a.oneofs&&(A._senderKeyDistributionMessage="senderKeyDistributionMessage")),e.imageMessage!=null&&e.hasOwnProperty("imageMessage")&&(A.imageMessage=p.proto.Message.ImageMessage.toObject(e.imageMessage,a),a.oneofs&&(A._imageMessage="imageMessage")),e.contactMessage!=null&&e.hasOwnProperty("contactMessage")&&(A.contactMessage=p.proto.Message.ContactMessage.toObject(e.contactMessage,a),a.oneofs&&(A._contactMessage="contactMessage")),e.locationMessage!=null&&e.hasOwnProperty("locationMessage")&&(A.locationMessage=p.proto.Message.LocationMessage.toObject(e.locationMessage,a),a.oneofs&&(A._locationMessage="locationMessage")),e.extendedTextMessage!=null&&e.hasOwnProperty("extendedTextMessage")&&(A.extendedTextMessage=p.proto.Message.ExtendedTextMessage.toObject(e.extendedTextMessage,a),a.oneofs&&(A._extendedTextMessage="extendedTextMessage")),e.documentMessage!=null&&e.hasOwnProperty("documentMessage")&&(A.documentMessage=p.proto.Message.DocumentMessage.toObject(e.documentMessage,a),a.oneofs&&(A._documentMessage="documentMessage")),e.audioMessage!=null&&e.hasOwnProperty("audioMessage")&&(A.audioMessage=p.proto.Message.AudioMessage.toObject(e.audioMessage,a),a.oneofs&&(A._audioMessage="audioMessage")),e.videoMessage!=null&&e.hasOwnProperty("videoMessage")&&(A.videoMessage=p.proto.Message.VideoMessage.toObject(e.videoMessage,a),a.oneofs&&(A._videoMessage="videoMessage")),e.call!=null&&e.hasOwnProperty("call")&&(A.call=p.proto.Message.Call.toObject(e.call,a),a.oneofs&&(A._call="call")),e.chat!=null&&e.hasOwnProperty("chat")&&(A.chat=p.proto.Message.Chat.toObject(e.chat,a),a.oneofs&&(A._chat="chat")),e.protocolMessage!=null&&e.hasOwnProperty("protocolMessage")&&(A.protocolMessage=p.proto.Message.ProtocolMessage.toObject(e.protocolMessage,a),a.oneofs&&(A._protocolMessage="protocolMessage")),e.contactsArrayMessage!=null&&e.hasOwnProperty("contactsArrayMessage")&&(A.contactsArrayMessage=p.proto.Message.ContactsArrayMessage.toObject(e.contactsArrayMessage,a),a.oneofs&&(A._contactsArrayMessage="contactsArrayMessage")),e.highlyStructuredMessage!=null&&e.hasOwnProperty("highlyStructuredMessage")&&(A.highlyStructuredMessage=p.proto.Message.HighlyStructuredMessage.toObject(e.highlyStructuredMessage,a),a.oneofs&&(A._highlyStructuredMessage="highlyStructuredMessage")),e.fastRatchetKeySenderKeyDistributionMessage!=null&&e.hasOwnProperty("fastRatchetKeySenderKeyDistributionMessage")&&(A.fastRatchetKeySenderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.toObject(e.fastRatchetKeySenderKeyDistributionMessage,a),a.oneofs&&(A._fastRatchetKeySenderKeyDistributionMessage="fastRatchetKeySenderKeyDistributionMessage")),e.sendPaymentMessage!=null&&e.hasOwnProperty("sendPaymentMessage")&&(A.sendPaymentMessage=p.proto.Message.SendPaymentMessage.toObject(e.sendPaymentMessage,a),a.oneofs&&(A._sendPaymentMessage="sendPaymentMessage")),e.liveLocationMessage!=null&&e.hasOwnProperty("liveLocationMessage")&&(A.liveLocationMessage=p.proto.Message.LiveLocationMessage.toObject(e.liveLocationMessage,a),a.oneofs&&(A._liveLocationMessage="liveLocationMessage")),e.requestPaymentMessage!=null&&e.hasOwnProperty("requestPaymentMessage")&&(A.requestPaymentMessage=p.proto.Message.RequestPaymentMessage.toObject(e.requestPaymentMessage,a),a.oneofs&&(A._requestPaymentMessage="requestPaymentMessage")),e.declinePaymentRequestMessage!=null&&e.hasOwnProperty("declinePaymentRequestMessage")&&(A.declinePaymentRequestMessage=p.proto.Message.DeclinePaymentRequestMessage.toObject(e.declinePaymentRequestMessage,a),a.oneofs&&(A._declinePaymentRequestMessage="declinePaymentRequestMessage")),e.cancelPaymentRequestMessage!=null&&e.hasOwnProperty("cancelPaymentRequestMessage")&&(A.cancelPaymentRequestMessage=p.proto.Message.CancelPaymentRequestMessage.toObject(e.cancelPaymentRequestMessage,a),a.oneofs&&(A._cancelPaymentRequestMessage="cancelPaymentRequestMessage")),e.templateMessage!=null&&e.hasOwnProperty("templateMessage")&&(A.templateMessage=p.proto.Message.TemplateMessage.toObject(e.templateMessage,a),a.oneofs&&(A._templateMessage="templateMessage")),e.stickerMessage!=null&&e.hasOwnProperty("stickerMessage")&&(A.stickerMessage=p.proto.Message.StickerMessage.toObject(e.stickerMessage,a),a.oneofs&&(A._stickerMessage="stickerMessage")),e.groupInviteMessage!=null&&e.hasOwnProperty("groupInviteMessage")&&(A.groupInviteMessage=p.proto.Message.GroupInviteMessage.toObject(e.groupInviteMessage,a),a.oneofs&&(A._groupInviteMessage="groupInviteMessage")),e.templateButtonReplyMessage!=null&&e.hasOwnProperty("templateButtonReplyMessage")&&(A.templateButtonReplyMessage=p.proto.Message.TemplateButtonReplyMessage.toObject(e.templateButtonReplyMessage,a),a.oneofs&&(A._templateButtonReplyMessage="templateButtonReplyMessage")),e.productMessage!=null&&e.hasOwnProperty("productMessage")&&(A.productMessage=p.proto.Message.ProductMessage.toObject(e.productMessage,a),a.oneofs&&(A._productMessage="productMessage")),e.deviceSentMessage!=null&&e.hasOwnProperty("deviceSentMessage")&&(A.deviceSentMessage=p.proto.Message.DeviceSentMessage.toObject(e.deviceSentMessage,a),a.oneofs&&(A._deviceSentMessage="deviceSentMessage")),e.messageContextInfo!=null&&e.hasOwnProperty("messageContextInfo")&&(A.messageContextInfo=p.proto.MessageContextInfo.toObject(e.messageContextInfo,a),a.oneofs&&(A._messageContextInfo="messageContextInfo")),e.listMessage!=null&&e.hasOwnProperty("listMessage")&&(A.listMessage=p.proto.Message.ListMessage.toObject(e.listMessage,a),a.oneofs&&(A._listMessage="listMessage")),e.viewOnceMessage!=null&&e.hasOwnProperty("viewOnceMessage")&&(A.viewOnceMessage=p.proto.Message.FutureProofMessage.toObject(e.viewOnceMessage,a),a.oneofs&&(A._viewOnceMessage="viewOnceMessage")),e.orderMessage!=null&&e.hasOwnProperty("orderMessage")&&(A.orderMessage=p.proto.Message.OrderMessage.toObject(e.orderMessage,a),a.oneofs&&(A._orderMessage="orderMessage")),e.listResponseMessage!=null&&e.hasOwnProperty("listResponseMessage")&&(A.listResponseMessage=p.proto.Message.ListResponseMessage.toObject(e.listResponseMessage,a),a.oneofs&&(A._listResponseMessage="listResponseMessage")),e.ephemeralMessage!=null&&e.hasOwnProperty("ephemeralMessage")&&(A.ephemeralMessage=p.proto.Message.FutureProofMessage.toObject(e.ephemeralMessage,a),a.oneofs&&(A._ephemeralMessage="ephemeralMessage")),e.invoiceMessage!=null&&e.hasOwnProperty("invoiceMessage")&&(A.invoiceMessage=p.proto.Message.InvoiceMessage.toObject(e.invoiceMessage,a),a.oneofs&&(A._invoiceMessage="invoiceMessage")),e.buttonsMessage!=null&&e.hasOwnProperty("buttonsMessage")&&(A.buttonsMessage=p.proto.Message.ButtonsMessage.toObject(e.buttonsMessage,a),a.oneofs&&(A._buttonsMessage="buttonsMessage")),e.buttonsResponseMessage!=null&&e.hasOwnProperty("buttonsResponseMessage")&&(A.buttonsResponseMessage=p.proto.Message.ButtonsResponseMessage.toObject(e.buttonsResponseMessage,a),a.oneofs&&(A._buttonsResponseMessage="buttonsResponseMessage")),e.paymentInviteMessage!=null&&e.hasOwnProperty("paymentInviteMessage")&&(A.paymentInviteMessage=p.proto.Message.PaymentInviteMessage.toObject(e.paymentInviteMessage,a),a.oneofs&&(A._paymentInviteMessage="paymentInviteMessage")),e.interactiveMessage!=null&&e.hasOwnProperty("interactiveMessage")&&(A.interactiveMessage=p.proto.Message.InteractiveMessage.toObject(e.interactiveMessage,a),a.oneofs&&(A._interactiveMessage="interactiveMessage")),e.reactionMessage!=null&&e.hasOwnProperty("reactionMessage")&&(A.reactionMessage=p.proto.Message.ReactionMessage.toObject(e.reactionMessage,a),a.oneofs&&(A._reactionMessage="reactionMessage")),e.stickerSyncRmrMessage!=null&&e.hasOwnProperty("stickerSyncRmrMessage")&&(A.stickerSyncRmrMessage=p.proto.Message.StickerSyncRMRMessage.toObject(e.stickerSyncRmrMessage,a),a.oneofs&&(A._stickerSyncRmrMessage="stickerSyncRmrMessage")),e.interactiveResponseMessage!=null&&e.hasOwnProperty("interactiveResponseMessage")&&(A.interactiveResponseMessage=p.proto.Message.InteractiveResponseMessage.toObject(e.interactiveResponseMessage,a),a.oneofs&&(A._interactiveResponseMessage="interactiveResponseMessage")),e.pollCreationMessage!=null&&e.hasOwnProperty("pollCreationMessage")&&(A.pollCreationMessage=p.proto.Message.PollCreationMessage.toObject(e.pollCreationMessage,a),a.oneofs&&(A._pollCreationMessage="pollCreationMessage")),e.pollUpdateMessage!=null&&e.hasOwnProperty("pollUpdateMessage")&&(A.pollUpdateMessage=p.proto.Message.PollUpdateMessage.toObject(e.pollUpdateMessage,a),a.oneofs&&(A._pollUpdateMessage="pollUpdateMessage")),e.keepInChatMessage!=null&&e.hasOwnProperty("keepInChatMessage")&&(A.keepInChatMessage=p.proto.Message.KeepInChatMessage.toObject(e.keepInChatMessage,a),a.oneofs&&(A._keepInChatMessage="keepInChatMessage")),e.documentWithCaptionMessage!=null&&e.hasOwnProperty("documentWithCaptionMessage")&&(A.documentWithCaptionMessage=p.proto.Message.FutureProofMessage.toObject(e.documentWithCaptionMessage,a),a.oneofs&&(A._documentWithCaptionMessage="documentWithCaptionMessage")),e.requestPhoneNumberMessage!=null&&e.hasOwnProperty("requestPhoneNumberMessage")&&(A.requestPhoneNumberMessage=p.proto.Message.RequestPhoneNumberMessage.toObject(e.requestPhoneNumberMessage,a),a.oneofs&&(A._requestPhoneNumberMessage="requestPhoneNumberMessage")),e.viewOnceMessageV2!=null&&e.hasOwnProperty("viewOnceMessageV2")&&(A.viewOnceMessageV2=p.proto.Message.FutureProofMessage.toObject(e.viewOnceMessageV2,a),a.oneofs&&(A._viewOnceMessageV2="viewOnceMessageV2")),e.encReactionMessage!=null&&e.hasOwnProperty("encReactionMessage")&&(A.encReactionMessage=p.proto.Message.EncReactionMessage.toObject(e.encReactionMessage,a),a.oneofs&&(A._encReactionMessage="encReactionMessage")),e.editedMessage!=null&&e.hasOwnProperty("editedMessage")&&(A.editedMessage=p.proto.Message.FutureProofMessage.toObject(e.editedMessage,a),a.oneofs&&(A._editedMessage="editedMessage")),e.viewOnceMessageV2Extension!=null&&e.hasOwnProperty("viewOnceMessageV2Extension")&&(A.viewOnceMessageV2Extension=p.proto.Message.FutureProofMessage.toObject(e.viewOnceMessageV2Extension,a),a.oneofs&&(A._viewOnceMessageV2Extension="viewOnceMessageV2Extension")),e.pollCreationMessageV2!=null&&e.hasOwnProperty("pollCreationMessageV2")&&(A.pollCreationMessageV2=p.proto.Message.PollCreationMessage.toObject(e.pollCreationMessageV2,a),a.oneofs&&(A._pollCreationMessageV2="pollCreationMessageV2")),e.scheduledCallCreationMessage!=null&&e.hasOwnProperty("scheduledCallCreationMessage")&&(A.scheduledCallCreationMessage=p.proto.Message.ScheduledCallCreationMessage.toObject(e.scheduledCallCreationMessage,a),a.oneofs&&(A._scheduledCallCreationMessage="scheduledCallCreationMessage")),e.groupMentionedMessage!=null&&e.hasOwnProperty("groupMentionedMessage")&&(A.groupMentionedMessage=p.proto.Message.FutureProofMessage.toObject(e.groupMentionedMessage,a),a.oneofs&&(A._groupMentionedMessage="groupMentionedMessage")),e.pinInChatMessage!=null&&e.hasOwnProperty("pinInChatMessage")&&(A.pinInChatMessage=p.proto.Message.PinInChatMessage.toObject(e.pinInChatMessage,a),a.oneofs&&(A._pinInChatMessage="pinInChatMessage")),e.pollCreationMessageV3!=null&&e.hasOwnProperty("pollCreationMessageV3")&&(A.pollCreationMessageV3=p.proto.Message.PollCreationMessage.toObject(e.pollCreationMessageV3,a),a.oneofs&&(A._pollCreationMessageV3="pollCreationMessageV3")),e.scheduledCallEditMessage!=null&&e.hasOwnProperty("scheduledCallEditMessage")&&(A.scheduledCallEditMessage=p.proto.Message.ScheduledCallEditMessage.toObject(e.scheduledCallEditMessage,a),a.oneofs&&(A._scheduledCallEditMessage="scheduledCallEditMessage")),e.ptvMessage!=null&&e.hasOwnProperty("ptvMessage")&&(A.ptvMessage=p.proto.Message.VideoMessage.toObject(e.ptvMessage,a),a.oneofs&&(A._ptvMessage="ptvMessage")),e.botInvokeMessage!=null&&e.hasOwnProperty("botInvokeMessage")&&(A.botInvokeMessage=p.proto.Message.FutureProofMessage.toObject(e.botInvokeMessage,a),a.oneofs&&(A._botInvokeMessage="botInvokeMessage")),e.callLogMesssage!=null&&e.hasOwnProperty("callLogMesssage")&&(A.callLogMesssage=p.proto.Message.CallLogMessage.toObject(e.callLogMesssage,a),a.oneofs&&(A._callLogMesssage="callLogMesssage")),e.messageHistoryBundle!=null&&e.hasOwnProperty("messageHistoryBundle")&&(A.messageHistoryBundle=p.proto.Message.MessageHistoryBundle.toObject(e.messageHistoryBundle,a),a.oneofs&&(A._messageHistoryBundle="messageHistoryBundle")),e.encCommentMessage!=null&&e.hasOwnProperty("encCommentMessage")&&(A.encCommentMessage=p.proto.Message.EncCommentMessage.toObject(e.encCommentMessage,a),a.oneofs&&(A._encCommentMessage="encCommentMessage")),e.bcallMessage!=null&&e.hasOwnProperty("bcallMessage")&&(A.bcallMessage=p.proto.Message.BCallMessage.toObject(e.bcallMessage,a),a.oneofs&&(A._bcallMessage="bcallMessage")),e.lottieStickerMessage!=null&&e.hasOwnProperty("lottieStickerMessage")&&(A.lottieStickerMessage=p.proto.Message.FutureProofMessage.toObject(e.lottieStickerMessage,a),a.oneofs&&(A._lottieStickerMessage="lottieStickerMessage")),e.eventMessage!=null&&e.hasOwnProperty("eventMessage")&&(A.eventMessage=p.proto.Message.EventMessage.toObject(e.eventMessage,a),a.oneofs&&(A._eventMessage="eventMessage")),e.encEventResponseMessage!=null&&e.hasOwnProperty("encEventResponseMessage")&&(A.encEventResponseMessage=p.proto.Message.EncEventResponseMessage.toObject(e.encEventResponseMessage,a),a.oneofs&&(A._encEventResponseMessage="encEventResponseMessage")),e.commentMessage!=null&&e.hasOwnProperty("commentMessage")&&(A.commentMessage=p.proto.Message.CommentMessage.toObject(e.commentMessage,a),a.oneofs&&(A._commentMessage="commentMessage")),e.newsletterAdminInviteMessage!=null&&e.hasOwnProperty("newsletterAdminInviteMessage")&&(A.newsletterAdminInviteMessage=p.proto.Message.NewsletterAdminInviteMessage.toObject(e.newsletterAdminInviteMessage,a),a.oneofs&&(A._newsletterAdminInviteMessage="newsletterAdminInviteMessage")),e.placeholderMessage!=null&&e.hasOwnProperty("placeholderMessage")&&(A.placeholderMessage=p.proto.Message.PlaceholderMessage.toObject(e.placeholderMessage,a),a.oneofs&&(A._placeholderMessage="placeholderMessage")),e.secretEncryptedMessage!=null&&e.hasOwnProperty("secretEncryptedMessage")&&(A.secretEncryptedMessage=p.proto.Message.SecretEncryptedMessage.toObject(e.secretEncryptedMessage,a),a.oneofs&&(A._secretEncryptedMessage="secretEncryptedMessage")),e.albumMessage!=null&&e.hasOwnProperty("albumMessage")&&(A.albumMessage=p.proto.Message.AlbumMessage.toObject(e.albumMessage,a),a.oneofs&&(A._albumMessage="albumMessage")),e.eventCoverImage!=null&&e.hasOwnProperty("eventCoverImage")&&(A.eventCoverImage=p.proto.Message.FutureProofMessage.toObject(e.eventCoverImage,a),a.oneofs&&(A._eventCoverImage="eventCoverImage")),e.stickerPackMessage!=null&&e.hasOwnProperty("stickerPackMessage")&&(A.stickerPackMessage=p.proto.Message.StickerPackMessage.toObject(e.stickerPackMessage,a),a.oneofs&&(A._stickerPackMessage="stickerPackMessage")),e.statusMentionMessage!=null&&e.hasOwnProperty("statusMentionMessage")&&(A.statusMentionMessage=p.proto.Message.FutureProofMessage.toObject(e.statusMentionMessage,a),a.oneofs&&(A._statusMentionMessage="statusMentionMessage")),e.pollResultSnapshotMessage!=null&&e.hasOwnProperty("pollResultSnapshotMessage")&&(A.pollResultSnapshotMessage=p.proto.Message.PollResultSnapshotMessage.toObject(e.pollResultSnapshotMessage,a),a.oneofs&&(A._pollResultSnapshotMessage="pollResultSnapshotMessage")),e.pollCreationOptionImageMessage!=null&&e.hasOwnProperty("pollCreationOptionImageMessage")&&(A.pollCreationOptionImageMessage=p.proto.Message.FutureProofMessage.toObject(e.pollCreationOptionImageMessage,a),a.oneofs&&(A._pollCreationOptionImageMessage="pollCreationOptionImageMessage")),e.associatedChildMessage!=null&&e.hasOwnProperty("associatedChildMessage")&&(A.associatedChildMessage=p.proto.Message.FutureProofMessage.toObject(e.associatedChildMessage,a),a.oneofs&&(A._associatedChildMessage="associatedChildMessage")),e.groupStatusMentionMessage!=null&&e.hasOwnProperty("groupStatusMentionMessage")&&(A.groupStatusMentionMessage=p.proto.Message.FutureProofMessage.toObject(e.groupStatusMentionMessage,a),a.oneofs&&(A._groupStatusMentionMessage="groupStatusMentionMessage")),e.pollCreationMessageV4!=null&&e.hasOwnProperty("pollCreationMessageV4")&&(A.pollCreationMessageV4=p.proto.Message.FutureProofMessage.toObject(e.pollCreationMessageV4,a),a.oneofs&&(A._pollCreationMessageV4="pollCreationMessageV4")),e.statusAddYours!=null&&e.hasOwnProperty("statusAddYours")&&(A.statusAddYours=p.proto.Message.FutureProofMessage.toObject(e.statusAddYours,a),a.oneofs&&(A._statusAddYours="statusAddYours")),e.groupStatusMessage!=null&&e.hasOwnProperty("groupStatusMessage")&&(A.groupStatusMessage=p.proto.Message.FutureProofMessage.toObject(e.groupStatusMessage,a),a.oneofs&&(A._groupStatusMessage="groupStatusMessage")),e.richResponseMessage!=null&&e.hasOwnProperty("richResponseMessage")&&(A.richResponseMessage=p.proto.AIRichResponseMessage.toObject(e.richResponseMessage,a),a.oneofs&&(A._richResponseMessage="richResponseMessage")),e.statusNotificationMessage!=null&&e.hasOwnProperty("statusNotificationMessage")&&(A.statusNotificationMessage=p.proto.Message.StatusNotificationMessage.toObject(e.statusNotificationMessage,a),a.oneofs&&(A._statusNotificationMessage="statusNotificationMessage")),e.limitSharingMessage!=null&&e.hasOwnProperty("limitSharingMessage")&&(A.limitSharingMessage=p.proto.Message.FutureProofMessage.toObject(e.limitSharingMessage,a),a.oneofs&&(A._limitSharingMessage="limitSharingMessage")),e.botTaskMessage!=null&&e.hasOwnProperty("botTaskMessage")&&(A.botTaskMessage=p.proto.Message.FutureProofMessage.toObject(e.botTaskMessage,a),a.oneofs&&(A._botTaskMessage="botTaskMessage")),e.questionMessage!=null&&e.hasOwnProperty("questionMessage")&&(A.questionMessage=p.proto.Message.FutureProofMessage.toObject(e.questionMessage,a),a.oneofs&&(A._questionMessage="questionMessage")),e.messageHistoryNotice!=null&&e.hasOwnProperty("messageHistoryNotice")&&(A.messageHistoryNotice=p.proto.Message.MessageHistoryNotice.toObject(e.messageHistoryNotice,a),a.oneofs&&(A._messageHistoryNotice="messageHistoryNotice")),e.groupStatusMessageV2!=null&&e.hasOwnProperty("groupStatusMessageV2")&&(A.groupStatusMessageV2=p.proto.Message.FutureProofMessage.toObject(e.groupStatusMessageV2,a),a.oneofs&&(A._groupStatusMessageV2="groupStatusMessageV2")),e.botForwardedMessage!=null&&e.hasOwnProperty("botForwardedMessage")&&(A.botForwardedMessage=p.proto.Message.FutureProofMessage.toObject(e.botForwardedMessage,a),a.oneofs&&(A._botForwardedMessage="botForwardedMessage")),e.statusQuestionAnswerMessage!=null&&e.hasOwnProperty("statusQuestionAnswerMessage")&&(A.statusQuestionAnswerMessage=p.proto.Message.StatusQuestionAnswerMessage.toObject(e.statusQuestionAnswerMessage,a),a.oneofs&&(A._statusQuestionAnswerMessage="statusQuestionAnswerMessage")),e.questionReplyMessage!=null&&e.hasOwnProperty("questionReplyMessage")&&(A.questionReplyMessage=p.proto.Message.FutureProofMessage.toObject(e.questionReplyMessage,a),a.oneofs&&(A._questionReplyMessage="questionReplyMessage")),e.questionResponseMessage!=null&&e.hasOwnProperty("questionResponseMessage")&&(A.questionResponseMessage=p.proto.Message.QuestionResponseMessage.toObject(e.questionResponseMessage,a),a.oneofs&&(A._questionResponseMessage="questionResponseMessage")),e.statusQuotedMessage!=null&&e.hasOwnProperty("statusQuotedMessage")&&(A.statusQuotedMessage=p.proto.Message.StatusQuotedMessage.toObject(e.statusQuotedMessage,a),a.oneofs&&(A._statusQuotedMessage="statusQuotedMessage")),e.statusStickerInteractionMessage!=null&&e.hasOwnProperty("statusStickerInteractionMessage")&&(A.statusStickerInteractionMessage=p.proto.Message.StatusStickerInteractionMessage.toObject(e.statusStickerInteractionMessage,a),a.oneofs&&(A._statusStickerInteractionMessage="statusStickerInteractionMessage")),e.pollCreationMessageV5!=null&&e.hasOwnProperty("pollCreationMessageV5")&&(A.pollCreationMessageV5=p.proto.Message.PollCreationMessage.toObject(e.pollCreationMessageV5,a),a.oneofs&&(A._pollCreationMessageV5="pollCreationMessageV5")),e.newsletterFollowerInviteMessageV2!=null&&e.hasOwnProperty("newsletterFollowerInviteMessageV2")&&(A.newsletterFollowerInviteMessageV2=p.proto.Message.NewsletterFollowerInviteMessage.toObject(e.newsletterFollowerInviteMessageV2,a),a.oneofs&&(A._newsletterFollowerInviteMessageV2="newsletterFollowerInviteMessageV2")),e.pollResultSnapshotMessageV3!=null&&e.hasOwnProperty("pollResultSnapshotMessageV3")&&(A.pollResultSnapshotMessageV3=p.proto.Message.PollResultSnapshotMessage.toObject(e.pollResultSnapshotMessageV3,a),a.oneofs&&(A._pollResultSnapshotMessageV3="pollResultSnapshotMessageV3")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Message"},t.AlbumMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 2:{c.expectedImageCount=A.uint32();break}case 3:{c.expectedVideoCount=A.uint32();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AlbumMessage)return A;var r=new p.proto.Message.AlbumMessage;if(A.expectedImageCount!=null&&(r.expectedImageCount=A.expectedImageCount>>>0),A.expectedVideoCount!=null&&(r.expectedVideoCount=A.expectedVideoCount>>>0),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.AlbumMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.expectedImageCount!=null&&A.hasOwnProperty("expectedImageCount")&&(s.expectedImageCount=A.expectedImageCount,r.oneofs&&(s._expectedImageCount="expectedImageCount")),A.expectedVideoCount!=null&&A.hasOwnProperty("expectedVideoCount")&&(s.expectedVideoCount=A.expectedVideoCount,r.oneofs&&(s._expectedVideoCount="expectedVideoCount")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AlbumMessage"},i})(),t.AppStateFatalExceptionNotification=(function(){function i(a){if(this.collectionNames=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.collectionNames&&c.collectionNames.length||(c.collectionNames=[]),c.collectionNames.push(A.string());break}case 2:{c.timestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AppStateFatalExceptionNotification)return A;var r=new p.proto.Message.AppStateFatalExceptionNotification;if(A.collectionNames){if(!Array.isArray(A.collectionNames))throw TypeError(".proto.Message.AppStateFatalExceptionNotification.collectionNames: array expected");r.collectionNames=[];for(var s=0;s>>0,A.timestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.collectionNames=[]),A.collectionNames&&A.collectionNames.length){s.collectionNames=[];for(var g=0;g>>3){case 1:{c.keyId=p.proto.Message.AppStateSyncKeyId.decode(A,A.uint32());break}case 2:{c.keyData=p.proto.Message.AppStateSyncKeyData.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AppStateSyncKey)return A;var r=new p.proto.Message.AppStateSyncKey;if(A.keyId!=null){if(typeof A.keyId!="object")throw TypeError(".proto.Message.AppStateSyncKey.keyId: object expected");r.keyId=p.proto.Message.AppStateSyncKeyId.fromObject(A.keyId)}if(A.keyData!=null){if(typeof A.keyData!="object")throw TypeError(".proto.Message.AppStateSyncKey.keyData: object expected");r.keyData=p.proto.Message.AppStateSyncKeyData.fromObject(A.keyData)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.keyId!=null&&A.hasOwnProperty("keyId")&&(s.keyId=p.proto.Message.AppStateSyncKeyId.toObject(A.keyId,r),r.oneofs&&(s._keyId="keyId")),A.keyData!=null&&A.hasOwnProperty("keyData")&&(s.keyData=p.proto.Message.AppStateSyncKeyData.toObject(A.keyData,r),r.oneofs&&(s._keyData="keyData")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AppStateSyncKey"},i})(),t.AppStateSyncKeyData=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.keyData=A.bytes();break}case 2:{c.fingerprint=p.proto.Message.AppStateSyncKeyFingerprint.decode(A,A.uint32());break}case 3:{c.timestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AppStateSyncKeyData)return A;var r=new p.proto.Message.AppStateSyncKeyData;if(A.keyData!=null&&(typeof A.keyData=="string"?l.base64.decode(A.keyData,r.keyData=l.newBuffer(l.base64.length(A.keyData)),0):A.keyData.length>=0&&(r.keyData=A.keyData)),A.fingerprint!=null){if(typeof A.fingerprint!="object")throw TypeError(".proto.Message.AppStateSyncKeyData.fingerprint: object expected");r.fingerprint=p.proto.Message.AppStateSyncKeyFingerprint.fromObject(A.fingerprint)}return A.timestamp!=null&&(l.Long?(r.timestamp=l.Long.fromValue(A.timestamp)).unsigned=!1:typeof A.timestamp=="string"?r.timestamp=parseInt(A.timestamp,10):typeof A.timestamp=="number"?r.timestamp=A.timestamp:typeof A.timestamp=="object"&&(r.timestamp=new l.LongBits(A.timestamp.low>>>0,A.timestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.keyData!=null&&A.hasOwnProperty("keyData")&&(s.keyData=r.bytes===String?l.base64.encode(A.keyData,0,A.keyData.length):r.bytes===Array?Array.prototype.slice.call(A.keyData):A.keyData,r.oneofs&&(s._keyData="keyData")),A.fingerprint!=null&&A.hasOwnProperty("fingerprint")&&(s.fingerprint=p.proto.Message.AppStateSyncKeyFingerprint.toObject(A.fingerprint,r),r.oneofs&&(s._fingerprint="fingerprint")),A.timestamp!=null&&A.hasOwnProperty("timestamp")&&(typeof A.timestamp=="number"?s.timestamp=r.longs===String?String(A.timestamp):A.timestamp:s.timestamp=r.longs===String?se(A.timestamp):r.longs===Number?ge(A.timestamp):A.timestamp,r.oneofs&&(s._timestamp="timestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AppStateSyncKeyData"},i})(),t.AppStateSyncKeyFingerprint=(function(){function i(a){if(this.deviceIndexes=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.rawId=A.uint32();break}case 2:{c.currentIndex=A.uint32();break}case 3:{if(c.deviceIndexes&&c.deviceIndexes.length||(c.deviceIndexes=[]),(I&7)===2)for(var d=A.uint32()+A.pos;A.pos>>0),A.currentIndex!=null&&(r.currentIndex=A.currentIndex>>>0),A.deviceIndexes){if(!Array.isArray(A.deviceIndexes))throw TypeError(".proto.Message.AppStateSyncKeyFingerprint.deviceIndexes: array expected");r.deviceIndexes=[];for(var s=0;s>>0}return r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.deviceIndexes=[]),A.rawId!=null&&A.hasOwnProperty("rawId")&&(s.rawId=A.rawId,r.oneofs&&(s._rawId="rawId")),A.currentIndex!=null&&A.hasOwnProperty("currentIndex")&&(s.currentIndex=A.currentIndex,r.oneofs&&(s._currentIndex="currentIndex")),A.deviceIndexes&&A.deviceIndexes.length){s.deviceIndexes=[];for(var g=0;g>>3){case 1:{c.keyId=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AppStateSyncKeyId)return A;var r=new p.proto.Message.AppStateSyncKeyId;return A.keyId!=null&&(typeof A.keyId=="string"?l.base64.decode(A.keyId,r.keyId=l.newBuffer(l.base64.length(A.keyId)),0):A.keyId.length>=0&&(r.keyId=A.keyId)),r},i.toObject=function(A,r){r||(r={});var s={};return A.keyId!=null&&A.hasOwnProperty("keyId")&&(s.keyId=r.bytes===String?l.base64.encode(A.keyId,0,A.keyId.length):r.bytes===Array?Array.prototype.slice.call(A.keyId):A.keyId,r.oneofs&&(s._keyId="keyId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AppStateSyncKeyId"},i})(),t.AppStateSyncKeyRequest=(function(){function i(e){if(this.keyIds=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.keyIds&&g.keyIds.length||(g.keyIds=[]),g.keyIds.push(p.proto.Message.AppStateSyncKeyId.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.Message.AppStateSyncKeyRequest)return a;var A=new p.proto.Message.AppStateSyncKeyRequest;if(a.keyIds){if(!Array.isArray(a.keyIds))throw TypeError(".proto.Message.AppStateSyncKeyRequest.keyIds: array expected");A.keyIds=[];for(var r=0;r>>3){case 1:{g.keys&&g.keys.length||(g.keys=[]),g.keys.push(p.proto.Message.AppStateSyncKey.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.Message.AppStateSyncKeyShare)return a;var A=new p.proto.Message.AppStateSyncKeyShare;if(a.keys){if(!Array.isArray(a.keys))throw TypeError(".proto.Message.AppStateSyncKeyShare.keys: array expected");A.keys=[];for(var r=0;r>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.fileSha256=A.bytes();break}case 4:{c.fileLength=A.uint64();break}case 5:{c.seconds=A.uint32();break}case 6:{c.ptt=A.bool();break}case 7:{c.mediaKey=A.bytes();break}case 8:{c.fileEncSha256=A.bytes();break}case 9:{c.directPath=A.string();break}case 10:{c.mediaKeyTimestamp=A.int64();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.streamingSidecar=A.bytes();break}case 19:{c.waveform=A.bytes();break}case 20:{c.backgroundArgb=A.fixed32();break}case 21:{c.viewOnce=A.bool();break}case 22:{c.accessibilityLabel=A.string();break}case 23:{c.mediaKeyDomain=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AudioMessage)return A;var r=new p.proto.Message.AudioMessage;if(A.url!=null&&(r.url=String(A.url)),A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.seconds!=null&&(r.seconds=A.seconds>>>0),A.ptt!=null&&(r.ptt=!!A.ptt),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(r.directPath=String(A.directPath)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.AudioMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.streamingSidecar!=null&&(typeof A.streamingSidecar=="string"?l.base64.decode(A.streamingSidecar,r.streamingSidecar=l.newBuffer(l.base64.length(A.streamingSidecar)),0):A.streamingSidecar.length>=0&&(r.streamingSidecar=A.streamingSidecar)),A.waveform!=null&&(typeof A.waveform=="string"?l.base64.decode(A.waveform,r.waveform=l.newBuffer(l.base64.length(A.waveform)),0):A.waveform.length>=0&&(r.waveform=A.waveform)),A.backgroundArgb!=null&&(r.backgroundArgb=A.backgroundArgb>>>0),A.viewOnce!=null&&(r.viewOnce=!!A.viewOnce),A.accessibilityLabel!=null&&(r.accessibilityLabel=String(A.accessibilityLabel)),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){r.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:r.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:r.mediaKeyDomain=1;break;case"STATUS":case 2:r.mediaKeyDomain=2;break;case"CAPI":case 3:r.mediaKeyDomain=3;break;case"BOT":case 4:r.mediaKeyDomain=4;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.seconds!=null&&A.hasOwnProperty("seconds")&&(s.seconds=A.seconds,r.oneofs&&(s._seconds="seconds")),A.ptt!=null&&A.hasOwnProperty("ptt")&&(s.ptt=A.ptt,r.oneofs&&(s._ptt="ptt")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.streamingSidecar!=null&&A.hasOwnProperty("streamingSidecar")&&(s.streamingSidecar=r.bytes===String?l.base64.encode(A.streamingSidecar,0,A.streamingSidecar.length):r.bytes===Array?Array.prototype.slice.call(A.streamingSidecar):A.streamingSidecar,r.oneofs&&(s._streamingSidecar="streamingSidecar")),A.waveform!=null&&A.hasOwnProperty("waveform")&&(s.waveform=r.bytes===String?l.base64.encode(A.waveform,0,A.waveform.length):r.bytes===Array?Array.prototype.slice.call(A.waveform):A.waveform,r.oneofs&&(s._waveform="waveform")),A.backgroundArgb!=null&&A.hasOwnProperty("backgroundArgb")&&(s.backgroundArgb=A.backgroundArgb,r.oneofs&&(s._backgroundArgb="backgroundArgb")),A.viewOnce!=null&&A.hasOwnProperty("viewOnce")&&(s.viewOnce=A.viewOnce,r.oneofs&&(s._viewOnce="viewOnce")),A.accessibilityLabel!=null&&A.hasOwnProperty("accessibilityLabel")&&(s.accessibilityLabel=A.accessibilityLabel,r.oneofs&&(s._accessibilityLabel="accessibilityLabel")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=r.enums===String?p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,r.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AudioMessage"},i})(),t.BCallMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.sessionId=A.string();break}case 2:{c.mediaType=A.int32();break}case 3:{c.masterKey=A.bytes();break}case 4:{c.caption=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.BCallMessage)return A;var r=new p.proto.Message.BCallMessage;switch(A.sessionId!=null&&(r.sessionId=String(A.sessionId)),A.mediaType){default:if(typeof A.mediaType=="number"){r.mediaType=A.mediaType;break}break;case"UNKNOWN":case 0:r.mediaType=0;break;case"AUDIO":case 1:r.mediaType=1;break;case"VIDEO":case 2:r.mediaType=2;break}return A.masterKey!=null&&(typeof A.masterKey=="string"?l.base64.decode(A.masterKey,r.masterKey=l.newBuffer(l.base64.length(A.masterKey)),0):A.masterKey.length>=0&&(r.masterKey=A.masterKey)),A.caption!=null&&(r.caption=String(A.caption)),r},i.toObject=function(A,r){r||(r={});var s={};return A.sessionId!=null&&A.hasOwnProperty("sessionId")&&(s.sessionId=A.sessionId,r.oneofs&&(s._sessionId="sessionId")),A.mediaType!=null&&A.hasOwnProperty("mediaType")&&(s.mediaType=r.enums===String?p.proto.Message.BCallMessage.MediaType[A.mediaType]===void 0?A.mediaType:p.proto.Message.BCallMessage.MediaType[A.mediaType]:A.mediaType,r.oneofs&&(s._mediaType="mediaType")),A.masterKey!=null&&A.hasOwnProperty("masterKey")&&(s.masterKey=r.bytes===String?l.base64.encode(A.masterKey,0,A.masterKey.length):r.bytes===Array?Array.prototype.slice.call(A.masterKey):A.masterKey,r.oneofs&&(s._masterKey="masterKey")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.BCallMessage"},i.MediaType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="AUDIO"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),t.ButtonsMessage=(function(){function i(a){if(this.buttons=[],a)for(var A=Object.keys(a),r=0;r>>3){case 6:{c.contentText=A.string();break}case 7:{c.footerText=A.string();break}case 8:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 9:{c.buttons&&c.buttons.length||(c.buttons=[]),c.buttons.push(p.proto.Message.ButtonsMessage.Button.decode(A,A.uint32()));break}case 10:{c.headerType=A.int32();break}case 1:{c.text=A.string();break}case 2:{c.documentMessage=p.proto.Message.DocumentMessage.decode(A,A.uint32());break}case 3:{c.imageMessage=p.proto.Message.ImageMessage.decode(A,A.uint32());break}case 4:{c.videoMessage=p.proto.Message.VideoMessage.decode(A,A.uint32());break}case 5:{c.locationMessage=p.proto.Message.LocationMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ButtonsMessage)return A;var r=new p.proto.Message.ButtonsMessage;if(A.contentText!=null&&(r.contentText=String(A.contentText)),A.footerText!=null&&(r.footerText=String(A.footerText)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ButtonsMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.buttons){if(!Array.isArray(A.buttons))throw TypeError(".proto.Message.ButtonsMessage.buttons: array expected");r.buttons=[];for(var s=0;s>>3){case 1:{d.buttonId=s.string();break}case 2:{d.buttonText=p.proto.Message.ButtonsMessage.Button.ButtonText.decode(s,s.uint32());break}case 3:{d.type=s.int32();break}case 4:{d.nativeFlowInfo=p.proto.Message.ButtonsMessage.Button.NativeFlowInfo.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ButtonsMessage.Button)return s;var g=new p.proto.Message.ButtonsMessage.Button;if(s.buttonId!=null&&(g.buttonId=String(s.buttonId)),s.buttonText!=null){if(typeof s.buttonText!="object")throw TypeError(".proto.Message.ButtonsMessage.Button.buttonText: object expected");g.buttonText=p.proto.Message.ButtonsMessage.Button.ButtonText.fromObject(s.buttonText)}switch(s.type){default:if(typeof s.type=="number"){g.type=s.type;break}break;case"UNKNOWN":case 0:g.type=0;break;case"RESPONSE":case 1:g.type=1;break;case"NATIVE_FLOW":case 2:g.type=2;break}if(s.nativeFlowInfo!=null){if(typeof s.nativeFlowInfo!="object")throw TypeError(".proto.Message.ButtonsMessage.Button.nativeFlowInfo: object expected");g.nativeFlowInfo=p.proto.Message.ButtonsMessage.Button.NativeFlowInfo.fromObject(s.nativeFlowInfo)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.buttonId!=null&&s.hasOwnProperty("buttonId")&&(c.buttonId=s.buttonId,g.oneofs&&(c._buttonId="buttonId")),s.buttonText!=null&&s.hasOwnProperty("buttonText")&&(c.buttonText=p.proto.Message.ButtonsMessage.Button.ButtonText.toObject(s.buttonText,g),g.oneofs&&(c._buttonText="buttonText")),s.type!=null&&s.hasOwnProperty("type")&&(c.type=g.enums===String?p.proto.Message.ButtonsMessage.Button.Type[s.type]===void 0?s.type:p.proto.Message.ButtonsMessage.Button.Type[s.type]:s.type,g.oneofs&&(c._type="type")),s.nativeFlowInfo!=null&&s.hasOwnProperty("nativeFlowInfo")&&(c.nativeFlowInfo=p.proto.Message.ButtonsMessage.Button.NativeFlowInfo.toObject(s.nativeFlowInfo,g),g.oneofs&&(c._nativeFlowInfo="nativeFlowInfo")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ButtonsMessage.Button"},a.ButtonText=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.displayText=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.ButtonsMessage.Button.ButtonText)return c;var I=new p.proto.Message.ButtonsMessage.Button.ButtonText;return c.displayText!=null&&(I.displayText=String(c.displayText)),I},r.toObject=function(c,I){I||(I={});var d={};return c.displayText!=null&&c.hasOwnProperty("displayText")&&(d.displayText=c.displayText,I.oneofs&&(d._displayText="displayText")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.ButtonsMessage.Button.ButtonText"},r})(),a.NativeFlowInfo=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.name=c.string();break}case 2:{f.paramsJson=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.ButtonsMessage.Button.NativeFlowInfo)return c;var I=new p.proto.Message.ButtonsMessage.Button.NativeFlowInfo;return c.name!=null&&(I.name=String(c.name)),c.paramsJson!=null&&(I.paramsJson=String(c.paramsJson)),I},r.toObject=function(c,I){I||(I={});var d={};return c.name!=null&&c.hasOwnProperty("name")&&(d.name=c.name,I.oneofs&&(d._name="name")),c.paramsJson!=null&&c.hasOwnProperty("paramsJson")&&(d.paramsJson=c.paramsJson,I.oneofs&&(d._paramsJson="paramsJson")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.ButtonsMessage.Button.NativeFlowInfo"},r})(),a.Type=(function(){let r={},s=Object.create(r);return s[r[0]="UNKNOWN"]=0,s[r[1]="RESPONSE"]=1,s[r[2]="NATIVE_FLOW"]=2,s})(),a})(),i.HeaderType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="EMPTY"]=1,A[a[2]="TEXT"]=2,A[a[3]="DOCUMENT"]=3,A[a[4]="IMAGE"]=4,A[a[5]="VIDEO"]=5,A[a[6]="LOCATION"]=6,A})(),i})(),t.ButtonsResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.selectedButtonId=A.string();break}case 3:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.type=A.int32();break}case 2:{c.selectedDisplayText=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ButtonsResponseMessage)return A;var r=new p.proto.Message.ButtonsResponseMessage;if(A.selectedButtonId!=null&&(r.selectedButtonId=String(A.selectedButtonId)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ButtonsResponseMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNKNOWN":case 0:r.type=0;break;case"DISPLAY_TEXT":case 1:r.type=1;break}return A.selectedDisplayText!=null&&(r.selectedDisplayText=String(A.selectedDisplayText)),r},i.toObject=function(A,r){r||(r={});var s={};return A.selectedButtonId!=null&&A.hasOwnProperty("selectedButtonId")&&(s.selectedButtonId=A.selectedButtonId,r.oneofs&&(s._selectedButtonId="selectedButtonId")),A.selectedDisplayText!=null&&A.hasOwnProperty("selectedDisplayText")&&(s.selectedDisplayText=A.selectedDisplayText,r.oneofs&&(s.response="selectedDisplayText")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.ButtonsResponseMessage.Type[A.type]===void 0?A.type:p.proto.Message.ButtonsResponseMessage.Type[A.type]:A.type,r.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ButtonsResponseMessage"},i.Type=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="DISPLAY_TEXT"]=1,A})(),i})(),t.Call=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.callKey=A.bytes();break}case 2:{c.conversionSource=A.string();break}case 3:{c.conversionData=A.bytes();break}case 4:{c.conversionDelaySeconds=A.uint32();break}case 5:{c.ctwaSignals=A.string();break}case 6:{c.ctwaPayload=A.bytes();break}case 7:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 8:{c.nativeFlowCallButtonPayload=A.string();break}case 9:{c.deeplinkPayload=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.Call)return A;var r=new p.proto.Message.Call;if(A.callKey!=null&&(typeof A.callKey=="string"?l.base64.decode(A.callKey,r.callKey=l.newBuffer(l.base64.length(A.callKey)),0):A.callKey.length>=0&&(r.callKey=A.callKey)),A.conversionSource!=null&&(r.conversionSource=String(A.conversionSource)),A.conversionData!=null&&(typeof A.conversionData=="string"?l.base64.decode(A.conversionData,r.conversionData=l.newBuffer(l.base64.length(A.conversionData)),0):A.conversionData.length>=0&&(r.conversionData=A.conversionData)),A.conversionDelaySeconds!=null&&(r.conversionDelaySeconds=A.conversionDelaySeconds>>>0),A.ctwaSignals!=null&&(r.ctwaSignals=String(A.ctwaSignals)),A.ctwaPayload!=null&&(typeof A.ctwaPayload=="string"?l.base64.decode(A.ctwaPayload,r.ctwaPayload=l.newBuffer(l.base64.length(A.ctwaPayload)),0):A.ctwaPayload.length>=0&&(r.ctwaPayload=A.ctwaPayload)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.Call.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return A.nativeFlowCallButtonPayload!=null&&(r.nativeFlowCallButtonPayload=String(A.nativeFlowCallButtonPayload)),A.deeplinkPayload!=null&&(r.deeplinkPayload=String(A.deeplinkPayload)),r},i.toObject=function(A,r){r||(r={});var s={};return A.callKey!=null&&A.hasOwnProperty("callKey")&&(s.callKey=r.bytes===String?l.base64.encode(A.callKey,0,A.callKey.length):r.bytes===Array?Array.prototype.slice.call(A.callKey):A.callKey,r.oneofs&&(s._callKey="callKey")),A.conversionSource!=null&&A.hasOwnProperty("conversionSource")&&(s.conversionSource=A.conversionSource,r.oneofs&&(s._conversionSource="conversionSource")),A.conversionData!=null&&A.hasOwnProperty("conversionData")&&(s.conversionData=r.bytes===String?l.base64.encode(A.conversionData,0,A.conversionData.length):r.bytes===Array?Array.prototype.slice.call(A.conversionData):A.conversionData,r.oneofs&&(s._conversionData="conversionData")),A.conversionDelaySeconds!=null&&A.hasOwnProperty("conversionDelaySeconds")&&(s.conversionDelaySeconds=A.conversionDelaySeconds,r.oneofs&&(s._conversionDelaySeconds="conversionDelaySeconds")),A.ctwaSignals!=null&&A.hasOwnProperty("ctwaSignals")&&(s.ctwaSignals=A.ctwaSignals,r.oneofs&&(s._ctwaSignals="ctwaSignals")),A.ctwaPayload!=null&&A.hasOwnProperty("ctwaPayload")&&(s.ctwaPayload=r.bytes===String?l.base64.encode(A.ctwaPayload,0,A.ctwaPayload.length):r.bytes===Array?Array.prototype.slice.call(A.ctwaPayload):A.ctwaPayload,r.oneofs&&(s._ctwaPayload="ctwaPayload")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.nativeFlowCallButtonPayload!=null&&A.hasOwnProperty("nativeFlowCallButtonPayload")&&(s.nativeFlowCallButtonPayload=A.nativeFlowCallButtonPayload,r.oneofs&&(s._nativeFlowCallButtonPayload="nativeFlowCallButtonPayload")),A.deeplinkPayload!=null&&A.hasOwnProperty("deeplinkPayload")&&(s.deeplinkPayload=A.deeplinkPayload,r.oneofs&&(s._deeplinkPayload="deeplinkPayload")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.Call"},i})(),t.CallLogMessage=(function(){function i(a){if(this.participants=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isVideo=A.bool();break}case 2:{c.callOutcome=A.int32();break}case 3:{c.durationSecs=A.int64();break}case 4:{c.callType=A.int32();break}case 5:{c.participants&&c.participants.length||(c.participants=[]),c.participants.push(p.proto.Message.CallLogMessage.CallParticipant.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.CallLogMessage)return A;var r=new p.proto.Message.CallLogMessage;switch(A.isVideo!=null&&(r.isVideo=!!A.isVideo),A.callOutcome){default:if(typeof A.callOutcome=="number"){r.callOutcome=A.callOutcome;break}break;case"CONNECTED":case 0:r.callOutcome=0;break;case"MISSED":case 1:r.callOutcome=1;break;case"FAILED":case 2:r.callOutcome=2;break;case"REJECTED":case 3:r.callOutcome=3;break;case"ACCEPTED_ELSEWHERE":case 4:r.callOutcome=4;break;case"ONGOING":case 5:r.callOutcome=5;break;case"SILENCED_BY_DND":case 6:r.callOutcome=6;break;case"SILENCED_UNKNOWN_CALLER":case 7:r.callOutcome=7;break}switch(A.durationSecs!=null&&(l.Long?(r.durationSecs=l.Long.fromValue(A.durationSecs)).unsigned=!1:typeof A.durationSecs=="string"?r.durationSecs=parseInt(A.durationSecs,10):typeof A.durationSecs=="number"?r.durationSecs=A.durationSecs:typeof A.durationSecs=="object"&&(r.durationSecs=new l.LongBits(A.durationSecs.low>>>0,A.durationSecs.high>>>0).toNumber())),A.callType){default:if(typeof A.callType=="number"){r.callType=A.callType;break}break;case"REGULAR":case 0:r.callType=0;break;case"SCHEDULED_CALL":case 1:r.callType=1;break;case"VOICE_CHAT":case 2:r.callType=2;break}if(A.participants){if(!Array.isArray(A.participants))throw TypeError(".proto.Message.CallLogMessage.participants: array expected");r.participants=[];for(var s=0;s>>3){case 1:{d.jid=s.string();break}case 2:{d.callOutcome=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.CallLogMessage.CallParticipant)return s;var g=new p.proto.Message.CallLogMessage.CallParticipant;switch(s.jid!=null&&(g.jid=String(s.jid)),s.callOutcome){default:if(typeof s.callOutcome=="number"){g.callOutcome=s.callOutcome;break}break;case"CONNECTED":case 0:g.callOutcome=0;break;case"MISSED":case 1:g.callOutcome=1;break;case"FAILED":case 2:g.callOutcome=2;break;case"REJECTED":case 3:g.callOutcome=3;break;case"ACCEPTED_ELSEWHERE":case 4:g.callOutcome=4;break;case"ONGOING":case 5:g.callOutcome=5;break;case"SILENCED_BY_DND":case 6:g.callOutcome=6;break;case"SILENCED_UNKNOWN_CALLER":case 7:g.callOutcome=7;break}return g},a.toObject=function(s,g){g||(g={});var c={};return s.jid!=null&&s.hasOwnProperty("jid")&&(c.jid=s.jid,g.oneofs&&(c._jid="jid")),s.callOutcome!=null&&s.hasOwnProperty("callOutcome")&&(c.callOutcome=g.enums===String?p.proto.Message.CallLogMessage.CallOutcome[s.callOutcome]===void 0?s.callOutcome:p.proto.Message.CallLogMessage.CallOutcome[s.callOutcome]:s.callOutcome,g.oneofs&&(c._callOutcome="callOutcome")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.CallLogMessage.CallParticipant"},a})(),i.CallType=(function(){let a={},A=Object.create(a);return A[a[0]="REGULAR"]=0,A[a[1]="SCHEDULED_CALL"]=1,A[a[2]="VOICE_CHAT"]=2,A})(),i})(),t.CancelPaymentRequestMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.CancelPaymentRequestMessage)return A;var r=new p.proto.Message.CancelPaymentRequestMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.CancelPaymentRequestMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.CancelPaymentRequestMessage"},i})(),t.Chat=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayName=A.string();break}case 2:{c.id=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.Chat)return A;var r=new p.proto.Message.Chat;return A.displayName!=null&&(r.displayName=String(A.displayName)),A.id!=null&&(r.id=String(A.id)),r},i.toObject=function(A,r){r||(r={});var s={};return A.displayName!=null&&A.hasOwnProperty("displayName")&&(s.displayName=A.displayName,r.oneofs&&(s._displayName="displayName")),A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,r.oneofs&&(s._id="id")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.Chat"},i})(),t.CloudAPIThreadControlNotification=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.status=A.int32();break}case 2:{c.senderNotificationTimestampMs=A.int64();break}case 3:{c.consumerLid=A.string();break}case 4:{c.consumerPhoneNumber=A.string();break}case 5:{c.notificationContent=p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent.decode(A,A.uint32());break}case 6:{c.shouldSuppressNotification=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.CloudAPIThreadControlNotification)return A;var r=new p.proto.Message.CloudAPIThreadControlNotification;switch(A.status){default:if(typeof A.status=="number"){r.status=A.status;break}break;case"UNKNOWN":case 0:r.status=0;break;case"CONTROL_PASSED":case 1:r.status=1;break;case"CONTROL_TAKEN":case 2:r.status=2;break}if(A.senderNotificationTimestampMs!=null&&(l.Long?(r.senderNotificationTimestampMs=l.Long.fromValue(A.senderNotificationTimestampMs)).unsigned=!1:typeof A.senderNotificationTimestampMs=="string"?r.senderNotificationTimestampMs=parseInt(A.senderNotificationTimestampMs,10):typeof A.senderNotificationTimestampMs=="number"?r.senderNotificationTimestampMs=A.senderNotificationTimestampMs:typeof A.senderNotificationTimestampMs=="object"&&(r.senderNotificationTimestampMs=new l.LongBits(A.senderNotificationTimestampMs.low>>>0,A.senderNotificationTimestampMs.high>>>0).toNumber())),A.consumerLid!=null&&(r.consumerLid=String(A.consumerLid)),A.consumerPhoneNumber!=null&&(r.consumerPhoneNumber=String(A.consumerPhoneNumber)),A.notificationContent!=null){if(typeof A.notificationContent!="object")throw TypeError(".proto.Message.CloudAPIThreadControlNotification.notificationContent: object expected");r.notificationContent=p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent.fromObject(A.notificationContent)}return A.shouldSuppressNotification!=null&&(r.shouldSuppressNotification=!!A.shouldSuppressNotification),r},i.toObject=function(A,r){r||(r={});var s={};return A.status!=null&&A.hasOwnProperty("status")&&(s.status=r.enums===String?p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControl[A.status]===void 0?A.status:p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControl[A.status]:A.status,r.oneofs&&(s._status="status")),A.senderNotificationTimestampMs!=null&&A.hasOwnProperty("senderNotificationTimestampMs")&&(typeof A.senderNotificationTimestampMs=="number"?s.senderNotificationTimestampMs=r.longs===String?String(A.senderNotificationTimestampMs):A.senderNotificationTimestampMs:s.senderNotificationTimestampMs=r.longs===String?se(A.senderNotificationTimestampMs):r.longs===Number?ge(A.senderNotificationTimestampMs):A.senderNotificationTimestampMs,r.oneofs&&(s._senderNotificationTimestampMs="senderNotificationTimestampMs")),A.consumerLid!=null&&A.hasOwnProperty("consumerLid")&&(s.consumerLid=A.consumerLid,r.oneofs&&(s._consumerLid="consumerLid")),A.consumerPhoneNumber!=null&&A.hasOwnProperty("consumerPhoneNumber")&&(s.consumerPhoneNumber=A.consumerPhoneNumber,r.oneofs&&(s._consumerPhoneNumber="consumerPhoneNumber")),A.notificationContent!=null&&A.hasOwnProperty("notificationContent")&&(s.notificationContent=p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent.toObject(A.notificationContent,r),r.oneofs&&(s._notificationContent="notificationContent")),A.shouldSuppressNotification!=null&&A.hasOwnProperty("shouldSuppressNotification")&&(s.shouldSuppressNotification=A.shouldSuppressNotification,r.oneofs&&(s._shouldSuppressNotification="shouldSuppressNotification")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.CloudAPIThreadControlNotification"},i.CloudAPIThreadControl=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="CONTROL_PASSED"]=1,A[a[2]="CONTROL_TAKEN"]=2,A})(),i.CloudAPIThreadControlNotificationContent=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.handoffNotificationText=s.string();break}case 2:{d.extraJson=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent)return s;var g=new p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent;return s.handoffNotificationText!=null&&(g.handoffNotificationText=String(s.handoffNotificationText)),s.extraJson!=null&&(g.extraJson=String(s.extraJson)),g},a.toObject=function(s,g){g||(g={});var c={};return s.handoffNotificationText!=null&&s.hasOwnProperty("handoffNotificationText")&&(c.handoffNotificationText=s.handoffNotificationText,g.oneofs&&(c._handoffNotificationText="handoffNotificationText")),s.extraJson!=null&&s.hasOwnProperty("extraJson")&&(c.extraJson=s.extraJson,g.oneofs&&(c._extraJson="extraJson")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent"},a})(),i})(),t.CommentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.message=p.proto.Message.decode(A,A.uint32());break}case 2:{c.targetMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.CommentMessage)return A;var r=new p.proto.Message.CommentMessage;if(A.message!=null){if(typeof A.message!="object")throw TypeError(".proto.Message.CommentMessage.message: object expected");r.message=p.proto.Message.fromObject(A.message)}if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.CommentMessage.targetMessageKey: object expected");r.targetMessageKey=p.proto.MessageKey.fromObject(A.targetMessageKey)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.message!=null&&A.hasOwnProperty("message")&&(s.message=p.proto.Message.toObject(A.message,r),r.oneofs&&(s._message="message")),A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=p.proto.MessageKey.toObject(A.targetMessageKey,r),r.oneofs&&(s._targetMessageKey="targetMessageKey")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.CommentMessage"},i})(),t.ContactMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayName=A.string();break}case 16:{c.vcard=A.string();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ContactMessage)return A;var r=new p.proto.Message.ContactMessage;if(A.displayName!=null&&(r.displayName=String(A.displayName)),A.vcard!=null&&(r.vcard=String(A.vcard)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ContactMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.displayName!=null&&A.hasOwnProperty("displayName")&&(s.displayName=A.displayName,r.oneofs&&(s._displayName="displayName")),A.vcard!=null&&A.hasOwnProperty("vcard")&&(s.vcard=A.vcard,r.oneofs&&(s._vcard="vcard")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ContactMessage"},i})(),t.ContactsArrayMessage=(function(){function i(a){if(this.contacts=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayName=A.string();break}case 2:{c.contacts&&c.contacts.length||(c.contacts=[]),c.contacts.push(p.proto.Message.ContactMessage.decode(A,A.uint32()));break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ContactsArrayMessage)return A;var r=new p.proto.Message.ContactsArrayMessage;if(A.displayName!=null&&(r.displayName=String(A.displayName)),A.contacts){if(!Array.isArray(A.contacts))throw TypeError(".proto.Message.ContactsArrayMessage.contacts: array expected");r.contacts=[];for(var s=0;s>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.DeclinePaymentRequestMessage)return A;var r=new p.proto.Message.DeclinePaymentRequestMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.DeclinePaymentRequestMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.DeclinePaymentRequestMessage"},i})(),t.DeviceSentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.destinationJid=A.string();break}case 2:{c.message=p.proto.Message.decode(A,A.uint32());break}case 3:{c.phash=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.DeviceSentMessage)return A;var r=new p.proto.Message.DeviceSentMessage;if(A.destinationJid!=null&&(r.destinationJid=String(A.destinationJid)),A.message!=null){if(typeof A.message!="object")throw TypeError(".proto.Message.DeviceSentMessage.message: object expected");r.message=p.proto.Message.fromObject(A.message)}return A.phash!=null&&(r.phash=String(A.phash)),r},i.toObject=function(A,r){r||(r={});var s={};return A.destinationJid!=null&&A.hasOwnProperty("destinationJid")&&(s.destinationJid=A.destinationJid,r.oneofs&&(s._destinationJid="destinationJid")),A.message!=null&&A.hasOwnProperty("message")&&(s.message=p.proto.Message.toObject(A.message,r),r.oneofs&&(s._message="message")),A.phash!=null&&A.hasOwnProperty("phash")&&(s.phash=A.phash,r.oneofs&&(s._phash="phash")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.DeviceSentMessage"},i})(),t.DocumentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.title=A.string();break}case 4:{c.fileSha256=A.bytes();break}case 5:{c.fileLength=A.uint64();break}case 6:{c.pageCount=A.uint32();break}case 7:{c.mediaKey=A.bytes();break}case 8:{c.fileName=A.string();break}case 9:{c.fileEncSha256=A.bytes();break}case 10:{c.directPath=A.string();break}case 11:{c.mediaKeyTimestamp=A.int64();break}case 12:{c.contactVcard=A.bool();break}case 13:{c.thumbnailDirectPath=A.string();break}case 14:{c.thumbnailSha256=A.bytes();break}case 15:{c.thumbnailEncSha256=A.bytes();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.thumbnailHeight=A.uint32();break}case 19:{c.thumbnailWidth=A.uint32();break}case 20:{c.caption=A.string();break}case 21:{c.accessibilityLabel=A.string();break}case 22:{c.mediaKeyDomain=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.DocumentMessage)return A;var r=new p.proto.Message.DocumentMessage;if(A.url!=null&&(r.url=String(A.url)),A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.title!=null&&(r.title=String(A.title)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.pageCount!=null&&(r.pageCount=A.pageCount>>>0),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.fileName!=null&&(r.fileName=String(A.fileName)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(r.directPath=String(A.directPath)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.contactVcard!=null&&(r.contactVcard=!!A.contactVcard),A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.DocumentMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.thumbnailHeight!=null&&(r.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(r.thumbnailWidth=A.thumbnailWidth>>>0),A.caption!=null&&(r.caption=String(A.caption)),A.accessibilityLabel!=null&&(r.accessibilityLabel=String(A.accessibilityLabel)),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){r.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:r.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:r.mediaKeyDomain=1;break;case"STATUS":case 2:r.mediaKeyDomain=2;break;case"CAPI":case 3:r.mediaKeyDomain=3;break;case"BOT":case 4:r.mediaKeyDomain=4;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.pageCount!=null&&A.hasOwnProperty("pageCount")&&(s.pageCount=A.pageCount,r.oneofs&&(s._pageCount="pageCount")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.fileName!=null&&A.hasOwnProperty("fileName")&&(s.fileName=A.fileName,r.oneofs&&(s._fileName="fileName")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.contactVcard!=null&&A.hasOwnProperty("contactVcard")&&(s.contactVcard=A.contactVcard,r.oneofs&&(s._contactVcard="contactVcard")),A.thumbnailDirectPath!=null&&A.hasOwnProperty("thumbnailDirectPath")&&(s.thumbnailDirectPath=A.thumbnailDirectPath,r.oneofs&&(s._thumbnailDirectPath="thumbnailDirectPath")),A.thumbnailSha256!=null&&A.hasOwnProperty("thumbnailSha256")&&(s.thumbnailSha256=r.bytes===String?l.base64.encode(A.thumbnailSha256,0,A.thumbnailSha256.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnailSha256):A.thumbnailSha256,r.oneofs&&(s._thumbnailSha256="thumbnailSha256")),A.thumbnailEncSha256!=null&&A.hasOwnProperty("thumbnailEncSha256")&&(s.thumbnailEncSha256=r.bytes===String?l.base64.encode(A.thumbnailEncSha256,0,A.thumbnailEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnailEncSha256):A.thumbnailEncSha256,r.oneofs&&(s._thumbnailEncSha256="thumbnailEncSha256")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.thumbnailHeight!=null&&A.hasOwnProperty("thumbnailHeight")&&(s.thumbnailHeight=A.thumbnailHeight,r.oneofs&&(s._thumbnailHeight="thumbnailHeight")),A.thumbnailWidth!=null&&A.hasOwnProperty("thumbnailWidth")&&(s.thumbnailWidth=A.thumbnailWidth,r.oneofs&&(s._thumbnailWidth="thumbnailWidth")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.accessibilityLabel!=null&&A.hasOwnProperty("accessibilityLabel")&&(s.accessibilityLabel=A.accessibilityLabel,r.oneofs&&(s._accessibilityLabel="accessibilityLabel")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=r.enums===String?p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,r.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.DocumentMessage"},i})(),t.EncCommentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.targetMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.EncCommentMessage)return A;var r=new p.proto.Message.EncCommentMessage;if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.EncCommentMessage.targetMessageKey: object expected");r.targetMessageKey=p.proto.MessageKey.fromObject(A.targetMessageKey)}return A.encPayload!=null&&(typeof A.encPayload=="string"?l.base64.decode(A.encPayload,r.encPayload=l.newBuffer(l.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(r.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?l.base64.decode(A.encIv,r.encIv=l.newBuffer(l.base64.length(A.encIv)),0):A.encIv.length>=0&&(r.encIv=A.encIv)),r},i.toObject=function(A,r){r||(r={});var s={};return A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=p.proto.MessageKey.toObject(A.targetMessageKey,r),r.oneofs&&(s._targetMessageKey="targetMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=r.bytes===String?l.base64.encode(A.encPayload,0,A.encPayload.length):r.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,r.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=r.bytes===String?l.base64.encode(A.encIv,0,A.encIv.length):r.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,r.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EncCommentMessage"},i})(),t.EncEventResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.eventCreationMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.EncEventResponseMessage)return A;var r=new p.proto.Message.EncEventResponseMessage;if(A.eventCreationMessageKey!=null){if(typeof A.eventCreationMessageKey!="object")throw TypeError(".proto.Message.EncEventResponseMessage.eventCreationMessageKey: object expected");r.eventCreationMessageKey=p.proto.MessageKey.fromObject(A.eventCreationMessageKey)}return A.encPayload!=null&&(typeof A.encPayload=="string"?l.base64.decode(A.encPayload,r.encPayload=l.newBuffer(l.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(r.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?l.base64.decode(A.encIv,r.encIv=l.newBuffer(l.base64.length(A.encIv)),0):A.encIv.length>=0&&(r.encIv=A.encIv)),r},i.toObject=function(A,r){r||(r={});var s={};return A.eventCreationMessageKey!=null&&A.hasOwnProperty("eventCreationMessageKey")&&(s.eventCreationMessageKey=p.proto.MessageKey.toObject(A.eventCreationMessageKey,r),r.oneofs&&(s._eventCreationMessageKey="eventCreationMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=r.bytes===String?l.base64.encode(A.encPayload,0,A.encPayload.length):r.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,r.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=r.bytes===String?l.base64.encode(A.encIv,0,A.encIv.length):r.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,r.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EncEventResponseMessage"},i})(),t.EncReactionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.targetMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.EncReactionMessage)return A;var r=new p.proto.Message.EncReactionMessage;if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.EncReactionMessage.targetMessageKey: object expected");r.targetMessageKey=p.proto.MessageKey.fromObject(A.targetMessageKey)}return A.encPayload!=null&&(typeof A.encPayload=="string"?l.base64.decode(A.encPayload,r.encPayload=l.newBuffer(l.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(r.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?l.base64.decode(A.encIv,r.encIv=l.newBuffer(l.base64.length(A.encIv)),0):A.encIv.length>=0&&(r.encIv=A.encIv)),r},i.toObject=function(A,r){r||(r={});var s={};return A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=p.proto.MessageKey.toObject(A.targetMessageKey,r),r.oneofs&&(s._targetMessageKey="targetMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=r.bytes===String?l.base64.encode(A.encPayload,0,A.encPayload.length):r.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,r.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=r.bytes===String?l.base64.encode(A.encIv,0,A.encIv.length):r.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,r.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EncReactionMessage"},i})(),t.EventMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 2:{c.isCanceled=A.bool();break}case 3:{c.name=A.string();break}case 4:{c.description=A.string();break}case 5:{c.location=p.proto.Message.LocationMessage.decode(A,A.uint32());break}case 6:{c.joinLink=A.string();break}case 7:{c.startTime=A.int64();break}case 8:{c.endTime=A.int64();break}case 9:{c.extraGuestsAllowed=A.bool();break}case 10:{c.isScheduleCall=A.bool();break}case 11:{c.hasReminder=A.bool();break}case 12:{c.reminderOffsetSec=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.EventMessage)return A;var r=new p.proto.Message.EventMessage;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.EventMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.isCanceled!=null&&(r.isCanceled=!!A.isCanceled),A.name!=null&&(r.name=String(A.name)),A.description!=null&&(r.description=String(A.description)),A.location!=null){if(typeof A.location!="object")throw TypeError(".proto.Message.EventMessage.location: object expected");r.location=p.proto.Message.LocationMessage.fromObject(A.location)}return A.joinLink!=null&&(r.joinLink=String(A.joinLink)),A.startTime!=null&&(l.Long?(r.startTime=l.Long.fromValue(A.startTime)).unsigned=!1:typeof A.startTime=="string"?r.startTime=parseInt(A.startTime,10):typeof A.startTime=="number"?r.startTime=A.startTime:typeof A.startTime=="object"&&(r.startTime=new l.LongBits(A.startTime.low>>>0,A.startTime.high>>>0).toNumber())),A.endTime!=null&&(l.Long?(r.endTime=l.Long.fromValue(A.endTime)).unsigned=!1:typeof A.endTime=="string"?r.endTime=parseInt(A.endTime,10):typeof A.endTime=="number"?r.endTime=A.endTime:typeof A.endTime=="object"&&(r.endTime=new l.LongBits(A.endTime.low>>>0,A.endTime.high>>>0).toNumber())),A.extraGuestsAllowed!=null&&(r.extraGuestsAllowed=!!A.extraGuestsAllowed),A.isScheduleCall!=null&&(r.isScheduleCall=!!A.isScheduleCall),A.hasReminder!=null&&(r.hasReminder=!!A.hasReminder),A.reminderOffsetSec!=null&&(l.Long?(r.reminderOffsetSec=l.Long.fromValue(A.reminderOffsetSec)).unsigned=!1:typeof A.reminderOffsetSec=="string"?r.reminderOffsetSec=parseInt(A.reminderOffsetSec,10):typeof A.reminderOffsetSec=="number"?r.reminderOffsetSec=A.reminderOffsetSec:typeof A.reminderOffsetSec=="object"&&(r.reminderOffsetSec=new l.LongBits(A.reminderOffsetSec.low>>>0,A.reminderOffsetSec.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.isCanceled!=null&&A.hasOwnProperty("isCanceled")&&(s.isCanceled=A.isCanceled,r.oneofs&&(s._isCanceled="isCanceled")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.description!=null&&A.hasOwnProperty("description")&&(s.description=A.description,r.oneofs&&(s._description="description")),A.location!=null&&A.hasOwnProperty("location")&&(s.location=p.proto.Message.LocationMessage.toObject(A.location,r),r.oneofs&&(s._location="location")),A.joinLink!=null&&A.hasOwnProperty("joinLink")&&(s.joinLink=A.joinLink,r.oneofs&&(s._joinLink="joinLink")),A.startTime!=null&&A.hasOwnProperty("startTime")&&(typeof A.startTime=="number"?s.startTime=r.longs===String?String(A.startTime):A.startTime:s.startTime=r.longs===String?se(A.startTime):r.longs===Number?ge(A.startTime):A.startTime,r.oneofs&&(s._startTime="startTime")),A.endTime!=null&&A.hasOwnProperty("endTime")&&(typeof A.endTime=="number"?s.endTime=r.longs===String?String(A.endTime):A.endTime:s.endTime=r.longs===String?se(A.endTime):r.longs===Number?ge(A.endTime):A.endTime,r.oneofs&&(s._endTime="endTime")),A.extraGuestsAllowed!=null&&A.hasOwnProperty("extraGuestsAllowed")&&(s.extraGuestsAllowed=A.extraGuestsAllowed,r.oneofs&&(s._extraGuestsAllowed="extraGuestsAllowed")),A.isScheduleCall!=null&&A.hasOwnProperty("isScheduleCall")&&(s.isScheduleCall=A.isScheduleCall,r.oneofs&&(s._isScheduleCall="isScheduleCall")),A.hasReminder!=null&&A.hasOwnProperty("hasReminder")&&(s.hasReminder=A.hasReminder,r.oneofs&&(s._hasReminder="hasReminder")),A.reminderOffsetSec!=null&&A.hasOwnProperty("reminderOffsetSec")&&(typeof A.reminderOffsetSec=="number"?s.reminderOffsetSec=r.longs===String?String(A.reminderOffsetSec):A.reminderOffsetSec:s.reminderOffsetSec=r.longs===String?se(A.reminderOffsetSec):r.longs===Number?ge(A.reminderOffsetSec):A.reminderOffsetSec,r.oneofs&&(s._reminderOffsetSec="reminderOffsetSec")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EventMessage"},i})(),t.EventResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.response=A.int32();break}case 2:{c.timestampMs=A.int64();break}case 3:{c.extraGuestCount=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.EventResponseMessage)return A;var r=new p.proto.Message.EventResponseMessage;switch(A.response){default:if(typeof A.response=="number"){r.response=A.response;break}break;case"UNKNOWN":case 0:r.response=0;break;case"GOING":case 1:r.response=1;break;case"NOT_GOING":case 2:r.response=2;break;case"MAYBE":case 3:r.response=3;break}return A.timestampMs!=null&&(l.Long?(r.timestampMs=l.Long.fromValue(A.timestampMs)).unsigned=!1:typeof A.timestampMs=="string"?r.timestampMs=parseInt(A.timestampMs,10):typeof A.timestampMs=="number"?r.timestampMs=A.timestampMs:typeof A.timestampMs=="object"&&(r.timestampMs=new l.LongBits(A.timestampMs.low>>>0,A.timestampMs.high>>>0).toNumber())),A.extraGuestCount!=null&&(r.extraGuestCount=A.extraGuestCount|0),r},i.toObject=function(A,r){r||(r={});var s={};return A.response!=null&&A.hasOwnProperty("response")&&(s.response=r.enums===String?p.proto.Message.EventResponseMessage.EventResponseType[A.response]===void 0?A.response:p.proto.Message.EventResponseMessage.EventResponseType[A.response]:A.response,r.oneofs&&(s._response="response")),A.timestampMs!=null&&A.hasOwnProperty("timestampMs")&&(typeof A.timestampMs=="number"?s.timestampMs=r.longs===String?String(A.timestampMs):A.timestampMs:s.timestampMs=r.longs===String?se(A.timestampMs):r.longs===Number?ge(A.timestampMs):A.timestampMs,r.oneofs&&(s._timestampMs="timestampMs")),A.extraGuestCount!=null&&A.hasOwnProperty("extraGuestCount")&&(s.extraGuestCount=A.extraGuestCount,r.oneofs&&(s._extraGuestCount="extraGuestCount")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EventResponseMessage"},i.EventResponseType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="GOING"]=1,A[a[2]="NOT_GOING"]=2,A[a[3]="MAYBE"]=3,A})(),i})(),t.ExtendedTextMessage=(function(){function i(a){if(this.endCardTiles=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.text=A.string();break}case 2:{c.matchedText=A.string();break}case 5:{c.description=A.string();break}case 6:{c.title=A.string();break}case 7:{c.textArgb=A.fixed32();break}case 8:{c.backgroundArgb=A.fixed32();break}case 9:{c.font=A.int32();break}case 10:{c.previewType=A.int32();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.doNotPlayInline=A.bool();break}case 19:{c.thumbnailDirectPath=A.string();break}case 20:{c.thumbnailSha256=A.bytes();break}case 21:{c.thumbnailEncSha256=A.bytes();break}case 22:{c.mediaKey=A.bytes();break}case 23:{c.mediaKeyTimestamp=A.int64();break}case 24:{c.thumbnailHeight=A.uint32();break}case 25:{c.thumbnailWidth=A.uint32();break}case 26:{c.inviteLinkGroupType=A.int32();break}case 27:{c.inviteLinkParentGroupSubjectV2=A.string();break}case 28:{c.inviteLinkParentGroupThumbnailV2=A.bytes();break}case 29:{c.inviteLinkGroupTypeV2=A.int32();break}case 30:{c.viewOnce=A.bool();break}case 31:{c.videoHeight=A.uint32();break}case 32:{c.videoWidth=A.uint32();break}case 33:{c.faviconMMSMetadata=p.proto.Message.MMSThumbnailMetadata.decode(A,A.uint32());break}case 34:{c.linkPreviewMetadata=p.proto.Message.LinkPreviewMetadata.decode(A,A.uint32());break}case 35:{c.paymentLinkMetadata=p.proto.Message.PaymentLinkMetadata.decode(A,A.uint32());break}case 36:{c.endCardTiles&&c.endCardTiles.length||(c.endCardTiles=[]),c.endCardTiles.push(p.proto.Message.VideoEndCard.decode(A,A.uint32()));break}case 37:{c.videoContentUrl=A.string();break}case 38:{c.musicMetadata=p.proto.EmbeddedMusic.decode(A,A.uint32());break}case 39:{c.paymentExtendedMetadata=p.proto.Message.PaymentExtendedMetadata.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ExtendedTextMessage)return A;var r=new p.proto.Message.ExtendedTextMessage;switch(A.text!=null&&(r.text=String(A.text)),A.matchedText!=null&&(r.matchedText=String(A.matchedText)),A.description!=null&&(r.description=String(A.description)),A.title!=null&&(r.title=String(A.title)),A.textArgb!=null&&(r.textArgb=A.textArgb>>>0),A.backgroundArgb!=null&&(r.backgroundArgb=A.backgroundArgb>>>0),A.font){default:if(typeof A.font=="number"){r.font=A.font;break}break;case"SYSTEM":case 0:r.font=0;break;case"SYSTEM_TEXT":case 1:r.font=1;break;case"FB_SCRIPT":case 2:r.font=2;break;case"SYSTEM_BOLD":case 6:r.font=6;break;case"MORNINGBREEZE_REGULAR":case 7:r.font=7;break;case"CALISTOGA_REGULAR":case 8:r.font=8;break;case"EXO2_EXTRABOLD":case 9:r.font=9;break;case"COURIERPRIME_BOLD":case 10:r.font=10;break}switch(A.previewType){default:if(typeof A.previewType=="number"){r.previewType=A.previewType;break}break;case"NONE":case 0:r.previewType=0;break;case"VIDEO":case 1:r.previewType=1;break;case"PLACEHOLDER":case 4:r.previewType=4;break;case"IMAGE":case 5:r.previewType=5;break;case"PAYMENT_LINKS":case 6:r.previewType=6;break;case"PROFILE":case 7:r.previewType=7;break}if(A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ExtendedTextMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.doNotPlayInline!=null&&(r.doNotPlayInline=!!A.doNotPlayInline),A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.thumbnailHeight!=null&&(r.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(r.thumbnailWidth=A.thumbnailWidth>>>0),A.inviteLinkGroupType){default:if(typeof A.inviteLinkGroupType=="number"){r.inviteLinkGroupType=A.inviteLinkGroupType;break}break;case"DEFAULT":case 0:r.inviteLinkGroupType=0;break;case"PARENT":case 1:r.inviteLinkGroupType=1;break;case"SUB":case 2:r.inviteLinkGroupType=2;break;case"DEFAULT_SUB":case 3:r.inviteLinkGroupType=3;break}switch(A.inviteLinkParentGroupSubjectV2!=null&&(r.inviteLinkParentGroupSubjectV2=String(A.inviteLinkParentGroupSubjectV2)),A.inviteLinkParentGroupThumbnailV2!=null&&(typeof A.inviteLinkParentGroupThumbnailV2=="string"?l.base64.decode(A.inviteLinkParentGroupThumbnailV2,r.inviteLinkParentGroupThumbnailV2=l.newBuffer(l.base64.length(A.inviteLinkParentGroupThumbnailV2)),0):A.inviteLinkParentGroupThumbnailV2.length>=0&&(r.inviteLinkParentGroupThumbnailV2=A.inviteLinkParentGroupThumbnailV2)),A.inviteLinkGroupTypeV2){default:if(typeof A.inviteLinkGroupTypeV2=="number"){r.inviteLinkGroupTypeV2=A.inviteLinkGroupTypeV2;break}break;case"DEFAULT":case 0:r.inviteLinkGroupTypeV2=0;break;case"PARENT":case 1:r.inviteLinkGroupTypeV2=1;break;case"SUB":case 2:r.inviteLinkGroupTypeV2=2;break;case"DEFAULT_SUB":case 3:r.inviteLinkGroupTypeV2=3;break}if(A.viewOnce!=null&&(r.viewOnce=!!A.viewOnce),A.videoHeight!=null&&(r.videoHeight=A.videoHeight>>>0),A.videoWidth!=null&&(r.videoWidth=A.videoWidth>>>0),A.faviconMMSMetadata!=null){if(typeof A.faviconMMSMetadata!="object")throw TypeError(".proto.Message.ExtendedTextMessage.faviconMMSMetadata: object expected");r.faviconMMSMetadata=p.proto.Message.MMSThumbnailMetadata.fromObject(A.faviconMMSMetadata)}if(A.linkPreviewMetadata!=null){if(typeof A.linkPreviewMetadata!="object")throw TypeError(".proto.Message.ExtendedTextMessage.linkPreviewMetadata: object expected");r.linkPreviewMetadata=p.proto.Message.LinkPreviewMetadata.fromObject(A.linkPreviewMetadata)}if(A.paymentLinkMetadata!=null){if(typeof A.paymentLinkMetadata!="object")throw TypeError(".proto.Message.ExtendedTextMessage.paymentLinkMetadata: object expected");r.paymentLinkMetadata=p.proto.Message.PaymentLinkMetadata.fromObject(A.paymentLinkMetadata)}if(A.endCardTiles){if(!Array.isArray(A.endCardTiles))throw TypeError(".proto.Message.ExtendedTextMessage.endCardTiles: array expected");r.endCardTiles=[];for(var s=0;s>>3){case 1:{c.requestId=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.FullHistorySyncOnDemandRequestMetadata)return A;var r=new p.proto.Message.FullHistorySyncOnDemandRequestMetadata;return A.requestId!=null&&(r.requestId=String(A.requestId)),r},i.toObject=function(A,r){r||(r={});var s={};return A.requestId!=null&&A.hasOwnProperty("requestId")&&(s.requestId=A.requestId,r.oneofs&&(s._requestId="requestId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.FullHistorySyncOnDemandRequestMetadata"},i})(),t.FutureProofMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.message=p.proto.Message.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.FutureProofMessage)return A;var r=new p.proto.Message.FutureProofMessage;if(A.message!=null){if(typeof A.message!="object")throw TypeError(".proto.Message.FutureProofMessage.message: object expected");r.message=p.proto.Message.fromObject(A.message)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.message!=null&&A.hasOwnProperty("message")&&(s.message=p.proto.Message.toObject(A.message,r),r.oneofs&&(s._message="message")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.FutureProofMessage"},i})(),t.GroupInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.groupJid=A.string();break}case 2:{c.inviteCode=A.string();break}case 3:{c.inviteExpiration=A.int64();break}case 4:{c.groupName=A.string();break}case 5:{c.jpegThumbnail=A.bytes();break}case 6:{c.caption=A.string();break}case 7:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 8:{c.groupType=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.GroupInviteMessage)return A;var r=new p.proto.Message.GroupInviteMessage;if(A.groupJid!=null&&(r.groupJid=String(A.groupJid)),A.inviteCode!=null&&(r.inviteCode=String(A.inviteCode)),A.inviteExpiration!=null&&(l.Long?(r.inviteExpiration=l.Long.fromValue(A.inviteExpiration)).unsigned=!1:typeof A.inviteExpiration=="string"?r.inviteExpiration=parseInt(A.inviteExpiration,10):typeof A.inviteExpiration=="number"?r.inviteExpiration=A.inviteExpiration:typeof A.inviteExpiration=="object"&&(r.inviteExpiration=new l.LongBits(A.inviteExpiration.low>>>0,A.inviteExpiration.high>>>0).toNumber())),A.groupName!=null&&(r.groupName=String(A.groupName)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(r.caption=String(A.caption)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.GroupInviteMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.groupType){default:if(typeof A.groupType=="number"){r.groupType=A.groupType;break}break;case"DEFAULT":case 0:r.groupType=0;break;case"PARENT":case 1:r.groupType=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.groupJid!=null&&A.hasOwnProperty("groupJid")&&(s.groupJid=A.groupJid,r.oneofs&&(s._groupJid="groupJid")),A.inviteCode!=null&&A.hasOwnProperty("inviteCode")&&(s.inviteCode=A.inviteCode,r.oneofs&&(s._inviteCode="inviteCode")),A.inviteExpiration!=null&&A.hasOwnProperty("inviteExpiration")&&(typeof A.inviteExpiration=="number"?s.inviteExpiration=r.longs===String?String(A.inviteExpiration):A.inviteExpiration:s.inviteExpiration=r.longs===String?se(A.inviteExpiration):r.longs===Number?ge(A.inviteExpiration):A.inviteExpiration,r.oneofs&&(s._inviteExpiration="inviteExpiration")),A.groupName!=null&&A.hasOwnProperty("groupName")&&(s.groupName=A.groupName,r.oneofs&&(s._groupName="groupName")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.groupType!=null&&A.hasOwnProperty("groupType")&&(s.groupType=r.enums===String?p.proto.Message.GroupInviteMessage.GroupType[A.groupType]===void 0?A.groupType:p.proto.Message.GroupInviteMessage.GroupType[A.groupType]:A.groupType,r.oneofs&&(s._groupType="groupType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.GroupInviteMessage"},i.GroupType=(function(){let a={},A=Object.create(a);return A[a[0]="DEFAULT"]=0,A[a[1]="PARENT"]=1,A})(),i})(),t.HighlyStructuredMessage=(function(){function i(a){if(this.params=[],this.localizableParams=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.namespace=A.string();break}case 2:{c.elementName=A.string();break}case 3:{c.params&&c.params.length||(c.params=[]),c.params.push(A.string());break}case 4:{c.fallbackLg=A.string();break}case 5:{c.fallbackLc=A.string();break}case 6:{c.localizableParams&&c.localizableParams.length||(c.localizableParams=[]),c.localizableParams.push(p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.decode(A,A.uint32()));break}case 7:{c.deterministicLg=A.string();break}case 8:{c.deterministicLc=A.string();break}case 9:{c.hydratedHsm=p.proto.Message.TemplateMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.HighlyStructuredMessage)return A;var r=new p.proto.Message.HighlyStructuredMessage;if(A.namespace!=null&&(r.namespace=String(A.namespace)),A.elementName!=null&&(r.elementName=String(A.elementName)),A.params){if(!Array.isArray(A.params))throw TypeError(".proto.Message.HighlyStructuredMessage.params: array expected");r.params=[];for(var s=0;s>>3){case 1:{d.default=s.string();break}case 2:{d.currency=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency.decode(s,s.uint32());break}case 3:{d.dateTime=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter)return s;var g=new p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter;if(s.default!=null&&(g.default=String(s.default)),s.currency!=null){if(typeof s.currency!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.currency: object expected");g.currency=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency.fromObject(s.currency)}if(s.dateTime!=null){if(typeof s.dateTime!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.dateTime: object expected");g.dateTime=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.fromObject(s.dateTime)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.default!=null&&s.hasOwnProperty("default")&&(c.default=s.default,g.oneofs&&(c._default="default")),s.currency!=null&&s.hasOwnProperty("currency")&&(c.currency=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency.toObject(s.currency,g),g.oneofs&&(c.paramOneof="currency")),s.dateTime!=null&&s.hasOwnProperty("dateTime")&&(c.dateTime=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.toObject(s.dateTime,g),g.oneofs&&(c.paramOneof="dateTime")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter"},a.HSMCurrency=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.currencyCode=c.string();break}case 2:{f.amount1000=c.int64();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency)return c;var I=new p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency;return c.currencyCode!=null&&(I.currencyCode=String(c.currencyCode)),c.amount1000!=null&&(l.Long?(I.amount1000=l.Long.fromValue(c.amount1000)).unsigned=!1:typeof c.amount1000=="string"?I.amount1000=parseInt(c.amount1000,10):typeof c.amount1000=="number"?I.amount1000=c.amount1000:typeof c.amount1000=="object"&&(I.amount1000=new l.LongBits(c.amount1000.low>>>0,c.amount1000.high>>>0).toNumber())),I},r.toObject=function(c,I){I||(I={});var d={};return c.currencyCode!=null&&c.hasOwnProperty("currencyCode")&&(d.currencyCode=c.currencyCode,I.oneofs&&(d._currencyCode="currencyCode")),c.amount1000!=null&&c.hasOwnProperty("amount1000")&&(typeof c.amount1000=="number"?d.amount1000=I.longs===String?String(c.amount1000):c.amount1000:d.amount1000=I.longs===String?se(c.amount1000):I.longs===Number?ge(c.amount1000):c.amount1000,I.oneofs&&(d._amount1000="amount1000")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency"},r})(),a.HSMDateTime=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.component=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.decode(c,c.uint32());break}case 2:{f.unixEpoch=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch.decode(c,c.uint32());break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime)return c;var I=new p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime;if(c.component!=null){if(typeof c.component!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.component: object expected");I.component=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.fromObject(c.component)}if(c.unixEpoch!=null){if(typeof c.unixEpoch!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.unixEpoch: object expected");I.unixEpoch=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch.fromObject(c.unixEpoch)}return I},r.toObject=function(c,I){I||(I={});var d={};return c.component!=null&&c.hasOwnProperty("component")&&(d.component=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.toObject(c.component,I),I.oneofs&&(d.datetimeOneof="component")),c.unixEpoch!=null&&c.hasOwnProperty("unixEpoch")&&(d.unixEpoch=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch.toObject(c.unixEpoch,I),I.oneofs&&(d.datetimeOneof="unixEpoch")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime"},r.HSMDateTimeComponent=(function(){function g(I){if(I)for(var d=Object.keys(I),B=0;B>>3){case 1:{y.dayOfWeek=d.int32();break}case 2:{y.year=d.uint32();break}case 3:{y.month=d.uint32();break}case 4:{y.dayOfMonth=d.uint32();break}case 5:{y.hour=d.uint32();break}case 6:{y.minute=d.uint32();break}case 7:{y.calendar=d.int32();break}default:d.skipType(m&7);break}}return y},g.fromObject=function(d){if(d instanceof p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent)return d;var B=new p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent;switch(d.dayOfWeek){default:if(typeof d.dayOfWeek=="number"){B.dayOfWeek=d.dayOfWeek;break}break;case"MONDAY":case 1:B.dayOfWeek=1;break;case"TUESDAY":case 2:B.dayOfWeek=2;break;case"WEDNESDAY":case 3:B.dayOfWeek=3;break;case"THURSDAY":case 4:B.dayOfWeek=4;break;case"FRIDAY":case 5:B.dayOfWeek=5;break;case"SATURDAY":case 6:B.dayOfWeek=6;break;case"SUNDAY":case 7:B.dayOfWeek=7;break}switch(d.year!=null&&(B.year=d.year>>>0),d.month!=null&&(B.month=d.month>>>0),d.dayOfMonth!=null&&(B.dayOfMonth=d.dayOfMonth>>>0),d.hour!=null&&(B.hour=d.hour>>>0),d.minute!=null&&(B.minute=d.minute>>>0),d.calendar){default:if(typeof d.calendar=="number"){B.calendar=d.calendar;break}break;case"GREGORIAN":case 1:B.calendar=1;break;case"SOLAR_HIJRI":case 2:B.calendar=2;break}return B},g.toObject=function(d,B){B||(B={});var f={};return d.dayOfWeek!=null&&d.hasOwnProperty("dayOfWeek")&&(f.dayOfWeek=B.enums===String?p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.DayOfWeekType[d.dayOfWeek]===void 0?d.dayOfWeek:p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.DayOfWeekType[d.dayOfWeek]:d.dayOfWeek,B.oneofs&&(f._dayOfWeek="dayOfWeek")),d.year!=null&&d.hasOwnProperty("year")&&(f.year=d.year,B.oneofs&&(f._year="year")),d.month!=null&&d.hasOwnProperty("month")&&(f.month=d.month,B.oneofs&&(f._month="month")),d.dayOfMonth!=null&&d.hasOwnProperty("dayOfMonth")&&(f.dayOfMonth=d.dayOfMonth,B.oneofs&&(f._dayOfMonth="dayOfMonth")),d.hour!=null&&d.hasOwnProperty("hour")&&(f.hour=d.hour,B.oneofs&&(f._hour="hour")),d.minute!=null&&d.hasOwnProperty("minute")&&(f.minute=d.minute,B.oneofs&&(f._minute="minute")),d.calendar!=null&&d.hasOwnProperty("calendar")&&(f.calendar=B.enums===String?p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.CalendarType[d.calendar]===void 0?d.calendar:p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.CalendarType[d.calendar]:d.calendar,B.oneofs&&(f._calendar="calendar")),f},g.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},g.getTypeUrl=function(d){return d===void 0&&(d="type.googleapis.com"),d+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent"},g.CalendarType=(function(){let I={},d=Object.create(I);return d[I[1]="GREGORIAN"]=1,d[I[2]="SOLAR_HIJRI"]=2,d})(),g.DayOfWeekType=(function(){let I={},d=Object.create(I);return d[I[1]="MONDAY"]=1,d[I[2]="TUESDAY"]=2,d[I[3]="WEDNESDAY"]=3,d[I[4]="THURSDAY"]=4,d[I[5]="FRIDAY"]=5,d[I[6]="SATURDAY"]=6,d[I[7]="SUNDAY"]=7,d})(),g})(),r.HSMDateTimeUnixEpoch=(function(){function g(I){if(I)for(var d=Object.keys(I),B=0;B>>3){case 1:{y.timestamp=d.int64();break}default:d.skipType(m&7);break}}return y},g.fromObject=function(d){if(d instanceof p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch)return d;var B=new p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch;return d.timestamp!=null&&(l.Long?(B.timestamp=l.Long.fromValue(d.timestamp)).unsigned=!1:typeof d.timestamp=="string"?B.timestamp=parseInt(d.timestamp,10):typeof d.timestamp=="number"?B.timestamp=d.timestamp:typeof d.timestamp=="object"&&(B.timestamp=new l.LongBits(d.timestamp.low>>>0,d.timestamp.high>>>0).toNumber())),B},g.toObject=function(d,B){B||(B={});var f={};return d.timestamp!=null&&d.hasOwnProperty("timestamp")&&(typeof d.timestamp=="number"?f.timestamp=B.longs===String?String(d.timestamp):d.timestamp:f.timestamp=B.longs===String?se(d.timestamp):B.longs===Number?ge(d.timestamp):d.timestamp,B.oneofs&&(f._timestamp="timestamp")),f},g.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},g.getTypeUrl=function(d){return d===void 0&&(d="type.googleapis.com"),d+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch"},g})(),r})(),a})(),i})(),t.HistorySyncMessageAccessStatus=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.completeAccessGranted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.HistorySyncMessageAccessStatus)return A;var r=new p.proto.Message.HistorySyncMessageAccessStatus;return A.completeAccessGranted!=null&&(r.completeAccessGranted=!!A.completeAccessGranted),r},i.toObject=function(A,r){r||(r={});var s={};return A.completeAccessGranted!=null&&A.hasOwnProperty("completeAccessGranted")&&(s.completeAccessGranted=A.completeAccessGranted,r.oneofs&&(s._completeAccessGranted="completeAccessGranted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.HistorySyncMessageAccessStatus"},i})(),t.HistorySyncNotification=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.fileSha256=A.bytes();break}case 2:{c.fileLength=A.uint64();break}case 3:{c.mediaKey=A.bytes();break}case 4:{c.fileEncSha256=A.bytes();break}case 5:{c.directPath=A.string();break}case 6:{c.syncType=A.int32();break}case 7:{c.chunkOrder=A.uint32();break}case 8:{c.originalMessageId=A.string();break}case 9:{c.progress=A.uint32();break}case 10:{c.oldestMsgInChunkTimestampSec=A.int64();break}case 11:{c.initialHistBootstrapInlinePayload=A.bytes();break}case 12:{c.peerDataRequestSessionId=A.string();break}case 13:{c.fullHistorySyncOnDemandRequestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.decode(A,A.uint32());break}case 14:{c.encHandle=A.string();break}case 15:{c.messageAccessStatus=p.proto.Message.HistorySyncMessageAccessStatus.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.HistorySyncNotification)return A;var r=new p.proto.Message.HistorySyncNotification;switch(A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(r.directPath=String(A.directPath)),A.syncType){default:if(typeof A.syncType=="number"){r.syncType=A.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:r.syncType=0;break;case"INITIAL_STATUS_V3":case 1:r.syncType=1;break;case"FULL":case 2:r.syncType=2;break;case"RECENT":case 3:r.syncType=3;break;case"PUSH_NAME":case 4:r.syncType=4;break;case"NON_BLOCKING_DATA":case 5:r.syncType=5;break;case"ON_DEMAND":case 6:r.syncType=6;break;case"NO_HISTORY":case 7:r.syncType=7;break;case"MESSAGE_ACCESS_STATUS":case 8:r.syncType=8;break}if(A.chunkOrder!=null&&(r.chunkOrder=A.chunkOrder>>>0),A.originalMessageId!=null&&(r.originalMessageId=String(A.originalMessageId)),A.progress!=null&&(r.progress=A.progress>>>0),A.oldestMsgInChunkTimestampSec!=null&&(l.Long?(r.oldestMsgInChunkTimestampSec=l.Long.fromValue(A.oldestMsgInChunkTimestampSec)).unsigned=!1:typeof A.oldestMsgInChunkTimestampSec=="string"?r.oldestMsgInChunkTimestampSec=parseInt(A.oldestMsgInChunkTimestampSec,10):typeof A.oldestMsgInChunkTimestampSec=="number"?r.oldestMsgInChunkTimestampSec=A.oldestMsgInChunkTimestampSec:typeof A.oldestMsgInChunkTimestampSec=="object"&&(r.oldestMsgInChunkTimestampSec=new l.LongBits(A.oldestMsgInChunkTimestampSec.low>>>0,A.oldestMsgInChunkTimestampSec.high>>>0).toNumber())),A.initialHistBootstrapInlinePayload!=null&&(typeof A.initialHistBootstrapInlinePayload=="string"?l.base64.decode(A.initialHistBootstrapInlinePayload,r.initialHistBootstrapInlinePayload=l.newBuffer(l.base64.length(A.initialHistBootstrapInlinePayload)),0):A.initialHistBootstrapInlinePayload.length>=0&&(r.initialHistBootstrapInlinePayload=A.initialHistBootstrapInlinePayload)),A.peerDataRequestSessionId!=null&&(r.peerDataRequestSessionId=String(A.peerDataRequestSessionId)),A.fullHistorySyncOnDemandRequestMetadata!=null){if(typeof A.fullHistorySyncOnDemandRequestMetadata!="object")throw TypeError(".proto.Message.HistorySyncNotification.fullHistorySyncOnDemandRequestMetadata: object expected");r.fullHistorySyncOnDemandRequestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.fromObject(A.fullHistorySyncOnDemandRequestMetadata)}if(A.encHandle!=null&&(r.encHandle=String(A.encHandle)),A.messageAccessStatus!=null){if(typeof A.messageAccessStatus!="object")throw TypeError(".proto.Message.HistorySyncNotification.messageAccessStatus: object expected");r.messageAccessStatus=p.proto.Message.HistorySyncMessageAccessStatus.fromObject(A.messageAccessStatus)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.syncType!=null&&A.hasOwnProperty("syncType")&&(s.syncType=r.enums===String?p.proto.Message.HistorySyncType[A.syncType]===void 0?A.syncType:p.proto.Message.HistorySyncType[A.syncType]:A.syncType,r.oneofs&&(s._syncType="syncType")),A.chunkOrder!=null&&A.hasOwnProperty("chunkOrder")&&(s.chunkOrder=A.chunkOrder,r.oneofs&&(s._chunkOrder="chunkOrder")),A.originalMessageId!=null&&A.hasOwnProperty("originalMessageId")&&(s.originalMessageId=A.originalMessageId,r.oneofs&&(s._originalMessageId="originalMessageId")),A.progress!=null&&A.hasOwnProperty("progress")&&(s.progress=A.progress,r.oneofs&&(s._progress="progress")),A.oldestMsgInChunkTimestampSec!=null&&A.hasOwnProperty("oldestMsgInChunkTimestampSec")&&(typeof A.oldestMsgInChunkTimestampSec=="number"?s.oldestMsgInChunkTimestampSec=r.longs===String?String(A.oldestMsgInChunkTimestampSec):A.oldestMsgInChunkTimestampSec:s.oldestMsgInChunkTimestampSec=r.longs===String?se(A.oldestMsgInChunkTimestampSec):r.longs===Number?ge(A.oldestMsgInChunkTimestampSec):A.oldestMsgInChunkTimestampSec,r.oneofs&&(s._oldestMsgInChunkTimestampSec="oldestMsgInChunkTimestampSec")),A.initialHistBootstrapInlinePayload!=null&&A.hasOwnProperty("initialHistBootstrapInlinePayload")&&(s.initialHistBootstrapInlinePayload=r.bytes===String?l.base64.encode(A.initialHistBootstrapInlinePayload,0,A.initialHistBootstrapInlinePayload.length):r.bytes===Array?Array.prototype.slice.call(A.initialHistBootstrapInlinePayload):A.initialHistBootstrapInlinePayload,r.oneofs&&(s._initialHistBootstrapInlinePayload="initialHistBootstrapInlinePayload")),A.peerDataRequestSessionId!=null&&A.hasOwnProperty("peerDataRequestSessionId")&&(s.peerDataRequestSessionId=A.peerDataRequestSessionId,r.oneofs&&(s._peerDataRequestSessionId="peerDataRequestSessionId")),A.fullHistorySyncOnDemandRequestMetadata!=null&&A.hasOwnProperty("fullHistorySyncOnDemandRequestMetadata")&&(s.fullHistorySyncOnDemandRequestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.toObject(A.fullHistorySyncOnDemandRequestMetadata,r),r.oneofs&&(s._fullHistorySyncOnDemandRequestMetadata="fullHistorySyncOnDemandRequestMetadata")),A.encHandle!=null&&A.hasOwnProperty("encHandle")&&(s.encHandle=A.encHandle,r.oneofs&&(s._encHandle="encHandle")),A.messageAccessStatus!=null&&A.hasOwnProperty("messageAccessStatus")&&(s.messageAccessStatus=p.proto.Message.HistorySyncMessageAccessStatus.toObject(A.messageAccessStatus,r),r.oneofs&&(s._messageAccessStatus="messageAccessStatus")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.HistorySyncNotification"},i})(),t.HistorySyncType=(function(){let i={},e=Object.create(i);return e[i[0]="INITIAL_BOOTSTRAP"]=0,e[i[1]="INITIAL_STATUS_V3"]=1,e[i[2]="FULL"]=2,e[i[3]="RECENT"]=3,e[i[4]="PUSH_NAME"]=4,e[i[5]="NON_BLOCKING_DATA"]=5,e[i[6]="ON_DEMAND"]=6,e[i[7]="NO_HISTORY"]=7,e[i[8]="MESSAGE_ACCESS_STATUS"]=8,e})(),t.ImageMessage=(function(){function i(a){if(this.interactiveAnnotations=[],this.scanLengths=[],this.annotations=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.caption=A.string();break}case 4:{c.fileSha256=A.bytes();break}case 5:{c.fileLength=A.uint64();break}case 6:{c.height=A.uint32();break}case 7:{c.width=A.uint32();break}case 8:{c.mediaKey=A.bytes();break}case 9:{c.fileEncSha256=A.bytes();break}case 10:{c.interactiveAnnotations&&c.interactiveAnnotations.length||(c.interactiveAnnotations=[]),c.interactiveAnnotations.push(p.proto.InteractiveAnnotation.decode(A,A.uint32()));break}case 11:{c.directPath=A.string();break}case 12:{c.mediaKeyTimestamp=A.int64();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.firstScanSidecar=A.bytes();break}case 19:{c.firstScanLength=A.uint32();break}case 20:{c.experimentGroupId=A.uint32();break}case 21:{c.scansSidecar=A.bytes();break}case 22:{if(c.scanLengths&&c.scanLengths.length||(c.scanLengths=[]),(I&7)===2)for(var d=A.uint32()+A.pos;A.pos=0&&(r.fileSha256=A.fileSha256)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.height!=null&&(r.height=A.height>>>0),A.width!=null&&(r.width=A.width>>>0),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.interactiveAnnotations){if(!Array.isArray(A.interactiveAnnotations))throw TypeError(".proto.Message.ImageMessage.interactiveAnnotations: array expected");r.interactiveAnnotations=[];for(var s=0;s>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ImageMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.firstScanSidecar!=null&&(typeof A.firstScanSidecar=="string"?l.base64.decode(A.firstScanSidecar,r.firstScanSidecar=l.newBuffer(l.base64.length(A.firstScanSidecar)),0):A.firstScanSidecar.length>=0&&(r.firstScanSidecar=A.firstScanSidecar)),A.firstScanLength!=null&&(r.firstScanLength=A.firstScanLength>>>0),A.experimentGroupId!=null&&(r.experimentGroupId=A.experimentGroupId>>>0),A.scansSidecar!=null&&(typeof A.scansSidecar=="string"?l.base64.decode(A.scansSidecar,r.scansSidecar=l.newBuffer(l.base64.length(A.scansSidecar)),0):A.scansSidecar.length>=0&&(r.scansSidecar=A.scansSidecar)),A.scanLengths){if(!Array.isArray(A.scanLengths))throw TypeError(".proto.Message.ImageMessage.scanLengths: array expected");r.scanLengths=[];for(var s=0;s>>0}if(A.midQualityFileSha256!=null&&(typeof A.midQualityFileSha256=="string"?l.base64.decode(A.midQualityFileSha256,r.midQualityFileSha256=l.newBuffer(l.base64.length(A.midQualityFileSha256)),0):A.midQualityFileSha256.length>=0&&(r.midQualityFileSha256=A.midQualityFileSha256)),A.midQualityFileEncSha256!=null&&(typeof A.midQualityFileEncSha256=="string"?l.base64.decode(A.midQualityFileEncSha256,r.midQualityFileEncSha256=l.newBuffer(l.base64.length(A.midQualityFileEncSha256)),0):A.midQualityFileEncSha256.length>=0&&(r.midQualityFileEncSha256=A.midQualityFileEncSha256)),A.viewOnce!=null&&(r.viewOnce=!!A.viewOnce),A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.staticUrl!=null&&(r.staticUrl=String(A.staticUrl)),A.annotations){if(!Array.isArray(A.annotations))throw TypeError(".proto.Message.ImageMessage.annotations: array expected");r.annotations=[];for(var s=0;s>>3){case 1:{c.securityNotificationEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.InitialSecurityNotificationSettingSync)return A;var r=new p.proto.Message.InitialSecurityNotificationSettingSync;return A.securityNotificationEnabled!=null&&(r.securityNotificationEnabled=!!A.securityNotificationEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.securityNotificationEnabled!=null&&A.hasOwnProperty("securityNotificationEnabled")&&(s.securityNotificationEnabled=A.securityNotificationEnabled,r.oneofs&&(s._securityNotificationEnabled="securityNotificationEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InitialSecurityNotificationSettingSync"},i})(),t.InteractiveMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.header=p.proto.Message.InteractiveMessage.Header.decode(A,A.uint32());break}case 2:{c.body=p.proto.Message.InteractiveMessage.Body.decode(A,A.uint32());break}case 3:{c.footer=p.proto.Message.InteractiveMessage.Footer.decode(A,A.uint32());break}case 15:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 16:{c.urlTrackingMap=p.proto.UrlTrackingMap.decode(A,A.uint32());break}case 4:{c.shopStorefrontMessage=p.proto.Message.InteractiveMessage.ShopMessage.decode(A,A.uint32());break}case 5:{c.collectionMessage=p.proto.Message.InteractiveMessage.CollectionMessage.decode(A,A.uint32());break}case 6:{c.nativeFlowMessage=p.proto.Message.InteractiveMessage.NativeFlowMessage.decode(A,A.uint32());break}case 7:{c.carouselMessage=p.proto.Message.InteractiveMessage.CarouselMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.InteractiveMessage)return A;var r=new p.proto.Message.InteractiveMessage;if(A.header!=null){if(typeof A.header!="object")throw TypeError(".proto.Message.InteractiveMessage.header: object expected");r.header=p.proto.Message.InteractiveMessage.Header.fromObject(A.header)}if(A.body!=null){if(typeof A.body!="object")throw TypeError(".proto.Message.InteractiveMessage.body: object expected");r.body=p.proto.Message.InteractiveMessage.Body.fromObject(A.body)}if(A.footer!=null){if(typeof A.footer!="object")throw TypeError(".proto.Message.InteractiveMessage.footer: object expected");r.footer=p.proto.Message.InteractiveMessage.Footer.fromObject(A.footer)}if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.InteractiveMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.urlTrackingMap!=null){if(typeof A.urlTrackingMap!="object")throw TypeError(".proto.Message.InteractiveMessage.urlTrackingMap: object expected");r.urlTrackingMap=p.proto.UrlTrackingMap.fromObject(A.urlTrackingMap)}if(A.shopStorefrontMessage!=null){if(typeof A.shopStorefrontMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.shopStorefrontMessage: object expected");r.shopStorefrontMessage=p.proto.Message.InteractiveMessage.ShopMessage.fromObject(A.shopStorefrontMessage)}if(A.collectionMessage!=null){if(typeof A.collectionMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.collectionMessage: object expected");r.collectionMessage=p.proto.Message.InteractiveMessage.CollectionMessage.fromObject(A.collectionMessage)}if(A.nativeFlowMessage!=null){if(typeof A.nativeFlowMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.nativeFlowMessage: object expected");r.nativeFlowMessage=p.proto.Message.InteractiveMessage.NativeFlowMessage.fromObject(A.nativeFlowMessage)}if(A.carouselMessage!=null){if(typeof A.carouselMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.carouselMessage: object expected");r.carouselMessage=p.proto.Message.InteractiveMessage.CarouselMessage.fromObject(A.carouselMessage)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.header!=null&&A.hasOwnProperty("header")&&(s.header=p.proto.Message.InteractiveMessage.Header.toObject(A.header,r),r.oneofs&&(s._header="header")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=p.proto.Message.InteractiveMessage.Body.toObject(A.body,r),r.oneofs&&(s._body="body")),A.footer!=null&&A.hasOwnProperty("footer")&&(s.footer=p.proto.Message.InteractiveMessage.Footer.toObject(A.footer,r),r.oneofs&&(s._footer="footer")),A.shopStorefrontMessage!=null&&A.hasOwnProperty("shopStorefrontMessage")&&(s.shopStorefrontMessage=p.proto.Message.InteractiveMessage.ShopMessage.toObject(A.shopStorefrontMessage,r),r.oneofs&&(s.interactiveMessage="shopStorefrontMessage")),A.collectionMessage!=null&&A.hasOwnProperty("collectionMessage")&&(s.collectionMessage=p.proto.Message.InteractiveMessage.CollectionMessage.toObject(A.collectionMessage,r),r.oneofs&&(s.interactiveMessage="collectionMessage")),A.nativeFlowMessage!=null&&A.hasOwnProperty("nativeFlowMessage")&&(s.nativeFlowMessage=p.proto.Message.InteractiveMessage.NativeFlowMessage.toObject(A.nativeFlowMessage,r),r.oneofs&&(s.interactiveMessage="nativeFlowMessage")),A.carouselMessage!=null&&A.hasOwnProperty("carouselMessage")&&(s.carouselMessage=p.proto.Message.InteractiveMessage.CarouselMessage.toObject(A.carouselMessage,r),r.oneofs&&(s.interactiveMessage="carouselMessage")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.urlTrackingMap!=null&&A.hasOwnProperty("urlTrackingMap")&&(s.urlTrackingMap=p.proto.UrlTrackingMap.toObject(A.urlTrackingMap,r),r.oneofs&&(s._urlTrackingMap="urlTrackingMap")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InteractiveMessage"},i.Body=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.text=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.Body)return s;var g=new p.proto.Message.InteractiveMessage.Body;return s.text!=null&&(g.text=String(s.text)),g},a.toObject=function(s,g){g||(g={});var c={};return s.text!=null&&s.hasOwnProperty("text")&&(c.text=s.text,g.oneofs&&(c._text="text")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.Body"},a})(),i.CarouselMessage=(function(){function a(r){if(this.cards=[],r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.cards&&d.cards.length||(d.cards=[]),d.cards.push(p.proto.Message.InteractiveMessage.decode(s,s.uint32()));break}case 2:{d.messageVersion=s.int32();break}case 3:{d.carouselCardType=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.CarouselMessage)return s;var g=new p.proto.Message.InteractiveMessage.CarouselMessage;if(s.cards){if(!Array.isArray(s.cards))throw TypeError(".proto.Message.InteractiveMessage.CarouselMessage.cards: array expected");g.cards=[];for(var c=0;c>>3){case 1:{d.bizJid=s.string();break}case 2:{d.id=s.string();break}case 3:{d.messageVersion=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.CollectionMessage)return s;var g=new p.proto.Message.InteractiveMessage.CollectionMessage;return s.bizJid!=null&&(g.bizJid=String(s.bizJid)),s.id!=null&&(g.id=String(s.id)),s.messageVersion!=null&&(g.messageVersion=s.messageVersion|0),g},a.toObject=function(s,g){g||(g={});var c={};return s.bizJid!=null&&s.hasOwnProperty("bizJid")&&(c.bizJid=s.bizJid,g.oneofs&&(c._bizJid="bizJid")),s.id!=null&&s.hasOwnProperty("id")&&(c.id=s.id,g.oneofs&&(c._id="id")),s.messageVersion!=null&&s.hasOwnProperty("messageVersion")&&(c.messageVersion=s.messageVersion,g.oneofs&&(c._messageVersion="messageVersion")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.CollectionMessage"},a})(),i.Footer=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.text=s.string();break}case 3:{d.hasMediaAttachment=s.bool();break}case 2:{d.audioMessage=p.proto.Message.AudioMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.Footer)return s;var g=new p.proto.Message.InteractiveMessage.Footer;if(s.text!=null&&(g.text=String(s.text)),s.hasMediaAttachment!=null&&(g.hasMediaAttachment=!!s.hasMediaAttachment),s.audioMessage!=null){if(typeof s.audioMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Footer.audioMessage: object expected");g.audioMessage=p.proto.Message.AudioMessage.fromObject(s.audioMessage)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.text!=null&&s.hasOwnProperty("text")&&(c.text=s.text,g.oneofs&&(c._text="text")),s.audioMessage!=null&&s.hasOwnProperty("audioMessage")&&(c.audioMessage=p.proto.Message.AudioMessage.toObject(s.audioMessage,g),g.oneofs&&(c.media="audioMessage")),s.hasMediaAttachment!=null&&s.hasOwnProperty("hasMediaAttachment")&&(c.hasMediaAttachment=s.hasMediaAttachment,g.oneofs&&(c._hasMediaAttachment="hasMediaAttachment")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.Footer"},a})(),i.Header=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.title=s.string();break}case 2:{d.subtitle=s.string();break}case 5:{d.hasMediaAttachment=s.bool();break}case 3:{d.documentMessage=p.proto.Message.DocumentMessage.decode(s,s.uint32());break}case 4:{d.imageMessage=p.proto.Message.ImageMessage.decode(s,s.uint32());break}case 6:{d.jpegThumbnail=s.bytes();break}case 7:{d.videoMessage=p.proto.Message.VideoMessage.decode(s,s.uint32());break}case 8:{d.locationMessage=p.proto.Message.LocationMessage.decode(s,s.uint32());break}case 9:{d.productMessage=p.proto.Message.ProductMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.Header)return s;var g=new p.proto.Message.InteractiveMessage.Header;if(s.title!=null&&(g.title=String(s.title)),s.subtitle!=null&&(g.subtitle=String(s.subtitle)),s.hasMediaAttachment!=null&&(g.hasMediaAttachment=!!s.hasMediaAttachment),s.documentMessage!=null){if(typeof s.documentMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.documentMessage: object expected");g.documentMessage=p.proto.Message.DocumentMessage.fromObject(s.documentMessage)}if(s.imageMessage!=null){if(typeof s.imageMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.imageMessage: object expected");g.imageMessage=p.proto.Message.ImageMessage.fromObject(s.imageMessage)}if(s.jpegThumbnail!=null&&(typeof s.jpegThumbnail=="string"?l.base64.decode(s.jpegThumbnail,g.jpegThumbnail=l.newBuffer(l.base64.length(s.jpegThumbnail)),0):s.jpegThumbnail.length>=0&&(g.jpegThumbnail=s.jpegThumbnail)),s.videoMessage!=null){if(typeof s.videoMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.videoMessage: object expected");g.videoMessage=p.proto.Message.VideoMessage.fromObject(s.videoMessage)}if(s.locationMessage!=null){if(typeof s.locationMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.locationMessage: object expected");g.locationMessage=p.proto.Message.LocationMessage.fromObject(s.locationMessage)}if(s.productMessage!=null){if(typeof s.productMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.productMessage: object expected");g.productMessage=p.proto.Message.ProductMessage.fromObject(s.productMessage)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.subtitle!=null&&s.hasOwnProperty("subtitle")&&(c.subtitle=s.subtitle,g.oneofs&&(c._subtitle="subtitle")),s.documentMessage!=null&&s.hasOwnProperty("documentMessage")&&(c.documentMessage=p.proto.Message.DocumentMessage.toObject(s.documentMessage,g),g.oneofs&&(c.media="documentMessage")),s.imageMessage!=null&&s.hasOwnProperty("imageMessage")&&(c.imageMessage=p.proto.Message.ImageMessage.toObject(s.imageMessage,g),g.oneofs&&(c.media="imageMessage")),s.hasMediaAttachment!=null&&s.hasOwnProperty("hasMediaAttachment")&&(c.hasMediaAttachment=s.hasMediaAttachment,g.oneofs&&(c._hasMediaAttachment="hasMediaAttachment")),s.jpegThumbnail!=null&&s.hasOwnProperty("jpegThumbnail")&&(c.jpegThumbnail=g.bytes===String?l.base64.encode(s.jpegThumbnail,0,s.jpegThumbnail.length):g.bytes===Array?Array.prototype.slice.call(s.jpegThumbnail):s.jpegThumbnail,g.oneofs&&(c.media="jpegThumbnail")),s.videoMessage!=null&&s.hasOwnProperty("videoMessage")&&(c.videoMessage=p.proto.Message.VideoMessage.toObject(s.videoMessage,g),g.oneofs&&(c.media="videoMessage")),s.locationMessage!=null&&s.hasOwnProperty("locationMessage")&&(c.locationMessage=p.proto.Message.LocationMessage.toObject(s.locationMessage,g),g.oneofs&&(c.media="locationMessage")),s.productMessage!=null&&s.hasOwnProperty("productMessage")&&(c.productMessage=p.proto.Message.ProductMessage.toObject(s.productMessage,g),g.oneofs&&(c.media="productMessage")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.Header"},a})(),i.NativeFlowMessage=(function(){function a(r){if(this.buttons=[],r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.buttons&&d.buttons.length||(d.buttons=[]),d.buttons.push(p.proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton.decode(s,s.uint32()));break}case 2:{d.messageParamsJson=s.string();break}case 3:{d.messageVersion=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.NativeFlowMessage)return s;var g=new p.proto.Message.InteractiveMessage.NativeFlowMessage;if(s.buttons){if(!Array.isArray(s.buttons))throw TypeError(".proto.Message.InteractiveMessage.NativeFlowMessage.buttons: array expected");g.buttons=[];for(var c=0;c>>3){case 1:{f.name=c.string();break}case 2:{f.buttonParamsJson=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton)return c;var I=new p.proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton;return c.name!=null&&(I.name=String(c.name)),c.buttonParamsJson!=null&&(I.buttonParamsJson=String(c.buttonParamsJson)),I},r.toObject=function(c,I){I||(I={});var d={};return c.name!=null&&c.hasOwnProperty("name")&&(d.name=c.name,I.oneofs&&(d._name="name")),c.buttonParamsJson!=null&&c.hasOwnProperty("buttonParamsJson")&&(d.buttonParamsJson=c.buttonParamsJson,I.oneofs&&(d._buttonParamsJson="buttonParamsJson")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton"},r})(),a})(),i.ShopMessage=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.id=s.string();break}case 2:{d.surface=s.int32();break}case 3:{d.messageVersion=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.ShopMessage)return s;var g=new p.proto.Message.InteractiveMessage.ShopMessage;switch(s.id!=null&&(g.id=String(s.id)),s.surface){default:if(typeof s.surface=="number"){g.surface=s.surface;break}break;case"UNKNOWN_SURFACE":case 0:g.surface=0;break;case"FB":case 1:g.surface=1;break;case"IG":case 2:g.surface=2;break;case"WA":case 3:g.surface=3;break}return s.messageVersion!=null&&(g.messageVersion=s.messageVersion|0),g},a.toObject=function(s,g){g||(g={});var c={};return s.id!=null&&s.hasOwnProperty("id")&&(c.id=s.id,g.oneofs&&(c._id="id")),s.surface!=null&&s.hasOwnProperty("surface")&&(c.surface=g.enums===String?p.proto.Message.InteractiveMessage.ShopMessage.Surface[s.surface]===void 0?s.surface:p.proto.Message.InteractiveMessage.ShopMessage.Surface[s.surface]:s.surface,g.oneofs&&(c._surface="surface")),s.messageVersion!=null&&s.hasOwnProperty("messageVersion")&&(c.messageVersion=s.messageVersion,g.oneofs&&(c._messageVersion="messageVersion")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.ShopMessage"},a.Surface=(function(){let r={},s=Object.create(r);return s[r[0]="UNKNOWN_SURFACE"]=0,s[r[1]="FB"]=1,s[r[2]="IG"]=2,s[r[3]="WA"]=3,s})(),a})(),i})(),t.InteractiveResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.body=p.proto.Message.InteractiveResponseMessage.Body.decode(A,A.uint32());break}case 15:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 2:{c.nativeFlowResponseMessage=p.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.InteractiveResponseMessage)return A;var r=new p.proto.Message.InteractiveResponseMessage;if(A.body!=null){if(typeof A.body!="object")throw TypeError(".proto.Message.InteractiveResponseMessage.body: object expected");r.body=p.proto.Message.InteractiveResponseMessage.Body.fromObject(A.body)}if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.InteractiveResponseMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.nativeFlowResponseMessage!=null){if(typeof A.nativeFlowResponseMessage!="object")throw TypeError(".proto.Message.InteractiveResponseMessage.nativeFlowResponseMessage: object expected");r.nativeFlowResponseMessage=p.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage.fromObject(A.nativeFlowResponseMessage)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.body!=null&&A.hasOwnProperty("body")&&(s.body=p.proto.Message.InteractiveResponseMessage.Body.toObject(A.body,r),r.oneofs&&(s._body="body")),A.nativeFlowResponseMessage!=null&&A.hasOwnProperty("nativeFlowResponseMessage")&&(s.nativeFlowResponseMessage=p.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage.toObject(A.nativeFlowResponseMessage,r),r.oneofs&&(s.interactiveResponseMessage="nativeFlowResponseMessage")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InteractiveResponseMessage"},i.Body=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.text=s.string();break}case 2:{d.format=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveResponseMessage.Body)return s;var g=new p.proto.Message.InteractiveResponseMessage.Body;switch(s.text!=null&&(g.text=String(s.text)),s.format){default:if(typeof s.format=="number"){g.format=s.format;break}break;case"DEFAULT":case 0:g.format=0;break;case"EXTENSIONS_1":case 1:g.format=1;break}return g},a.toObject=function(s,g){g||(g={});var c={};return s.text!=null&&s.hasOwnProperty("text")&&(c.text=s.text,g.oneofs&&(c._text="text")),s.format!=null&&s.hasOwnProperty("format")&&(c.format=g.enums===String?p.proto.Message.InteractiveResponseMessage.Body.Format[s.format]===void 0?s.format:p.proto.Message.InteractiveResponseMessage.Body.Format[s.format]:s.format,g.oneofs&&(c._format="format")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveResponseMessage.Body"},a.Format=(function(){let r={},s=Object.create(r);return s[r[0]="DEFAULT"]=0,s[r[1]="EXTENSIONS_1"]=1,s})(),a})(),i.NativeFlowResponseMessage=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.name=s.string();break}case 2:{d.paramsJson=s.string();break}case 3:{d.version=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage)return s;var g=new p.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage;return s.name!=null&&(g.name=String(s.name)),s.paramsJson!=null&&(g.paramsJson=String(s.paramsJson)),s.version!=null&&(g.version=s.version|0),g},a.toObject=function(s,g){g||(g={});var c={};return s.name!=null&&s.hasOwnProperty("name")&&(c.name=s.name,g.oneofs&&(c._name="name")),s.paramsJson!=null&&s.hasOwnProperty("paramsJson")&&(c.paramsJson=s.paramsJson,g.oneofs&&(c._paramsJson="paramsJson")),s.version!=null&&s.hasOwnProperty("version")&&(c.version=s.version,g.oneofs&&(c._version="version")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage"},a})(),i})(),t.InvoiceMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.note=A.string();break}case 2:{c.token=A.string();break}case 3:{c.attachmentType=A.int32();break}case 4:{c.attachmentMimetype=A.string();break}case 5:{c.attachmentMediaKey=A.bytes();break}case 6:{c.attachmentMediaKeyTimestamp=A.int64();break}case 7:{c.attachmentFileSha256=A.bytes();break}case 8:{c.attachmentFileEncSha256=A.bytes();break}case 9:{c.attachmentDirectPath=A.string();break}case 10:{c.attachmentJpegThumbnail=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.InvoiceMessage)return A;var r=new p.proto.Message.InvoiceMessage;switch(A.note!=null&&(r.note=String(A.note)),A.token!=null&&(r.token=String(A.token)),A.attachmentType){default:if(typeof A.attachmentType=="number"){r.attachmentType=A.attachmentType;break}break;case"IMAGE":case 0:r.attachmentType=0;break;case"PDF":case 1:r.attachmentType=1;break}return A.attachmentMimetype!=null&&(r.attachmentMimetype=String(A.attachmentMimetype)),A.attachmentMediaKey!=null&&(typeof A.attachmentMediaKey=="string"?l.base64.decode(A.attachmentMediaKey,r.attachmentMediaKey=l.newBuffer(l.base64.length(A.attachmentMediaKey)),0):A.attachmentMediaKey.length>=0&&(r.attachmentMediaKey=A.attachmentMediaKey)),A.attachmentMediaKeyTimestamp!=null&&(l.Long?(r.attachmentMediaKeyTimestamp=l.Long.fromValue(A.attachmentMediaKeyTimestamp)).unsigned=!1:typeof A.attachmentMediaKeyTimestamp=="string"?r.attachmentMediaKeyTimestamp=parseInt(A.attachmentMediaKeyTimestamp,10):typeof A.attachmentMediaKeyTimestamp=="number"?r.attachmentMediaKeyTimestamp=A.attachmentMediaKeyTimestamp:typeof A.attachmentMediaKeyTimestamp=="object"&&(r.attachmentMediaKeyTimestamp=new l.LongBits(A.attachmentMediaKeyTimestamp.low>>>0,A.attachmentMediaKeyTimestamp.high>>>0).toNumber())),A.attachmentFileSha256!=null&&(typeof A.attachmentFileSha256=="string"?l.base64.decode(A.attachmentFileSha256,r.attachmentFileSha256=l.newBuffer(l.base64.length(A.attachmentFileSha256)),0):A.attachmentFileSha256.length>=0&&(r.attachmentFileSha256=A.attachmentFileSha256)),A.attachmentFileEncSha256!=null&&(typeof A.attachmentFileEncSha256=="string"?l.base64.decode(A.attachmentFileEncSha256,r.attachmentFileEncSha256=l.newBuffer(l.base64.length(A.attachmentFileEncSha256)),0):A.attachmentFileEncSha256.length>=0&&(r.attachmentFileEncSha256=A.attachmentFileEncSha256)),A.attachmentDirectPath!=null&&(r.attachmentDirectPath=String(A.attachmentDirectPath)),A.attachmentJpegThumbnail!=null&&(typeof A.attachmentJpegThumbnail=="string"?l.base64.decode(A.attachmentJpegThumbnail,r.attachmentJpegThumbnail=l.newBuffer(l.base64.length(A.attachmentJpegThumbnail)),0):A.attachmentJpegThumbnail.length>=0&&(r.attachmentJpegThumbnail=A.attachmentJpegThumbnail)),r},i.toObject=function(A,r){r||(r={});var s={};return A.note!=null&&A.hasOwnProperty("note")&&(s.note=A.note,r.oneofs&&(s._note="note")),A.token!=null&&A.hasOwnProperty("token")&&(s.token=A.token,r.oneofs&&(s._token="token")),A.attachmentType!=null&&A.hasOwnProperty("attachmentType")&&(s.attachmentType=r.enums===String?p.proto.Message.InvoiceMessage.AttachmentType[A.attachmentType]===void 0?A.attachmentType:p.proto.Message.InvoiceMessage.AttachmentType[A.attachmentType]:A.attachmentType,r.oneofs&&(s._attachmentType="attachmentType")),A.attachmentMimetype!=null&&A.hasOwnProperty("attachmentMimetype")&&(s.attachmentMimetype=A.attachmentMimetype,r.oneofs&&(s._attachmentMimetype="attachmentMimetype")),A.attachmentMediaKey!=null&&A.hasOwnProperty("attachmentMediaKey")&&(s.attachmentMediaKey=r.bytes===String?l.base64.encode(A.attachmentMediaKey,0,A.attachmentMediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.attachmentMediaKey):A.attachmentMediaKey,r.oneofs&&(s._attachmentMediaKey="attachmentMediaKey")),A.attachmentMediaKeyTimestamp!=null&&A.hasOwnProperty("attachmentMediaKeyTimestamp")&&(typeof A.attachmentMediaKeyTimestamp=="number"?s.attachmentMediaKeyTimestamp=r.longs===String?String(A.attachmentMediaKeyTimestamp):A.attachmentMediaKeyTimestamp:s.attachmentMediaKeyTimestamp=r.longs===String?se(A.attachmentMediaKeyTimestamp):r.longs===Number?ge(A.attachmentMediaKeyTimestamp):A.attachmentMediaKeyTimestamp,r.oneofs&&(s._attachmentMediaKeyTimestamp="attachmentMediaKeyTimestamp")),A.attachmentFileSha256!=null&&A.hasOwnProperty("attachmentFileSha256")&&(s.attachmentFileSha256=r.bytes===String?l.base64.encode(A.attachmentFileSha256,0,A.attachmentFileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.attachmentFileSha256):A.attachmentFileSha256,r.oneofs&&(s._attachmentFileSha256="attachmentFileSha256")),A.attachmentFileEncSha256!=null&&A.hasOwnProperty("attachmentFileEncSha256")&&(s.attachmentFileEncSha256=r.bytes===String?l.base64.encode(A.attachmentFileEncSha256,0,A.attachmentFileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.attachmentFileEncSha256):A.attachmentFileEncSha256,r.oneofs&&(s._attachmentFileEncSha256="attachmentFileEncSha256")),A.attachmentDirectPath!=null&&A.hasOwnProperty("attachmentDirectPath")&&(s.attachmentDirectPath=A.attachmentDirectPath,r.oneofs&&(s._attachmentDirectPath="attachmentDirectPath")),A.attachmentJpegThumbnail!=null&&A.hasOwnProperty("attachmentJpegThumbnail")&&(s.attachmentJpegThumbnail=r.bytes===String?l.base64.encode(A.attachmentJpegThumbnail,0,A.attachmentJpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.attachmentJpegThumbnail):A.attachmentJpegThumbnail,r.oneofs&&(s._attachmentJpegThumbnail="attachmentJpegThumbnail")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InvoiceMessage"},i.AttachmentType=(function(){let a={},A=Object.create(a);return A[a[0]="IMAGE"]=0,A[a[1]="PDF"]=1,A})(),i})(),t.KeepInChatMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.keepType=A.int32();break}case 3:{c.timestampMs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.KeepInChatMessage)return A;var r=new p.proto.Message.KeepInChatMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.KeepInChatMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}switch(A.keepType){default:if(typeof A.keepType=="number"){r.keepType=A.keepType;break}break;case"UNKNOWN":case 0:r.keepType=0;break;case"KEEP_FOR_ALL":case 1:r.keepType=1;break;case"UNDO_KEEP_FOR_ALL":case 2:r.keepType=2;break}return A.timestampMs!=null&&(l.Long?(r.timestampMs=l.Long.fromValue(A.timestampMs)).unsigned=!1:typeof A.timestampMs=="string"?r.timestampMs=parseInt(A.timestampMs,10):typeof A.timestampMs=="number"?r.timestampMs=A.timestampMs:typeof A.timestampMs=="object"&&(r.timestampMs=new l.LongBits(A.timestampMs.low>>>0,A.timestampMs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.keepType!=null&&A.hasOwnProperty("keepType")&&(s.keepType=r.enums===String?p.proto.KeepType[A.keepType]===void 0?A.keepType:p.proto.KeepType[A.keepType]:A.keepType,r.oneofs&&(s._keepType="keepType")),A.timestampMs!=null&&A.hasOwnProperty("timestampMs")&&(typeof A.timestampMs=="number"?s.timestampMs=r.longs===String?String(A.timestampMs):A.timestampMs:s.timestampMs=r.longs===String?se(A.timestampMs):r.longs===Number?ge(A.timestampMs):A.timestampMs,r.oneofs&&(s._timestampMs="timestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.KeepInChatMessage"},i})(),t.LinkPreviewMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.paymentLinkMetadata=p.proto.Message.PaymentLinkMetadata.decode(A,A.uint32());break}case 2:{c.urlMetadata=p.proto.Message.URLMetadata.decode(A,A.uint32());break}case 3:{c.fbExperimentId=A.uint32();break}case 4:{c.linkMediaDuration=A.uint32();break}case 5:{c.socialMediaPostType=A.int32();break}case 6:{c.linkInlineVideoMuted=A.bool();break}case 7:{c.videoContentUrl=A.string();break}case 8:{c.musicMetadata=p.proto.EmbeddedMusic.decode(A,A.uint32());break}case 9:{c.videoContentCaption=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.LinkPreviewMetadata)return A;var r=new p.proto.Message.LinkPreviewMetadata;if(A.paymentLinkMetadata!=null){if(typeof A.paymentLinkMetadata!="object")throw TypeError(".proto.Message.LinkPreviewMetadata.paymentLinkMetadata: object expected");r.paymentLinkMetadata=p.proto.Message.PaymentLinkMetadata.fromObject(A.paymentLinkMetadata)}if(A.urlMetadata!=null){if(typeof A.urlMetadata!="object")throw TypeError(".proto.Message.LinkPreviewMetadata.urlMetadata: object expected");r.urlMetadata=p.proto.Message.URLMetadata.fromObject(A.urlMetadata)}switch(A.fbExperimentId!=null&&(r.fbExperimentId=A.fbExperimentId>>>0),A.linkMediaDuration!=null&&(r.linkMediaDuration=A.linkMediaDuration>>>0),A.socialMediaPostType){default:if(typeof A.socialMediaPostType=="number"){r.socialMediaPostType=A.socialMediaPostType;break}break;case"NONE":case 0:r.socialMediaPostType=0;break;case"REEL":case 1:r.socialMediaPostType=1;break;case"LIVE_VIDEO":case 2:r.socialMediaPostType=2;break;case"LONG_VIDEO":case 3:r.socialMediaPostType=3;break;case"SINGLE_IMAGE":case 4:r.socialMediaPostType=4;break;case"CAROUSEL":case 5:r.socialMediaPostType=5;break}if(A.linkInlineVideoMuted!=null&&(r.linkInlineVideoMuted=!!A.linkInlineVideoMuted),A.videoContentUrl!=null&&(r.videoContentUrl=String(A.videoContentUrl)),A.musicMetadata!=null){if(typeof A.musicMetadata!="object")throw TypeError(".proto.Message.LinkPreviewMetadata.musicMetadata: object expected");r.musicMetadata=p.proto.EmbeddedMusic.fromObject(A.musicMetadata)}return A.videoContentCaption!=null&&(r.videoContentCaption=String(A.videoContentCaption)),r},i.toObject=function(A,r){r||(r={});var s={};return A.paymentLinkMetadata!=null&&A.hasOwnProperty("paymentLinkMetadata")&&(s.paymentLinkMetadata=p.proto.Message.PaymentLinkMetadata.toObject(A.paymentLinkMetadata,r),r.oneofs&&(s._paymentLinkMetadata="paymentLinkMetadata")),A.urlMetadata!=null&&A.hasOwnProperty("urlMetadata")&&(s.urlMetadata=p.proto.Message.URLMetadata.toObject(A.urlMetadata,r),r.oneofs&&(s._urlMetadata="urlMetadata")),A.fbExperimentId!=null&&A.hasOwnProperty("fbExperimentId")&&(s.fbExperimentId=A.fbExperimentId,r.oneofs&&(s._fbExperimentId="fbExperimentId")),A.linkMediaDuration!=null&&A.hasOwnProperty("linkMediaDuration")&&(s.linkMediaDuration=A.linkMediaDuration,r.oneofs&&(s._linkMediaDuration="linkMediaDuration")),A.socialMediaPostType!=null&&A.hasOwnProperty("socialMediaPostType")&&(s.socialMediaPostType=r.enums===String?p.proto.Message.LinkPreviewMetadata.SocialMediaPostType[A.socialMediaPostType]===void 0?A.socialMediaPostType:p.proto.Message.LinkPreviewMetadata.SocialMediaPostType[A.socialMediaPostType]:A.socialMediaPostType,r.oneofs&&(s._socialMediaPostType="socialMediaPostType")),A.linkInlineVideoMuted!=null&&A.hasOwnProperty("linkInlineVideoMuted")&&(s.linkInlineVideoMuted=A.linkInlineVideoMuted,r.oneofs&&(s._linkInlineVideoMuted="linkInlineVideoMuted")),A.videoContentUrl!=null&&A.hasOwnProperty("videoContentUrl")&&(s.videoContentUrl=A.videoContentUrl,r.oneofs&&(s._videoContentUrl="videoContentUrl")),A.musicMetadata!=null&&A.hasOwnProperty("musicMetadata")&&(s.musicMetadata=p.proto.EmbeddedMusic.toObject(A.musicMetadata,r),r.oneofs&&(s._musicMetadata="musicMetadata")),A.videoContentCaption!=null&&A.hasOwnProperty("videoContentCaption")&&(s.videoContentCaption=A.videoContentCaption,r.oneofs&&(s._videoContentCaption="videoContentCaption")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.LinkPreviewMetadata"},i.SocialMediaPostType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="REEL"]=1,A[a[2]="LIVE_VIDEO"]=2,A[a[3]="LONG_VIDEO"]=3,A[a[4]="SINGLE_IMAGE"]=4,A[a[5]="CAROUSEL"]=5,A})(),i})(),t.ListMessage=(function(){function i(a){if(this.sections=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.title=A.string();break}case 2:{c.description=A.string();break}case 3:{c.buttonText=A.string();break}case 4:{c.listType=A.int32();break}case 5:{c.sections&&c.sections.length||(c.sections=[]),c.sections.push(p.proto.Message.ListMessage.Section.decode(A,A.uint32()));break}case 6:{c.productListInfo=p.proto.Message.ListMessage.ProductListInfo.decode(A,A.uint32());break}case 7:{c.footerText=A.string();break}case 8:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ListMessage)return A;var r=new p.proto.Message.ListMessage;switch(A.title!=null&&(r.title=String(A.title)),A.description!=null&&(r.description=String(A.description)),A.buttonText!=null&&(r.buttonText=String(A.buttonText)),A.listType){default:if(typeof A.listType=="number"){r.listType=A.listType;break}break;case"UNKNOWN":case 0:r.listType=0;break;case"SINGLE_SELECT":case 1:r.listType=1;break;case"PRODUCT_LIST":case 2:r.listType=2;break}if(A.sections){if(!Array.isArray(A.sections))throw TypeError(".proto.Message.ListMessage.sections: array expected");r.sections=[];for(var s=0;s>>3){case 1:{d.productId=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.Product)return s;var g=new p.proto.Message.ListMessage.Product;return s.productId!=null&&(g.productId=String(s.productId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.productId!=null&&s.hasOwnProperty("productId")&&(c.productId=s.productId,g.oneofs&&(c._productId="productId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListMessage.Product"},a})(),i.ProductListHeaderImage=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.productId=s.string();break}case 2:{d.jpegThumbnail=s.bytes();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.ProductListHeaderImage)return s;var g=new p.proto.Message.ListMessage.ProductListHeaderImage;return s.productId!=null&&(g.productId=String(s.productId)),s.jpegThumbnail!=null&&(typeof s.jpegThumbnail=="string"?l.base64.decode(s.jpegThumbnail,g.jpegThumbnail=l.newBuffer(l.base64.length(s.jpegThumbnail)),0):s.jpegThumbnail.length>=0&&(g.jpegThumbnail=s.jpegThumbnail)),g},a.toObject=function(s,g){g||(g={});var c={};return s.productId!=null&&s.hasOwnProperty("productId")&&(c.productId=s.productId,g.oneofs&&(c._productId="productId")),s.jpegThumbnail!=null&&s.hasOwnProperty("jpegThumbnail")&&(c.jpegThumbnail=g.bytes===String?l.base64.encode(s.jpegThumbnail,0,s.jpegThumbnail.length):g.bytes===Array?Array.prototype.slice.call(s.jpegThumbnail):s.jpegThumbnail,g.oneofs&&(c._jpegThumbnail="jpegThumbnail")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListMessage.ProductListHeaderImage"},a})(),i.ProductListInfo=(function(){function a(r){if(this.productSections=[],r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.productSections&&d.productSections.length||(d.productSections=[]),d.productSections.push(p.proto.Message.ListMessage.ProductSection.decode(s,s.uint32()));break}case 2:{d.headerImage=p.proto.Message.ListMessage.ProductListHeaderImage.decode(s,s.uint32());break}case 3:{d.businessOwnerJid=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.ProductListInfo)return s;var g=new p.proto.Message.ListMessage.ProductListInfo;if(s.productSections){if(!Array.isArray(s.productSections))throw TypeError(".proto.Message.ListMessage.ProductListInfo.productSections: array expected");g.productSections=[];for(var c=0;c>>3){case 1:{d.title=s.string();break}case 2:{d.products&&d.products.length||(d.products=[]),d.products.push(p.proto.Message.ListMessage.Product.decode(s,s.uint32()));break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.ProductSection)return s;var g=new p.proto.Message.ListMessage.ProductSection;if(s.title!=null&&(g.title=String(s.title)),s.products){if(!Array.isArray(s.products))throw TypeError(".proto.Message.ListMessage.ProductSection.products: array expected");g.products=[];for(var c=0;c>>3){case 1:{d.title=s.string();break}case 2:{d.description=s.string();break}case 3:{d.rowId=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.Row)return s;var g=new p.proto.Message.ListMessage.Row;return s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),s.rowId!=null&&(g.rowId=String(s.rowId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),s.rowId!=null&&s.hasOwnProperty("rowId")&&(c.rowId=s.rowId,g.oneofs&&(c._rowId="rowId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListMessage.Row"},a})(),i.Section=(function(){function a(r){if(this.rows=[],r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.title=s.string();break}case 2:{d.rows&&d.rows.length||(d.rows=[]),d.rows.push(p.proto.Message.ListMessage.Row.decode(s,s.uint32()));break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.Section)return s;var g=new p.proto.Message.ListMessage.Section;if(s.title!=null&&(g.title=String(s.title)),s.rows){if(!Array.isArray(s.rows))throw TypeError(".proto.Message.ListMessage.Section.rows: array expected");g.rows=[];for(var c=0;c>>3){case 1:{c.title=A.string();break}case 2:{c.listType=A.int32();break}case 3:{c.singleSelectReply=p.proto.Message.ListResponseMessage.SingleSelectReply.decode(A,A.uint32());break}case 4:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 5:{c.description=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ListResponseMessage)return A;var r=new p.proto.Message.ListResponseMessage;switch(A.title!=null&&(r.title=String(A.title)),A.listType){default:if(typeof A.listType=="number"){r.listType=A.listType;break}break;case"UNKNOWN":case 0:r.listType=0;break;case"SINGLE_SELECT":case 1:r.listType=1;break}if(A.singleSelectReply!=null){if(typeof A.singleSelectReply!="object")throw TypeError(".proto.Message.ListResponseMessage.singleSelectReply: object expected");r.singleSelectReply=p.proto.Message.ListResponseMessage.SingleSelectReply.fromObject(A.singleSelectReply)}if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ListResponseMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return A.description!=null&&(r.description=String(A.description)),r},i.toObject=function(A,r){r||(r={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.listType!=null&&A.hasOwnProperty("listType")&&(s.listType=r.enums===String?p.proto.Message.ListResponseMessage.ListType[A.listType]===void 0?A.listType:p.proto.Message.ListResponseMessage.ListType[A.listType]:A.listType,r.oneofs&&(s._listType="listType")),A.singleSelectReply!=null&&A.hasOwnProperty("singleSelectReply")&&(s.singleSelectReply=p.proto.Message.ListResponseMessage.SingleSelectReply.toObject(A.singleSelectReply,r),r.oneofs&&(s._singleSelectReply="singleSelectReply")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.description!=null&&A.hasOwnProperty("description")&&(s.description=A.description,r.oneofs&&(s._description="description")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ListResponseMessage"},i.ListType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="SINGLE_SELECT"]=1,A})(),i.SingleSelectReply=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.selectedRowId=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListResponseMessage.SingleSelectReply)return s;var g=new p.proto.Message.ListResponseMessage.SingleSelectReply;return s.selectedRowId!=null&&(g.selectedRowId=String(s.selectedRowId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.selectedRowId!=null&&s.hasOwnProperty("selectedRowId")&&(c.selectedRowId=s.selectedRowId,g.oneofs&&(c._selectedRowId="selectedRowId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListResponseMessage.SingleSelectReply"},a})(),i})(),t.LiveLocationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.degreesLatitude=A.double();break}case 2:{c.degreesLongitude=A.double();break}case 3:{c.accuracyInMeters=A.uint32();break}case 4:{c.speedInMps=A.float();break}case 5:{c.degreesClockwiseFromMagneticNorth=A.uint32();break}case 6:{c.caption=A.string();break}case 7:{c.sequenceNumber=A.int64();break}case 8:{c.timeOffset=A.uint32();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.LiveLocationMessage)return A;var r=new p.proto.Message.LiveLocationMessage;if(A.degreesLatitude!=null&&(r.degreesLatitude=Number(A.degreesLatitude)),A.degreesLongitude!=null&&(r.degreesLongitude=Number(A.degreesLongitude)),A.accuracyInMeters!=null&&(r.accuracyInMeters=A.accuracyInMeters>>>0),A.speedInMps!=null&&(r.speedInMps=Number(A.speedInMps)),A.degreesClockwiseFromMagneticNorth!=null&&(r.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth>>>0),A.caption!=null&&(r.caption=String(A.caption)),A.sequenceNumber!=null&&(l.Long?(r.sequenceNumber=l.Long.fromValue(A.sequenceNumber)).unsigned=!1:typeof A.sequenceNumber=="string"?r.sequenceNumber=parseInt(A.sequenceNumber,10):typeof A.sequenceNumber=="number"?r.sequenceNumber=A.sequenceNumber:typeof A.sequenceNumber=="object"&&(r.sequenceNumber=new l.LongBits(A.sequenceNumber.low>>>0,A.sequenceNumber.high>>>0).toNumber())),A.timeOffset!=null&&(r.timeOffset=A.timeOffset>>>0),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.LiveLocationMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.degreesLatitude!=null&&A.hasOwnProperty("degreesLatitude")&&(s.degreesLatitude=r.json&&!isFinite(A.degreesLatitude)?String(A.degreesLatitude):A.degreesLatitude,r.oneofs&&(s._degreesLatitude="degreesLatitude")),A.degreesLongitude!=null&&A.hasOwnProperty("degreesLongitude")&&(s.degreesLongitude=r.json&&!isFinite(A.degreesLongitude)?String(A.degreesLongitude):A.degreesLongitude,r.oneofs&&(s._degreesLongitude="degreesLongitude")),A.accuracyInMeters!=null&&A.hasOwnProperty("accuracyInMeters")&&(s.accuracyInMeters=A.accuracyInMeters,r.oneofs&&(s._accuracyInMeters="accuracyInMeters")),A.speedInMps!=null&&A.hasOwnProperty("speedInMps")&&(s.speedInMps=r.json&&!isFinite(A.speedInMps)?String(A.speedInMps):A.speedInMps,r.oneofs&&(s._speedInMps="speedInMps")),A.degreesClockwiseFromMagneticNorth!=null&&A.hasOwnProperty("degreesClockwiseFromMagneticNorth")&&(s.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth,r.oneofs&&(s._degreesClockwiseFromMagneticNorth="degreesClockwiseFromMagneticNorth")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.sequenceNumber!=null&&A.hasOwnProperty("sequenceNumber")&&(typeof A.sequenceNumber=="number"?s.sequenceNumber=r.longs===String?String(A.sequenceNumber):A.sequenceNumber:s.sequenceNumber=r.longs===String?se(A.sequenceNumber):r.longs===Number?ge(A.sequenceNumber):A.sequenceNumber,r.oneofs&&(s._sequenceNumber="sequenceNumber")),A.timeOffset!=null&&A.hasOwnProperty("timeOffset")&&(s.timeOffset=A.timeOffset,r.oneofs&&(s._timeOffset="timeOffset")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.LiveLocationMessage"},i})(),t.LocationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.degreesLatitude=A.double();break}case 2:{c.degreesLongitude=A.double();break}case 3:{c.name=A.string();break}case 4:{c.address=A.string();break}case 5:{c.url=A.string();break}case 6:{c.isLive=A.bool();break}case 7:{c.accuracyInMeters=A.uint32();break}case 8:{c.speedInMps=A.float();break}case 9:{c.degreesClockwiseFromMagneticNorth=A.uint32();break}case 11:{c.comment=A.string();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.LocationMessage)return A;var r=new p.proto.Message.LocationMessage;if(A.degreesLatitude!=null&&(r.degreesLatitude=Number(A.degreesLatitude)),A.degreesLongitude!=null&&(r.degreesLongitude=Number(A.degreesLongitude)),A.name!=null&&(r.name=String(A.name)),A.address!=null&&(r.address=String(A.address)),A.url!=null&&(r.url=String(A.url)),A.isLive!=null&&(r.isLive=!!A.isLive),A.accuracyInMeters!=null&&(r.accuracyInMeters=A.accuracyInMeters>>>0),A.speedInMps!=null&&(r.speedInMps=Number(A.speedInMps)),A.degreesClockwiseFromMagneticNorth!=null&&(r.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth>>>0),A.comment!=null&&(r.comment=String(A.comment)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.LocationMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.degreesLatitude!=null&&A.hasOwnProperty("degreesLatitude")&&(s.degreesLatitude=r.json&&!isFinite(A.degreesLatitude)?String(A.degreesLatitude):A.degreesLatitude,r.oneofs&&(s._degreesLatitude="degreesLatitude")),A.degreesLongitude!=null&&A.hasOwnProperty("degreesLongitude")&&(s.degreesLongitude=r.json&&!isFinite(A.degreesLongitude)?String(A.degreesLongitude):A.degreesLongitude,r.oneofs&&(s._degreesLongitude="degreesLongitude")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.address!=null&&A.hasOwnProperty("address")&&(s.address=A.address,r.oneofs&&(s._address="address")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.isLive!=null&&A.hasOwnProperty("isLive")&&(s.isLive=A.isLive,r.oneofs&&(s._isLive="isLive")),A.accuracyInMeters!=null&&A.hasOwnProperty("accuracyInMeters")&&(s.accuracyInMeters=A.accuracyInMeters,r.oneofs&&(s._accuracyInMeters="accuracyInMeters")),A.speedInMps!=null&&A.hasOwnProperty("speedInMps")&&(s.speedInMps=r.json&&!isFinite(A.speedInMps)?String(A.speedInMps):A.speedInMps,r.oneofs&&(s._speedInMps="speedInMps")),A.degreesClockwiseFromMagneticNorth!=null&&A.hasOwnProperty("degreesClockwiseFromMagneticNorth")&&(s.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth,r.oneofs&&(s._degreesClockwiseFromMagneticNorth="degreesClockwiseFromMagneticNorth")),A.comment!=null&&A.hasOwnProperty("comment")&&(s.comment=A.comment,r.oneofs&&(s._comment="comment")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.LocationMessage"},i})(),t.MMSThumbnailMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.thumbnailDirectPath=A.string();break}case 2:{c.thumbnailSha256=A.bytes();break}case 3:{c.thumbnailEncSha256=A.bytes();break}case 4:{c.mediaKey=A.bytes();break}case 5:{c.mediaKeyTimestamp=A.int64();break}case 6:{c.thumbnailHeight=A.uint32();break}case 7:{c.thumbnailWidth=A.uint32();break}case 8:{c.mediaKeyDomain=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.MMSThumbnailMetadata)return A;var r=new p.proto.Message.MMSThumbnailMetadata;switch(A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.thumbnailHeight!=null&&(r.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(r.thumbnailWidth=A.thumbnailWidth>>>0),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){r.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:r.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:r.mediaKeyDomain=1;break;case"STATUS":case 2:r.mediaKeyDomain=2;break;case"CAPI":case 3:r.mediaKeyDomain=3;break;case"BOT":case 4:r.mediaKeyDomain=4;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.thumbnailDirectPath!=null&&A.hasOwnProperty("thumbnailDirectPath")&&(s.thumbnailDirectPath=A.thumbnailDirectPath,r.oneofs&&(s._thumbnailDirectPath="thumbnailDirectPath")),A.thumbnailSha256!=null&&A.hasOwnProperty("thumbnailSha256")&&(s.thumbnailSha256=r.bytes===String?l.base64.encode(A.thumbnailSha256,0,A.thumbnailSha256.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnailSha256):A.thumbnailSha256,r.oneofs&&(s._thumbnailSha256="thumbnailSha256")),A.thumbnailEncSha256!=null&&A.hasOwnProperty("thumbnailEncSha256")&&(s.thumbnailEncSha256=r.bytes===String?l.base64.encode(A.thumbnailEncSha256,0,A.thumbnailEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnailEncSha256):A.thumbnailEncSha256,r.oneofs&&(s._thumbnailEncSha256="thumbnailEncSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.thumbnailHeight!=null&&A.hasOwnProperty("thumbnailHeight")&&(s.thumbnailHeight=A.thumbnailHeight,r.oneofs&&(s._thumbnailHeight="thumbnailHeight")),A.thumbnailWidth!=null&&A.hasOwnProperty("thumbnailWidth")&&(s.thumbnailWidth=A.thumbnailWidth,r.oneofs&&(s._thumbnailWidth="thumbnailWidth")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=r.enums===String?p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,r.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.MMSThumbnailMetadata"},i})(),t.MediaKeyDomain=(function(){let i={},e=Object.create(i);return e[i[0]="UNSET"]=0,e[i[1]="E2EE_CHAT"]=1,e[i[2]="STATUS"]=2,e[i[3]="CAPI"]=3,e[i[4]="BOT"]=4,e})(),t.MessageHistoryBundle=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.mimetype=A.string();break}case 2:{c.fileSha256=A.bytes();break}case 3:{c.mediaKey=A.bytes();break}case 4:{c.fileEncSha256=A.bytes();break}case 5:{c.directPath=A.string();break}case 6:{c.mediaKeyTimestamp=A.int64();break}case 7:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 8:{c.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.MessageHistoryBundle)return A;var r=new p.proto.Message.MessageHistoryBundle;if(A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(r.directPath=String(A.directPath)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.MessageHistoryBundle.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.messageHistoryMetadata!=null){if(typeof A.messageHistoryMetadata!="object")throw TypeError(".proto.Message.MessageHistoryBundle.messageHistoryMetadata: object expected");r.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.fromObject(A.messageHistoryMetadata)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.messageHistoryMetadata!=null&&A.hasOwnProperty("messageHistoryMetadata")&&(s.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.toObject(A.messageHistoryMetadata,r),r.oneofs&&(s._messageHistoryMetadata="messageHistoryMetadata")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.MessageHistoryBundle"},i})(),t.MessageHistoryMetadata=(function(){function i(a){if(this.historyReceivers=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.historyReceivers&&c.historyReceivers.length||(c.historyReceivers=[]),c.historyReceivers.push(A.string());break}case 2:{c.oldestMessageTimestamp=A.int64();break}case 3:{c.messageCount=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.MessageHistoryMetadata)return A;var r=new p.proto.Message.MessageHistoryMetadata;if(A.historyReceivers){if(!Array.isArray(A.historyReceivers))throw TypeError(".proto.Message.MessageHistoryMetadata.historyReceivers: array expected");r.historyReceivers=[];for(var s=0;s>>0,A.oldestMessageTimestamp.high>>>0).toNumber())),A.messageCount!=null&&(l.Long?(r.messageCount=l.Long.fromValue(A.messageCount)).unsigned=!1:typeof A.messageCount=="string"?r.messageCount=parseInt(A.messageCount,10):typeof A.messageCount=="number"?r.messageCount=A.messageCount:typeof A.messageCount=="object"&&(r.messageCount=new l.LongBits(A.messageCount.low>>>0,A.messageCount.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.historyReceivers=[]),A.historyReceivers&&A.historyReceivers.length){s.historyReceivers=[];for(var g=0;g>>3){case 1:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 2:{c.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.MessageHistoryNotice)return A;var r=new p.proto.Message.MessageHistoryNotice;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.MessageHistoryNotice.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.messageHistoryMetadata!=null){if(typeof A.messageHistoryMetadata!="object")throw TypeError(".proto.Message.MessageHistoryNotice.messageHistoryMetadata: object expected");r.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.fromObject(A.messageHistoryMetadata)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.messageHistoryMetadata!=null&&A.hasOwnProperty("messageHistoryMetadata")&&(s.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.toObject(A.messageHistoryMetadata,r),r.oneofs&&(s._messageHistoryMetadata="messageHistoryMetadata")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.MessageHistoryNotice"},i})(),t.NewsletterAdminInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.newsletterJid=A.string();break}case 2:{c.newsletterName=A.string();break}case 3:{c.jpegThumbnail=A.bytes();break}case 4:{c.caption=A.string();break}case 5:{c.inviteExpiration=A.int64();break}case 6:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.NewsletterAdminInviteMessage)return A;var r=new p.proto.Message.NewsletterAdminInviteMessage;if(A.newsletterJid!=null&&(r.newsletterJid=String(A.newsletterJid)),A.newsletterName!=null&&(r.newsletterName=String(A.newsletterName)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(r.caption=String(A.caption)),A.inviteExpiration!=null&&(l.Long?(r.inviteExpiration=l.Long.fromValue(A.inviteExpiration)).unsigned=!1:typeof A.inviteExpiration=="string"?r.inviteExpiration=parseInt(A.inviteExpiration,10):typeof A.inviteExpiration=="number"?r.inviteExpiration=A.inviteExpiration:typeof A.inviteExpiration=="object"&&(r.inviteExpiration=new l.LongBits(A.inviteExpiration.low>>>0,A.inviteExpiration.high>>>0).toNumber())),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.NewsletterAdminInviteMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.newsletterJid!=null&&A.hasOwnProperty("newsletterJid")&&(s.newsletterJid=A.newsletterJid,r.oneofs&&(s._newsletterJid="newsletterJid")),A.newsletterName!=null&&A.hasOwnProperty("newsletterName")&&(s.newsletterName=A.newsletterName,r.oneofs&&(s._newsletterName="newsletterName")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.inviteExpiration!=null&&A.hasOwnProperty("inviteExpiration")&&(typeof A.inviteExpiration=="number"?s.inviteExpiration=r.longs===String?String(A.inviteExpiration):A.inviteExpiration:s.inviteExpiration=r.longs===String?se(A.inviteExpiration):r.longs===Number?ge(A.inviteExpiration):A.inviteExpiration,r.oneofs&&(s._inviteExpiration="inviteExpiration")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.NewsletterAdminInviteMessage"},i})(),t.NewsletterFollowerInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.newsletterJid=A.string();break}case 2:{c.newsletterName=A.string();break}case 3:{c.jpegThumbnail=A.bytes();break}case 4:{c.caption=A.string();break}case 5:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.NewsletterFollowerInviteMessage)return A;var r=new p.proto.Message.NewsletterFollowerInviteMessage;if(A.newsletterJid!=null&&(r.newsletterJid=String(A.newsletterJid)),A.newsletterName!=null&&(r.newsletterName=String(A.newsletterName)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(r.caption=String(A.caption)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.NewsletterFollowerInviteMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.newsletterJid!=null&&A.hasOwnProperty("newsletterJid")&&(s.newsletterJid=A.newsletterJid,r.oneofs&&(s._newsletterJid="newsletterJid")),A.newsletterName!=null&&A.hasOwnProperty("newsletterName")&&(s.newsletterName=A.newsletterName,r.oneofs&&(s._newsletterName="newsletterName")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.NewsletterFollowerInviteMessage"},i})(),t.OrderMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.orderId=A.string();break}case 2:{c.thumbnail=A.bytes();break}case 3:{c.itemCount=A.int32();break}case 4:{c.status=A.int32();break}case 5:{c.surface=A.int32();break}case 6:{c.message=A.string();break}case 7:{c.orderTitle=A.string();break}case 8:{c.sellerJid=A.string();break}case 9:{c.token=A.string();break}case 10:{c.totalAmount1000=A.int64();break}case 11:{c.totalCurrencyCode=A.string();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 12:{c.messageVersion=A.int32();break}case 13:{c.orderRequestMessageId=p.proto.MessageKey.decode(A,A.uint32());break}case 15:{c.catalogType=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.OrderMessage)return A;var r=new p.proto.Message.OrderMessage;switch(A.orderId!=null&&(r.orderId=String(A.orderId)),A.thumbnail!=null&&(typeof A.thumbnail=="string"?l.base64.decode(A.thumbnail,r.thumbnail=l.newBuffer(l.base64.length(A.thumbnail)),0):A.thumbnail.length>=0&&(r.thumbnail=A.thumbnail)),A.itemCount!=null&&(r.itemCount=A.itemCount|0),A.status){default:if(typeof A.status=="number"){r.status=A.status;break}break;case"INQUIRY":case 1:r.status=1;break;case"ACCEPTED":case 2:r.status=2;break;case"DECLINED":case 3:r.status=3;break}switch(A.surface){default:if(typeof A.surface=="number"){r.surface=A.surface;break}break;case"CATALOG":case 1:r.surface=1;break}if(A.message!=null&&(r.message=String(A.message)),A.orderTitle!=null&&(r.orderTitle=String(A.orderTitle)),A.sellerJid!=null&&(r.sellerJid=String(A.sellerJid)),A.token!=null&&(r.token=String(A.token)),A.totalAmount1000!=null&&(l.Long?(r.totalAmount1000=l.Long.fromValue(A.totalAmount1000)).unsigned=!1:typeof A.totalAmount1000=="string"?r.totalAmount1000=parseInt(A.totalAmount1000,10):typeof A.totalAmount1000=="number"?r.totalAmount1000=A.totalAmount1000:typeof A.totalAmount1000=="object"&&(r.totalAmount1000=new l.LongBits(A.totalAmount1000.low>>>0,A.totalAmount1000.high>>>0).toNumber())),A.totalCurrencyCode!=null&&(r.totalCurrencyCode=String(A.totalCurrencyCode)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.OrderMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.messageVersion!=null&&(r.messageVersion=A.messageVersion|0),A.orderRequestMessageId!=null){if(typeof A.orderRequestMessageId!="object")throw TypeError(".proto.Message.OrderMessage.orderRequestMessageId: object expected");r.orderRequestMessageId=p.proto.MessageKey.fromObject(A.orderRequestMessageId)}return A.catalogType!=null&&(r.catalogType=String(A.catalogType)),r},i.toObject=function(A,r){r||(r={});var s={};return A.orderId!=null&&A.hasOwnProperty("orderId")&&(s.orderId=A.orderId,r.oneofs&&(s._orderId="orderId")),A.thumbnail!=null&&A.hasOwnProperty("thumbnail")&&(s.thumbnail=r.bytes===String?l.base64.encode(A.thumbnail,0,A.thumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnail):A.thumbnail,r.oneofs&&(s._thumbnail="thumbnail")),A.itemCount!=null&&A.hasOwnProperty("itemCount")&&(s.itemCount=A.itemCount,r.oneofs&&(s._itemCount="itemCount")),A.status!=null&&A.hasOwnProperty("status")&&(s.status=r.enums===String?p.proto.Message.OrderMessage.OrderStatus[A.status]===void 0?A.status:p.proto.Message.OrderMessage.OrderStatus[A.status]:A.status,r.oneofs&&(s._status="status")),A.surface!=null&&A.hasOwnProperty("surface")&&(s.surface=r.enums===String?p.proto.Message.OrderMessage.OrderSurface[A.surface]===void 0?A.surface:p.proto.Message.OrderMessage.OrderSurface[A.surface]:A.surface,r.oneofs&&(s._surface="surface")),A.message!=null&&A.hasOwnProperty("message")&&(s.message=A.message,r.oneofs&&(s._message="message")),A.orderTitle!=null&&A.hasOwnProperty("orderTitle")&&(s.orderTitle=A.orderTitle,r.oneofs&&(s._orderTitle="orderTitle")),A.sellerJid!=null&&A.hasOwnProperty("sellerJid")&&(s.sellerJid=A.sellerJid,r.oneofs&&(s._sellerJid="sellerJid")),A.token!=null&&A.hasOwnProperty("token")&&(s.token=A.token,r.oneofs&&(s._token="token")),A.totalAmount1000!=null&&A.hasOwnProperty("totalAmount1000")&&(typeof A.totalAmount1000=="number"?s.totalAmount1000=r.longs===String?String(A.totalAmount1000):A.totalAmount1000:s.totalAmount1000=r.longs===String?se(A.totalAmount1000):r.longs===Number?ge(A.totalAmount1000):A.totalAmount1000,r.oneofs&&(s._totalAmount1000="totalAmount1000")),A.totalCurrencyCode!=null&&A.hasOwnProperty("totalCurrencyCode")&&(s.totalCurrencyCode=A.totalCurrencyCode,r.oneofs&&(s._totalCurrencyCode="totalCurrencyCode")),A.messageVersion!=null&&A.hasOwnProperty("messageVersion")&&(s.messageVersion=A.messageVersion,r.oneofs&&(s._messageVersion="messageVersion")),A.orderRequestMessageId!=null&&A.hasOwnProperty("orderRequestMessageId")&&(s.orderRequestMessageId=p.proto.MessageKey.toObject(A.orderRequestMessageId,r),r.oneofs&&(s._orderRequestMessageId="orderRequestMessageId")),A.catalogType!=null&&A.hasOwnProperty("catalogType")&&(s.catalogType=A.catalogType,r.oneofs&&(s._catalogType="catalogType")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.OrderMessage"},i.OrderStatus=(function(){let a={},A=Object.create(a);return A[a[1]="INQUIRY"]=1,A[a[2]="ACCEPTED"]=2,A[a[3]="DECLINED"]=3,A})(),i.OrderSurface=(function(){let a={},A=Object.create(a);return A[a[1]="CATALOG"]=1,A})(),i})(),t.PaymentExtendedMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.type=A.uint32();break}case 2:{c.platform=A.string();break}case 3:{c.messageParamsJson=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PaymentExtendedMetadata)return A;var r=new p.proto.Message.PaymentExtendedMetadata;return A.type!=null&&(r.type=A.type>>>0),A.platform!=null&&(r.platform=String(A.platform)),A.messageParamsJson!=null&&(r.messageParamsJson=String(A.messageParamsJson)),r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=A.type,r.oneofs&&(s._type="type")),A.platform!=null&&A.hasOwnProperty("platform")&&(s.platform=A.platform,r.oneofs&&(s._platform="platform")),A.messageParamsJson!=null&&A.hasOwnProperty("messageParamsJson")&&(s.messageParamsJson=A.messageParamsJson,r.oneofs&&(s._messageParamsJson="messageParamsJson")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PaymentExtendedMetadata"},i})(),t.PaymentInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.serviceType=A.int32();break}case 2:{c.expiryTimestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PaymentInviteMessage)return A;var r=new p.proto.Message.PaymentInviteMessage;switch(A.serviceType){default:if(typeof A.serviceType=="number"){r.serviceType=A.serviceType;break}break;case"UNKNOWN":case 0:r.serviceType=0;break;case"FBPAY":case 1:r.serviceType=1;break;case"NOVI":case 2:r.serviceType=2;break;case"UPI":case 3:r.serviceType=3;break}return A.expiryTimestamp!=null&&(l.Long?(r.expiryTimestamp=l.Long.fromValue(A.expiryTimestamp)).unsigned=!1:typeof A.expiryTimestamp=="string"?r.expiryTimestamp=parseInt(A.expiryTimestamp,10):typeof A.expiryTimestamp=="number"?r.expiryTimestamp=A.expiryTimestamp:typeof A.expiryTimestamp=="object"&&(r.expiryTimestamp=new l.LongBits(A.expiryTimestamp.low>>>0,A.expiryTimestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.serviceType!=null&&A.hasOwnProperty("serviceType")&&(s.serviceType=r.enums===String?p.proto.Message.PaymentInviteMessage.ServiceType[A.serviceType]===void 0?A.serviceType:p.proto.Message.PaymentInviteMessage.ServiceType[A.serviceType]:A.serviceType,r.oneofs&&(s._serviceType="serviceType")),A.expiryTimestamp!=null&&A.hasOwnProperty("expiryTimestamp")&&(typeof A.expiryTimestamp=="number"?s.expiryTimestamp=r.longs===String?String(A.expiryTimestamp):A.expiryTimestamp:s.expiryTimestamp=r.longs===String?se(A.expiryTimestamp):r.longs===Number?ge(A.expiryTimestamp):A.expiryTimestamp,r.oneofs&&(s._expiryTimestamp="expiryTimestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PaymentInviteMessage"},i.ServiceType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="FBPAY"]=1,A[a[2]="NOVI"]=2,A[a[3]="UPI"]=3,A})(),i})(),t.PaymentLinkMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.button=p.proto.Message.PaymentLinkMetadata.PaymentLinkButton.decode(A,A.uint32());break}case 2:{c.header=p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.decode(A,A.uint32());break}case 3:{c.provider=p.proto.Message.PaymentLinkMetadata.PaymentLinkProvider.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PaymentLinkMetadata)return A;var r=new p.proto.Message.PaymentLinkMetadata;if(A.button!=null){if(typeof A.button!="object")throw TypeError(".proto.Message.PaymentLinkMetadata.button: object expected");r.button=p.proto.Message.PaymentLinkMetadata.PaymentLinkButton.fromObject(A.button)}if(A.header!=null){if(typeof A.header!="object")throw TypeError(".proto.Message.PaymentLinkMetadata.header: object expected");r.header=p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.fromObject(A.header)}if(A.provider!=null){if(typeof A.provider!="object")throw TypeError(".proto.Message.PaymentLinkMetadata.provider: object expected");r.provider=p.proto.Message.PaymentLinkMetadata.PaymentLinkProvider.fromObject(A.provider)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.button!=null&&A.hasOwnProperty("button")&&(s.button=p.proto.Message.PaymentLinkMetadata.PaymentLinkButton.toObject(A.button,r),r.oneofs&&(s._button="button")),A.header!=null&&A.hasOwnProperty("header")&&(s.header=p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.toObject(A.header,r),r.oneofs&&(s._header="header")),A.provider!=null&&A.hasOwnProperty("provider")&&(s.provider=p.proto.Message.PaymentLinkMetadata.PaymentLinkProvider.toObject(A.provider,r),r.oneofs&&(s._provider="provider")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PaymentLinkMetadata"},i.PaymentLinkButton=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.displayText=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PaymentLinkMetadata.PaymentLinkButton)return s;var g=new p.proto.Message.PaymentLinkMetadata.PaymentLinkButton;return s.displayText!=null&&(g.displayText=String(s.displayText)),g},a.toObject=function(s,g){g||(g={});var c={};return s.displayText!=null&&s.hasOwnProperty("displayText")&&(c.displayText=s.displayText,g.oneofs&&(c._displayText="displayText")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PaymentLinkMetadata.PaymentLinkButton"},a})(),i.PaymentLinkHeader=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.headerType=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader)return s;var g=new p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader;switch(s.headerType){default:if(typeof s.headerType=="number"){g.headerType=s.headerType;break}break;case"LINK_PREVIEW":case 0:g.headerType=0;break;case"ORDER":case 1:g.headerType=1;break}return g},a.toObject=function(s,g){g||(g={});var c={};return s.headerType!=null&&s.hasOwnProperty("headerType")&&(c.headerType=g.enums===String?p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.PaymentLinkHeaderType[s.headerType]===void 0?s.headerType:p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.PaymentLinkHeaderType[s.headerType]:s.headerType,g.oneofs&&(c._headerType="headerType")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PaymentLinkMetadata.PaymentLinkHeader"},a.PaymentLinkHeaderType=(function(){let r={},s=Object.create(r);return s[r[0]="LINK_PREVIEW"]=0,s[r[1]="ORDER"]=1,s})(),a})(),i.PaymentLinkProvider=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.paramsJson=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PaymentLinkMetadata.PaymentLinkProvider)return s;var g=new p.proto.Message.PaymentLinkMetadata.PaymentLinkProvider;return s.paramsJson!=null&&(g.paramsJson=String(s.paramsJson)),g},a.toObject=function(s,g){g||(g={});var c={};return s.paramsJson!=null&&s.hasOwnProperty("paramsJson")&&(c.paramsJson=s.paramsJson,g.oneofs&&(c._paramsJson="paramsJson")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PaymentLinkMetadata.PaymentLinkProvider"},a})(),i})(),t.PeerDataOperationRequestMessage=(function(){function i(a){if(this.requestStickerReupload=[],this.requestUrlPreview=[],this.placeholderMessageResendRequest=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.peerDataOperationRequestType=A.int32();break}case 2:{c.requestStickerReupload&&c.requestStickerReupload.length||(c.requestStickerReupload=[]),c.requestStickerReupload.push(p.proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload.decode(A,A.uint32()));break}case 3:{c.requestUrlPreview&&c.requestUrlPreview.length||(c.requestUrlPreview=[]),c.requestUrlPreview.push(p.proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview.decode(A,A.uint32()));break}case 4:{c.historySyncOnDemandRequest=p.proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest.decode(A,A.uint32());break}case 5:{c.placeholderMessageResendRequest&&c.placeholderMessageResendRequest.length||(c.placeholderMessageResendRequest=[]),c.placeholderMessageResendRequest.push(p.proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest.decode(A,A.uint32()));break}case 6:{c.fullHistorySyncOnDemandRequest=p.proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest.decode(A,A.uint32());break}case 7:{c.syncdCollectionFatalRecoveryRequest=p.proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest.decode(A,A.uint32());break}case 8:{c.historySyncChunkRetryRequest=p.proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest.decode(A,A.uint32());break}case 9:{c.galaxyFlowAction=p.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PeerDataOperationRequestMessage)return A;var r=new p.proto.Message.PeerDataOperationRequestMessage;switch(A.peerDataOperationRequestType){default:if(typeof A.peerDataOperationRequestType=="number"){r.peerDataOperationRequestType=A.peerDataOperationRequestType;break}break;case"UPLOAD_STICKER":case 0:r.peerDataOperationRequestType=0;break;case"SEND_RECENT_STICKER_BOOTSTRAP":case 1:r.peerDataOperationRequestType=1;break;case"GENERATE_LINK_PREVIEW":case 2:r.peerDataOperationRequestType=2;break;case"HISTORY_SYNC_ON_DEMAND":case 3:r.peerDataOperationRequestType=3;break;case"PLACEHOLDER_MESSAGE_RESEND":case 4:r.peerDataOperationRequestType=4;break;case"WAFFLE_LINKING_NONCE_FETCH":case 5:r.peerDataOperationRequestType=5;break;case"FULL_HISTORY_SYNC_ON_DEMAND":case 6:r.peerDataOperationRequestType=6;break;case"COMPANION_META_NONCE_FETCH":case 7:r.peerDataOperationRequestType=7;break;case"COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY":case 8:r.peerDataOperationRequestType=8;break;case"COMPANION_CANONICAL_USER_NONCE_FETCH":case 9:r.peerDataOperationRequestType=9;break;case"HISTORY_SYNC_CHUNK_RETRY":case 10:r.peerDataOperationRequestType=10;break;case"GALAXY_FLOW_ACTION":case 11:r.peerDataOperationRequestType=11;break}if(A.requestStickerReupload){if(!Array.isArray(A.requestStickerReupload))throw TypeError(".proto.Message.PeerDataOperationRequestMessage.requestStickerReupload: array expected");r.requestStickerReupload=[];for(var s=0;s>>3){case 1:{d.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.decode(s,s.uint32());break}case 2:{d.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest;if(s.requestMetadata!=null){if(typeof s.requestMetadata!="object")throw TypeError(".proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest.requestMetadata: object expected");g.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.fromObject(s.requestMetadata)}if(s.historySyncConfig!=null){if(typeof s.historySyncConfig!="object")throw TypeError(".proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest.historySyncConfig: object expected");g.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.fromObject(s.historySyncConfig)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.requestMetadata!=null&&s.hasOwnProperty("requestMetadata")&&(c.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.toObject(s.requestMetadata,g),g.oneofs&&(c._requestMetadata="requestMetadata")),s.historySyncConfig!=null&&s.hasOwnProperty("historySyncConfig")&&(c.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.toObject(s.historySyncConfig,g),g.oneofs&&(c._historySyncConfig="historySyncConfig")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest"},a})(),i.GalaxyFlowAction=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.type=s.int32();break}case 2:{d.flowId=s.string();break}case 3:{d.stanzaId=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction;switch(s.type){default:if(typeof s.type=="number"){g.type=s.type;break}break;case"NOTIFY_LAUNCH":case 1:g.type=1;break}return s.flowId!=null&&(g.flowId=String(s.flowId)),s.stanzaId!=null&&(g.stanzaId=String(s.stanzaId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.type!=null&&s.hasOwnProperty("type")&&(c.type=g.enums===String?p.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction.GalaxyFlowActionType[s.type]===void 0?s.type:p.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction.GalaxyFlowActionType[s.type]:s.type,g.oneofs&&(c._type="type")),s.flowId!=null&&s.hasOwnProperty("flowId")&&(c.flowId=s.flowId,g.oneofs&&(c._flowId="flowId")),s.stanzaId!=null&&s.hasOwnProperty("stanzaId")&&(c.stanzaId=s.stanzaId,g.oneofs&&(c._stanzaId="stanzaId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction"},a.GalaxyFlowActionType=(function(){let r={},s=Object.create(r);return s[r[1]="NOTIFY_LAUNCH"]=1,s})(),a})(),i.HistorySyncChunkRetryRequest=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.syncType=s.int32();break}case 2:{d.chunkOrder=s.uint32();break}case 3:{d.chunkNotificationId=s.string();break}case 4:{d.regenerateChunk=s.bool();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest;switch(s.syncType){default:if(typeof s.syncType=="number"){g.syncType=s.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:g.syncType=0;break;case"INITIAL_STATUS_V3":case 1:g.syncType=1;break;case"FULL":case 2:g.syncType=2;break;case"RECENT":case 3:g.syncType=3;break;case"PUSH_NAME":case 4:g.syncType=4;break;case"NON_BLOCKING_DATA":case 5:g.syncType=5;break;case"ON_DEMAND":case 6:g.syncType=6;break;case"NO_HISTORY":case 7:g.syncType=7;break;case"MESSAGE_ACCESS_STATUS":case 8:g.syncType=8;break}return s.chunkOrder!=null&&(g.chunkOrder=s.chunkOrder>>>0),s.chunkNotificationId!=null&&(g.chunkNotificationId=String(s.chunkNotificationId)),s.regenerateChunk!=null&&(g.regenerateChunk=!!s.regenerateChunk),g},a.toObject=function(s,g){g||(g={});var c={};return s.syncType!=null&&s.hasOwnProperty("syncType")&&(c.syncType=g.enums===String?p.proto.Message.HistorySyncType[s.syncType]===void 0?s.syncType:p.proto.Message.HistorySyncType[s.syncType]:s.syncType,g.oneofs&&(c._syncType="syncType")),s.chunkOrder!=null&&s.hasOwnProperty("chunkOrder")&&(c.chunkOrder=s.chunkOrder,g.oneofs&&(c._chunkOrder="chunkOrder")),s.chunkNotificationId!=null&&s.hasOwnProperty("chunkNotificationId")&&(c.chunkNotificationId=s.chunkNotificationId,g.oneofs&&(c._chunkNotificationId="chunkNotificationId")),s.regenerateChunk!=null&&s.hasOwnProperty("regenerateChunk")&&(c.regenerateChunk=s.regenerateChunk,g.oneofs&&(c._regenerateChunk="regenerateChunk")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest"},a})(),i.HistorySyncOnDemandRequest=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.chatJid=s.string();break}case 2:{d.oldestMsgId=s.string();break}case 3:{d.oldestMsgFromMe=s.bool();break}case 4:{d.onDemandMsgCount=s.int32();break}case 5:{d.oldestMsgTimestampMs=s.int64();break}case 6:{d.accountLid=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest;return s.chatJid!=null&&(g.chatJid=String(s.chatJid)),s.oldestMsgId!=null&&(g.oldestMsgId=String(s.oldestMsgId)),s.oldestMsgFromMe!=null&&(g.oldestMsgFromMe=!!s.oldestMsgFromMe),s.onDemandMsgCount!=null&&(g.onDemandMsgCount=s.onDemandMsgCount|0),s.oldestMsgTimestampMs!=null&&(l.Long?(g.oldestMsgTimestampMs=l.Long.fromValue(s.oldestMsgTimestampMs)).unsigned=!1:typeof s.oldestMsgTimestampMs=="string"?g.oldestMsgTimestampMs=parseInt(s.oldestMsgTimestampMs,10):typeof s.oldestMsgTimestampMs=="number"?g.oldestMsgTimestampMs=s.oldestMsgTimestampMs:typeof s.oldestMsgTimestampMs=="object"&&(g.oldestMsgTimestampMs=new l.LongBits(s.oldestMsgTimestampMs.low>>>0,s.oldestMsgTimestampMs.high>>>0).toNumber())),s.accountLid!=null&&(g.accountLid=String(s.accountLid)),g},a.toObject=function(s,g){g||(g={});var c={};return s.chatJid!=null&&s.hasOwnProperty("chatJid")&&(c.chatJid=s.chatJid,g.oneofs&&(c._chatJid="chatJid")),s.oldestMsgId!=null&&s.hasOwnProperty("oldestMsgId")&&(c.oldestMsgId=s.oldestMsgId,g.oneofs&&(c._oldestMsgId="oldestMsgId")),s.oldestMsgFromMe!=null&&s.hasOwnProperty("oldestMsgFromMe")&&(c.oldestMsgFromMe=s.oldestMsgFromMe,g.oneofs&&(c._oldestMsgFromMe="oldestMsgFromMe")),s.onDemandMsgCount!=null&&s.hasOwnProperty("onDemandMsgCount")&&(c.onDemandMsgCount=s.onDemandMsgCount,g.oneofs&&(c._onDemandMsgCount="onDemandMsgCount")),s.oldestMsgTimestampMs!=null&&s.hasOwnProperty("oldestMsgTimestampMs")&&(typeof s.oldestMsgTimestampMs=="number"?c.oldestMsgTimestampMs=g.longs===String?String(s.oldestMsgTimestampMs):s.oldestMsgTimestampMs:c.oldestMsgTimestampMs=g.longs===String?se(s.oldestMsgTimestampMs):g.longs===Number?ge(s.oldestMsgTimestampMs):s.oldestMsgTimestampMs,g.oneofs&&(c._oldestMsgTimestampMs="oldestMsgTimestampMs")),s.accountLid!=null&&s.hasOwnProperty("accountLid")&&(c.accountLid=s.accountLid,g.oneofs&&(c._accountLid="accountLid")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest"},a})(),i.PlaceholderMessageResendRequest=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.messageKey=p.proto.MessageKey.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest;if(s.messageKey!=null){if(typeof s.messageKey!="object")throw TypeError(".proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest.messageKey: object expected");g.messageKey=p.proto.MessageKey.fromObject(s.messageKey)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.messageKey!=null&&s.hasOwnProperty("messageKey")&&(c.messageKey=p.proto.MessageKey.toObject(s.messageKey,g),g.oneofs&&(c._messageKey="messageKey")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest"},a})(),i.RequestStickerReupload=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.fileSha256=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload;return s.fileSha256!=null&&(g.fileSha256=String(s.fileSha256)),g},a.toObject=function(s,g){g||(g={});var c={};return s.fileSha256!=null&&s.hasOwnProperty("fileSha256")&&(c.fileSha256=s.fileSha256,g.oneofs&&(c._fileSha256="fileSha256")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload"},a})(),i.RequestUrlPreview=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.url=s.string();break}case 2:{d.includeHqThumbnail=s.bool();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview;return s.url!=null&&(g.url=String(s.url)),s.includeHqThumbnail!=null&&(g.includeHqThumbnail=!!s.includeHqThumbnail),g},a.toObject=function(s,g){g||(g={});var c={};return s.url!=null&&s.hasOwnProperty("url")&&(c.url=s.url,g.oneofs&&(c._url="url")),s.includeHqThumbnail!=null&&s.hasOwnProperty("includeHqThumbnail")&&(c.includeHqThumbnail=s.includeHqThumbnail,g.oneofs&&(c._includeHqThumbnail="includeHqThumbnail")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview"},a})(),i.SyncDCollectionFatalRecoveryRequest=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.collectionName=s.string();break}case 2:{d.timestamp=s.int64();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest;return s.collectionName!=null&&(g.collectionName=String(s.collectionName)),s.timestamp!=null&&(l.Long?(g.timestamp=l.Long.fromValue(s.timestamp)).unsigned=!1:typeof s.timestamp=="string"?g.timestamp=parseInt(s.timestamp,10):typeof s.timestamp=="number"?g.timestamp=s.timestamp:typeof s.timestamp=="object"&&(g.timestamp=new l.LongBits(s.timestamp.low>>>0,s.timestamp.high>>>0).toNumber())),g},a.toObject=function(s,g){g||(g={});var c={};return s.collectionName!=null&&s.hasOwnProperty("collectionName")&&(c.collectionName=s.collectionName,g.oneofs&&(c._collectionName="collectionName")),s.timestamp!=null&&s.hasOwnProperty("timestamp")&&(typeof s.timestamp=="number"?c.timestamp=g.longs===String?String(s.timestamp):s.timestamp:c.timestamp=g.longs===String?se(s.timestamp):g.longs===Number?ge(s.timestamp):s.timestamp,g.oneofs&&(c._timestamp="timestamp")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest"},a})(),i})(),t.PeerDataOperationRequestResponseMessage=(function(){function i(a){if(this.peerDataOperationResult=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.peerDataOperationRequestType=A.int32();break}case 2:{c.stanzaId=A.string();break}case 3:{c.peerDataOperationResult&&c.peerDataOperationResult.length||(c.peerDataOperationResult=[]),c.peerDataOperationResult.push(p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PeerDataOperationRequestResponseMessage)return A;var r=new p.proto.Message.PeerDataOperationRequestResponseMessage;switch(A.peerDataOperationRequestType){default:if(typeof A.peerDataOperationRequestType=="number"){r.peerDataOperationRequestType=A.peerDataOperationRequestType;break}break;case"UPLOAD_STICKER":case 0:r.peerDataOperationRequestType=0;break;case"SEND_RECENT_STICKER_BOOTSTRAP":case 1:r.peerDataOperationRequestType=1;break;case"GENERATE_LINK_PREVIEW":case 2:r.peerDataOperationRequestType=2;break;case"HISTORY_SYNC_ON_DEMAND":case 3:r.peerDataOperationRequestType=3;break;case"PLACEHOLDER_MESSAGE_RESEND":case 4:r.peerDataOperationRequestType=4;break;case"WAFFLE_LINKING_NONCE_FETCH":case 5:r.peerDataOperationRequestType=5;break;case"FULL_HISTORY_SYNC_ON_DEMAND":case 6:r.peerDataOperationRequestType=6;break;case"COMPANION_META_NONCE_FETCH":case 7:r.peerDataOperationRequestType=7;break;case"COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY":case 8:r.peerDataOperationRequestType=8;break;case"COMPANION_CANONICAL_USER_NONCE_FETCH":case 9:r.peerDataOperationRequestType=9;break;case"HISTORY_SYNC_CHUNK_RETRY":case 10:r.peerDataOperationRequestType=10;break;case"GALAXY_FLOW_ACTION":case 11:r.peerDataOperationRequestType=11;break}if(A.stanzaId!=null&&(r.stanzaId=String(A.stanzaId)),A.peerDataOperationResult){if(!Array.isArray(A.peerDataOperationResult))throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.peerDataOperationResult: array expected");r.peerDataOperationResult=[];for(var s=0;s>>3){case 1:{d.mediaUploadResult=s.int32();break}case 2:{d.stickerMessage=p.proto.Message.StickerMessage.decode(s,s.uint32());break}case 3:{d.linkPreviewResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.decode(s,s.uint32());break}case 4:{d.placeholderMessageResendResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse.decode(s,s.uint32());break}case 5:{d.waffleNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse.decode(s,s.uint32());break}case 6:{d.fullHistorySyncOnDemandRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.decode(s,s.uint32());break}case 7:{d.companionMetaNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse.decode(s,s.uint32());break}case 8:{d.syncdSnapshotFatalRecoveryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse.decode(s,s.uint32());break}case 9:{d.companionCanonicalUserNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse.decode(s,s.uint32());break}case 10:{d.historySyncChunkRetryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult)return s;var g=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult;switch(s.mediaUploadResult){default:if(typeof s.mediaUploadResult=="number"){g.mediaUploadResult=s.mediaUploadResult;break}break;case"GENERAL_ERROR":case 0:g.mediaUploadResult=0;break;case"SUCCESS":case 1:g.mediaUploadResult=1;break;case"NOT_FOUND":case 2:g.mediaUploadResult=2;break;case"DECRYPTION_ERROR":case 3:g.mediaUploadResult=3;break}if(s.stickerMessage!=null){if(typeof s.stickerMessage!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.stickerMessage: object expected");g.stickerMessage=p.proto.Message.StickerMessage.fromObject(s.stickerMessage)}if(s.linkPreviewResponse!=null){if(typeof s.linkPreviewResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.linkPreviewResponse: object expected");g.linkPreviewResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.fromObject(s.linkPreviewResponse)}if(s.placeholderMessageResendResponse!=null){if(typeof s.placeholderMessageResendResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.placeholderMessageResendResponse: object expected");g.placeholderMessageResendResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse.fromObject(s.placeholderMessageResendResponse)}if(s.waffleNonceFetchRequestResponse!=null){if(typeof s.waffleNonceFetchRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.waffleNonceFetchRequestResponse: object expected");g.waffleNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse.fromObject(s.waffleNonceFetchRequestResponse)}if(s.fullHistorySyncOnDemandRequestResponse!=null){if(typeof s.fullHistorySyncOnDemandRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.fullHistorySyncOnDemandRequestResponse: object expected");g.fullHistorySyncOnDemandRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.fromObject(s.fullHistorySyncOnDemandRequestResponse)}if(s.companionMetaNonceFetchRequestResponse!=null){if(typeof s.companionMetaNonceFetchRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.companionMetaNonceFetchRequestResponse: object expected");g.companionMetaNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse.fromObject(s.companionMetaNonceFetchRequestResponse)}if(s.syncdSnapshotFatalRecoveryResponse!=null){if(typeof s.syncdSnapshotFatalRecoveryResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.syncdSnapshotFatalRecoveryResponse: object expected");g.syncdSnapshotFatalRecoveryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse.fromObject(s.syncdSnapshotFatalRecoveryResponse)}if(s.companionCanonicalUserNonceFetchRequestResponse!=null){if(typeof s.companionCanonicalUserNonceFetchRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.companionCanonicalUserNonceFetchRequestResponse: object expected");g.companionCanonicalUserNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse.fromObject(s.companionCanonicalUserNonceFetchRequestResponse)}if(s.historySyncChunkRetryResponse!=null){if(typeof s.historySyncChunkRetryResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.historySyncChunkRetryResponse: object expected");g.historySyncChunkRetryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse.fromObject(s.historySyncChunkRetryResponse)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.mediaUploadResult!=null&&s.hasOwnProperty("mediaUploadResult")&&(c.mediaUploadResult=g.enums===String?p.proto.MediaRetryNotification.ResultType[s.mediaUploadResult]===void 0?s.mediaUploadResult:p.proto.MediaRetryNotification.ResultType[s.mediaUploadResult]:s.mediaUploadResult,g.oneofs&&(c._mediaUploadResult="mediaUploadResult")),s.stickerMessage!=null&&s.hasOwnProperty("stickerMessage")&&(c.stickerMessage=p.proto.Message.StickerMessage.toObject(s.stickerMessage,g),g.oneofs&&(c._stickerMessage="stickerMessage")),s.linkPreviewResponse!=null&&s.hasOwnProperty("linkPreviewResponse")&&(c.linkPreviewResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.toObject(s.linkPreviewResponse,g),g.oneofs&&(c._linkPreviewResponse="linkPreviewResponse")),s.placeholderMessageResendResponse!=null&&s.hasOwnProperty("placeholderMessageResendResponse")&&(c.placeholderMessageResendResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse.toObject(s.placeholderMessageResendResponse,g),g.oneofs&&(c._placeholderMessageResendResponse="placeholderMessageResendResponse")),s.waffleNonceFetchRequestResponse!=null&&s.hasOwnProperty("waffleNonceFetchRequestResponse")&&(c.waffleNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse.toObject(s.waffleNonceFetchRequestResponse,g),g.oneofs&&(c._waffleNonceFetchRequestResponse="waffleNonceFetchRequestResponse")),s.fullHistorySyncOnDemandRequestResponse!=null&&s.hasOwnProperty("fullHistorySyncOnDemandRequestResponse")&&(c.fullHistorySyncOnDemandRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.toObject(s.fullHistorySyncOnDemandRequestResponse,g),g.oneofs&&(c._fullHistorySyncOnDemandRequestResponse="fullHistorySyncOnDemandRequestResponse")),s.companionMetaNonceFetchRequestResponse!=null&&s.hasOwnProperty("companionMetaNonceFetchRequestResponse")&&(c.companionMetaNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse.toObject(s.companionMetaNonceFetchRequestResponse,g),g.oneofs&&(c._companionMetaNonceFetchRequestResponse="companionMetaNonceFetchRequestResponse")),s.syncdSnapshotFatalRecoveryResponse!=null&&s.hasOwnProperty("syncdSnapshotFatalRecoveryResponse")&&(c.syncdSnapshotFatalRecoveryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse.toObject(s.syncdSnapshotFatalRecoveryResponse,g),g.oneofs&&(c._syncdSnapshotFatalRecoveryResponse="syncdSnapshotFatalRecoveryResponse")),s.companionCanonicalUserNonceFetchRequestResponse!=null&&s.hasOwnProperty("companionCanonicalUserNonceFetchRequestResponse")&&(c.companionCanonicalUserNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse.toObject(s.companionCanonicalUserNonceFetchRequestResponse,g),g.oneofs&&(c._companionCanonicalUserNonceFetchRequestResponse="companionCanonicalUserNonceFetchRequestResponse")),s.historySyncChunkRetryResponse!=null&&s.hasOwnProperty("historySyncChunkRetryResponse")&&(c.historySyncChunkRetryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse.toObject(s.historySyncChunkRetryResponse,g),g.oneofs&&(c._historySyncChunkRetryResponse="historySyncChunkRetryResponse")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult"},a.CompanionCanonicalUserNonceFetchResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.nonce=c.string();break}case 2:{f.waFbid=c.string();break}case 3:{f.forceRefresh=c.bool();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse;return c.nonce!=null&&(I.nonce=String(c.nonce)),c.waFbid!=null&&(I.waFbid=String(c.waFbid)),c.forceRefresh!=null&&(I.forceRefresh=!!c.forceRefresh),I},r.toObject=function(c,I){I||(I={});var d={};return c.nonce!=null&&c.hasOwnProperty("nonce")&&(d.nonce=c.nonce,I.oneofs&&(d._nonce="nonce")),c.waFbid!=null&&c.hasOwnProperty("waFbid")&&(d.waFbid=c.waFbid,I.oneofs&&(d._waFbid="waFbid")),c.forceRefresh!=null&&c.hasOwnProperty("forceRefresh")&&(d.forceRefresh=c.forceRefresh,I.oneofs&&(d._forceRefresh="forceRefresh")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse"},r})(),a.CompanionMetaNonceFetchResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.nonce=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse;return c.nonce!=null&&(I.nonce=String(c.nonce)),I},r.toObject=function(c,I){I||(I={});var d={};return c.nonce!=null&&c.hasOwnProperty("nonce")&&(d.nonce=c.nonce,I.oneofs&&(d._nonce="nonce")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse"},r})(),a.FullHistorySyncOnDemandRequestResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.decode(c,c.uint32());break}case 2:{f.responseCode=c.int32();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse;if(c.requestMetadata!=null){if(typeof c.requestMetadata!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.requestMetadata: object expected");I.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.fromObject(c.requestMetadata)}switch(c.responseCode){default:if(typeof c.responseCode=="number"){I.responseCode=c.responseCode;break}break;case"REQUEST_SUCCESS":case 0:I.responseCode=0;break;case"REQUEST_TIME_EXPIRED":case 1:I.responseCode=1;break;case"DECLINED_SHARING_HISTORY":case 2:I.responseCode=2;break;case"GENERIC_ERROR":case 3:I.responseCode=3;break;case"ERROR_REQUEST_ON_NON_SMB_PRIMARY":case 4:I.responseCode=4;break;case"ERROR_HOSTED_DEVICE_NOT_CONNECTED":case 5:I.responseCode=5;break;case"ERROR_HOSTED_DEVICE_LOGIN_TIME_NOT_SET":case 6:I.responseCode=6;break}return I},r.toObject=function(c,I){I||(I={});var d={};return c.requestMetadata!=null&&c.hasOwnProperty("requestMetadata")&&(d.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.toObject(c.requestMetadata,I),I.oneofs&&(d._requestMetadata="requestMetadata")),c.responseCode!=null&&c.hasOwnProperty("responseCode")&&(d.responseCode=I.enums===String?p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandResponseCode[c.responseCode]===void 0?c.responseCode:p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandResponseCode[c.responseCode]:c.responseCode,I.oneofs&&(d._responseCode="responseCode")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse"},r})(),a.FullHistorySyncOnDemandResponseCode=(function(){let r={},s=Object.create(r);return s[r[0]="REQUEST_SUCCESS"]=0,s[r[1]="REQUEST_TIME_EXPIRED"]=1,s[r[2]="DECLINED_SHARING_HISTORY"]=2,s[r[3]="GENERIC_ERROR"]=3,s[r[4]="ERROR_REQUEST_ON_NON_SMB_PRIMARY"]=4,s[r[5]="ERROR_HOSTED_DEVICE_NOT_CONNECTED"]=5,s[r[6]="ERROR_HOSTED_DEVICE_LOGIN_TIME_NOT_SET"]=6,s})(),a.HistorySyncChunkRetryResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.syncType=c.int32();break}case 2:{f.chunkOrder=c.uint32();break}case 3:{f.requestId=c.string();break}case 4:{f.responseCode=c.int32();break}case 5:{f.canRecover=c.bool();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse;switch(c.syncType){default:if(typeof c.syncType=="number"){I.syncType=c.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:I.syncType=0;break;case"INITIAL_STATUS_V3":case 1:I.syncType=1;break;case"FULL":case 2:I.syncType=2;break;case"RECENT":case 3:I.syncType=3;break;case"PUSH_NAME":case 4:I.syncType=4;break;case"NON_BLOCKING_DATA":case 5:I.syncType=5;break;case"ON_DEMAND":case 6:I.syncType=6;break;case"NO_HISTORY":case 7:I.syncType=7;break;case"MESSAGE_ACCESS_STATUS":case 8:I.syncType=8;break}switch(c.chunkOrder!=null&&(I.chunkOrder=c.chunkOrder>>>0),c.requestId!=null&&(I.requestId=String(c.requestId)),c.responseCode){default:if(typeof c.responseCode=="number"){I.responseCode=c.responseCode;break}break;case"GENERATION_ERROR":case 1:I.responseCode=1;break;case"CHUNK_CONSUMED":case 2:I.responseCode=2;break;case"TIMEOUT":case 3:I.responseCode=3;break;case"SESSION_EXHAUSTED":case 4:I.responseCode=4;break;case"CHUNK_EXHAUSTED":case 5:I.responseCode=5;break;case"DUPLICATED_REQUEST":case 6:I.responseCode=6;break}return c.canRecover!=null&&(I.canRecover=!!c.canRecover),I},r.toObject=function(c,I){I||(I={});var d={};return c.syncType!=null&&c.hasOwnProperty("syncType")&&(d.syncType=I.enums===String?p.proto.Message.HistorySyncType[c.syncType]===void 0?c.syncType:p.proto.Message.HistorySyncType[c.syncType]:c.syncType,I.oneofs&&(d._syncType="syncType")),c.chunkOrder!=null&&c.hasOwnProperty("chunkOrder")&&(d.chunkOrder=c.chunkOrder,I.oneofs&&(d._chunkOrder="chunkOrder")),c.requestId!=null&&c.hasOwnProperty("requestId")&&(d.requestId=c.requestId,I.oneofs&&(d._requestId="requestId")),c.responseCode!=null&&c.hasOwnProperty("responseCode")&&(d.responseCode=I.enums===String?p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponseCode[c.responseCode]===void 0?c.responseCode:p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponseCode[c.responseCode]:c.responseCode,I.oneofs&&(d._responseCode="responseCode")),c.canRecover!=null&&c.hasOwnProperty("canRecover")&&(d.canRecover=c.canRecover,I.oneofs&&(d._canRecover="canRecover")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse"},r})(),a.HistorySyncChunkRetryResponseCode=(function(){let r={},s=Object.create(r);return s[r[1]="GENERATION_ERROR"]=1,s[r[2]="CHUNK_CONSUMED"]=2,s[r[3]="TIMEOUT"]=3,s[r[4]="SESSION_EXHAUSTED"]=4,s[r[5]="CHUNK_EXHAUSTED"]=5,s[r[6]="DUPLICATED_REQUEST"]=6,s})(),a.LinkPreviewResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.url=c.string();break}case 2:{f.title=c.string();break}case 3:{f.description=c.string();break}case 4:{f.thumbData=c.bytes();break}case 6:{f.matchText=c.string();break}case 7:{f.previewType=c.string();break}case 8:{f.hqThumbnail=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail.decode(c,c.uint32());break}case 9:{f.previewMetadata=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata.decode(c,c.uint32());break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse;if(c.url!=null&&(I.url=String(c.url)),c.title!=null&&(I.title=String(c.title)),c.description!=null&&(I.description=String(c.description)),c.thumbData!=null&&(typeof c.thumbData=="string"?l.base64.decode(c.thumbData,I.thumbData=l.newBuffer(l.base64.length(c.thumbData)),0):c.thumbData.length>=0&&(I.thumbData=c.thumbData)),c.matchText!=null&&(I.matchText=String(c.matchText)),c.previewType!=null&&(I.previewType=String(c.previewType)),c.hqThumbnail!=null){if(typeof c.hqThumbnail!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.hqThumbnail: object expected");I.hqThumbnail=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail.fromObject(c.hqThumbnail)}if(c.previewMetadata!=null){if(typeof c.previewMetadata!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.previewMetadata: object expected");I.previewMetadata=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata.fromObject(c.previewMetadata)}return I},r.toObject=function(c,I){I||(I={});var d={};return c.url!=null&&c.hasOwnProperty("url")&&(d.url=c.url,I.oneofs&&(d._url="url")),c.title!=null&&c.hasOwnProperty("title")&&(d.title=c.title,I.oneofs&&(d._title="title")),c.description!=null&&c.hasOwnProperty("description")&&(d.description=c.description,I.oneofs&&(d._description="description")),c.thumbData!=null&&c.hasOwnProperty("thumbData")&&(d.thumbData=I.bytes===String?l.base64.encode(c.thumbData,0,c.thumbData.length):I.bytes===Array?Array.prototype.slice.call(c.thumbData):c.thumbData,I.oneofs&&(d._thumbData="thumbData")),c.matchText!=null&&c.hasOwnProperty("matchText")&&(d.matchText=c.matchText,I.oneofs&&(d._matchText="matchText")),c.previewType!=null&&c.hasOwnProperty("previewType")&&(d.previewType=c.previewType,I.oneofs&&(d._previewType="previewType")),c.hqThumbnail!=null&&c.hasOwnProperty("hqThumbnail")&&(d.hqThumbnail=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail.toObject(c.hqThumbnail,I),I.oneofs&&(d._hqThumbnail="hqThumbnail")),c.previewMetadata!=null&&c.hasOwnProperty("previewMetadata")&&(d.previewMetadata=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata.toObject(c.previewMetadata,I),I.oneofs&&(d._previewMetadata="previewMetadata")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse"},r.LinkPreviewHighQualityThumbnail=(function(){function g(I){if(I)for(var d=Object.keys(I),B=0;B>>3){case 1:{y.directPath=d.string();break}case 2:{y.thumbHash=d.string();break}case 3:{y.encThumbHash=d.string();break}case 4:{y.mediaKey=d.bytes();break}case 5:{y.mediaKeyTimestampMs=d.int64();break}case 6:{y.thumbWidth=d.int32();break}case 7:{y.thumbHeight=d.int32();break}default:d.skipType(m&7);break}}return y},g.fromObject=function(d){if(d instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail)return d;var B=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail;return d.directPath!=null&&(B.directPath=String(d.directPath)),d.thumbHash!=null&&(B.thumbHash=String(d.thumbHash)),d.encThumbHash!=null&&(B.encThumbHash=String(d.encThumbHash)),d.mediaKey!=null&&(typeof d.mediaKey=="string"?l.base64.decode(d.mediaKey,B.mediaKey=l.newBuffer(l.base64.length(d.mediaKey)),0):d.mediaKey.length>=0&&(B.mediaKey=d.mediaKey)),d.mediaKeyTimestampMs!=null&&(l.Long?(B.mediaKeyTimestampMs=l.Long.fromValue(d.mediaKeyTimestampMs)).unsigned=!1:typeof d.mediaKeyTimestampMs=="string"?B.mediaKeyTimestampMs=parseInt(d.mediaKeyTimestampMs,10):typeof d.mediaKeyTimestampMs=="number"?B.mediaKeyTimestampMs=d.mediaKeyTimestampMs:typeof d.mediaKeyTimestampMs=="object"&&(B.mediaKeyTimestampMs=new l.LongBits(d.mediaKeyTimestampMs.low>>>0,d.mediaKeyTimestampMs.high>>>0).toNumber())),d.thumbWidth!=null&&(B.thumbWidth=d.thumbWidth|0),d.thumbHeight!=null&&(B.thumbHeight=d.thumbHeight|0),B},g.toObject=function(d,B){B||(B={});var f={};return d.directPath!=null&&d.hasOwnProperty("directPath")&&(f.directPath=d.directPath,B.oneofs&&(f._directPath="directPath")),d.thumbHash!=null&&d.hasOwnProperty("thumbHash")&&(f.thumbHash=d.thumbHash,B.oneofs&&(f._thumbHash="thumbHash")),d.encThumbHash!=null&&d.hasOwnProperty("encThumbHash")&&(f.encThumbHash=d.encThumbHash,B.oneofs&&(f._encThumbHash="encThumbHash")),d.mediaKey!=null&&d.hasOwnProperty("mediaKey")&&(f.mediaKey=B.bytes===String?l.base64.encode(d.mediaKey,0,d.mediaKey.length):B.bytes===Array?Array.prototype.slice.call(d.mediaKey):d.mediaKey,B.oneofs&&(f._mediaKey="mediaKey")),d.mediaKeyTimestampMs!=null&&d.hasOwnProperty("mediaKeyTimestampMs")&&(typeof d.mediaKeyTimestampMs=="number"?f.mediaKeyTimestampMs=B.longs===String?String(d.mediaKeyTimestampMs):d.mediaKeyTimestampMs:f.mediaKeyTimestampMs=B.longs===String?se(d.mediaKeyTimestampMs):B.longs===Number?ge(d.mediaKeyTimestampMs):d.mediaKeyTimestampMs,B.oneofs&&(f._mediaKeyTimestampMs="mediaKeyTimestampMs")),d.thumbWidth!=null&&d.hasOwnProperty("thumbWidth")&&(f.thumbWidth=d.thumbWidth,B.oneofs&&(f._thumbWidth="thumbWidth")),d.thumbHeight!=null&&d.hasOwnProperty("thumbHeight")&&(f.thumbHeight=d.thumbHeight,B.oneofs&&(f._thumbHeight="thumbHeight")),f},g.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},g.getTypeUrl=function(d){return d===void 0&&(d="type.googleapis.com"),d+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail"},g})(),r.PaymentLinkPreviewMetadata=(function(){function g(I){if(I)for(var d=Object.keys(I),B=0;B>>3){case 1:{y.isBusinessVerified=d.bool();break}case 2:{y.providerName=d.string();break}default:d.skipType(m&7);break}}return y},g.fromObject=function(d){if(d instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata)return d;var B=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata;return d.isBusinessVerified!=null&&(B.isBusinessVerified=!!d.isBusinessVerified),d.providerName!=null&&(B.providerName=String(d.providerName)),B},g.toObject=function(d,B){B||(B={});var f={};return d.isBusinessVerified!=null&&d.hasOwnProperty("isBusinessVerified")&&(f.isBusinessVerified=d.isBusinessVerified,B.oneofs&&(f._isBusinessVerified="isBusinessVerified")),d.providerName!=null&&d.hasOwnProperty("providerName")&&(f.providerName=d.providerName,B.oneofs&&(f._providerName="providerName")),f},g.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},g.getTypeUrl=function(d){return d===void 0&&(d="type.googleapis.com"),d+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata"},g})(),r})(),a.PlaceholderMessageResendResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.webMessageInfoBytes=c.bytes();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse;return c.webMessageInfoBytes!=null&&(typeof c.webMessageInfoBytes=="string"?l.base64.decode(c.webMessageInfoBytes,I.webMessageInfoBytes=l.newBuffer(l.base64.length(c.webMessageInfoBytes)),0):c.webMessageInfoBytes.length>=0&&(I.webMessageInfoBytes=c.webMessageInfoBytes)),I},r.toObject=function(c,I){I||(I={});var d={};return c.webMessageInfoBytes!=null&&c.hasOwnProperty("webMessageInfoBytes")&&(d.webMessageInfoBytes=I.bytes===String?l.base64.encode(c.webMessageInfoBytes,0,c.webMessageInfoBytes.length):I.bytes===Array?Array.prototype.slice.call(c.webMessageInfoBytes):c.webMessageInfoBytes,I.oneofs&&(d._webMessageInfoBytes="webMessageInfoBytes")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse"},r})(),a.SyncDSnapshotFatalRecoveryResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.collectionSnapshot=c.bytes();break}case 2:{f.isCompressed=c.bool();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse;return c.collectionSnapshot!=null&&(typeof c.collectionSnapshot=="string"?l.base64.decode(c.collectionSnapshot,I.collectionSnapshot=l.newBuffer(l.base64.length(c.collectionSnapshot)),0):c.collectionSnapshot.length>=0&&(I.collectionSnapshot=c.collectionSnapshot)),c.isCompressed!=null&&(I.isCompressed=!!c.isCompressed),I},r.toObject=function(c,I){I||(I={});var d={};return c.collectionSnapshot!=null&&c.hasOwnProperty("collectionSnapshot")&&(d.collectionSnapshot=I.bytes===String?l.base64.encode(c.collectionSnapshot,0,c.collectionSnapshot.length):I.bytes===Array?Array.prototype.slice.call(c.collectionSnapshot):c.collectionSnapshot,I.oneofs&&(d._collectionSnapshot="collectionSnapshot")),c.isCompressed!=null&&c.hasOwnProperty("isCompressed")&&(d.isCompressed=c.isCompressed,I.oneofs&&(d._isCompressed="isCompressed")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse"},r})(),a.WaffleNonceFetchResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.nonce=c.string();break}case 2:{f.waEntFbid=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse;return c.nonce!=null&&(I.nonce=String(c.nonce)),c.waEntFbid!=null&&(I.waEntFbid=String(c.waEntFbid)),I},r.toObject=function(c,I){I||(I={});var d={};return c.nonce!=null&&c.hasOwnProperty("nonce")&&(d.nonce=c.nonce,I.oneofs&&(d._nonce="nonce")),c.waEntFbid!=null&&c.hasOwnProperty("waEntFbid")&&(d.waEntFbid=c.waEntFbid,I.oneofs&&(d._waEntFbid="waEntFbid")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse"},r})(),a})(),i})(),t.PeerDataOperationRequestType=(function(){let i={},e=Object.create(i);return e[i[0]="UPLOAD_STICKER"]=0,e[i[1]="SEND_RECENT_STICKER_BOOTSTRAP"]=1,e[i[2]="GENERATE_LINK_PREVIEW"]=2,e[i[3]="HISTORY_SYNC_ON_DEMAND"]=3,e[i[4]="PLACEHOLDER_MESSAGE_RESEND"]=4,e[i[5]="WAFFLE_LINKING_NONCE_FETCH"]=5,e[i[6]="FULL_HISTORY_SYNC_ON_DEMAND"]=6,e[i[7]="COMPANION_META_NONCE_FETCH"]=7,e[i[8]="COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY"]=8,e[i[9]="COMPANION_CANONICAL_USER_NONCE_FETCH"]=9,e[i[10]="HISTORY_SYNC_CHUNK_RETRY"]=10,e[i[11]="GALAXY_FLOW_ACTION"]=11,e})(),t.PinInChatMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.type=A.int32();break}case 3:{c.senderTimestampMs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PinInChatMessage)return A;var r=new p.proto.Message.PinInChatMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.PinInChatMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNKNOWN_TYPE":case 0:r.type=0;break;case"PIN_FOR_ALL":case 1:r.type=1;break;case"UNPIN_FOR_ALL":case 2:r.type=2;break}return A.senderTimestampMs!=null&&(l.Long?(r.senderTimestampMs=l.Long.fromValue(A.senderTimestampMs)).unsigned=!1:typeof A.senderTimestampMs=="string"?r.senderTimestampMs=parseInt(A.senderTimestampMs,10):typeof A.senderTimestampMs=="number"?r.senderTimestampMs=A.senderTimestampMs:typeof A.senderTimestampMs=="object"&&(r.senderTimestampMs=new l.LongBits(A.senderTimestampMs.low>>>0,A.senderTimestampMs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.PinInChatMessage.Type[A.type]===void 0?A.type:p.proto.Message.PinInChatMessage.Type[A.type]:A.type,r.oneofs&&(s._type="type")),A.senderTimestampMs!=null&&A.hasOwnProperty("senderTimestampMs")&&(typeof A.senderTimestampMs=="number"?s.senderTimestampMs=r.longs===String?String(A.senderTimestampMs):A.senderTimestampMs:s.senderTimestampMs=r.longs===String?se(A.senderTimestampMs):r.longs===Number?ge(A.senderTimestampMs):A.senderTimestampMs,r.oneofs&&(s._senderTimestampMs="senderTimestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PinInChatMessage"},i.Type=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN_TYPE"]=0,A[a[1]="PIN_FOR_ALL"]=1,A[a[2]="UNPIN_FOR_ALL"]=2,A})(),i})(),t.PlaceholderMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.type=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PlaceholderMessage)return A;var r=new p.proto.Message.PlaceholderMessage;switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"MASK_LINKED_DEVICES":case 0:r.type=0;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.PlaceholderMessage.PlaceholderType[A.type]===void 0?A.type:p.proto.Message.PlaceholderMessage.PlaceholderType[A.type]:A.type,r.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PlaceholderMessage"},i.PlaceholderType=(function(){let a={},A=Object.create(a);return A[a[0]="MASK_LINKED_DEVICES"]=0,A})(),i})(),t.PollContentType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="TEXT"]=1,e[i[2]="IMAGE"]=2,e})(),t.PollCreationMessage=(function(){function i(a){if(this.options=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.encKey=A.bytes();break}case 2:{c.name=A.string();break}case 3:{c.options&&c.options.length||(c.options=[]),c.options.push(p.proto.Message.PollCreationMessage.Option.decode(A,A.uint32()));break}case 4:{c.selectableOptionsCount=A.uint32();break}case 5:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 6:{c.pollContentType=A.int32();break}case 7:{c.pollType=A.int32();break}case 8:{c.correctAnswer=p.proto.Message.PollCreationMessage.Option.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PollCreationMessage)return A;var r=new p.proto.Message.PollCreationMessage;if(A.encKey!=null&&(typeof A.encKey=="string"?l.base64.decode(A.encKey,r.encKey=l.newBuffer(l.base64.length(A.encKey)),0):A.encKey.length>=0&&(r.encKey=A.encKey)),A.name!=null&&(r.name=String(A.name)),A.options){if(!Array.isArray(A.options))throw TypeError(".proto.Message.PollCreationMessage.options: array expected");r.options=[];for(var s=0;s>>0),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.PollCreationMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.pollContentType){default:if(typeof A.pollContentType=="number"){r.pollContentType=A.pollContentType;break}break;case"UNKNOWN":case 0:r.pollContentType=0;break;case"TEXT":case 1:r.pollContentType=1;break;case"IMAGE":case 2:r.pollContentType=2;break}switch(A.pollType){default:if(typeof A.pollType=="number"){r.pollType=A.pollType;break}break;case"POLL":case 0:r.pollType=0;break;case"QUIZ":case 1:r.pollType=1;break}if(A.correctAnswer!=null){if(typeof A.correctAnswer!="object")throw TypeError(".proto.Message.PollCreationMessage.correctAnswer: object expected");r.correctAnswer=p.proto.Message.PollCreationMessage.Option.fromObject(A.correctAnswer)}return r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.options=[]),A.encKey!=null&&A.hasOwnProperty("encKey")&&(s.encKey=r.bytes===String?l.base64.encode(A.encKey,0,A.encKey.length):r.bytes===Array?Array.prototype.slice.call(A.encKey):A.encKey,r.oneofs&&(s._encKey="encKey")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.options&&A.options.length){s.options=[];for(var g=0;g>>3){case 1:{d.optionName=s.string();break}case 2:{d.optionHash=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PollCreationMessage.Option)return s;var g=new p.proto.Message.PollCreationMessage.Option;return s.optionName!=null&&(g.optionName=String(s.optionName)),s.optionHash!=null&&(g.optionHash=String(s.optionHash)),g},a.toObject=function(s,g){g||(g={});var c={};return s.optionName!=null&&s.hasOwnProperty("optionName")&&(c.optionName=s.optionName,g.oneofs&&(c._optionName="optionName")),s.optionHash!=null&&s.hasOwnProperty("optionHash")&&(c.optionHash=s.optionHash,g.oneofs&&(c._optionHash="optionHash")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PollCreationMessage.Option"},a})(),i})(),t.PollEncValue=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.encPayload=A.bytes();break}case 2:{c.encIv=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PollEncValue)return A;var r=new p.proto.Message.PollEncValue;return A.encPayload!=null&&(typeof A.encPayload=="string"?l.base64.decode(A.encPayload,r.encPayload=l.newBuffer(l.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(r.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?l.base64.decode(A.encIv,r.encIv=l.newBuffer(l.base64.length(A.encIv)),0):A.encIv.length>=0&&(r.encIv=A.encIv)),r},i.toObject=function(A,r){r||(r={});var s={};return A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=r.bytes===String?l.base64.encode(A.encPayload,0,A.encPayload.length):r.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,r.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=r.bytes===String?l.base64.encode(A.encIv,0,A.encIv.length):r.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,r.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PollEncValue"},i})(),t.PollResultSnapshotMessage=(function(){function i(a){if(this.pollVotes=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}case 2:{c.pollVotes&&c.pollVotes.length||(c.pollVotes=[]),c.pollVotes.push(p.proto.Message.PollResultSnapshotMessage.PollVote.decode(A,A.uint32()));break}case 3:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.pollType=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PollResultSnapshotMessage)return A;var r=new p.proto.Message.PollResultSnapshotMessage;if(A.name!=null&&(r.name=String(A.name)),A.pollVotes){if(!Array.isArray(A.pollVotes))throw TypeError(".proto.Message.PollResultSnapshotMessage.pollVotes: array expected");r.pollVotes=[];for(var s=0;s>>3){case 1:{d.optionName=s.string();break}case 2:{d.optionVoteCount=s.int64();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PollResultSnapshotMessage.PollVote)return s;var g=new p.proto.Message.PollResultSnapshotMessage.PollVote;return s.optionName!=null&&(g.optionName=String(s.optionName)),s.optionVoteCount!=null&&(l.Long?(g.optionVoteCount=l.Long.fromValue(s.optionVoteCount)).unsigned=!1:typeof s.optionVoteCount=="string"?g.optionVoteCount=parseInt(s.optionVoteCount,10):typeof s.optionVoteCount=="number"?g.optionVoteCount=s.optionVoteCount:typeof s.optionVoteCount=="object"&&(g.optionVoteCount=new l.LongBits(s.optionVoteCount.low>>>0,s.optionVoteCount.high>>>0).toNumber())),g},a.toObject=function(s,g){g||(g={});var c={};return s.optionName!=null&&s.hasOwnProperty("optionName")&&(c.optionName=s.optionName,g.oneofs&&(c._optionName="optionName")),s.optionVoteCount!=null&&s.hasOwnProperty("optionVoteCount")&&(typeof s.optionVoteCount=="number"?c.optionVoteCount=g.longs===String?String(s.optionVoteCount):s.optionVoteCount:c.optionVoteCount=g.longs===String?se(s.optionVoteCount):g.longs===Number?ge(s.optionVoteCount):s.optionVoteCount,g.oneofs&&(c._optionVoteCount="optionVoteCount")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PollResultSnapshotMessage.PollVote"},a})(),i})(),t.PollType=(function(){let i={},e=Object.create(i);return e[i[0]="POLL"]=0,e[i[1]="QUIZ"]=1,e})(),t.PollUpdateMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.pollCreationMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.vote=p.proto.Message.PollEncValue.decode(A,A.uint32());break}case 3:{c.metadata=p.proto.Message.PollUpdateMessageMetadata.decode(A,A.uint32());break}case 4:{c.senderTimestampMs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PollUpdateMessage)return A;var r=new p.proto.Message.PollUpdateMessage;if(A.pollCreationMessageKey!=null){if(typeof A.pollCreationMessageKey!="object")throw TypeError(".proto.Message.PollUpdateMessage.pollCreationMessageKey: object expected");r.pollCreationMessageKey=p.proto.MessageKey.fromObject(A.pollCreationMessageKey)}if(A.vote!=null){if(typeof A.vote!="object")throw TypeError(".proto.Message.PollUpdateMessage.vote: object expected");r.vote=p.proto.Message.PollEncValue.fromObject(A.vote)}if(A.metadata!=null){if(typeof A.metadata!="object")throw TypeError(".proto.Message.PollUpdateMessage.metadata: object expected");r.metadata=p.proto.Message.PollUpdateMessageMetadata.fromObject(A.metadata)}return A.senderTimestampMs!=null&&(l.Long?(r.senderTimestampMs=l.Long.fromValue(A.senderTimestampMs)).unsigned=!1:typeof A.senderTimestampMs=="string"?r.senderTimestampMs=parseInt(A.senderTimestampMs,10):typeof A.senderTimestampMs=="number"?r.senderTimestampMs=A.senderTimestampMs:typeof A.senderTimestampMs=="object"&&(r.senderTimestampMs=new l.LongBits(A.senderTimestampMs.low>>>0,A.senderTimestampMs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.pollCreationMessageKey!=null&&A.hasOwnProperty("pollCreationMessageKey")&&(s.pollCreationMessageKey=p.proto.MessageKey.toObject(A.pollCreationMessageKey,r),r.oneofs&&(s._pollCreationMessageKey="pollCreationMessageKey")),A.vote!=null&&A.hasOwnProperty("vote")&&(s.vote=p.proto.Message.PollEncValue.toObject(A.vote,r),r.oneofs&&(s._vote="vote")),A.metadata!=null&&A.hasOwnProperty("metadata")&&(s.metadata=p.proto.Message.PollUpdateMessageMetadata.toObject(A.metadata,r),r.oneofs&&(s._metadata="metadata")),A.senderTimestampMs!=null&&A.hasOwnProperty("senderTimestampMs")&&(typeof A.senderTimestampMs=="number"?s.senderTimestampMs=r.longs===String?String(A.senderTimestampMs):A.senderTimestampMs:s.senderTimestampMs=r.longs===String?se(A.senderTimestampMs):r.longs===Number?ge(A.senderTimestampMs):A.senderTimestampMs,r.oneofs&&(s._senderTimestampMs="senderTimestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PollUpdateMessage"},i})(),t.PollUpdateMessageMetadata=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){default:a.skipType(c&7);break}}return g},i.fromObject=function(a){return a instanceof p.proto.Message.PollUpdateMessageMetadata?a:new p.proto.Message.PollUpdateMessageMetadata},i.toObject=function(){return{}},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Message.PollUpdateMessageMetadata"},i})(),t.PollVoteMessage=(function(){function i(e){if(this.selectedOptions=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.selectedOptions&&g.selectedOptions.length||(g.selectedOptions=[]),g.selectedOptions.push(a.bytes());break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.Message.PollVoteMessage)return a;var A=new p.proto.Message.PollVoteMessage;if(a.selectedOptions){if(!Array.isArray(a.selectedOptions))throw TypeError(".proto.Message.PollVoteMessage.selectedOptions: array expected");A.selectedOptions=[];for(var r=0;r=0&&(A.selectedOptions[r]=a.selectedOptions[r])}return A},i.toObject=function(a,A){A||(A={});var r={};if((A.arrays||A.defaults)&&(r.selectedOptions=[]),a.selectedOptions&&a.selectedOptions.length){r.selectedOptions=[];for(var s=0;s>>3){case 1:{c.product=p.proto.Message.ProductMessage.ProductSnapshot.decode(A,A.uint32());break}case 2:{c.businessOwnerJid=A.string();break}case 4:{c.catalog=p.proto.Message.ProductMessage.CatalogSnapshot.decode(A,A.uint32());break}case 5:{c.body=A.string();break}case 6:{c.footer=A.string();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ProductMessage)return A;var r=new p.proto.Message.ProductMessage;if(A.product!=null){if(typeof A.product!="object")throw TypeError(".proto.Message.ProductMessage.product: object expected");r.product=p.proto.Message.ProductMessage.ProductSnapshot.fromObject(A.product)}if(A.businessOwnerJid!=null&&(r.businessOwnerJid=String(A.businessOwnerJid)),A.catalog!=null){if(typeof A.catalog!="object")throw TypeError(".proto.Message.ProductMessage.catalog: object expected");r.catalog=p.proto.Message.ProductMessage.CatalogSnapshot.fromObject(A.catalog)}if(A.body!=null&&(r.body=String(A.body)),A.footer!=null&&(r.footer=String(A.footer)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ProductMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.product!=null&&A.hasOwnProperty("product")&&(s.product=p.proto.Message.ProductMessage.ProductSnapshot.toObject(A.product,r),r.oneofs&&(s._product="product")),A.businessOwnerJid!=null&&A.hasOwnProperty("businessOwnerJid")&&(s.businessOwnerJid=A.businessOwnerJid,r.oneofs&&(s._businessOwnerJid="businessOwnerJid")),A.catalog!=null&&A.hasOwnProperty("catalog")&&(s.catalog=p.proto.Message.ProductMessage.CatalogSnapshot.toObject(A.catalog,r),r.oneofs&&(s._catalog="catalog")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=A.body,r.oneofs&&(s._body="body")),A.footer!=null&&A.hasOwnProperty("footer")&&(s.footer=A.footer,r.oneofs&&(s._footer="footer")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ProductMessage"},i.CatalogSnapshot=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.catalogImage=p.proto.Message.ImageMessage.decode(s,s.uint32());break}case 2:{d.title=s.string();break}case 3:{d.description=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ProductMessage.CatalogSnapshot)return s;var g=new p.proto.Message.ProductMessage.CatalogSnapshot;if(s.catalogImage!=null){if(typeof s.catalogImage!="object")throw TypeError(".proto.Message.ProductMessage.CatalogSnapshot.catalogImage: object expected");g.catalogImage=p.proto.Message.ImageMessage.fromObject(s.catalogImage)}return s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),g},a.toObject=function(s,g){g||(g={});var c={};return s.catalogImage!=null&&s.hasOwnProperty("catalogImage")&&(c.catalogImage=p.proto.Message.ImageMessage.toObject(s.catalogImage,g),g.oneofs&&(c._catalogImage="catalogImage")),s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ProductMessage.CatalogSnapshot"},a})(),i.ProductSnapshot=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.productImage=p.proto.Message.ImageMessage.decode(s,s.uint32());break}case 2:{d.productId=s.string();break}case 3:{d.title=s.string();break}case 4:{d.description=s.string();break}case 5:{d.currencyCode=s.string();break}case 6:{d.priceAmount1000=s.int64();break}case 7:{d.retailerId=s.string();break}case 8:{d.url=s.string();break}case 9:{d.productImageCount=s.uint32();break}case 11:{d.firstImageId=s.string();break}case 12:{d.salePriceAmount1000=s.int64();break}case 13:{d.signedUrl=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ProductMessage.ProductSnapshot)return s;var g=new p.proto.Message.ProductMessage.ProductSnapshot;if(s.productImage!=null){if(typeof s.productImage!="object")throw TypeError(".proto.Message.ProductMessage.ProductSnapshot.productImage: object expected");g.productImage=p.proto.Message.ImageMessage.fromObject(s.productImage)}return s.productId!=null&&(g.productId=String(s.productId)),s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),s.currencyCode!=null&&(g.currencyCode=String(s.currencyCode)),s.priceAmount1000!=null&&(l.Long?(g.priceAmount1000=l.Long.fromValue(s.priceAmount1000)).unsigned=!1:typeof s.priceAmount1000=="string"?g.priceAmount1000=parseInt(s.priceAmount1000,10):typeof s.priceAmount1000=="number"?g.priceAmount1000=s.priceAmount1000:typeof s.priceAmount1000=="object"&&(g.priceAmount1000=new l.LongBits(s.priceAmount1000.low>>>0,s.priceAmount1000.high>>>0).toNumber())),s.retailerId!=null&&(g.retailerId=String(s.retailerId)),s.url!=null&&(g.url=String(s.url)),s.productImageCount!=null&&(g.productImageCount=s.productImageCount>>>0),s.firstImageId!=null&&(g.firstImageId=String(s.firstImageId)),s.salePriceAmount1000!=null&&(l.Long?(g.salePriceAmount1000=l.Long.fromValue(s.salePriceAmount1000)).unsigned=!1:typeof s.salePriceAmount1000=="string"?g.salePriceAmount1000=parseInt(s.salePriceAmount1000,10):typeof s.salePriceAmount1000=="number"?g.salePriceAmount1000=s.salePriceAmount1000:typeof s.salePriceAmount1000=="object"&&(g.salePriceAmount1000=new l.LongBits(s.salePriceAmount1000.low>>>0,s.salePriceAmount1000.high>>>0).toNumber())),s.signedUrl!=null&&(g.signedUrl=String(s.signedUrl)),g},a.toObject=function(s,g){g||(g={});var c={};return s.productImage!=null&&s.hasOwnProperty("productImage")&&(c.productImage=p.proto.Message.ImageMessage.toObject(s.productImage,g),g.oneofs&&(c._productImage="productImage")),s.productId!=null&&s.hasOwnProperty("productId")&&(c.productId=s.productId,g.oneofs&&(c._productId="productId")),s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),s.currencyCode!=null&&s.hasOwnProperty("currencyCode")&&(c.currencyCode=s.currencyCode,g.oneofs&&(c._currencyCode="currencyCode")),s.priceAmount1000!=null&&s.hasOwnProperty("priceAmount1000")&&(typeof s.priceAmount1000=="number"?c.priceAmount1000=g.longs===String?String(s.priceAmount1000):s.priceAmount1000:c.priceAmount1000=g.longs===String?se(s.priceAmount1000):g.longs===Number?ge(s.priceAmount1000):s.priceAmount1000,g.oneofs&&(c._priceAmount1000="priceAmount1000")),s.retailerId!=null&&s.hasOwnProperty("retailerId")&&(c.retailerId=s.retailerId,g.oneofs&&(c._retailerId="retailerId")),s.url!=null&&s.hasOwnProperty("url")&&(c.url=s.url,g.oneofs&&(c._url="url")),s.productImageCount!=null&&s.hasOwnProperty("productImageCount")&&(c.productImageCount=s.productImageCount,g.oneofs&&(c._productImageCount="productImageCount")),s.firstImageId!=null&&s.hasOwnProperty("firstImageId")&&(c.firstImageId=s.firstImageId,g.oneofs&&(c._firstImageId="firstImageId")),s.salePriceAmount1000!=null&&s.hasOwnProperty("salePriceAmount1000")&&(typeof s.salePriceAmount1000=="number"?c.salePriceAmount1000=g.longs===String?String(s.salePriceAmount1000):s.salePriceAmount1000:c.salePriceAmount1000=g.longs===String?se(s.salePriceAmount1000):g.longs===Number?ge(s.salePriceAmount1000):s.salePriceAmount1000,g.oneofs&&(c._salePriceAmount1000="salePriceAmount1000")),s.signedUrl!=null&&s.hasOwnProperty("signedUrl")&&(c.signedUrl=s.signedUrl,g.oneofs&&(c._signedUrl="signedUrl")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ProductMessage.ProductSnapshot"},a})(),i})(),t.ProtocolMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.type=A.int32();break}case 4:{c.ephemeralExpiration=A.uint32();break}case 5:{c.ephemeralSettingTimestamp=A.int64();break}case 6:{c.historySyncNotification=p.proto.Message.HistorySyncNotification.decode(A,A.uint32());break}case 7:{c.appStateSyncKeyShare=p.proto.Message.AppStateSyncKeyShare.decode(A,A.uint32());break}case 8:{c.appStateSyncKeyRequest=p.proto.Message.AppStateSyncKeyRequest.decode(A,A.uint32());break}case 9:{c.initialSecurityNotificationSettingSync=p.proto.Message.InitialSecurityNotificationSettingSync.decode(A,A.uint32());break}case 10:{c.appStateFatalExceptionNotification=p.proto.Message.AppStateFatalExceptionNotification.decode(A,A.uint32());break}case 11:{c.disappearingMode=p.proto.DisappearingMode.decode(A,A.uint32());break}case 14:{c.editedMessage=p.proto.Message.decode(A,A.uint32());break}case 15:{c.timestampMs=A.int64();break}case 16:{c.peerDataOperationRequestMessage=p.proto.Message.PeerDataOperationRequestMessage.decode(A,A.uint32());break}case 17:{c.peerDataOperationRequestResponseMessage=p.proto.Message.PeerDataOperationRequestResponseMessage.decode(A,A.uint32());break}case 18:{c.botFeedbackMessage=p.proto.BotFeedbackMessage.decode(A,A.uint32());break}case 19:{c.invokerJid=A.string();break}case 20:{c.requestWelcomeMessageMetadata=p.proto.Message.RequestWelcomeMessageMetadata.decode(A,A.uint32());break}case 21:{c.mediaNotifyMessage=p.proto.MediaNotifyMessage.decode(A,A.uint32());break}case 22:{c.cloudApiThreadControlNotification=p.proto.Message.CloudAPIThreadControlNotification.decode(A,A.uint32());break}case 23:{c.lidMigrationMappingSyncMessage=p.proto.LIDMigrationMappingSyncMessage.decode(A,A.uint32());break}case 24:{c.limitSharing=p.proto.LimitSharing.decode(A,A.uint32());break}case 25:{c.aiPsiMetadata=A.bytes();break}case 26:{c.aiQueryFanout=p.proto.AIQueryFanout.decode(A,A.uint32());break}case 27:{c.memberLabel=p.proto.MemberLabel.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ProtocolMessage)return A;var r=new p.proto.Message.ProtocolMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.ProtocolMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"REVOKE":case 0:r.type=0;break;case"EPHEMERAL_SETTING":case 3:r.type=3;break;case"EPHEMERAL_SYNC_RESPONSE":case 4:r.type=4;break;case"HISTORY_SYNC_NOTIFICATION":case 5:r.type=5;break;case"APP_STATE_SYNC_KEY_SHARE":case 6:r.type=6;break;case"APP_STATE_SYNC_KEY_REQUEST":case 7:r.type=7;break;case"MSG_FANOUT_BACKFILL_REQUEST":case 8:r.type=8;break;case"INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC":case 9:r.type=9;break;case"APP_STATE_FATAL_EXCEPTION_NOTIFICATION":case 10:r.type=10;break;case"SHARE_PHONE_NUMBER":case 11:r.type=11;break;case"MESSAGE_EDIT":case 14:r.type=14;break;case"PEER_DATA_OPERATION_REQUEST_MESSAGE":case 16:r.type=16;break;case"PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE":case 17:r.type=17;break;case"REQUEST_WELCOME_MESSAGE":case 18:r.type=18;break;case"BOT_FEEDBACK_MESSAGE":case 19:r.type=19;break;case"MEDIA_NOTIFY_MESSAGE":case 20:r.type=20;break;case"CLOUD_API_THREAD_CONTROL_NOTIFICATION":case 21:r.type=21;break;case"LID_MIGRATION_MAPPING_SYNC":case 22:r.type=22;break;case"REMINDER_MESSAGE":case 23:r.type=23;break;case"BOT_MEMU_ONBOARDING_MESSAGE":case 24:r.type=24;break;case"STATUS_MENTION_MESSAGE":case 25:r.type=25;break;case"STOP_GENERATION_MESSAGE":case 26:r.type=26;break;case"LIMIT_SHARING":case 27:r.type=27;break;case"AI_PSI_METADATA":case 28:r.type=28;break;case"AI_QUERY_FANOUT":case 29:r.type=29;break;case"GROUP_MEMBER_LABEL_CHANGE":case 30:r.type=30;break}if(A.ephemeralExpiration!=null&&(r.ephemeralExpiration=A.ephemeralExpiration>>>0),A.ephemeralSettingTimestamp!=null&&(l.Long?(r.ephemeralSettingTimestamp=l.Long.fromValue(A.ephemeralSettingTimestamp)).unsigned=!1:typeof A.ephemeralSettingTimestamp=="string"?r.ephemeralSettingTimestamp=parseInt(A.ephemeralSettingTimestamp,10):typeof A.ephemeralSettingTimestamp=="number"?r.ephemeralSettingTimestamp=A.ephemeralSettingTimestamp:typeof A.ephemeralSettingTimestamp=="object"&&(r.ephemeralSettingTimestamp=new l.LongBits(A.ephemeralSettingTimestamp.low>>>0,A.ephemeralSettingTimestamp.high>>>0).toNumber())),A.historySyncNotification!=null){if(typeof A.historySyncNotification!="object")throw TypeError(".proto.Message.ProtocolMessage.historySyncNotification: object expected");r.historySyncNotification=p.proto.Message.HistorySyncNotification.fromObject(A.historySyncNotification)}if(A.appStateSyncKeyShare!=null){if(typeof A.appStateSyncKeyShare!="object")throw TypeError(".proto.Message.ProtocolMessage.appStateSyncKeyShare: object expected");r.appStateSyncKeyShare=p.proto.Message.AppStateSyncKeyShare.fromObject(A.appStateSyncKeyShare)}if(A.appStateSyncKeyRequest!=null){if(typeof A.appStateSyncKeyRequest!="object")throw TypeError(".proto.Message.ProtocolMessage.appStateSyncKeyRequest: object expected");r.appStateSyncKeyRequest=p.proto.Message.AppStateSyncKeyRequest.fromObject(A.appStateSyncKeyRequest)}if(A.initialSecurityNotificationSettingSync!=null){if(typeof A.initialSecurityNotificationSettingSync!="object")throw TypeError(".proto.Message.ProtocolMessage.initialSecurityNotificationSettingSync: object expected");r.initialSecurityNotificationSettingSync=p.proto.Message.InitialSecurityNotificationSettingSync.fromObject(A.initialSecurityNotificationSettingSync)}if(A.appStateFatalExceptionNotification!=null){if(typeof A.appStateFatalExceptionNotification!="object")throw TypeError(".proto.Message.ProtocolMessage.appStateFatalExceptionNotification: object expected");r.appStateFatalExceptionNotification=p.proto.Message.AppStateFatalExceptionNotification.fromObject(A.appStateFatalExceptionNotification)}if(A.disappearingMode!=null){if(typeof A.disappearingMode!="object")throw TypeError(".proto.Message.ProtocolMessage.disappearingMode: object expected");r.disappearingMode=p.proto.DisappearingMode.fromObject(A.disappearingMode)}if(A.editedMessage!=null){if(typeof A.editedMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.editedMessage: object expected");r.editedMessage=p.proto.Message.fromObject(A.editedMessage)}if(A.timestampMs!=null&&(l.Long?(r.timestampMs=l.Long.fromValue(A.timestampMs)).unsigned=!1:typeof A.timestampMs=="string"?r.timestampMs=parseInt(A.timestampMs,10):typeof A.timestampMs=="number"?r.timestampMs=A.timestampMs:typeof A.timestampMs=="object"&&(r.timestampMs=new l.LongBits(A.timestampMs.low>>>0,A.timestampMs.high>>>0).toNumber())),A.peerDataOperationRequestMessage!=null){if(typeof A.peerDataOperationRequestMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.peerDataOperationRequestMessage: object expected");r.peerDataOperationRequestMessage=p.proto.Message.PeerDataOperationRequestMessage.fromObject(A.peerDataOperationRequestMessage)}if(A.peerDataOperationRequestResponseMessage!=null){if(typeof A.peerDataOperationRequestResponseMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.peerDataOperationRequestResponseMessage: object expected");r.peerDataOperationRequestResponseMessage=p.proto.Message.PeerDataOperationRequestResponseMessage.fromObject(A.peerDataOperationRequestResponseMessage)}if(A.botFeedbackMessage!=null){if(typeof A.botFeedbackMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.botFeedbackMessage: object expected");r.botFeedbackMessage=p.proto.BotFeedbackMessage.fromObject(A.botFeedbackMessage)}if(A.invokerJid!=null&&(r.invokerJid=String(A.invokerJid)),A.requestWelcomeMessageMetadata!=null){if(typeof A.requestWelcomeMessageMetadata!="object")throw TypeError(".proto.Message.ProtocolMessage.requestWelcomeMessageMetadata: object expected");r.requestWelcomeMessageMetadata=p.proto.Message.RequestWelcomeMessageMetadata.fromObject(A.requestWelcomeMessageMetadata)}if(A.mediaNotifyMessage!=null){if(typeof A.mediaNotifyMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.mediaNotifyMessage: object expected");r.mediaNotifyMessage=p.proto.MediaNotifyMessage.fromObject(A.mediaNotifyMessage)}if(A.cloudApiThreadControlNotification!=null){if(typeof A.cloudApiThreadControlNotification!="object")throw TypeError(".proto.Message.ProtocolMessage.cloudApiThreadControlNotification: object expected");r.cloudApiThreadControlNotification=p.proto.Message.CloudAPIThreadControlNotification.fromObject(A.cloudApiThreadControlNotification)}if(A.lidMigrationMappingSyncMessage!=null){if(typeof A.lidMigrationMappingSyncMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.lidMigrationMappingSyncMessage: object expected");r.lidMigrationMappingSyncMessage=p.proto.LIDMigrationMappingSyncMessage.fromObject(A.lidMigrationMappingSyncMessage)}if(A.limitSharing!=null){if(typeof A.limitSharing!="object")throw TypeError(".proto.Message.ProtocolMessage.limitSharing: object expected");r.limitSharing=p.proto.LimitSharing.fromObject(A.limitSharing)}if(A.aiPsiMetadata!=null&&(typeof A.aiPsiMetadata=="string"?l.base64.decode(A.aiPsiMetadata,r.aiPsiMetadata=l.newBuffer(l.base64.length(A.aiPsiMetadata)),0):A.aiPsiMetadata.length>=0&&(r.aiPsiMetadata=A.aiPsiMetadata)),A.aiQueryFanout!=null){if(typeof A.aiQueryFanout!="object")throw TypeError(".proto.Message.ProtocolMessage.aiQueryFanout: object expected");r.aiQueryFanout=p.proto.AIQueryFanout.fromObject(A.aiQueryFanout)}if(A.memberLabel!=null){if(typeof A.memberLabel!="object")throw TypeError(".proto.Message.ProtocolMessage.memberLabel: object expected");r.memberLabel=p.proto.MemberLabel.fromObject(A.memberLabel)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.ProtocolMessage.Type[A.type]===void 0?A.type:p.proto.Message.ProtocolMessage.Type[A.type]:A.type,r.oneofs&&(s._type="type")),A.ephemeralExpiration!=null&&A.hasOwnProperty("ephemeralExpiration")&&(s.ephemeralExpiration=A.ephemeralExpiration,r.oneofs&&(s._ephemeralExpiration="ephemeralExpiration")),A.ephemeralSettingTimestamp!=null&&A.hasOwnProperty("ephemeralSettingTimestamp")&&(typeof A.ephemeralSettingTimestamp=="number"?s.ephemeralSettingTimestamp=r.longs===String?String(A.ephemeralSettingTimestamp):A.ephemeralSettingTimestamp:s.ephemeralSettingTimestamp=r.longs===String?se(A.ephemeralSettingTimestamp):r.longs===Number?ge(A.ephemeralSettingTimestamp):A.ephemeralSettingTimestamp,r.oneofs&&(s._ephemeralSettingTimestamp="ephemeralSettingTimestamp")),A.historySyncNotification!=null&&A.hasOwnProperty("historySyncNotification")&&(s.historySyncNotification=p.proto.Message.HistorySyncNotification.toObject(A.historySyncNotification,r),r.oneofs&&(s._historySyncNotification="historySyncNotification")),A.appStateSyncKeyShare!=null&&A.hasOwnProperty("appStateSyncKeyShare")&&(s.appStateSyncKeyShare=p.proto.Message.AppStateSyncKeyShare.toObject(A.appStateSyncKeyShare,r),r.oneofs&&(s._appStateSyncKeyShare="appStateSyncKeyShare")),A.appStateSyncKeyRequest!=null&&A.hasOwnProperty("appStateSyncKeyRequest")&&(s.appStateSyncKeyRequest=p.proto.Message.AppStateSyncKeyRequest.toObject(A.appStateSyncKeyRequest,r),r.oneofs&&(s._appStateSyncKeyRequest="appStateSyncKeyRequest")),A.initialSecurityNotificationSettingSync!=null&&A.hasOwnProperty("initialSecurityNotificationSettingSync")&&(s.initialSecurityNotificationSettingSync=p.proto.Message.InitialSecurityNotificationSettingSync.toObject(A.initialSecurityNotificationSettingSync,r),r.oneofs&&(s._initialSecurityNotificationSettingSync="initialSecurityNotificationSettingSync")),A.appStateFatalExceptionNotification!=null&&A.hasOwnProperty("appStateFatalExceptionNotification")&&(s.appStateFatalExceptionNotification=p.proto.Message.AppStateFatalExceptionNotification.toObject(A.appStateFatalExceptionNotification,r),r.oneofs&&(s._appStateFatalExceptionNotification="appStateFatalExceptionNotification")),A.disappearingMode!=null&&A.hasOwnProperty("disappearingMode")&&(s.disappearingMode=p.proto.DisappearingMode.toObject(A.disappearingMode,r),r.oneofs&&(s._disappearingMode="disappearingMode")),A.editedMessage!=null&&A.hasOwnProperty("editedMessage")&&(s.editedMessage=p.proto.Message.toObject(A.editedMessage,r),r.oneofs&&(s._editedMessage="editedMessage")),A.timestampMs!=null&&A.hasOwnProperty("timestampMs")&&(typeof A.timestampMs=="number"?s.timestampMs=r.longs===String?String(A.timestampMs):A.timestampMs:s.timestampMs=r.longs===String?se(A.timestampMs):r.longs===Number?ge(A.timestampMs):A.timestampMs,r.oneofs&&(s._timestampMs="timestampMs")),A.peerDataOperationRequestMessage!=null&&A.hasOwnProperty("peerDataOperationRequestMessage")&&(s.peerDataOperationRequestMessage=p.proto.Message.PeerDataOperationRequestMessage.toObject(A.peerDataOperationRequestMessage,r),r.oneofs&&(s._peerDataOperationRequestMessage="peerDataOperationRequestMessage")),A.peerDataOperationRequestResponseMessage!=null&&A.hasOwnProperty("peerDataOperationRequestResponseMessage")&&(s.peerDataOperationRequestResponseMessage=p.proto.Message.PeerDataOperationRequestResponseMessage.toObject(A.peerDataOperationRequestResponseMessage,r),r.oneofs&&(s._peerDataOperationRequestResponseMessage="peerDataOperationRequestResponseMessage")),A.botFeedbackMessage!=null&&A.hasOwnProperty("botFeedbackMessage")&&(s.botFeedbackMessage=p.proto.BotFeedbackMessage.toObject(A.botFeedbackMessage,r),r.oneofs&&(s._botFeedbackMessage="botFeedbackMessage")),A.invokerJid!=null&&A.hasOwnProperty("invokerJid")&&(s.invokerJid=A.invokerJid,r.oneofs&&(s._invokerJid="invokerJid")),A.requestWelcomeMessageMetadata!=null&&A.hasOwnProperty("requestWelcomeMessageMetadata")&&(s.requestWelcomeMessageMetadata=p.proto.Message.RequestWelcomeMessageMetadata.toObject(A.requestWelcomeMessageMetadata,r),r.oneofs&&(s._requestWelcomeMessageMetadata="requestWelcomeMessageMetadata")),A.mediaNotifyMessage!=null&&A.hasOwnProperty("mediaNotifyMessage")&&(s.mediaNotifyMessage=p.proto.MediaNotifyMessage.toObject(A.mediaNotifyMessage,r),r.oneofs&&(s._mediaNotifyMessage="mediaNotifyMessage")),A.cloudApiThreadControlNotification!=null&&A.hasOwnProperty("cloudApiThreadControlNotification")&&(s.cloudApiThreadControlNotification=p.proto.Message.CloudAPIThreadControlNotification.toObject(A.cloudApiThreadControlNotification,r),r.oneofs&&(s._cloudApiThreadControlNotification="cloudApiThreadControlNotification")),A.lidMigrationMappingSyncMessage!=null&&A.hasOwnProperty("lidMigrationMappingSyncMessage")&&(s.lidMigrationMappingSyncMessage=p.proto.LIDMigrationMappingSyncMessage.toObject(A.lidMigrationMappingSyncMessage,r),r.oneofs&&(s._lidMigrationMappingSyncMessage="lidMigrationMappingSyncMessage")),A.limitSharing!=null&&A.hasOwnProperty("limitSharing")&&(s.limitSharing=p.proto.LimitSharing.toObject(A.limitSharing,r),r.oneofs&&(s._limitSharing="limitSharing")),A.aiPsiMetadata!=null&&A.hasOwnProperty("aiPsiMetadata")&&(s.aiPsiMetadata=r.bytes===String?l.base64.encode(A.aiPsiMetadata,0,A.aiPsiMetadata.length):r.bytes===Array?Array.prototype.slice.call(A.aiPsiMetadata):A.aiPsiMetadata,r.oneofs&&(s._aiPsiMetadata="aiPsiMetadata")),A.aiQueryFanout!=null&&A.hasOwnProperty("aiQueryFanout")&&(s.aiQueryFanout=p.proto.AIQueryFanout.toObject(A.aiQueryFanout,r),r.oneofs&&(s._aiQueryFanout="aiQueryFanout")),A.memberLabel!=null&&A.hasOwnProperty("memberLabel")&&(s.memberLabel=p.proto.MemberLabel.toObject(A.memberLabel,r),r.oneofs&&(s._memberLabel="memberLabel")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ProtocolMessage"},i.Type=(function(){let a={},A=Object.create(a);return A[a[0]="REVOKE"]=0,A[a[3]="EPHEMERAL_SETTING"]=3,A[a[4]="EPHEMERAL_SYNC_RESPONSE"]=4,A[a[5]="HISTORY_SYNC_NOTIFICATION"]=5,A[a[6]="APP_STATE_SYNC_KEY_SHARE"]=6,A[a[7]="APP_STATE_SYNC_KEY_REQUEST"]=7,A[a[8]="MSG_FANOUT_BACKFILL_REQUEST"]=8,A[a[9]="INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC"]=9,A[a[10]="APP_STATE_FATAL_EXCEPTION_NOTIFICATION"]=10,A[a[11]="SHARE_PHONE_NUMBER"]=11,A[a[14]="MESSAGE_EDIT"]=14,A[a[16]="PEER_DATA_OPERATION_REQUEST_MESSAGE"]=16,A[a[17]="PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]=17,A[a[18]="REQUEST_WELCOME_MESSAGE"]=18,A[a[19]="BOT_FEEDBACK_MESSAGE"]=19,A[a[20]="MEDIA_NOTIFY_MESSAGE"]=20,A[a[21]="CLOUD_API_THREAD_CONTROL_NOTIFICATION"]=21,A[a[22]="LID_MIGRATION_MAPPING_SYNC"]=22,A[a[23]="REMINDER_MESSAGE"]=23,A[a[24]="BOT_MEMU_ONBOARDING_MESSAGE"]=24,A[a[25]="STATUS_MENTION_MESSAGE"]=25,A[a[26]="STOP_GENERATION_MESSAGE"]=26,A[a[27]="LIMIT_SHARING"]=27,A[a[28]="AI_PSI_METADATA"]=28,A[a[29]="AI_QUERY_FANOUT"]=29,A[a[30]="GROUP_MEMBER_LABEL_CHANGE"]=30,A})(),i})(),t.QuestionResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.text=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.QuestionResponseMessage)return A;var r=new p.proto.Message.QuestionResponseMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.QuestionResponseMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return A.text!=null&&(r.text=String(A.text)),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.QuestionResponseMessage"},i})(),t.ReactionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.text=A.string();break}case 3:{c.groupingKey=A.string();break}case 4:{c.senderTimestampMs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ReactionMessage)return A;var r=new p.proto.Message.ReactionMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.ReactionMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return A.text!=null&&(r.text=String(A.text)),A.groupingKey!=null&&(r.groupingKey=String(A.groupingKey)),A.senderTimestampMs!=null&&(l.Long?(r.senderTimestampMs=l.Long.fromValue(A.senderTimestampMs)).unsigned=!1:typeof A.senderTimestampMs=="string"?r.senderTimestampMs=parseInt(A.senderTimestampMs,10):typeof A.senderTimestampMs=="number"?r.senderTimestampMs=A.senderTimestampMs:typeof A.senderTimestampMs=="object"&&(r.senderTimestampMs=new l.LongBits(A.senderTimestampMs.low>>>0,A.senderTimestampMs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),A.groupingKey!=null&&A.hasOwnProperty("groupingKey")&&(s.groupingKey=A.groupingKey,r.oneofs&&(s._groupingKey="groupingKey")),A.senderTimestampMs!=null&&A.hasOwnProperty("senderTimestampMs")&&(typeof A.senderTimestampMs=="number"?s.senderTimestampMs=r.longs===String?String(A.senderTimestampMs):A.senderTimestampMs:s.senderTimestampMs=r.longs===String?se(A.senderTimestampMs):r.longs===Number?ge(A.senderTimestampMs):A.senderTimestampMs,r.oneofs&&(s._senderTimestampMs="senderTimestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ReactionMessage"},i})(),t.RequestPaymentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 4:{c.noteMessage=p.proto.Message.decode(A,A.uint32());break}case 1:{c.currencyCodeIso4217=A.string();break}case 2:{c.amount1000=A.uint64();break}case 3:{c.requestFrom=A.string();break}case 5:{c.expiryTimestamp=A.int64();break}case 6:{c.amount=p.proto.Money.decode(A,A.uint32());break}case 7:{c.background=p.proto.PaymentBackground.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.RequestPaymentMessage)return A;var r=new p.proto.Message.RequestPaymentMessage;if(A.noteMessage!=null){if(typeof A.noteMessage!="object")throw TypeError(".proto.Message.RequestPaymentMessage.noteMessage: object expected");r.noteMessage=p.proto.Message.fromObject(A.noteMessage)}if(A.currencyCodeIso4217!=null&&(r.currencyCodeIso4217=String(A.currencyCodeIso4217)),A.amount1000!=null&&(l.Long?(r.amount1000=l.Long.fromValue(A.amount1000)).unsigned=!0:typeof A.amount1000=="string"?r.amount1000=parseInt(A.amount1000,10):typeof A.amount1000=="number"?r.amount1000=A.amount1000:typeof A.amount1000=="object"&&(r.amount1000=new l.LongBits(A.amount1000.low>>>0,A.amount1000.high>>>0).toNumber(!0))),A.requestFrom!=null&&(r.requestFrom=String(A.requestFrom)),A.expiryTimestamp!=null&&(l.Long?(r.expiryTimestamp=l.Long.fromValue(A.expiryTimestamp)).unsigned=!1:typeof A.expiryTimestamp=="string"?r.expiryTimestamp=parseInt(A.expiryTimestamp,10):typeof A.expiryTimestamp=="number"?r.expiryTimestamp=A.expiryTimestamp:typeof A.expiryTimestamp=="object"&&(r.expiryTimestamp=new l.LongBits(A.expiryTimestamp.low>>>0,A.expiryTimestamp.high>>>0).toNumber())),A.amount!=null){if(typeof A.amount!="object")throw TypeError(".proto.Message.RequestPaymentMessage.amount: object expected");r.amount=p.proto.Money.fromObject(A.amount)}if(A.background!=null){if(typeof A.background!="object")throw TypeError(".proto.Message.RequestPaymentMessage.background: object expected");r.background=p.proto.PaymentBackground.fromObject(A.background)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.currencyCodeIso4217!=null&&A.hasOwnProperty("currencyCodeIso4217")&&(s.currencyCodeIso4217=A.currencyCodeIso4217,r.oneofs&&(s._currencyCodeIso4217="currencyCodeIso4217")),A.amount1000!=null&&A.hasOwnProperty("amount1000")&&(typeof A.amount1000=="number"?s.amount1000=r.longs===String?String(A.amount1000):A.amount1000:s.amount1000=r.longs===String?se(A.amount1000,!0):r.longs===Number?ge(A.amount1000,!0):A.amount1000,r.oneofs&&(s._amount1000="amount1000")),A.requestFrom!=null&&A.hasOwnProperty("requestFrom")&&(s.requestFrom=A.requestFrom,r.oneofs&&(s._requestFrom="requestFrom")),A.noteMessage!=null&&A.hasOwnProperty("noteMessage")&&(s.noteMessage=p.proto.Message.toObject(A.noteMessage,r),r.oneofs&&(s._noteMessage="noteMessage")),A.expiryTimestamp!=null&&A.hasOwnProperty("expiryTimestamp")&&(typeof A.expiryTimestamp=="number"?s.expiryTimestamp=r.longs===String?String(A.expiryTimestamp):A.expiryTimestamp:s.expiryTimestamp=r.longs===String?se(A.expiryTimestamp):r.longs===Number?ge(A.expiryTimestamp):A.expiryTimestamp,r.oneofs&&(s._expiryTimestamp="expiryTimestamp")),A.amount!=null&&A.hasOwnProperty("amount")&&(s.amount=p.proto.Money.toObject(A.amount,r),r.oneofs&&(s._amount="amount")),A.background!=null&&A.hasOwnProperty("background")&&(s.background=p.proto.PaymentBackground.toObject(A.background,r),r.oneofs&&(s._background="background")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.RequestPaymentMessage"},i})(),t.RequestPhoneNumberMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.RequestPhoneNumberMessage)return A;var r=new p.proto.Message.RequestPhoneNumberMessage;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.RequestPhoneNumberMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.RequestPhoneNumberMessage"},i})(),t.RequestWelcomeMessageMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.localChatState=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.RequestWelcomeMessageMetadata)return A;var r=new p.proto.Message.RequestWelcomeMessageMetadata;switch(A.localChatState){default:if(typeof A.localChatState=="number"){r.localChatState=A.localChatState;break}break;case"EMPTY":case 0:r.localChatState=0;break;case"NON_EMPTY":case 1:r.localChatState=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.localChatState!=null&&A.hasOwnProperty("localChatState")&&(s.localChatState=r.enums===String?p.proto.Message.RequestWelcomeMessageMetadata.LocalChatState[A.localChatState]===void 0?A.localChatState:p.proto.Message.RequestWelcomeMessageMetadata.LocalChatState[A.localChatState]:A.localChatState,r.oneofs&&(s._localChatState="localChatState")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.RequestWelcomeMessageMetadata"},i.LocalChatState=(function(){let a={},A=Object.create(a);return A[a[0]="EMPTY"]=0,A[a[1]="NON_EMPTY"]=1,A})(),i})(),t.ScheduledCallCreationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.scheduledTimestampMs=A.int64();break}case 2:{c.callType=A.int32();break}case 3:{c.title=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ScheduledCallCreationMessage)return A;var r=new p.proto.Message.ScheduledCallCreationMessage;switch(A.scheduledTimestampMs!=null&&(l.Long?(r.scheduledTimestampMs=l.Long.fromValue(A.scheduledTimestampMs)).unsigned=!1:typeof A.scheduledTimestampMs=="string"?r.scheduledTimestampMs=parseInt(A.scheduledTimestampMs,10):typeof A.scheduledTimestampMs=="number"?r.scheduledTimestampMs=A.scheduledTimestampMs:typeof A.scheduledTimestampMs=="object"&&(r.scheduledTimestampMs=new l.LongBits(A.scheduledTimestampMs.low>>>0,A.scheduledTimestampMs.high>>>0).toNumber())),A.callType){default:if(typeof A.callType=="number"){r.callType=A.callType;break}break;case"UNKNOWN":case 0:r.callType=0;break;case"VOICE":case 1:r.callType=1;break;case"VIDEO":case 2:r.callType=2;break}return A.title!=null&&(r.title=String(A.title)),r},i.toObject=function(A,r){r||(r={});var s={};return A.scheduledTimestampMs!=null&&A.hasOwnProperty("scheduledTimestampMs")&&(typeof A.scheduledTimestampMs=="number"?s.scheduledTimestampMs=r.longs===String?String(A.scheduledTimestampMs):A.scheduledTimestampMs:s.scheduledTimestampMs=r.longs===String?se(A.scheduledTimestampMs):r.longs===Number?ge(A.scheduledTimestampMs):A.scheduledTimestampMs,r.oneofs&&(s._scheduledTimestampMs="scheduledTimestampMs")),A.callType!=null&&A.hasOwnProperty("callType")&&(s.callType=r.enums===String?p.proto.Message.ScheduledCallCreationMessage.CallType[A.callType]===void 0?A.callType:p.proto.Message.ScheduledCallCreationMessage.CallType[A.callType]:A.callType,r.oneofs&&(s._callType="callType")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ScheduledCallCreationMessage"},i.CallType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="VOICE"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),t.ScheduledCallEditMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.editType=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ScheduledCallEditMessage)return A;var r=new p.proto.Message.ScheduledCallEditMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.ScheduledCallEditMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}switch(A.editType){default:if(typeof A.editType=="number"){r.editType=A.editType;break}break;case"UNKNOWN":case 0:r.editType=0;break;case"CANCEL":case 1:r.editType=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.editType!=null&&A.hasOwnProperty("editType")&&(s.editType=r.enums===String?p.proto.Message.ScheduledCallEditMessage.EditType[A.editType]===void 0?A.editType:p.proto.Message.ScheduledCallEditMessage.EditType[A.editType]:A.editType,r.oneofs&&(s._editType="editType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ScheduledCallEditMessage"},i.EditType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="CANCEL"]=1,A})(),i})(),t.SecretEncryptedMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.targetMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}case 4:{c.secretEncType=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.SecretEncryptedMessage)return A;var r=new p.proto.Message.SecretEncryptedMessage;if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.SecretEncryptedMessage.targetMessageKey: object expected");r.targetMessageKey=p.proto.MessageKey.fromObject(A.targetMessageKey)}switch(A.encPayload!=null&&(typeof A.encPayload=="string"?l.base64.decode(A.encPayload,r.encPayload=l.newBuffer(l.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(r.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?l.base64.decode(A.encIv,r.encIv=l.newBuffer(l.base64.length(A.encIv)),0):A.encIv.length>=0&&(r.encIv=A.encIv)),A.secretEncType){default:if(typeof A.secretEncType=="number"){r.secretEncType=A.secretEncType;break}break;case"UNKNOWN":case 0:r.secretEncType=0;break;case"EVENT_EDIT":case 1:r.secretEncType=1;break;case"MESSAGE_EDIT":case 2:r.secretEncType=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=p.proto.MessageKey.toObject(A.targetMessageKey,r),r.oneofs&&(s._targetMessageKey="targetMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=r.bytes===String?l.base64.encode(A.encPayload,0,A.encPayload.length):r.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,r.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=r.bytes===String?l.base64.encode(A.encIv,0,A.encIv.length):r.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,r.oneofs&&(s._encIv="encIv")),A.secretEncType!=null&&A.hasOwnProperty("secretEncType")&&(s.secretEncType=r.enums===String?p.proto.Message.SecretEncryptedMessage.SecretEncType[A.secretEncType]===void 0?A.secretEncType:p.proto.Message.SecretEncryptedMessage.SecretEncType[A.secretEncType]:A.secretEncType,r.oneofs&&(s._secretEncType="secretEncType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.SecretEncryptedMessage"},i.SecretEncType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="EVENT_EDIT"]=1,A[a[2]="MESSAGE_EDIT"]=2,A})(),i})(),t.SendPaymentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 2:{c.noteMessage=p.proto.Message.decode(A,A.uint32());break}case 3:{c.requestMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 4:{c.background=p.proto.PaymentBackground.decode(A,A.uint32());break}case 5:{c.transactionData=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.SendPaymentMessage)return A;var r=new p.proto.Message.SendPaymentMessage;if(A.noteMessage!=null){if(typeof A.noteMessage!="object")throw TypeError(".proto.Message.SendPaymentMessage.noteMessage: object expected");r.noteMessage=p.proto.Message.fromObject(A.noteMessage)}if(A.requestMessageKey!=null){if(typeof A.requestMessageKey!="object")throw TypeError(".proto.Message.SendPaymentMessage.requestMessageKey: object expected");r.requestMessageKey=p.proto.MessageKey.fromObject(A.requestMessageKey)}if(A.background!=null){if(typeof A.background!="object")throw TypeError(".proto.Message.SendPaymentMessage.background: object expected");r.background=p.proto.PaymentBackground.fromObject(A.background)}return A.transactionData!=null&&(r.transactionData=String(A.transactionData)),r},i.toObject=function(A,r){r||(r={});var s={};return A.noteMessage!=null&&A.hasOwnProperty("noteMessage")&&(s.noteMessage=p.proto.Message.toObject(A.noteMessage,r),r.oneofs&&(s._noteMessage="noteMessage")),A.requestMessageKey!=null&&A.hasOwnProperty("requestMessageKey")&&(s.requestMessageKey=p.proto.MessageKey.toObject(A.requestMessageKey,r),r.oneofs&&(s._requestMessageKey="requestMessageKey")),A.background!=null&&A.hasOwnProperty("background")&&(s.background=p.proto.PaymentBackground.toObject(A.background,r),r.oneofs&&(s._background="background")),A.transactionData!=null&&A.hasOwnProperty("transactionData")&&(s.transactionData=A.transactionData,r.oneofs&&(s._transactionData="transactionData")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.SendPaymentMessage"},i})(),t.SenderKeyDistributionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.groupId=A.string();break}case 2:{c.axolotlSenderKeyDistributionMessage=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.SenderKeyDistributionMessage)return A;var r=new p.proto.Message.SenderKeyDistributionMessage;return A.groupId!=null&&(r.groupId=String(A.groupId)),A.axolotlSenderKeyDistributionMessage!=null&&(typeof A.axolotlSenderKeyDistributionMessage=="string"?l.base64.decode(A.axolotlSenderKeyDistributionMessage,r.axolotlSenderKeyDistributionMessage=l.newBuffer(l.base64.length(A.axolotlSenderKeyDistributionMessage)),0):A.axolotlSenderKeyDistributionMessage.length>=0&&(r.axolotlSenderKeyDistributionMessage=A.axolotlSenderKeyDistributionMessage)),r},i.toObject=function(A,r){r||(r={});var s={};return A.groupId!=null&&A.hasOwnProperty("groupId")&&(s.groupId=A.groupId,r.oneofs&&(s._groupId="groupId")),A.axolotlSenderKeyDistributionMessage!=null&&A.hasOwnProperty("axolotlSenderKeyDistributionMessage")&&(s.axolotlSenderKeyDistributionMessage=r.bytes===String?l.base64.encode(A.axolotlSenderKeyDistributionMessage,0,A.axolotlSenderKeyDistributionMessage.length):r.bytes===Array?Array.prototype.slice.call(A.axolotlSenderKeyDistributionMessage):A.axolotlSenderKeyDistributionMessage,r.oneofs&&(s._axolotlSenderKeyDistributionMessage="axolotlSenderKeyDistributionMessage")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.SenderKeyDistributionMessage"},i})(),t.StatusNotificationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.responseMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.originalMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 3:{c.type=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StatusNotificationMessage)return A;var r=new p.proto.Message.StatusNotificationMessage;if(A.responseMessageKey!=null){if(typeof A.responseMessageKey!="object")throw TypeError(".proto.Message.StatusNotificationMessage.responseMessageKey: object expected");r.responseMessageKey=p.proto.MessageKey.fromObject(A.responseMessageKey)}if(A.originalMessageKey!=null){if(typeof A.originalMessageKey!="object")throw TypeError(".proto.Message.StatusNotificationMessage.originalMessageKey: object expected");r.originalMessageKey=p.proto.MessageKey.fromObject(A.originalMessageKey)}switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNKNOWN":case 0:r.type=0;break;case"STATUS_ADD_YOURS":case 1:r.type=1;break;case"STATUS_RESHARE":case 2:r.type=2;break;case"STATUS_QUESTION_ANSWER_RESHARE":case 3:r.type=3;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.responseMessageKey!=null&&A.hasOwnProperty("responseMessageKey")&&(s.responseMessageKey=p.proto.MessageKey.toObject(A.responseMessageKey,r),r.oneofs&&(s._responseMessageKey="responseMessageKey")),A.originalMessageKey!=null&&A.hasOwnProperty("originalMessageKey")&&(s.originalMessageKey=p.proto.MessageKey.toObject(A.originalMessageKey,r),r.oneofs&&(s._originalMessageKey="originalMessageKey")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.StatusNotificationMessage.StatusNotificationType[A.type]===void 0?A.type:p.proto.Message.StatusNotificationMessage.StatusNotificationType[A.type]:A.type,r.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusNotificationMessage"},i.StatusNotificationType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="STATUS_ADD_YOURS"]=1,A[a[2]="STATUS_RESHARE"]=2,A[a[3]="STATUS_QUESTION_ANSWER_RESHARE"]=3,A})(),i})(),t.StatusQuestionAnswerMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.text=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StatusQuestionAnswerMessage)return A;var r=new p.proto.Message.StatusQuestionAnswerMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.StatusQuestionAnswerMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return A.text!=null&&(r.text=String(A.text)),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusQuestionAnswerMessage"},i})(),t.StatusQuotedMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.type=A.int32();break}case 2:{c.text=A.string();break}case 3:{c.thumbnail=A.bytes();break}case 4:{c.originalStatusId=p.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StatusQuotedMessage)return A;var r=new p.proto.Message.StatusQuotedMessage;switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"QUESTION_ANSWER":case 1:r.type=1;break}if(A.text!=null&&(r.text=String(A.text)),A.thumbnail!=null&&(typeof A.thumbnail=="string"?l.base64.decode(A.thumbnail,r.thumbnail=l.newBuffer(l.base64.length(A.thumbnail)),0):A.thumbnail.length>=0&&(r.thumbnail=A.thumbnail)),A.originalStatusId!=null){if(typeof A.originalStatusId!="object")throw TypeError(".proto.Message.StatusQuotedMessage.originalStatusId: object expected");r.originalStatusId=p.proto.MessageKey.fromObject(A.originalStatusId)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.StatusQuotedMessage.StatusQuotedMessageType[A.type]===void 0?A.type:p.proto.Message.StatusQuotedMessage.StatusQuotedMessageType[A.type]:A.type,r.oneofs&&(s._type="type")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),A.thumbnail!=null&&A.hasOwnProperty("thumbnail")&&(s.thumbnail=r.bytes===String?l.base64.encode(A.thumbnail,0,A.thumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnail):A.thumbnail,r.oneofs&&(s._thumbnail="thumbnail")),A.originalStatusId!=null&&A.hasOwnProperty("originalStatusId")&&(s.originalStatusId=p.proto.MessageKey.toObject(A.originalStatusId,r),r.oneofs&&(s._originalStatusId="originalStatusId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusQuotedMessage"},i.StatusQuotedMessageType=(function(){let a={},A=Object.create(a);return A[a[1]="QUESTION_ANSWER"]=1,A})(),i})(),t.StatusStickerInteractionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.stickerKey=A.string();break}case 3:{c.type=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StatusStickerInteractionMessage)return A;var r=new p.proto.Message.StatusStickerInteractionMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.StatusStickerInteractionMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}switch(A.stickerKey!=null&&(r.stickerKey=String(A.stickerKey)),A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNKNOWN":case 0:r.type=0;break;case"REACTION":case 1:r.type=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.stickerKey!=null&&A.hasOwnProperty("stickerKey")&&(s.stickerKey=A.stickerKey,r.oneofs&&(s._stickerKey="stickerKey")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.StatusStickerInteractionMessage.StatusStickerType[A.type]===void 0?A.type:p.proto.Message.StatusStickerInteractionMessage.StatusStickerType[A.type]:A.type,r.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusStickerInteractionMessage"},i.StatusStickerType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="REACTION"]=1,A})(),i})(),t.StickerMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.url=A.string();break}case 2:{c.fileSha256=A.bytes();break}case 3:{c.fileEncSha256=A.bytes();break}case 4:{c.mediaKey=A.bytes();break}case 5:{c.mimetype=A.string();break}case 6:{c.height=A.uint32();break}case 7:{c.width=A.uint32();break}case 8:{c.directPath=A.string();break}case 9:{c.fileLength=A.uint64();break}case 10:{c.mediaKeyTimestamp=A.int64();break}case 11:{c.firstFrameLength=A.uint32();break}case 12:{c.firstFrameSidecar=A.bytes();break}case 13:{c.isAnimated=A.bool();break}case 16:{c.pngThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.stickerSentTs=A.int64();break}case 19:{c.isAvatar=A.bool();break}case 20:{c.isAiSticker=A.bool();break}case 21:{c.isLottie=A.bool();break}case 22:{c.accessibilityLabel=A.string();break}case 23:{c.mediaKeyDomain=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StickerMessage)return A;var r=new p.proto.Message.StickerMessage;if(A.url!=null&&(r.url=String(A.url)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.height!=null&&(r.height=A.height>>>0),A.width!=null&&(r.width=A.width>>>0),A.directPath!=null&&(r.directPath=String(A.directPath)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.firstFrameLength!=null&&(r.firstFrameLength=A.firstFrameLength>>>0),A.firstFrameSidecar!=null&&(typeof A.firstFrameSidecar=="string"?l.base64.decode(A.firstFrameSidecar,r.firstFrameSidecar=l.newBuffer(l.base64.length(A.firstFrameSidecar)),0):A.firstFrameSidecar.length>=0&&(r.firstFrameSidecar=A.firstFrameSidecar)),A.isAnimated!=null&&(r.isAnimated=!!A.isAnimated),A.pngThumbnail!=null&&(typeof A.pngThumbnail=="string"?l.base64.decode(A.pngThumbnail,r.pngThumbnail=l.newBuffer(l.base64.length(A.pngThumbnail)),0):A.pngThumbnail.length>=0&&(r.pngThumbnail=A.pngThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.StickerMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.stickerSentTs!=null&&(l.Long?(r.stickerSentTs=l.Long.fromValue(A.stickerSentTs)).unsigned=!1:typeof A.stickerSentTs=="string"?r.stickerSentTs=parseInt(A.stickerSentTs,10):typeof A.stickerSentTs=="number"?r.stickerSentTs=A.stickerSentTs:typeof A.stickerSentTs=="object"&&(r.stickerSentTs=new l.LongBits(A.stickerSentTs.low>>>0,A.stickerSentTs.high>>>0).toNumber())),A.isAvatar!=null&&(r.isAvatar=!!A.isAvatar),A.isAiSticker!=null&&(r.isAiSticker=!!A.isAiSticker),A.isLottie!=null&&(r.isLottie=!!A.isLottie),A.accessibilityLabel!=null&&(r.accessibilityLabel=String(A.accessibilityLabel)),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){r.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:r.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:r.mediaKeyDomain=1;break;case"STATUS":case 2:r.mediaKeyDomain=2;break;case"CAPI":case 3:r.mediaKeyDomain=3;break;case"BOT":case 4:r.mediaKeyDomain=4;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=A.height,r.oneofs&&(s._height="height")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=A.width,r.oneofs&&(s._width="width")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.firstFrameLength!=null&&A.hasOwnProperty("firstFrameLength")&&(s.firstFrameLength=A.firstFrameLength,r.oneofs&&(s._firstFrameLength="firstFrameLength")),A.firstFrameSidecar!=null&&A.hasOwnProperty("firstFrameSidecar")&&(s.firstFrameSidecar=r.bytes===String?l.base64.encode(A.firstFrameSidecar,0,A.firstFrameSidecar.length):r.bytes===Array?Array.prototype.slice.call(A.firstFrameSidecar):A.firstFrameSidecar,r.oneofs&&(s._firstFrameSidecar="firstFrameSidecar")),A.isAnimated!=null&&A.hasOwnProperty("isAnimated")&&(s.isAnimated=A.isAnimated,r.oneofs&&(s._isAnimated="isAnimated")),A.pngThumbnail!=null&&A.hasOwnProperty("pngThumbnail")&&(s.pngThumbnail=r.bytes===String?l.base64.encode(A.pngThumbnail,0,A.pngThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.pngThumbnail):A.pngThumbnail,r.oneofs&&(s._pngThumbnail="pngThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.stickerSentTs!=null&&A.hasOwnProperty("stickerSentTs")&&(typeof A.stickerSentTs=="number"?s.stickerSentTs=r.longs===String?String(A.stickerSentTs):A.stickerSentTs:s.stickerSentTs=r.longs===String?se(A.stickerSentTs):r.longs===Number?ge(A.stickerSentTs):A.stickerSentTs,r.oneofs&&(s._stickerSentTs="stickerSentTs")),A.isAvatar!=null&&A.hasOwnProperty("isAvatar")&&(s.isAvatar=A.isAvatar,r.oneofs&&(s._isAvatar="isAvatar")),A.isAiSticker!=null&&A.hasOwnProperty("isAiSticker")&&(s.isAiSticker=A.isAiSticker,r.oneofs&&(s._isAiSticker="isAiSticker")),A.isLottie!=null&&A.hasOwnProperty("isLottie")&&(s.isLottie=A.isLottie,r.oneofs&&(s._isLottie="isLottie")),A.accessibilityLabel!=null&&A.hasOwnProperty("accessibilityLabel")&&(s.accessibilityLabel=A.accessibilityLabel,r.oneofs&&(s._accessibilityLabel="accessibilityLabel")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=r.enums===String?p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,r.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StickerMessage"},i})(),t.StickerPackMessage=(function(){function i(a){if(this.stickers=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.stickerPackId=A.string();break}case 2:{c.name=A.string();break}case 3:{c.publisher=A.string();break}case 4:{c.stickers&&c.stickers.length||(c.stickers=[]),c.stickers.push(p.proto.Message.StickerPackMessage.Sticker.decode(A,A.uint32()));break}case 5:{c.fileLength=A.uint64();break}case 6:{c.fileSha256=A.bytes();break}case 7:{c.fileEncSha256=A.bytes();break}case 8:{c.mediaKey=A.bytes();break}case 9:{c.directPath=A.string();break}case 10:{c.caption=A.string();break}case 11:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 12:{c.packDescription=A.string();break}case 13:{c.mediaKeyTimestamp=A.int64();break}case 14:{c.trayIconFileName=A.string();break}case 15:{c.thumbnailDirectPath=A.string();break}case 16:{c.thumbnailSha256=A.bytes();break}case 17:{c.thumbnailEncSha256=A.bytes();break}case 18:{c.thumbnailHeight=A.uint32();break}case 19:{c.thumbnailWidth=A.uint32();break}case 20:{c.imageDataHash=A.string();break}case 21:{c.stickerPackSize=A.uint64();break}case 22:{c.stickerPackOrigin=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StickerPackMessage)return A;var r=new p.proto.Message.StickerPackMessage;if(A.stickerPackId!=null&&(r.stickerPackId=String(A.stickerPackId)),A.name!=null&&(r.name=String(A.name)),A.publisher!=null&&(r.publisher=String(A.publisher)),A.stickers){if(!Array.isArray(A.stickers))throw TypeError(".proto.Message.StickerPackMessage.stickers: array expected");r.stickers=[];for(var s=0;s>>0,A.fileLength.high>>>0).toNumber(!0))),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.directPath!=null&&(r.directPath=String(A.directPath)),A.caption!=null&&(r.caption=String(A.caption)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.StickerPackMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.packDescription!=null&&(r.packDescription=String(A.packDescription)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.trayIconFileName!=null&&(r.trayIconFileName=String(A.trayIconFileName)),A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.thumbnailHeight!=null&&(r.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(r.thumbnailWidth=A.thumbnailWidth>>>0),A.imageDataHash!=null&&(r.imageDataHash=String(A.imageDataHash)),A.stickerPackSize!=null&&(l.Long?(r.stickerPackSize=l.Long.fromValue(A.stickerPackSize)).unsigned=!0:typeof A.stickerPackSize=="string"?r.stickerPackSize=parseInt(A.stickerPackSize,10):typeof A.stickerPackSize=="number"?r.stickerPackSize=A.stickerPackSize:typeof A.stickerPackSize=="object"&&(r.stickerPackSize=new l.LongBits(A.stickerPackSize.low>>>0,A.stickerPackSize.high>>>0).toNumber(!0))),A.stickerPackOrigin){default:if(typeof A.stickerPackOrigin=="number"){r.stickerPackOrigin=A.stickerPackOrigin;break}break;case"FIRST_PARTY":case 0:r.stickerPackOrigin=0;break;case"THIRD_PARTY":case 1:r.stickerPackOrigin=1;break;case"USER_CREATED":case 2:r.stickerPackOrigin=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.stickers=[]),A.stickerPackId!=null&&A.hasOwnProperty("stickerPackId")&&(s.stickerPackId=A.stickerPackId,r.oneofs&&(s._stickerPackId="stickerPackId")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.publisher!=null&&A.hasOwnProperty("publisher")&&(s.publisher=A.publisher,r.oneofs&&(s._publisher="publisher")),A.stickers&&A.stickers.length){s.stickers=[];for(var g=0;g>>3){case 1:{d.fileName=s.string();break}case 2:{d.isAnimated=s.bool();break}case 3:{d.emojis&&d.emojis.length||(d.emojis=[]),d.emojis.push(s.string());break}case 4:{d.accessibilityLabel=s.string();break}case 5:{d.isLottie=s.bool();break}case 6:{d.mimetype=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.StickerPackMessage.Sticker)return s;var g=new p.proto.Message.StickerPackMessage.Sticker;if(s.fileName!=null&&(g.fileName=String(s.fileName)),s.isAnimated!=null&&(g.isAnimated=!!s.isAnimated),s.emojis){if(!Array.isArray(s.emojis))throw TypeError(".proto.Message.StickerPackMessage.Sticker.emojis: array expected");g.emojis=[];for(var c=0;c>>3){case 1:{c.filehash&&c.filehash.length||(c.filehash=[]),c.filehash.push(A.string());break}case 2:{c.rmrSource=A.string();break}case 3:{c.requestTimestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StickerSyncRMRMessage)return A;var r=new p.proto.Message.StickerSyncRMRMessage;if(A.filehash){if(!Array.isArray(A.filehash))throw TypeError(".proto.Message.StickerSyncRMRMessage.filehash: array expected");r.filehash=[];for(var s=0;s>>0,A.requestTimestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.filehash=[]),A.filehash&&A.filehash.length){s.filehash=[];for(var g=0;g>>3){case 1:{c.selectedId=A.string();break}case 2:{c.selectedDisplayText=A.string();break}case 3:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.selectedIndex=A.uint32();break}case 5:{c.selectedCarouselCardIndex=A.uint32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.TemplateButtonReplyMessage)return A;var r=new p.proto.Message.TemplateButtonReplyMessage;if(A.selectedId!=null&&(r.selectedId=String(A.selectedId)),A.selectedDisplayText!=null&&(r.selectedDisplayText=String(A.selectedDisplayText)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.TemplateButtonReplyMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return A.selectedIndex!=null&&(r.selectedIndex=A.selectedIndex>>>0),A.selectedCarouselCardIndex!=null&&(r.selectedCarouselCardIndex=A.selectedCarouselCardIndex>>>0),r},i.toObject=function(A,r){r||(r={});var s={};return A.selectedId!=null&&A.hasOwnProperty("selectedId")&&(s.selectedId=A.selectedId,r.oneofs&&(s._selectedId="selectedId")),A.selectedDisplayText!=null&&A.hasOwnProperty("selectedDisplayText")&&(s.selectedDisplayText=A.selectedDisplayText,r.oneofs&&(s._selectedDisplayText="selectedDisplayText")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.selectedIndex!=null&&A.hasOwnProperty("selectedIndex")&&(s.selectedIndex=A.selectedIndex,r.oneofs&&(s._selectedIndex="selectedIndex")),A.selectedCarouselCardIndex!=null&&A.hasOwnProperty("selectedCarouselCardIndex")&&(s.selectedCarouselCardIndex=A.selectedCarouselCardIndex,r.oneofs&&(s._selectedCarouselCardIndex="selectedCarouselCardIndex")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.TemplateButtonReplyMessage"},i})(),t.TemplateMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 3:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.hydratedTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.decode(A,A.uint32());break}case 9:{c.templateId=A.string();break}case 1:{c.fourRowTemplate=p.proto.Message.TemplateMessage.FourRowTemplate.decode(A,A.uint32());break}case 2:{c.hydratedFourRowTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.decode(A,A.uint32());break}case 5:{c.interactiveMessageTemplate=p.proto.Message.InteractiveMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.TemplateMessage)return A;var r=new p.proto.Message.TemplateMessage;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.TemplateMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.hydratedTemplate!=null){if(typeof A.hydratedTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.hydratedTemplate: object expected");r.hydratedTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.fromObject(A.hydratedTemplate)}if(A.templateId!=null&&(r.templateId=String(A.templateId)),A.fourRowTemplate!=null){if(typeof A.fourRowTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.fourRowTemplate: object expected");r.fourRowTemplate=p.proto.Message.TemplateMessage.FourRowTemplate.fromObject(A.fourRowTemplate)}if(A.hydratedFourRowTemplate!=null){if(typeof A.hydratedFourRowTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.hydratedFourRowTemplate: object expected");r.hydratedFourRowTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.fromObject(A.hydratedFourRowTemplate)}if(A.interactiveMessageTemplate!=null){if(typeof A.interactiveMessageTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.interactiveMessageTemplate: object expected");r.interactiveMessageTemplate=p.proto.Message.InteractiveMessage.fromObject(A.interactiveMessageTemplate)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.fourRowTemplate!=null&&A.hasOwnProperty("fourRowTemplate")&&(s.fourRowTemplate=p.proto.Message.TemplateMessage.FourRowTemplate.toObject(A.fourRowTemplate,r),r.oneofs&&(s.format="fourRowTemplate")),A.hydratedFourRowTemplate!=null&&A.hasOwnProperty("hydratedFourRowTemplate")&&(s.hydratedFourRowTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.toObject(A.hydratedFourRowTemplate,r),r.oneofs&&(s.format="hydratedFourRowTemplate")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.hydratedTemplate!=null&&A.hasOwnProperty("hydratedTemplate")&&(s.hydratedTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.toObject(A.hydratedTemplate,r),r.oneofs&&(s._hydratedTemplate="hydratedTemplate")),A.interactiveMessageTemplate!=null&&A.hasOwnProperty("interactiveMessageTemplate")&&(s.interactiveMessageTemplate=p.proto.Message.InteractiveMessage.toObject(A.interactiveMessageTemplate,r),r.oneofs&&(s.format="interactiveMessageTemplate")),A.templateId!=null&&A.hasOwnProperty("templateId")&&(s.templateId=A.templateId,r.oneofs&&(s._templateId="templateId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.TemplateMessage"},i.FourRowTemplate=(function(){function a(r){if(this.buttons=[],r)for(var s=Object.keys(r),g=0;g>>3){case 6:{d.content=p.proto.Message.HighlyStructuredMessage.decode(s,s.uint32());break}case 7:{d.footer=p.proto.Message.HighlyStructuredMessage.decode(s,s.uint32());break}case 8:{d.buttons&&d.buttons.length||(d.buttons=[]),d.buttons.push(p.proto.TemplateButton.decode(s,s.uint32()));break}case 1:{d.documentMessage=p.proto.Message.DocumentMessage.decode(s,s.uint32());break}case 2:{d.highlyStructuredMessage=p.proto.Message.HighlyStructuredMessage.decode(s,s.uint32());break}case 3:{d.imageMessage=p.proto.Message.ImageMessage.decode(s,s.uint32());break}case 4:{d.videoMessage=p.proto.Message.VideoMessage.decode(s,s.uint32());break}case 5:{d.locationMessage=p.proto.Message.LocationMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.TemplateMessage.FourRowTemplate)return s;var g=new p.proto.Message.TemplateMessage.FourRowTemplate;if(s.content!=null){if(typeof s.content!="object")throw TypeError(".proto.Message.TemplateMessage.FourRowTemplate.content: object expected");g.content=p.proto.Message.HighlyStructuredMessage.fromObject(s.content)}if(s.footer!=null){if(typeof s.footer!="object")throw TypeError(".proto.Message.TemplateMessage.FourRowTemplate.footer: object expected");g.footer=p.proto.Message.HighlyStructuredMessage.fromObject(s.footer)}if(s.buttons){if(!Array.isArray(s.buttons))throw TypeError(".proto.Message.TemplateMessage.FourRowTemplate.buttons: array expected");g.buttons=[];for(var c=0;c>>3){case 6:{d.hydratedContentText=s.string();break}case 7:{d.hydratedFooterText=s.string();break}case 8:{d.hydratedButtons&&d.hydratedButtons.length||(d.hydratedButtons=[]),d.hydratedButtons.push(p.proto.HydratedTemplateButton.decode(s,s.uint32()));break}case 9:{d.templateId=s.string();break}case 10:{d.maskLinkedDevices=s.bool();break}case 1:{d.documentMessage=p.proto.Message.DocumentMessage.decode(s,s.uint32());break}case 2:{d.hydratedTitleText=s.string();break}case 3:{d.imageMessage=p.proto.Message.ImageMessage.decode(s,s.uint32());break}case 4:{d.videoMessage=p.proto.Message.VideoMessage.decode(s,s.uint32());break}case 5:{d.locationMessage=p.proto.Message.LocationMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.TemplateMessage.HydratedFourRowTemplate)return s;var g=new p.proto.Message.TemplateMessage.HydratedFourRowTemplate;if(s.hydratedContentText!=null&&(g.hydratedContentText=String(s.hydratedContentText)),s.hydratedFooterText!=null&&(g.hydratedFooterText=String(s.hydratedFooterText)),s.hydratedButtons){if(!Array.isArray(s.hydratedButtons))throw TypeError(".proto.Message.TemplateMessage.HydratedFourRowTemplate.hydratedButtons: array expected");g.hydratedButtons=[];for(var c=0;c>>3){case 1:{c.fbExperimentId=A.uint32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.URLMetadata)return A;var r=new p.proto.Message.URLMetadata;return A.fbExperimentId!=null&&(r.fbExperimentId=A.fbExperimentId>>>0),r},i.toObject=function(A,r){r||(r={});var s={};return A.fbExperimentId!=null&&A.hasOwnProperty("fbExperimentId")&&(s.fbExperimentId=A.fbExperimentId,r.oneofs&&(s._fbExperimentId="fbExperimentId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.URLMetadata"},i})(),t.VideoEndCard=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.username=a.string();break}case 2:{g.caption=a.string();break}case 3:{g.thumbnailImageUrl=a.string();break}case 4:{g.profilePictureUrl=a.string();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.Message.VideoEndCard)return a;var A=new p.proto.Message.VideoEndCard;return a.username!=null&&(A.username=String(a.username)),a.caption!=null&&(A.caption=String(a.caption)),a.thumbnailImageUrl!=null&&(A.thumbnailImageUrl=String(a.thumbnailImageUrl)),a.profilePictureUrl!=null&&(A.profilePictureUrl=String(a.profilePictureUrl)),A},i.toObject=function(a,A){A||(A={});var r={};return A.defaults&&(r.username="",r.caption="",r.thumbnailImageUrl="",r.profilePictureUrl=""),a.username!=null&&a.hasOwnProperty("username")&&(r.username=a.username),a.caption!=null&&a.hasOwnProperty("caption")&&(r.caption=a.caption),a.thumbnailImageUrl!=null&&a.hasOwnProperty("thumbnailImageUrl")&&(r.thumbnailImageUrl=a.thumbnailImageUrl),a.profilePictureUrl!=null&&a.hasOwnProperty("profilePictureUrl")&&(r.profilePictureUrl=a.profilePictureUrl),r},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Message.VideoEndCard"},i})(),t.VideoMessage=(function(){function i(a){if(this.interactiveAnnotations=[],this.annotations=[],this.processedVideos=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.fileSha256=A.bytes();break}case 4:{c.fileLength=A.uint64();break}case 5:{c.seconds=A.uint32();break}case 6:{c.mediaKey=A.bytes();break}case 7:{c.caption=A.string();break}case 8:{c.gifPlayback=A.bool();break}case 9:{c.height=A.uint32();break}case 10:{c.width=A.uint32();break}case 11:{c.fileEncSha256=A.bytes();break}case 12:{c.interactiveAnnotations&&c.interactiveAnnotations.length||(c.interactiveAnnotations=[]),c.interactiveAnnotations.push(p.proto.InteractiveAnnotation.decode(A,A.uint32()));break}case 13:{c.directPath=A.string();break}case 14:{c.mediaKeyTimestamp=A.int64();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.streamingSidecar=A.bytes();break}case 19:{c.gifAttribution=A.int32();break}case 20:{c.viewOnce=A.bool();break}case 21:{c.thumbnailDirectPath=A.string();break}case 22:{c.thumbnailSha256=A.bytes();break}case 23:{c.thumbnailEncSha256=A.bytes();break}case 24:{c.staticUrl=A.string();break}case 25:{c.annotations&&c.annotations.length||(c.annotations=[]),c.annotations.push(p.proto.InteractiveAnnotation.decode(A,A.uint32()));break}case 26:{c.accessibilityLabel=A.string();break}case 27:{c.processedVideos&&c.processedVideos.length||(c.processedVideos=[]),c.processedVideos.push(p.proto.ProcessedVideo.decode(A,A.uint32()));break}case 28:{c.externalShareFullVideoDurationInSeconds=A.uint32();break}case 29:{c.motionPhotoPresentationOffsetMs=A.uint64();break}case 30:{c.metadataUrl=A.string();break}case 31:{c.videoSourceType=A.int32();break}case 32:{c.mediaKeyDomain=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.VideoMessage)return A;var r=new p.proto.Message.VideoMessage;if(A.url!=null&&(r.url=String(A.url)),A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.seconds!=null&&(r.seconds=A.seconds>>>0),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.caption!=null&&(r.caption=String(A.caption)),A.gifPlayback!=null&&(r.gifPlayback=!!A.gifPlayback),A.height!=null&&(r.height=A.height>>>0),A.width!=null&&(r.width=A.width>>>0),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.interactiveAnnotations){if(!Array.isArray(A.interactiveAnnotations))throw TypeError(".proto.Message.VideoMessage.interactiveAnnotations: array expected");r.interactiveAnnotations=[];for(var s=0;s>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.VideoMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.streamingSidecar!=null&&(typeof A.streamingSidecar=="string"?l.base64.decode(A.streamingSidecar,r.streamingSidecar=l.newBuffer(l.base64.length(A.streamingSidecar)),0):A.streamingSidecar.length>=0&&(r.streamingSidecar=A.streamingSidecar)),A.gifAttribution){default:if(typeof A.gifAttribution=="number"){r.gifAttribution=A.gifAttribution;break}break;case"NONE":case 0:r.gifAttribution=0;break;case"GIPHY":case 1:r.gifAttribution=1;break;case"TENOR":case 2:r.gifAttribution=2;break;case"KLIPY":case 3:r.gifAttribution=3;break}if(A.viewOnce!=null&&(r.viewOnce=!!A.viewOnce),A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.staticUrl!=null&&(r.staticUrl=String(A.staticUrl)),A.annotations){if(!Array.isArray(A.annotations))throw TypeError(".proto.Message.VideoMessage.annotations: array expected");r.annotations=[];for(var s=0;s>>0),A.motionPhotoPresentationOffsetMs!=null&&(l.Long?(r.motionPhotoPresentationOffsetMs=l.Long.fromValue(A.motionPhotoPresentationOffsetMs)).unsigned=!0:typeof A.motionPhotoPresentationOffsetMs=="string"?r.motionPhotoPresentationOffsetMs=parseInt(A.motionPhotoPresentationOffsetMs,10):typeof A.motionPhotoPresentationOffsetMs=="number"?r.motionPhotoPresentationOffsetMs=A.motionPhotoPresentationOffsetMs:typeof A.motionPhotoPresentationOffsetMs=="object"&&(r.motionPhotoPresentationOffsetMs=new l.LongBits(A.motionPhotoPresentationOffsetMs.low>>>0,A.motionPhotoPresentationOffsetMs.high>>>0).toNumber(!0))),A.metadataUrl!=null&&(r.metadataUrl=String(A.metadataUrl)),A.videoSourceType){default:if(typeof A.videoSourceType=="number"){r.videoSourceType=A.videoSourceType;break}break;case"USER_VIDEO":case 0:r.videoSourceType=0;break;case"AI_GENERATED":case 1:r.videoSourceType=1;break}switch(A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){r.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:r.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:r.mediaKeyDomain=1;break;case"STATUS":case 2:r.mediaKeyDomain=2;break;case"CAPI":case 3:r.mediaKeyDomain=3;break;case"BOT":case 4:r.mediaKeyDomain=4;break}return r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.interactiveAnnotations=[],s.annotations=[],s.processedVideos=[]),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.seconds!=null&&A.hasOwnProperty("seconds")&&(s.seconds=A.seconds,r.oneofs&&(s._seconds="seconds")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.gifPlayback!=null&&A.hasOwnProperty("gifPlayback")&&(s.gifPlayback=A.gifPlayback,r.oneofs&&(s._gifPlayback="gifPlayback")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=A.height,r.oneofs&&(s._height="height")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=A.width,r.oneofs&&(s._width="width")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.interactiveAnnotations&&A.interactiveAnnotations.length){s.interactiveAnnotations=[];for(var g=0;g>>3){case 1:{s.messageAddOnType=e.int32();break}case 2:{s.messageAddOn=p.proto.Message.decode(e,e.uint32());break}case 3:{s.senderTimestampMs=e.int64();break}case 4:{s.serverTimestampMs=e.int64();break}case 5:{s.status=e.int32();break}case 6:{s.addOnContextInfo=p.proto.MessageAddOnContextInfo.decode(e,e.uint32());break}case 7:{s.messageAddOnKey=p.proto.MessageKey.decode(e,e.uint32());break}case 8:{s.legacyMessage=p.proto.LegacyMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageAddOn)return e;var a=new p.proto.MessageAddOn;switch(e.messageAddOnType){default:if(typeof e.messageAddOnType=="number"){a.messageAddOnType=e.messageAddOnType;break}break;case"UNDEFINED":case 0:a.messageAddOnType=0;break;case"REACTION":case 1:a.messageAddOnType=1;break;case"EVENT_RESPONSE":case 2:a.messageAddOnType=2;break;case"POLL_UPDATE":case 3:a.messageAddOnType=3;break;case"PIN_IN_CHAT":case 4:a.messageAddOnType=4;break}if(e.messageAddOn!=null){if(typeof e.messageAddOn!="object")throw TypeError(".proto.MessageAddOn.messageAddOn: object expected");a.messageAddOn=p.proto.Message.fromObject(e.messageAddOn)}switch(e.senderTimestampMs!=null&&(l.Long?(a.senderTimestampMs=l.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new l.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(l.Long?(a.serverTimestampMs=l.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new l.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),e.status){default:if(typeof e.status=="number"){a.status=e.status;break}break;case"ERROR":case 0:a.status=0;break;case"PENDING":case 1:a.status=1;break;case"SERVER_ACK":case 2:a.status=2;break;case"DELIVERY_ACK":case 3:a.status=3;break;case"READ":case 4:a.status=4;break;case"PLAYED":case 5:a.status=5;break}if(e.addOnContextInfo!=null){if(typeof e.addOnContextInfo!="object")throw TypeError(".proto.MessageAddOn.addOnContextInfo: object expected");a.addOnContextInfo=p.proto.MessageAddOnContextInfo.fromObject(e.addOnContextInfo)}if(e.messageAddOnKey!=null){if(typeof e.messageAddOnKey!="object")throw TypeError(".proto.MessageAddOn.messageAddOnKey: object expected");a.messageAddOnKey=p.proto.MessageKey.fromObject(e.messageAddOnKey)}if(e.legacyMessage!=null){if(typeof e.legacyMessage!="object")throw TypeError(".proto.MessageAddOn.legacyMessage: object expected");a.legacyMessage=p.proto.LegacyMessage.fromObject(e.legacyMessage)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.messageAddOnType!=null&&e.hasOwnProperty("messageAddOnType")&&(A.messageAddOnType=a.enums===String?p.proto.MessageAddOn.MessageAddOnType[e.messageAddOnType]===void 0?e.messageAddOnType:p.proto.MessageAddOn.MessageAddOnType[e.messageAddOnType]:e.messageAddOnType,a.oneofs&&(A._messageAddOnType="messageAddOnType")),e.messageAddOn!=null&&e.hasOwnProperty("messageAddOn")&&(A.messageAddOn=p.proto.Message.toObject(e.messageAddOn,a),a.oneofs&&(A._messageAddOn="messageAddOn")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?se(e.senderTimestampMs):a.longs===Number?ge(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?se(e.serverTimestampMs):a.longs===Number?ge(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),e.status!=null&&e.hasOwnProperty("status")&&(A.status=a.enums===String?p.proto.WebMessageInfo.Status[e.status]===void 0?e.status:p.proto.WebMessageInfo.Status[e.status]:e.status,a.oneofs&&(A._status="status")),e.addOnContextInfo!=null&&e.hasOwnProperty("addOnContextInfo")&&(A.addOnContextInfo=p.proto.MessageAddOnContextInfo.toObject(e.addOnContextInfo,a),a.oneofs&&(A._addOnContextInfo="addOnContextInfo")),e.messageAddOnKey!=null&&e.hasOwnProperty("messageAddOnKey")&&(A.messageAddOnKey=p.proto.MessageKey.toObject(e.messageAddOnKey,a),a.oneofs&&(A._messageAddOnKey="messageAddOnKey")),e.legacyMessage!=null&&e.hasOwnProperty("legacyMessage")&&(A.legacyMessage=p.proto.LegacyMessage.toObject(e.legacyMessage,a),a.oneofs&&(A._legacyMessage="legacyMessage")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageAddOn"},t.MessageAddOnType=(function(){let i={},e=Object.create(i);return e[i[0]="UNDEFINED"]=0,e[i[1]="REACTION"]=1,e[i[2]="EVENT_RESPONSE"]=2,e[i[3]="POLL_UPDATE"]=3,e[i[4]="PIN_IN_CHAT"]=4,e})(),t})(),n.MessageAddOnContextInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageAddOnDurationInSecs=e.uint32();break}case 2:{s.messageAddOnExpiryType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageAddOnContextInfo)return e;var a=new p.proto.MessageAddOnContextInfo;switch(e.messageAddOnDurationInSecs!=null&&(a.messageAddOnDurationInSecs=e.messageAddOnDurationInSecs>>>0),e.messageAddOnExpiryType){default:if(typeof e.messageAddOnExpiryType=="number"){a.messageAddOnExpiryType=e.messageAddOnExpiryType;break}break;case"STATIC":case 1:a.messageAddOnExpiryType=1;break;case"DEPENDENT_ON_PARENT":case 2:a.messageAddOnExpiryType=2;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.messageAddOnDurationInSecs!=null&&e.hasOwnProperty("messageAddOnDurationInSecs")&&(A.messageAddOnDurationInSecs=e.messageAddOnDurationInSecs,a.oneofs&&(A._messageAddOnDurationInSecs="messageAddOnDurationInSecs")),e.messageAddOnExpiryType!=null&&e.hasOwnProperty("messageAddOnExpiryType")&&(A.messageAddOnExpiryType=a.enums===String?p.proto.MessageContextInfo.MessageAddonExpiryType[e.messageAddOnExpiryType]===void 0?e.messageAddOnExpiryType:p.proto.MessageContextInfo.MessageAddonExpiryType[e.messageAddOnExpiryType]:e.messageAddOnExpiryType,a.oneofs&&(A._messageAddOnExpiryType="messageAddOnExpiryType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageAddOnContextInfo"},t})(),n.MessageAssociation=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.associationType=e.int32();break}case 2:{s.parentMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 3:{s.messageIndex=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageAssociation)return e;var a=new p.proto.MessageAssociation;switch(e.associationType){default:if(typeof e.associationType=="number"){a.associationType=e.associationType;break}break;case"UNKNOWN":case 0:a.associationType=0;break;case"MEDIA_ALBUM":case 1:a.associationType=1;break;case"BOT_PLUGIN":case 2:a.associationType=2;break;case"EVENT_COVER_IMAGE":case 3:a.associationType=3;break;case"STATUS_POLL":case 4:a.associationType=4;break;case"HD_VIDEO_DUAL_UPLOAD":case 5:a.associationType=5;break;case"STATUS_EXTERNAL_RESHARE":case 6:a.associationType=6;break;case"MEDIA_POLL":case 7:a.associationType=7;break;case"STATUS_ADD_YOURS":case 8:a.associationType=8;break;case"STATUS_NOTIFICATION":case 9:a.associationType=9;break;case"HD_IMAGE_DUAL_UPLOAD":case 10:a.associationType=10;break;case"STICKER_ANNOTATION":case 11:a.associationType=11;break;case"MOTION_PHOTO":case 12:a.associationType=12;break;case"STATUS_LINK_ACTION":case 13:a.associationType=13;break;case"VIEW_ALL_REPLIES":case 14:a.associationType=14;break;case"STATUS_ADD_YOURS_AI_IMAGINE":case 15:a.associationType=15;break;case"STATUS_QUESTION":case 16:a.associationType=16;break;case"STATUS_ADD_YOURS_DIWALI":case 17:a.associationType=17;break;case"STATUS_REACTION":case 18:a.associationType=18;break;case"HEVC_VIDEO_DUAL_UPLOAD":case 19:a.associationType=19;break}if(e.parentMessageKey!=null){if(typeof e.parentMessageKey!="object")throw TypeError(".proto.MessageAssociation.parentMessageKey: object expected");a.parentMessageKey=p.proto.MessageKey.fromObject(e.parentMessageKey)}return e.messageIndex!=null&&(a.messageIndex=e.messageIndex|0),a},t.toObject=function(e,a){a||(a={});var A={};return e.associationType!=null&&e.hasOwnProperty("associationType")&&(A.associationType=a.enums===String?p.proto.MessageAssociation.AssociationType[e.associationType]===void 0?e.associationType:p.proto.MessageAssociation.AssociationType[e.associationType]:e.associationType,a.oneofs&&(A._associationType="associationType")),e.parentMessageKey!=null&&e.hasOwnProperty("parentMessageKey")&&(A.parentMessageKey=p.proto.MessageKey.toObject(e.parentMessageKey,a),a.oneofs&&(A._parentMessageKey="parentMessageKey")),e.messageIndex!=null&&e.hasOwnProperty("messageIndex")&&(A.messageIndex=e.messageIndex,a.oneofs&&(A._messageIndex="messageIndex")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageAssociation"},t.AssociationType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="MEDIA_ALBUM"]=1,e[i[2]="BOT_PLUGIN"]=2,e[i[3]="EVENT_COVER_IMAGE"]=3,e[i[4]="STATUS_POLL"]=4,e[i[5]="HD_VIDEO_DUAL_UPLOAD"]=5,e[i[6]="STATUS_EXTERNAL_RESHARE"]=6,e[i[7]="MEDIA_POLL"]=7,e[i[8]="STATUS_ADD_YOURS"]=8,e[i[9]="STATUS_NOTIFICATION"]=9,e[i[10]="HD_IMAGE_DUAL_UPLOAD"]=10,e[i[11]="STICKER_ANNOTATION"]=11,e[i[12]="MOTION_PHOTO"]=12,e[i[13]="STATUS_LINK_ACTION"]=13,e[i[14]="VIEW_ALL_REPLIES"]=14,e[i[15]="STATUS_ADD_YOURS_AI_IMAGINE"]=15,e[i[16]="STATUS_QUESTION"]=16,e[i[17]="STATUS_ADD_YOURS_DIWALI"]=17,e[i[18]="STATUS_REACTION"]=18,e[i[19]="HEVC_VIDEO_DUAL_UPLOAD"]=19,e})(),t})(),n.MessageContextInfo=(function(){function t(i){if(this.threadId=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.deviceListMetadata=p.proto.DeviceListMetadata.decode(e,e.uint32());break}case 2:{s.deviceListMetadataVersion=e.int32();break}case 3:{s.messageSecret=e.bytes();break}case 4:{s.paddingBytes=e.bytes();break}case 5:{s.messageAddOnDurationInSecs=e.uint32();break}case 6:{s.botMessageSecret=e.bytes();break}case 7:{s.botMetadata=p.proto.BotMetadata.decode(e,e.uint32());break}case 8:{s.reportingTokenVersion=e.int32();break}case 9:{s.messageAddOnExpiryType=e.int32();break}case 10:{s.messageAssociation=p.proto.MessageAssociation.decode(e,e.uint32());break}case 11:{s.capiCreatedGroup=e.bool();break}case 12:{s.supportPayload=e.string();break}case 13:{s.limitSharing=p.proto.LimitSharing.decode(e,e.uint32());break}case 14:{s.limitSharingV2=p.proto.LimitSharing.decode(e,e.uint32());break}case 15:{s.threadId&&s.threadId.length||(s.threadId=[]),s.threadId.push(p.proto.ThreadID.decode(e,e.uint32()));break}case 16:{s.weblinkRenderConfig=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageContextInfo)return e;var a=new p.proto.MessageContextInfo;if(e.deviceListMetadata!=null){if(typeof e.deviceListMetadata!="object")throw TypeError(".proto.MessageContextInfo.deviceListMetadata: object expected");a.deviceListMetadata=p.proto.DeviceListMetadata.fromObject(e.deviceListMetadata)}if(e.deviceListMetadataVersion!=null&&(a.deviceListMetadataVersion=e.deviceListMetadataVersion|0),e.messageSecret!=null&&(typeof e.messageSecret=="string"?l.base64.decode(e.messageSecret,a.messageSecret=l.newBuffer(l.base64.length(e.messageSecret)),0):e.messageSecret.length>=0&&(a.messageSecret=e.messageSecret)),e.paddingBytes!=null&&(typeof e.paddingBytes=="string"?l.base64.decode(e.paddingBytes,a.paddingBytes=l.newBuffer(l.base64.length(e.paddingBytes)),0):e.paddingBytes.length>=0&&(a.paddingBytes=e.paddingBytes)),e.messageAddOnDurationInSecs!=null&&(a.messageAddOnDurationInSecs=e.messageAddOnDurationInSecs>>>0),e.botMessageSecret!=null&&(typeof e.botMessageSecret=="string"?l.base64.decode(e.botMessageSecret,a.botMessageSecret=l.newBuffer(l.base64.length(e.botMessageSecret)),0):e.botMessageSecret.length>=0&&(a.botMessageSecret=e.botMessageSecret)),e.botMetadata!=null){if(typeof e.botMetadata!="object")throw TypeError(".proto.MessageContextInfo.botMetadata: object expected");a.botMetadata=p.proto.BotMetadata.fromObject(e.botMetadata)}switch(e.reportingTokenVersion!=null&&(a.reportingTokenVersion=e.reportingTokenVersion|0),e.messageAddOnExpiryType){default:if(typeof e.messageAddOnExpiryType=="number"){a.messageAddOnExpiryType=e.messageAddOnExpiryType;break}break;case"STATIC":case 1:a.messageAddOnExpiryType=1;break;case"DEPENDENT_ON_PARENT":case 2:a.messageAddOnExpiryType=2;break}if(e.messageAssociation!=null){if(typeof e.messageAssociation!="object")throw TypeError(".proto.MessageContextInfo.messageAssociation: object expected");a.messageAssociation=p.proto.MessageAssociation.fromObject(e.messageAssociation)}if(e.capiCreatedGroup!=null&&(a.capiCreatedGroup=!!e.capiCreatedGroup),e.supportPayload!=null&&(a.supportPayload=String(e.supportPayload)),e.limitSharing!=null){if(typeof e.limitSharing!="object")throw TypeError(".proto.MessageContextInfo.limitSharing: object expected");a.limitSharing=p.proto.LimitSharing.fromObject(e.limitSharing)}if(e.limitSharingV2!=null){if(typeof e.limitSharingV2!="object")throw TypeError(".proto.MessageContextInfo.limitSharingV2: object expected");a.limitSharingV2=p.proto.LimitSharing.fromObject(e.limitSharingV2)}if(e.threadId){if(!Array.isArray(e.threadId))throw TypeError(".proto.MessageContextInfo.threadId: array expected");a.threadId=[];for(var A=0;A>>3){case 1:{s.remoteJid=e.string();break}case 2:{s.fromMe=e.bool();break}case 3:{s.id=e.string();break}case 4:{s.participant=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageKey)return e;var a=new p.proto.MessageKey;return e.remoteJid!=null&&(a.remoteJid=String(e.remoteJid)),e.fromMe!=null&&(a.fromMe=!!e.fromMe),e.id!=null&&(a.id=String(e.id)),e.participant!=null&&(a.participant=String(e.participant)),a},t.toObject=function(e,a){a||(a={});var A={};return e.remoteJid!=null&&e.hasOwnProperty("remoteJid")&&(A.remoteJid=e.remoteJid,a.oneofs&&(A._remoteJid="remoteJid")),e.fromMe!=null&&e.hasOwnProperty("fromMe")&&(A.fromMe=e.fromMe,a.oneofs&&(A._fromMe="fromMe")),e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.participant!=null&&e.hasOwnProperty("participant")&&(A.participant=e.participant,a.oneofs&&(A._participant="participant")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageKey"},t})(),n.MessageSecretMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.version=e.sfixed32();break}case 2:{s.encIv=e.bytes();break}case 3:{s.encPayload=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageSecretMessage)return e;var a=new p.proto.MessageSecretMessage;return e.version!=null&&(a.version=e.version|0),e.encIv!=null&&(typeof e.encIv=="string"?l.base64.decode(e.encIv,a.encIv=l.newBuffer(l.base64.length(e.encIv)),0):e.encIv.length>=0&&(a.encIv=e.encIv)),e.encPayload!=null&&(typeof e.encPayload=="string"?l.base64.decode(e.encPayload,a.encPayload=l.newBuffer(l.base64.length(e.encPayload)),0):e.encPayload.length>=0&&(a.encPayload=e.encPayload)),a},t.toObject=function(e,a){a||(a={});var A={};return e.version!=null&&e.hasOwnProperty("version")&&(A.version=e.version,a.oneofs&&(A._version="version")),e.encIv!=null&&e.hasOwnProperty("encIv")&&(A.encIv=a.bytes===String?l.base64.encode(e.encIv,0,e.encIv.length):a.bytes===Array?Array.prototype.slice.call(e.encIv):e.encIv,a.oneofs&&(A._encIv="encIv")),e.encPayload!=null&&e.hasOwnProperty("encPayload")&&(A.encPayload=a.bytes===String?l.base64.encode(e.encPayload,0,e.encPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encPayload):e.encPayload,a.oneofs&&(A._encPayload="encPayload")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageSecretMessage"},t})(),n.Money=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.value=e.int64();break}case 2:{s.offset=e.uint32();break}case 3:{s.currencyCode=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Money)return e;var a=new p.proto.Money;return e.value!=null&&(l.Long?(a.value=l.Long.fromValue(e.value)).unsigned=!1:typeof e.value=="string"?a.value=parseInt(e.value,10):typeof e.value=="number"?a.value=e.value:typeof e.value=="object"&&(a.value=new l.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber())),e.offset!=null&&(a.offset=e.offset>>>0),e.currencyCode!=null&&(a.currencyCode=String(e.currencyCode)),a},t.toObject=function(e,a){a||(a={});var A={};return e.value!=null&&e.hasOwnProperty("value")&&(typeof e.value=="number"?A.value=a.longs===String?String(e.value):e.value:A.value=a.longs===String?se(e.value):a.longs===Number?ge(e.value):e.value,a.oneofs&&(A._value="value")),e.offset!=null&&e.hasOwnProperty("offset")&&(A.offset=e.offset,a.oneofs&&(A._offset="offset")),e.currencyCode!=null&&e.hasOwnProperty("currencyCode")&&(A.currencyCode=e.currencyCode,a.oneofs&&(A._currencyCode="currencyCode")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Money"},t})(),n.MsgOpaqueData=(function(){function t(i){if(this.pollOptions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.body=e.string();break}case 3:{s.caption=e.string();break}case 5:{s.lng=e.double();break}case 6:{s.isLive=e.bool();break}case 7:{s.lat=e.double();break}case 8:{s.paymentAmount1000=e.int32();break}case 9:{s.paymentNoteMsgBody=e.string();break}case 11:{s.matchedText=e.string();break}case 12:{s.title=e.string();break}case 13:{s.description=e.string();break}case 14:{s.futureproofBuffer=e.bytes();break}case 15:{s.clientUrl=e.string();break}case 16:{s.loc=e.string();break}case 17:{s.pollName=e.string();break}case 18:{s.pollOptions&&s.pollOptions.length||(s.pollOptions=[]),s.pollOptions.push(p.proto.MsgOpaqueData.PollOption.decode(e,e.uint32()));break}case 20:{s.pollSelectableOptionsCount=e.uint32();break}case 21:{s.messageSecret=e.bytes();break}case 51:{s.originalSelfAuthor=e.string();break}case 22:{s.senderTimestampMs=e.int64();break}case 23:{s.pollUpdateParentKey=e.string();break}case 24:{s.encPollVote=p.proto.PollEncValue.decode(e,e.uint32());break}case 28:{s.isSentCagPollCreation=e.bool();break}case 42:{s.pollContentType=e.int32();break}case 46:{s.pollType=e.int32();break}case 47:{s.correctOptionIndex=e.int32();break}case 41:{s.pollVotesSnapshot=p.proto.MsgOpaqueData.PollVotesSnapshot.decode(e,e.uint32());break}case 25:{s.encReactionTargetMessageKey=e.string();break}case 26:{s.encReactionEncPayload=e.bytes();break}case 27:{s.encReactionEncIv=e.bytes();break}case 29:{s.botMessageSecret=e.bytes();break}case 30:{s.targetMessageKey=e.string();break}case 31:{s.encPayload=e.bytes();break}case 32:{s.encIv=e.bytes();break}case 33:{s.eventName=e.string();break}case 34:{s.isEventCanceled=e.bool();break}case 35:{s.eventDescription=e.string();break}case 36:{s.eventJoinLink=e.string();break}case 37:{s.eventStartTime=e.int64();break}case 38:{s.eventLocation=p.proto.MsgOpaqueData.EventLocation.decode(e,e.uint32());break}case 40:{s.eventEndTime=e.int64();break}case 44:{s.eventIsScheduledCall=e.bool();break}case 45:{s.eventExtraGuestsAllowed=e.bool();break}case 43:{s.plainProtobufBytes=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MsgOpaqueData)return e;var a=new p.proto.MsgOpaqueData;if(e.body!=null&&(a.body=String(e.body)),e.caption!=null&&(a.caption=String(e.caption)),e.lng!=null&&(a.lng=Number(e.lng)),e.isLive!=null&&(a.isLive=!!e.isLive),e.lat!=null&&(a.lat=Number(e.lat)),e.paymentAmount1000!=null&&(a.paymentAmount1000=e.paymentAmount1000|0),e.paymentNoteMsgBody!=null&&(a.paymentNoteMsgBody=String(e.paymentNoteMsgBody)),e.matchedText!=null&&(a.matchedText=String(e.matchedText)),e.title!=null&&(a.title=String(e.title)),e.description!=null&&(a.description=String(e.description)),e.futureproofBuffer!=null&&(typeof e.futureproofBuffer=="string"?l.base64.decode(e.futureproofBuffer,a.futureproofBuffer=l.newBuffer(l.base64.length(e.futureproofBuffer)),0):e.futureproofBuffer.length>=0&&(a.futureproofBuffer=e.futureproofBuffer)),e.clientUrl!=null&&(a.clientUrl=String(e.clientUrl)),e.loc!=null&&(a.loc=String(e.loc)),e.pollName!=null&&(a.pollName=String(e.pollName)),e.pollOptions){if(!Array.isArray(e.pollOptions))throw TypeError(".proto.MsgOpaqueData.pollOptions: array expected");a.pollOptions=[];for(var A=0;A>>0),e.messageSecret!=null&&(typeof e.messageSecret=="string"?l.base64.decode(e.messageSecret,a.messageSecret=l.newBuffer(l.base64.length(e.messageSecret)),0):e.messageSecret.length>=0&&(a.messageSecret=e.messageSecret)),e.originalSelfAuthor!=null&&(a.originalSelfAuthor=String(e.originalSelfAuthor)),e.senderTimestampMs!=null&&(l.Long?(a.senderTimestampMs=l.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new l.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.pollUpdateParentKey!=null&&(a.pollUpdateParentKey=String(e.pollUpdateParentKey)),e.encPollVote!=null){if(typeof e.encPollVote!="object")throw TypeError(".proto.MsgOpaqueData.encPollVote: object expected");a.encPollVote=p.proto.PollEncValue.fromObject(e.encPollVote)}switch(e.isSentCagPollCreation!=null&&(a.isSentCagPollCreation=!!e.isSentCagPollCreation),e.pollContentType){default:if(typeof e.pollContentType=="number"){a.pollContentType=e.pollContentType;break}break;case"UNKNOWN":case 0:a.pollContentType=0;break;case"TEXT":case 1:a.pollContentType=1;break;case"IMAGE":case 2:a.pollContentType=2;break}switch(e.pollType){default:if(typeof e.pollType=="number"){a.pollType=e.pollType;break}break;case"POLL":case 0:a.pollType=0;break;case"QUIZ":case 1:a.pollType=1;break}if(e.correctOptionIndex!=null&&(a.correctOptionIndex=e.correctOptionIndex|0),e.pollVotesSnapshot!=null){if(typeof e.pollVotesSnapshot!="object")throw TypeError(".proto.MsgOpaqueData.pollVotesSnapshot: object expected");a.pollVotesSnapshot=p.proto.MsgOpaqueData.PollVotesSnapshot.fromObject(e.pollVotesSnapshot)}if(e.encReactionTargetMessageKey!=null&&(a.encReactionTargetMessageKey=String(e.encReactionTargetMessageKey)),e.encReactionEncPayload!=null&&(typeof e.encReactionEncPayload=="string"?l.base64.decode(e.encReactionEncPayload,a.encReactionEncPayload=l.newBuffer(l.base64.length(e.encReactionEncPayload)),0):e.encReactionEncPayload.length>=0&&(a.encReactionEncPayload=e.encReactionEncPayload)),e.encReactionEncIv!=null&&(typeof e.encReactionEncIv=="string"?l.base64.decode(e.encReactionEncIv,a.encReactionEncIv=l.newBuffer(l.base64.length(e.encReactionEncIv)),0):e.encReactionEncIv.length>=0&&(a.encReactionEncIv=e.encReactionEncIv)),e.botMessageSecret!=null&&(typeof e.botMessageSecret=="string"?l.base64.decode(e.botMessageSecret,a.botMessageSecret=l.newBuffer(l.base64.length(e.botMessageSecret)),0):e.botMessageSecret.length>=0&&(a.botMessageSecret=e.botMessageSecret)),e.targetMessageKey!=null&&(a.targetMessageKey=String(e.targetMessageKey)),e.encPayload!=null&&(typeof e.encPayload=="string"?l.base64.decode(e.encPayload,a.encPayload=l.newBuffer(l.base64.length(e.encPayload)),0):e.encPayload.length>=0&&(a.encPayload=e.encPayload)),e.encIv!=null&&(typeof e.encIv=="string"?l.base64.decode(e.encIv,a.encIv=l.newBuffer(l.base64.length(e.encIv)),0):e.encIv.length>=0&&(a.encIv=e.encIv)),e.eventName!=null&&(a.eventName=String(e.eventName)),e.isEventCanceled!=null&&(a.isEventCanceled=!!e.isEventCanceled),e.eventDescription!=null&&(a.eventDescription=String(e.eventDescription)),e.eventJoinLink!=null&&(a.eventJoinLink=String(e.eventJoinLink)),e.eventStartTime!=null&&(l.Long?(a.eventStartTime=l.Long.fromValue(e.eventStartTime)).unsigned=!1:typeof e.eventStartTime=="string"?a.eventStartTime=parseInt(e.eventStartTime,10):typeof e.eventStartTime=="number"?a.eventStartTime=e.eventStartTime:typeof e.eventStartTime=="object"&&(a.eventStartTime=new l.LongBits(e.eventStartTime.low>>>0,e.eventStartTime.high>>>0).toNumber())),e.eventLocation!=null){if(typeof e.eventLocation!="object")throw TypeError(".proto.MsgOpaqueData.eventLocation: object expected");a.eventLocation=p.proto.MsgOpaqueData.EventLocation.fromObject(e.eventLocation)}return e.eventEndTime!=null&&(l.Long?(a.eventEndTime=l.Long.fromValue(e.eventEndTime)).unsigned=!1:typeof e.eventEndTime=="string"?a.eventEndTime=parseInt(e.eventEndTime,10):typeof e.eventEndTime=="number"?a.eventEndTime=e.eventEndTime:typeof e.eventEndTime=="object"&&(a.eventEndTime=new l.LongBits(e.eventEndTime.low>>>0,e.eventEndTime.high>>>0).toNumber())),e.eventIsScheduledCall!=null&&(a.eventIsScheduledCall=!!e.eventIsScheduledCall),e.eventExtraGuestsAllowed!=null&&(a.eventExtraGuestsAllowed=!!e.eventExtraGuestsAllowed),e.plainProtobufBytes!=null&&(typeof e.plainProtobufBytes=="string"?l.base64.decode(e.plainProtobufBytes,a.plainProtobufBytes=l.newBuffer(l.base64.length(e.plainProtobufBytes)),0):e.plainProtobufBytes.length>=0&&(a.plainProtobufBytes=e.plainProtobufBytes)),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.pollOptions=[]),e.body!=null&&e.hasOwnProperty("body")&&(A.body=e.body,a.oneofs&&(A._body="body")),e.caption!=null&&e.hasOwnProperty("caption")&&(A.caption=e.caption,a.oneofs&&(A._caption="caption")),e.lng!=null&&e.hasOwnProperty("lng")&&(A.lng=a.json&&!isFinite(e.lng)?String(e.lng):e.lng,a.oneofs&&(A._lng="lng")),e.isLive!=null&&e.hasOwnProperty("isLive")&&(A.isLive=e.isLive,a.oneofs&&(A._isLive="isLive")),e.lat!=null&&e.hasOwnProperty("lat")&&(A.lat=a.json&&!isFinite(e.lat)?String(e.lat):e.lat,a.oneofs&&(A._lat="lat")),e.paymentAmount1000!=null&&e.hasOwnProperty("paymentAmount1000")&&(A.paymentAmount1000=e.paymentAmount1000,a.oneofs&&(A._paymentAmount1000="paymentAmount1000")),e.paymentNoteMsgBody!=null&&e.hasOwnProperty("paymentNoteMsgBody")&&(A.paymentNoteMsgBody=e.paymentNoteMsgBody,a.oneofs&&(A._paymentNoteMsgBody="paymentNoteMsgBody")),e.matchedText!=null&&e.hasOwnProperty("matchedText")&&(A.matchedText=e.matchedText,a.oneofs&&(A._matchedText="matchedText")),e.title!=null&&e.hasOwnProperty("title")&&(A.title=e.title,a.oneofs&&(A._title="title")),e.description!=null&&e.hasOwnProperty("description")&&(A.description=e.description,a.oneofs&&(A._description="description")),e.futureproofBuffer!=null&&e.hasOwnProperty("futureproofBuffer")&&(A.futureproofBuffer=a.bytes===String?l.base64.encode(e.futureproofBuffer,0,e.futureproofBuffer.length):a.bytes===Array?Array.prototype.slice.call(e.futureproofBuffer):e.futureproofBuffer,a.oneofs&&(A._futureproofBuffer="futureproofBuffer")),e.clientUrl!=null&&e.hasOwnProperty("clientUrl")&&(A.clientUrl=e.clientUrl,a.oneofs&&(A._clientUrl="clientUrl")),e.loc!=null&&e.hasOwnProperty("loc")&&(A.loc=e.loc,a.oneofs&&(A._loc="loc")),e.pollName!=null&&e.hasOwnProperty("pollName")&&(A.pollName=e.pollName,a.oneofs&&(A._pollName="pollName")),e.pollOptions&&e.pollOptions.length){A.pollOptions=[];for(var r=0;r>>3){case 1:{c.degreesLatitude=A.double();break}case 2:{c.degreesLongitude=A.double();break}case 3:{c.name=A.string();break}case 4:{c.address=A.string();break}case 5:{c.url=A.string();break}case 6:{c.jpegThumbnail=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.MsgOpaqueData.EventLocation)return A;var r=new p.proto.MsgOpaqueData.EventLocation;return A.degreesLatitude!=null&&(r.degreesLatitude=Number(A.degreesLatitude)),A.degreesLongitude!=null&&(r.degreesLongitude=Number(A.degreesLongitude)),A.name!=null&&(r.name=String(A.name)),A.address!=null&&(r.address=String(A.address)),A.url!=null&&(r.url=String(A.url)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),r},i.toObject=function(A,r){r||(r={});var s={};return A.degreesLatitude!=null&&A.hasOwnProperty("degreesLatitude")&&(s.degreesLatitude=r.json&&!isFinite(A.degreesLatitude)?String(A.degreesLatitude):A.degreesLatitude,r.oneofs&&(s._degreesLatitude="degreesLatitude")),A.degreesLongitude!=null&&A.hasOwnProperty("degreesLongitude")&&(s.degreesLongitude=r.json&&!isFinite(A.degreesLongitude)?String(A.degreesLongitude):A.degreesLongitude,r.oneofs&&(s._degreesLongitude="degreesLongitude")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.address!=null&&A.hasOwnProperty("address")&&(s.address=A.address,r.oneofs&&(s._address="address")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.MsgOpaqueData.EventLocation"},i})(),t.PollContentType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="TEXT"]=1,e[i[2]="IMAGE"]=2,e})(),t.PollOption=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}case 2:{c.hash=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.MsgOpaqueData.PollOption)return A;var r=new p.proto.MsgOpaqueData.PollOption;return A.name!=null&&(r.name=String(A.name)),A.hash!=null&&(r.hash=String(A.hash)),r},i.toObject=function(A,r){r||(r={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.hash!=null&&A.hasOwnProperty("hash")&&(s.hash=A.hash,r.oneofs&&(s._hash="hash")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.MsgOpaqueData.PollOption"},i})(),t.PollType=(function(){let i={},e=Object.create(i);return e[i[0]="POLL"]=0,e[i[1]="QUIZ"]=1,e})(),t.PollVoteSnapshot=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.option=p.proto.MsgOpaqueData.PollOption.decode(A,A.uint32());break}case 2:{c.optionVoteCount=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.MsgOpaqueData.PollVoteSnapshot)return A;var r=new p.proto.MsgOpaqueData.PollVoteSnapshot;if(A.option!=null){if(typeof A.option!="object")throw TypeError(".proto.MsgOpaqueData.PollVoteSnapshot.option: object expected");r.option=p.proto.MsgOpaqueData.PollOption.fromObject(A.option)}return A.optionVoteCount!=null&&(r.optionVoteCount=A.optionVoteCount|0),r},i.toObject=function(A,r){r||(r={});var s={};return A.option!=null&&A.hasOwnProperty("option")&&(s.option=p.proto.MsgOpaqueData.PollOption.toObject(A.option,r),r.oneofs&&(s._option="option")),A.optionVoteCount!=null&&A.hasOwnProperty("optionVoteCount")&&(s.optionVoteCount=A.optionVoteCount,r.oneofs&&(s._optionVoteCount="optionVoteCount")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.MsgOpaqueData.PollVoteSnapshot"},i})(),t.PollVotesSnapshot=(function(){function i(e){if(this.pollVotes=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.pollVotes&&g.pollVotes.length||(g.pollVotes=[]),g.pollVotes.push(p.proto.MsgOpaqueData.PollVoteSnapshot.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.MsgOpaqueData.PollVotesSnapshot)return a;var A=new p.proto.MsgOpaqueData.PollVotesSnapshot;if(a.pollVotes){if(!Array.isArray(a.pollVotes))throw TypeError(".proto.MsgOpaqueData.PollVotesSnapshot.pollVotes: array expected");A.pollVotes=[];for(var r=0;r>>3){case 1:{s.currentMsg=p.proto.MsgOpaqueData.decode(e,e.uint32());break}case 2:{s.quotedMsg=p.proto.MsgOpaqueData.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MsgRowOpaqueData)return e;var a=new p.proto.MsgRowOpaqueData;if(e.currentMsg!=null){if(typeof e.currentMsg!="object")throw TypeError(".proto.MsgRowOpaqueData.currentMsg: object expected");a.currentMsg=p.proto.MsgOpaqueData.fromObject(e.currentMsg)}if(e.quotedMsg!=null){if(typeof e.quotedMsg!="object")throw TypeError(".proto.MsgRowOpaqueData.quotedMsg: object expected");a.quotedMsg=p.proto.MsgOpaqueData.fromObject(e.quotedMsg)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.currentMsg!=null&&e.hasOwnProperty("currentMsg")&&(A.currentMsg=p.proto.MsgOpaqueData.toObject(e.currentMsg,a),a.oneofs&&(A._currentMsg="currentMsg")),e.quotedMsg!=null&&e.hasOwnProperty("quotedMsg")&&(A.quotedMsg=p.proto.MsgOpaqueData.toObject(e.quotedMsg,a),a.oneofs&&(A._quotedMsg="quotedMsg")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MsgRowOpaqueData"},t})(),n.MutationProps=(function(){let t={},o=Object.create(t);return o[t[2]="STAR_ACTION"]=2,o[t[3]="CONTACT_ACTION"]=3,o[t[4]="MUTE_ACTION"]=4,o[t[5]="PIN_ACTION"]=5,o[t[6]="SECURITY_NOTIFICATION_SETTING"]=6,o[t[7]="PUSH_NAME_SETTING"]=7,o[t[8]="QUICK_REPLY_ACTION"]=8,o[t[11]="RECENT_EMOJI_WEIGHTS_ACTION"]=11,o[t[13]="LABEL_MESSAGE_ACTION"]=13,o[t[14]="LABEL_EDIT_ACTION"]=14,o[t[15]="LABEL_ASSOCIATION_ACTION"]=15,o[t[16]="LOCALE_SETTING"]=16,o[t[17]="ARCHIVE_CHAT_ACTION"]=17,o[t[18]="DELETE_MESSAGE_FOR_ME_ACTION"]=18,o[t[19]="KEY_EXPIRATION"]=19,o[t[20]="MARK_CHAT_AS_READ_ACTION"]=20,o[t[21]="CLEAR_CHAT_ACTION"]=21,o[t[22]="DELETE_CHAT_ACTION"]=22,o[t[23]="UNARCHIVE_CHATS_SETTING"]=23,o[t[24]="PRIMARY_FEATURE"]=24,o[t[26]="ANDROID_UNSUPPORTED_ACTIONS"]=26,o[t[27]="AGENT_ACTION"]=27,o[t[28]="SUBSCRIPTION_ACTION"]=28,o[t[29]="USER_STATUS_MUTE_ACTION"]=29,o[t[30]="TIME_FORMAT_ACTION"]=30,o[t[31]="NUX_ACTION"]=31,o[t[32]="PRIMARY_VERSION_ACTION"]=32,o[t[33]="STICKER_ACTION"]=33,o[t[34]="REMOVE_RECENT_STICKER_ACTION"]=34,o[t[35]="CHAT_ASSIGNMENT"]=35,o[t[36]="CHAT_ASSIGNMENT_OPENED_STATUS"]=36,o[t[37]="PN_FOR_LID_CHAT_ACTION"]=37,o[t[38]="MARKETING_MESSAGE_ACTION"]=38,o[t[39]="MARKETING_MESSAGE_BROADCAST_ACTION"]=39,o[t[40]="EXTERNAL_WEB_BETA_ACTION"]=40,o[t[41]="PRIVACY_SETTING_RELAY_ALL_CALLS"]=41,o[t[42]="CALL_LOG_ACTION"]=42,o[t[43]="UGC_BOT"]=43,o[t[44]="STATUS_PRIVACY"]=44,o[t[45]="BOT_WELCOME_REQUEST_ACTION"]=45,o[t[46]="DELETE_INDIVIDUAL_CALL_LOG"]=46,o[t[47]="LABEL_REORDERING_ACTION"]=47,o[t[48]="PAYMENT_INFO_ACTION"]=48,o[t[49]="CUSTOM_PAYMENT_METHODS_ACTION"]=49,o[t[50]="LOCK_CHAT_ACTION"]=50,o[t[51]="CHAT_LOCK_SETTINGS"]=51,o[t[52]="WAMO_USER_IDENTIFIER_ACTION"]=52,o[t[53]="PRIVACY_SETTING_DISABLE_LINK_PREVIEWS_ACTION"]=53,o[t[54]="DEVICE_CAPABILITIES"]=54,o[t[55]="NOTE_EDIT_ACTION"]=55,o[t[56]="FAVORITES_ACTION"]=56,o[t[57]="MERCHANT_PAYMENT_PARTNER_ACTION"]=57,o[t[58]="WAFFLE_ACCOUNT_LINK_STATE_ACTION"]=58,o[t[59]="USERNAME_CHAT_START_MODE"]=59,o[t[60]="NOTIFICATION_ACTIVITY_SETTING_ACTION"]=60,o[t[61]="LID_CONTACT_ACTION"]=61,o[t[62]="CTWA_PER_CUSTOMER_DATA_SHARING_ACTION"]=62,o[t[63]="PAYMENT_TOS_ACTION"]=63,o[t[64]="PRIVACY_SETTING_CHANNELS_PERSONALISED_RECOMMENDATION_ACTION"]=64,o[t[65]="BUSINESS_BROADCAST_ASSOCIATION_ACTION"]=65,o[t[66]="DETECTED_OUTCOMES_STATUS_ACTION"]=66,o[t[68]="MAIBA_AI_FEATURES_CONTROL_ACTION"]=68,o[t[69]="BUSINESS_BROADCAST_LIST_ACTION"]=69,o[t[70]="MUSIC_USER_ID_ACTION"]=70,o[t[71]="STATUS_POST_OPT_IN_NOTIFICATION_PREFERENCES_ACTION"]=71,o[t[72]="AVATAR_UPDATED_ACTION"]=72,o[t[73]="GALAXY_FLOW_ACTION"]=73,o[t[74]="PRIVATE_PROCESSING_SETTING_ACTION"]=74,o[t[75]="NEWSLETTER_SAVED_INTERESTS_ACTION"]=75,o[t[76]="AI_THREAD_RENAME_ACTION"]=76,o[t[77]="INTERACTIVE_MESSAGE_ACTION"]=77,o[t[10001]="SHARE_OWN_PN"]=10001,o[t[10002]="BUSINESS_BROADCAST_ACTION"]=10002,o})(),n.NoiseCertificate=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.details=e.bytes();break}case 2:{s.signature=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.NoiseCertificate)return e;var a=new p.proto.NoiseCertificate;return e.details!=null&&(typeof e.details=="string"?l.base64.decode(e.details,a.details=l.newBuffer(l.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.signature!=null&&(typeof e.signature=="string"?l.base64.decode(e.signature,a.signature=l.newBuffer(l.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),a},t.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?l.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?l.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.NoiseCertificate"},t.Details=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.serial=A.uint32();break}case 2:{c.issuer=A.string();break}case 3:{c.expires=A.uint64();break}case 4:{c.subject=A.string();break}case 5:{c.key=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.NoiseCertificate.Details)return A;var r=new p.proto.NoiseCertificate.Details;return A.serial!=null&&(r.serial=A.serial>>>0),A.issuer!=null&&(r.issuer=String(A.issuer)),A.expires!=null&&(l.Long?(r.expires=l.Long.fromValue(A.expires)).unsigned=!0:typeof A.expires=="string"?r.expires=parseInt(A.expires,10):typeof A.expires=="number"?r.expires=A.expires:typeof A.expires=="object"&&(r.expires=new l.LongBits(A.expires.low>>>0,A.expires.high>>>0).toNumber(!0))),A.subject!=null&&(r.subject=String(A.subject)),A.key!=null&&(typeof A.key=="string"?l.base64.decode(A.key,r.key=l.newBuffer(l.base64.length(A.key)),0):A.key.length>=0&&(r.key=A.key)),r},i.toObject=function(A,r){r||(r={});var s={};return A.serial!=null&&A.hasOwnProperty("serial")&&(s.serial=A.serial,r.oneofs&&(s._serial="serial")),A.issuer!=null&&A.hasOwnProperty("issuer")&&(s.issuer=A.issuer,r.oneofs&&(s._issuer="issuer")),A.expires!=null&&A.hasOwnProperty("expires")&&(typeof A.expires=="number"?s.expires=r.longs===String?String(A.expires):A.expires:s.expires=r.longs===String?se(A.expires,!0):r.longs===Number?ge(A.expires,!0):A.expires,r.oneofs&&(s._expires="expires")),A.subject!=null&&A.hasOwnProperty("subject")&&(s.subject=A.subject,r.oneofs&&(s._subject="subject")),A.key!=null&&A.hasOwnProperty("key")&&(s.key=r.bytes===String?l.base64.encode(A.key,0,A.key.length):r.bytes===Array?Array.prototype.slice.call(A.key):A.key,r.oneofs&&(s._key="key")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.NoiseCertificate.Details"},i})(),t})(),n.NotificationMessageInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.key=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.message=p.proto.Message.decode(e,e.uint32());break}case 3:{s.messageTimestamp=e.uint64();break}case 4:{s.participant=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.NotificationMessageInfo)return e;var a=new p.proto.NotificationMessageInfo;if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.NotificationMessageInfo.key: object expected");a.key=p.proto.MessageKey.fromObject(e.key)}if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.NotificationMessageInfo.message: object expected");a.message=p.proto.Message.fromObject(e.message)}return e.messageTimestamp!=null&&(l.Long?(a.messageTimestamp=l.Long.fromValue(e.messageTimestamp)).unsigned=!0:typeof e.messageTimestamp=="string"?a.messageTimestamp=parseInt(e.messageTimestamp,10):typeof e.messageTimestamp=="number"?a.messageTimestamp=e.messageTimestamp:typeof e.messageTimestamp=="object"&&(a.messageTimestamp=new l.LongBits(e.messageTimestamp.low>>>0,e.messageTimestamp.high>>>0).toNumber(!0))),e.participant!=null&&(a.participant=String(e.participant)),a},t.toObject=function(e,a){a||(a={});var A={};return e.key!=null&&e.hasOwnProperty("key")&&(A.key=p.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=p.proto.Message.toObject(e.message,a),a.oneofs&&(A._message="message")),e.messageTimestamp!=null&&e.hasOwnProperty("messageTimestamp")&&(typeof e.messageTimestamp=="number"?A.messageTimestamp=a.longs===String?String(e.messageTimestamp):e.messageTimestamp:A.messageTimestamp=a.longs===String?se(e.messageTimestamp,!0):a.longs===Number?ge(e.messageTimestamp,!0):e.messageTimestamp,a.oneofs&&(A._messageTimestamp="messageTimestamp")),e.participant!=null&&e.hasOwnProperty("participant")&&(A.participant=e.participant,a.oneofs&&(A._participant="participant")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.NotificationMessageInfo"},t})(),n.NotificationSettings=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageVibrate=e.string();break}case 2:{s.messagePopup=e.string();break}case 3:{s.messageLight=e.string();break}case 4:{s.lowPriorityNotifications=e.bool();break}case 5:{s.reactionsMuted=e.bool();break}case 6:{s.callVibrate=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.NotificationSettings)return e;var a=new p.proto.NotificationSettings;return e.messageVibrate!=null&&(a.messageVibrate=String(e.messageVibrate)),e.messagePopup!=null&&(a.messagePopup=String(e.messagePopup)),e.messageLight!=null&&(a.messageLight=String(e.messageLight)),e.lowPriorityNotifications!=null&&(a.lowPriorityNotifications=!!e.lowPriorityNotifications),e.reactionsMuted!=null&&(a.reactionsMuted=!!e.reactionsMuted),e.callVibrate!=null&&(a.callVibrate=String(e.callVibrate)),a},t.toObject=function(e,a){a||(a={});var A={};return e.messageVibrate!=null&&e.hasOwnProperty("messageVibrate")&&(A.messageVibrate=e.messageVibrate,a.oneofs&&(A._messageVibrate="messageVibrate")),e.messagePopup!=null&&e.hasOwnProperty("messagePopup")&&(A.messagePopup=e.messagePopup,a.oneofs&&(A._messagePopup="messagePopup")),e.messageLight!=null&&e.hasOwnProperty("messageLight")&&(A.messageLight=e.messageLight,a.oneofs&&(A._messageLight="messageLight")),e.lowPriorityNotifications!=null&&e.hasOwnProperty("lowPriorityNotifications")&&(A.lowPriorityNotifications=e.lowPriorityNotifications,a.oneofs&&(A._lowPriorityNotifications="lowPriorityNotifications")),e.reactionsMuted!=null&&e.hasOwnProperty("reactionsMuted")&&(A.reactionsMuted=e.reactionsMuted,a.oneofs&&(A._reactionsMuted="reactionsMuted")),e.callVibrate!=null&&e.hasOwnProperty("callVibrate")&&(A.callVibrate=e.callVibrate,a.oneofs&&(A._callVibrate="callVibrate")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.NotificationSettings"},t})(),n.PairingRequest=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.companionPublicKey=e.bytes();break}case 2:{s.companionIdentityKey=e.bytes();break}case 3:{s.advSecret=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PairingRequest)return e;var a=new p.proto.PairingRequest;return e.companionPublicKey!=null&&(typeof e.companionPublicKey=="string"?l.base64.decode(e.companionPublicKey,a.companionPublicKey=l.newBuffer(l.base64.length(e.companionPublicKey)),0):e.companionPublicKey.length>=0&&(a.companionPublicKey=e.companionPublicKey)),e.companionIdentityKey!=null&&(typeof e.companionIdentityKey=="string"?l.base64.decode(e.companionIdentityKey,a.companionIdentityKey=l.newBuffer(l.base64.length(e.companionIdentityKey)),0):e.companionIdentityKey.length>=0&&(a.companionIdentityKey=e.companionIdentityKey)),e.advSecret!=null&&(typeof e.advSecret=="string"?l.base64.decode(e.advSecret,a.advSecret=l.newBuffer(l.base64.length(e.advSecret)),0):e.advSecret.length>=0&&(a.advSecret=e.advSecret)),a},t.toObject=function(e,a){a||(a={});var A={};return e.companionPublicKey!=null&&e.hasOwnProperty("companionPublicKey")&&(A.companionPublicKey=a.bytes===String?l.base64.encode(e.companionPublicKey,0,e.companionPublicKey.length):a.bytes===Array?Array.prototype.slice.call(e.companionPublicKey):e.companionPublicKey,a.oneofs&&(A._companionPublicKey="companionPublicKey")),e.companionIdentityKey!=null&&e.hasOwnProperty("companionIdentityKey")&&(A.companionIdentityKey=a.bytes===String?l.base64.encode(e.companionIdentityKey,0,e.companionIdentityKey.length):a.bytes===Array?Array.prototype.slice.call(e.companionIdentityKey):e.companionIdentityKey,a.oneofs&&(A._companionIdentityKey="companionIdentityKey")),e.advSecret!=null&&e.hasOwnProperty("advSecret")&&(A.advSecret=a.bytes===String?l.base64.encode(e.advSecret,0,e.advSecret.length):a.bytes===Array?Array.prototype.slice.call(e.advSecret):e.advSecret,a.oneofs&&(A._advSecret="advSecret")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PairingRequest"},t})(),n.PastParticipant=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.userJid=e.string();break}case 2:{s.leaveReason=e.int32();break}case 3:{s.leaveTs=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PastParticipant)return e;var a=new p.proto.PastParticipant;switch(e.userJid!=null&&(a.userJid=String(e.userJid)),e.leaveReason){default:if(typeof e.leaveReason=="number"){a.leaveReason=e.leaveReason;break}break;case"LEFT":case 0:a.leaveReason=0;break;case"REMOVED":case 1:a.leaveReason=1;break}return e.leaveTs!=null&&(l.Long?(a.leaveTs=l.Long.fromValue(e.leaveTs)).unsigned=!0:typeof e.leaveTs=="string"?a.leaveTs=parseInt(e.leaveTs,10):typeof e.leaveTs=="number"?a.leaveTs=e.leaveTs:typeof e.leaveTs=="object"&&(a.leaveTs=new l.LongBits(e.leaveTs.low>>>0,e.leaveTs.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};return e.userJid!=null&&e.hasOwnProperty("userJid")&&(A.userJid=e.userJid,a.oneofs&&(A._userJid="userJid")),e.leaveReason!=null&&e.hasOwnProperty("leaveReason")&&(A.leaveReason=a.enums===String?p.proto.PastParticipant.LeaveReason[e.leaveReason]===void 0?e.leaveReason:p.proto.PastParticipant.LeaveReason[e.leaveReason]:e.leaveReason,a.oneofs&&(A._leaveReason="leaveReason")),e.leaveTs!=null&&e.hasOwnProperty("leaveTs")&&(typeof e.leaveTs=="number"?A.leaveTs=a.longs===String?String(e.leaveTs):e.leaveTs:A.leaveTs=a.longs===String?se(e.leaveTs,!0):a.longs===Number?ge(e.leaveTs,!0):e.leaveTs,a.oneofs&&(A._leaveTs="leaveTs")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PastParticipant"},t.LeaveReason=(function(){let i={},e=Object.create(i);return e[i[0]="LEFT"]=0,e[i[1]="REMOVED"]=1,e})(),t})(),n.PastParticipants=(function(){function t(i){if(this.pastParticipants=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.groupJid=e.string();break}case 2:{s.pastParticipants&&s.pastParticipants.length||(s.pastParticipants=[]),s.pastParticipants.push(p.proto.PastParticipant.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PastParticipants)return e;var a=new p.proto.PastParticipants;if(e.groupJid!=null&&(a.groupJid=String(e.groupJid)),e.pastParticipants){if(!Array.isArray(e.pastParticipants))throw TypeError(".proto.PastParticipants.pastParticipants: array expected");a.pastParticipants=[];for(var A=0;A>>3){case 1:{s.currentLthash=e.bytes();break}case 2:{s.newLthash=e.bytes();break}case 3:{s.patchVersion=e.bytes();break}case 4:{s.collectionName=e.bytes();break}case 5:{s.firstFourBytesFromAHashOfSnapshotMacKey=e.bytes();break}case 6:{s.newLthashSubtract=e.bytes();break}case 7:{s.numberAdd=e.int32();break}case 8:{s.numberRemove=e.int32();break}case 9:{s.numberOverride=e.int32();break}case 10:{s.senderPlatform=e.int32();break}case 11:{s.isSenderPrimary=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PatchDebugData)return e;var a=new p.proto.PatchDebugData;switch(e.currentLthash!=null&&(typeof e.currentLthash=="string"?l.base64.decode(e.currentLthash,a.currentLthash=l.newBuffer(l.base64.length(e.currentLthash)),0):e.currentLthash.length>=0&&(a.currentLthash=e.currentLthash)),e.newLthash!=null&&(typeof e.newLthash=="string"?l.base64.decode(e.newLthash,a.newLthash=l.newBuffer(l.base64.length(e.newLthash)),0):e.newLthash.length>=0&&(a.newLthash=e.newLthash)),e.patchVersion!=null&&(typeof e.patchVersion=="string"?l.base64.decode(e.patchVersion,a.patchVersion=l.newBuffer(l.base64.length(e.patchVersion)),0):e.patchVersion.length>=0&&(a.patchVersion=e.patchVersion)),e.collectionName!=null&&(typeof e.collectionName=="string"?l.base64.decode(e.collectionName,a.collectionName=l.newBuffer(l.base64.length(e.collectionName)),0):e.collectionName.length>=0&&(a.collectionName=e.collectionName)),e.firstFourBytesFromAHashOfSnapshotMacKey!=null&&(typeof e.firstFourBytesFromAHashOfSnapshotMacKey=="string"?l.base64.decode(e.firstFourBytesFromAHashOfSnapshotMacKey,a.firstFourBytesFromAHashOfSnapshotMacKey=l.newBuffer(l.base64.length(e.firstFourBytesFromAHashOfSnapshotMacKey)),0):e.firstFourBytesFromAHashOfSnapshotMacKey.length>=0&&(a.firstFourBytesFromAHashOfSnapshotMacKey=e.firstFourBytesFromAHashOfSnapshotMacKey)),e.newLthashSubtract!=null&&(typeof e.newLthashSubtract=="string"?l.base64.decode(e.newLthashSubtract,a.newLthashSubtract=l.newBuffer(l.base64.length(e.newLthashSubtract)),0):e.newLthashSubtract.length>=0&&(a.newLthashSubtract=e.newLthashSubtract)),e.numberAdd!=null&&(a.numberAdd=e.numberAdd|0),e.numberRemove!=null&&(a.numberRemove=e.numberRemove|0),e.numberOverride!=null&&(a.numberOverride=e.numberOverride|0),e.senderPlatform){default:if(typeof e.senderPlatform=="number"){a.senderPlatform=e.senderPlatform;break}break;case"ANDROID":case 0:a.senderPlatform=0;break;case"SMBA":case 1:a.senderPlatform=1;break;case"IPHONE":case 2:a.senderPlatform=2;break;case"SMBI":case 3:a.senderPlatform=3;break;case"WEB":case 4:a.senderPlatform=4;break;case"UWP":case 5:a.senderPlatform=5;break;case"DARWIN":case 6:a.senderPlatform=6;break;case"IPAD":case 7:a.senderPlatform=7;break;case"WEAROS":case 8:a.senderPlatform=8;break;case"WASG":case 9:a.senderPlatform=9;break;case"WEARM":case 10:a.senderPlatform=10;break;case"CAPI":case 11:a.senderPlatform=11;break}return e.isSenderPrimary!=null&&(a.isSenderPrimary=!!e.isSenderPrimary),a},t.toObject=function(e,a){a||(a={});var A={};return e.currentLthash!=null&&e.hasOwnProperty("currentLthash")&&(A.currentLthash=a.bytes===String?l.base64.encode(e.currentLthash,0,e.currentLthash.length):a.bytes===Array?Array.prototype.slice.call(e.currentLthash):e.currentLthash,a.oneofs&&(A._currentLthash="currentLthash")),e.newLthash!=null&&e.hasOwnProperty("newLthash")&&(A.newLthash=a.bytes===String?l.base64.encode(e.newLthash,0,e.newLthash.length):a.bytes===Array?Array.prototype.slice.call(e.newLthash):e.newLthash,a.oneofs&&(A._newLthash="newLthash")),e.patchVersion!=null&&e.hasOwnProperty("patchVersion")&&(A.patchVersion=a.bytes===String?l.base64.encode(e.patchVersion,0,e.patchVersion.length):a.bytes===Array?Array.prototype.slice.call(e.patchVersion):e.patchVersion,a.oneofs&&(A._patchVersion="patchVersion")),e.collectionName!=null&&e.hasOwnProperty("collectionName")&&(A.collectionName=a.bytes===String?l.base64.encode(e.collectionName,0,e.collectionName.length):a.bytes===Array?Array.prototype.slice.call(e.collectionName):e.collectionName,a.oneofs&&(A._collectionName="collectionName")),e.firstFourBytesFromAHashOfSnapshotMacKey!=null&&e.hasOwnProperty("firstFourBytesFromAHashOfSnapshotMacKey")&&(A.firstFourBytesFromAHashOfSnapshotMacKey=a.bytes===String?l.base64.encode(e.firstFourBytesFromAHashOfSnapshotMacKey,0,e.firstFourBytesFromAHashOfSnapshotMacKey.length):a.bytes===Array?Array.prototype.slice.call(e.firstFourBytesFromAHashOfSnapshotMacKey):e.firstFourBytesFromAHashOfSnapshotMacKey,a.oneofs&&(A._firstFourBytesFromAHashOfSnapshotMacKey="firstFourBytesFromAHashOfSnapshotMacKey")),e.newLthashSubtract!=null&&e.hasOwnProperty("newLthashSubtract")&&(A.newLthashSubtract=a.bytes===String?l.base64.encode(e.newLthashSubtract,0,e.newLthashSubtract.length):a.bytes===Array?Array.prototype.slice.call(e.newLthashSubtract):e.newLthashSubtract,a.oneofs&&(A._newLthashSubtract="newLthashSubtract")),e.numberAdd!=null&&e.hasOwnProperty("numberAdd")&&(A.numberAdd=e.numberAdd,a.oneofs&&(A._numberAdd="numberAdd")),e.numberRemove!=null&&e.hasOwnProperty("numberRemove")&&(A.numberRemove=e.numberRemove,a.oneofs&&(A._numberRemove="numberRemove")),e.numberOverride!=null&&e.hasOwnProperty("numberOverride")&&(A.numberOverride=e.numberOverride,a.oneofs&&(A._numberOverride="numberOverride")),e.senderPlatform!=null&&e.hasOwnProperty("senderPlatform")&&(A.senderPlatform=a.enums===String?p.proto.PatchDebugData.Platform[e.senderPlatform]===void 0?e.senderPlatform:p.proto.PatchDebugData.Platform[e.senderPlatform]:e.senderPlatform,a.oneofs&&(A._senderPlatform="senderPlatform")),e.isSenderPrimary!=null&&e.hasOwnProperty("isSenderPrimary")&&(A.isSenderPrimary=e.isSenderPrimary,a.oneofs&&(A._isSenderPrimary="isSenderPrimary")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PatchDebugData"},t.Platform=(function(){let i={},e=Object.create(i);return e[i[0]="ANDROID"]=0,e[i[1]="SMBA"]=1,e[i[2]="IPHONE"]=2,e[i[3]="SMBI"]=3,e[i[4]="WEB"]=4,e[i[5]="UWP"]=5,e[i[6]="DARWIN"]=6,e[i[7]="IPAD"]=7,e[i[8]="WEAROS"]=8,e[i[9]="WASG"]=9,e[i[10]="WEARM"]=10,e[i[11]="CAPI"]=11,e})(),t})(),n.PaymentBackground=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.string();break}case 2:{s.fileLength=e.uint64();break}case 3:{s.width=e.uint32();break}case 4:{s.height=e.uint32();break}case 5:{s.mimetype=e.string();break}case 6:{s.placeholderArgb=e.fixed32();break}case 7:{s.textArgb=e.fixed32();break}case 8:{s.subtextArgb=e.fixed32();break}case 9:{s.mediaData=p.proto.PaymentBackground.MediaData.decode(e,e.uint32());break}case 10:{s.type=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PaymentBackground)return e;var a=new p.proto.PaymentBackground;if(e.id!=null&&(a.id=String(e.id)),e.fileLength!=null&&(l.Long?(a.fileLength=l.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new l.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),e.width!=null&&(a.width=e.width>>>0),e.height!=null&&(a.height=e.height>>>0),e.mimetype!=null&&(a.mimetype=String(e.mimetype)),e.placeholderArgb!=null&&(a.placeholderArgb=e.placeholderArgb>>>0),e.textArgb!=null&&(a.textArgb=e.textArgb>>>0),e.subtextArgb!=null&&(a.subtextArgb=e.subtextArgb>>>0),e.mediaData!=null){if(typeof e.mediaData!="object")throw TypeError(".proto.PaymentBackground.mediaData: object expected");a.mediaData=p.proto.PaymentBackground.MediaData.fromObject(e.mediaData)}switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"UNKNOWN":case 0:a.type=0;break;case"DEFAULT":case 1:a.type=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.fileLength!=null&&e.hasOwnProperty("fileLength")&&(typeof e.fileLength=="number"?A.fileLength=a.longs===String?String(e.fileLength):e.fileLength:A.fileLength=a.longs===String?se(e.fileLength,!0):a.longs===Number?ge(e.fileLength,!0):e.fileLength,a.oneofs&&(A._fileLength="fileLength")),e.width!=null&&e.hasOwnProperty("width")&&(A.width=e.width,a.oneofs&&(A._width="width")),e.height!=null&&e.hasOwnProperty("height")&&(A.height=e.height,a.oneofs&&(A._height="height")),e.mimetype!=null&&e.hasOwnProperty("mimetype")&&(A.mimetype=e.mimetype,a.oneofs&&(A._mimetype="mimetype")),e.placeholderArgb!=null&&e.hasOwnProperty("placeholderArgb")&&(A.placeholderArgb=e.placeholderArgb,a.oneofs&&(A._placeholderArgb="placeholderArgb")),e.textArgb!=null&&e.hasOwnProperty("textArgb")&&(A.textArgb=e.textArgb,a.oneofs&&(A._textArgb="textArgb")),e.subtextArgb!=null&&e.hasOwnProperty("subtextArgb")&&(A.subtextArgb=e.subtextArgb,a.oneofs&&(A._subtextArgb="subtextArgb")),e.mediaData!=null&&e.hasOwnProperty("mediaData")&&(A.mediaData=p.proto.PaymentBackground.MediaData.toObject(e.mediaData,a),a.oneofs&&(A._mediaData="mediaData")),e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.PaymentBackground.Type[e.type]===void 0?e.type:p.proto.PaymentBackground.Type[e.type]:e.type,a.oneofs&&(A._type="type")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PaymentBackground"},t.MediaData=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.mediaKey=A.bytes();break}case 2:{c.mediaKeyTimestamp=A.int64();break}case 3:{c.fileSha256=A.bytes();break}case 4:{c.fileEncSha256=A.bytes();break}case 5:{c.directPath=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.PaymentBackground.MediaData)return A;var r=new p.proto.PaymentBackground.MediaData;return A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(r.directPath=String(A.directPath)),r},i.toObject=function(A,r){r||(r={});var s={};return A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.PaymentBackground.MediaData"},i})(),t.Type=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="DEFAULT"]=1,e})(),t})(),n.PaymentInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.currencyDeprecated=e.int32();break}case 2:{s.amount1000=e.uint64();break}case 3:{s.receiverJid=e.string();break}case 4:{s.status=e.int32();break}case 5:{s.transactionTimestamp=e.uint64();break}case 6:{s.requestMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 7:{s.expiryTimestamp=e.uint64();break}case 8:{s.futureproofed=e.bool();break}case 9:{s.currency=e.string();break}case 10:{s.txnStatus=e.int32();break}case 11:{s.useNoviFiatFormat=e.bool();break}case 12:{s.primaryAmount=p.proto.Money.decode(e,e.uint32());break}case 13:{s.exchangeAmount=p.proto.Money.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PaymentInfo)return e;var a=new p.proto.PaymentInfo;switch(e.currencyDeprecated){default:if(typeof e.currencyDeprecated=="number"){a.currencyDeprecated=e.currencyDeprecated;break}break;case"UNKNOWN_CURRENCY":case 0:a.currencyDeprecated=0;break;case"INR":case 1:a.currencyDeprecated=1;break}switch(e.amount1000!=null&&(l.Long?(a.amount1000=l.Long.fromValue(e.amount1000)).unsigned=!0:typeof e.amount1000=="string"?a.amount1000=parseInt(e.amount1000,10):typeof e.amount1000=="number"?a.amount1000=e.amount1000:typeof e.amount1000=="object"&&(a.amount1000=new l.LongBits(e.amount1000.low>>>0,e.amount1000.high>>>0).toNumber(!0))),e.receiverJid!=null&&(a.receiverJid=String(e.receiverJid)),e.status){default:if(typeof e.status=="number"){a.status=e.status;break}break;case"UNKNOWN_STATUS":case 0:a.status=0;break;case"PROCESSING":case 1:a.status=1;break;case"SENT":case 2:a.status=2;break;case"NEED_TO_ACCEPT":case 3:a.status=3;break;case"COMPLETE":case 4:a.status=4;break;case"COULD_NOT_COMPLETE":case 5:a.status=5;break;case"REFUNDED":case 6:a.status=6;break;case"EXPIRED":case 7:a.status=7;break;case"REJECTED":case 8:a.status=8;break;case"CANCELLED":case 9:a.status=9;break;case"WAITING_FOR_PAYER":case 10:a.status=10;break;case"WAITING":case 11:a.status=11;break}if(e.transactionTimestamp!=null&&(l.Long?(a.transactionTimestamp=l.Long.fromValue(e.transactionTimestamp)).unsigned=!0:typeof e.transactionTimestamp=="string"?a.transactionTimestamp=parseInt(e.transactionTimestamp,10):typeof e.transactionTimestamp=="number"?a.transactionTimestamp=e.transactionTimestamp:typeof e.transactionTimestamp=="object"&&(a.transactionTimestamp=new l.LongBits(e.transactionTimestamp.low>>>0,e.transactionTimestamp.high>>>0).toNumber(!0))),e.requestMessageKey!=null){if(typeof e.requestMessageKey!="object")throw TypeError(".proto.PaymentInfo.requestMessageKey: object expected");a.requestMessageKey=p.proto.MessageKey.fromObject(e.requestMessageKey)}switch(e.expiryTimestamp!=null&&(l.Long?(a.expiryTimestamp=l.Long.fromValue(e.expiryTimestamp)).unsigned=!0:typeof e.expiryTimestamp=="string"?a.expiryTimestamp=parseInt(e.expiryTimestamp,10):typeof e.expiryTimestamp=="number"?a.expiryTimestamp=e.expiryTimestamp:typeof e.expiryTimestamp=="object"&&(a.expiryTimestamp=new l.LongBits(e.expiryTimestamp.low>>>0,e.expiryTimestamp.high>>>0).toNumber(!0))),e.futureproofed!=null&&(a.futureproofed=!!e.futureproofed),e.currency!=null&&(a.currency=String(e.currency)),e.txnStatus){default:if(typeof e.txnStatus=="number"){a.txnStatus=e.txnStatus;break}break;case"UNKNOWN":case 0:a.txnStatus=0;break;case"PENDING_SETUP":case 1:a.txnStatus=1;break;case"PENDING_RECEIVER_SETUP":case 2:a.txnStatus=2;break;case"INIT":case 3:a.txnStatus=3;break;case"SUCCESS":case 4:a.txnStatus=4;break;case"COMPLETED":case 5:a.txnStatus=5;break;case"FAILED":case 6:a.txnStatus=6;break;case"FAILED_RISK":case 7:a.txnStatus=7;break;case"FAILED_PROCESSING":case 8:a.txnStatus=8;break;case"FAILED_RECEIVER_PROCESSING":case 9:a.txnStatus=9;break;case"FAILED_DA":case 10:a.txnStatus=10;break;case"FAILED_DA_FINAL":case 11:a.txnStatus=11;break;case"REFUNDED_TXN":case 12:a.txnStatus=12;break;case"REFUND_FAILED":case 13:a.txnStatus=13;break;case"REFUND_FAILED_PROCESSING":case 14:a.txnStatus=14;break;case"REFUND_FAILED_DA":case 15:a.txnStatus=15;break;case"EXPIRED_TXN":case 16:a.txnStatus=16;break;case"AUTH_CANCELED":case 17:a.txnStatus=17;break;case"AUTH_CANCEL_FAILED_PROCESSING":case 18:a.txnStatus=18;break;case"AUTH_CANCEL_FAILED":case 19:a.txnStatus=19;break;case"COLLECT_INIT":case 20:a.txnStatus=20;break;case"COLLECT_SUCCESS":case 21:a.txnStatus=21;break;case"COLLECT_FAILED":case 22:a.txnStatus=22;break;case"COLLECT_FAILED_RISK":case 23:a.txnStatus=23;break;case"COLLECT_REJECTED":case 24:a.txnStatus=24;break;case"COLLECT_EXPIRED":case 25:a.txnStatus=25;break;case"COLLECT_CANCELED":case 26:a.txnStatus=26;break;case"COLLECT_CANCELLING":case 27:a.txnStatus=27;break;case"IN_REVIEW":case 28:a.txnStatus=28;break;case"REVERSAL_SUCCESS":case 29:a.txnStatus=29;break;case"REVERSAL_PENDING":case 30:a.txnStatus=30;break;case"REFUND_PENDING":case 31:a.txnStatus=31;break}if(e.useNoviFiatFormat!=null&&(a.useNoviFiatFormat=!!e.useNoviFiatFormat),e.primaryAmount!=null){if(typeof e.primaryAmount!="object")throw TypeError(".proto.PaymentInfo.primaryAmount: object expected");a.primaryAmount=p.proto.Money.fromObject(e.primaryAmount)}if(e.exchangeAmount!=null){if(typeof e.exchangeAmount!="object")throw TypeError(".proto.PaymentInfo.exchangeAmount: object expected");a.exchangeAmount=p.proto.Money.fromObject(e.exchangeAmount)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.currencyDeprecated!=null&&e.hasOwnProperty("currencyDeprecated")&&(A.currencyDeprecated=a.enums===String?p.proto.PaymentInfo.Currency[e.currencyDeprecated]===void 0?e.currencyDeprecated:p.proto.PaymentInfo.Currency[e.currencyDeprecated]:e.currencyDeprecated,a.oneofs&&(A._currencyDeprecated="currencyDeprecated")),e.amount1000!=null&&e.hasOwnProperty("amount1000")&&(typeof e.amount1000=="number"?A.amount1000=a.longs===String?String(e.amount1000):e.amount1000:A.amount1000=a.longs===String?se(e.amount1000,!0):a.longs===Number?ge(e.amount1000,!0):e.amount1000,a.oneofs&&(A._amount1000="amount1000")),e.receiverJid!=null&&e.hasOwnProperty("receiverJid")&&(A.receiverJid=e.receiverJid,a.oneofs&&(A._receiverJid="receiverJid")),e.status!=null&&e.hasOwnProperty("status")&&(A.status=a.enums===String?p.proto.PaymentInfo.Status[e.status]===void 0?e.status:p.proto.PaymentInfo.Status[e.status]:e.status,a.oneofs&&(A._status="status")),e.transactionTimestamp!=null&&e.hasOwnProperty("transactionTimestamp")&&(typeof e.transactionTimestamp=="number"?A.transactionTimestamp=a.longs===String?String(e.transactionTimestamp):e.transactionTimestamp:A.transactionTimestamp=a.longs===String?se(e.transactionTimestamp,!0):a.longs===Number?ge(e.transactionTimestamp,!0):e.transactionTimestamp,a.oneofs&&(A._transactionTimestamp="transactionTimestamp")),e.requestMessageKey!=null&&e.hasOwnProperty("requestMessageKey")&&(A.requestMessageKey=p.proto.MessageKey.toObject(e.requestMessageKey,a),a.oneofs&&(A._requestMessageKey="requestMessageKey")),e.expiryTimestamp!=null&&e.hasOwnProperty("expiryTimestamp")&&(typeof e.expiryTimestamp=="number"?A.expiryTimestamp=a.longs===String?String(e.expiryTimestamp):e.expiryTimestamp:A.expiryTimestamp=a.longs===String?se(e.expiryTimestamp,!0):a.longs===Number?ge(e.expiryTimestamp,!0):e.expiryTimestamp,a.oneofs&&(A._expiryTimestamp="expiryTimestamp")),e.futureproofed!=null&&e.hasOwnProperty("futureproofed")&&(A.futureproofed=e.futureproofed,a.oneofs&&(A._futureproofed="futureproofed")),e.currency!=null&&e.hasOwnProperty("currency")&&(A.currency=e.currency,a.oneofs&&(A._currency="currency")),e.txnStatus!=null&&e.hasOwnProperty("txnStatus")&&(A.txnStatus=a.enums===String?p.proto.PaymentInfo.TxnStatus[e.txnStatus]===void 0?e.txnStatus:p.proto.PaymentInfo.TxnStatus[e.txnStatus]:e.txnStatus,a.oneofs&&(A._txnStatus="txnStatus")),e.useNoviFiatFormat!=null&&e.hasOwnProperty("useNoviFiatFormat")&&(A.useNoviFiatFormat=e.useNoviFiatFormat,a.oneofs&&(A._useNoviFiatFormat="useNoviFiatFormat")),e.primaryAmount!=null&&e.hasOwnProperty("primaryAmount")&&(A.primaryAmount=p.proto.Money.toObject(e.primaryAmount,a),a.oneofs&&(A._primaryAmount="primaryAmount")),e.exchangeAmount!=null&&e.hasOwnProperty("exchangeAmount")&&(A.exchangeAmount=p.proto.Money.toObject(e.exchangeAmount,a),a.oneofs&&(A._exchangeAmount="exchangeAmount")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PaymentInfo"},t.Currency=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_CURRENCY"]=0,e[i[1]="INR"]=1,e})(),t.Status=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_STATUS"]=0,e[i[1]="PROCESSING"]=1,e[i[2]="SENT"]=2,e[i[3]="NEED_TO_ACCEPT"]=3,e[i[4]="COMPLETE"]=4,e[i[5]="COULD_NOT_COMPLETE"]=5,e[i[6]="REFUNDED"]=6,e[i[7]="EXPIRED"]=7,e[i[8]="REJECTED"]=8,e[i[9]="CANCELLED"]=9,e[i[10]="WAITING_FOR_PAYER"]=10,e[i[11]="WAITING"]=11,e})(),t.TxnStatus=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="PENDING_SETUP"]=1,e[i[2]="PENDING_RECEIVER_SETUP"]=2,e[i[3]="INIT"]=3,e[i[4]="SUCCESS"]=4,e[i[5]="COMPLETED"]=5,e[i[6]="FAILED"]=6,e[i[7]="FAILED_RISK"]=7,e[i[8]="FAILED_PROCESSING"]=8,e[i[9]="FAILED_RECEIVER_PROCESSING"]=9,e[i[10]="FAILED_DA"]=10,e[i[11]="FAILED_DA_FINAL"]=11,e[i[12]="REFUNDED_TXN"]=12,e[i[13]="REFUND_FAILED"]=13,e[i[14]="REFUND_FAILED_PROCESSING"]=14,e[i[15]="REFUND_FAILED_DA"]=15,e[i[16]="EXPIRED_TXN"]=16,e[i[17]="AUTH_CANCELED"]=17,e[i[18]="AUTH_CANCEL_FAILED_PROCESSING"]=18,e[i[19]="AUTH_CANCEL_FAILED"]=19,e[i[20]="COLLECT_INIT"]=20,e[i[21]="COLLECT_SUCCESS"]=21,e[i[22]="COLLECT_FAILED"]=22,e[i[23]="COLLECT_FAILED_RISK"]=23,e[i[24]="COLLECT_REJECTED"]=24,e[i[25]="COLLECT_EXPIRED"]=25,e[i[26]="COLLECT_CANCELED"]=26,e[i[27]="COLLECT_CANCELLING"]=27,e[i[28]="IN_REVIEW"]=28,e[i[29]="REVERSAL_SUCCESS"]=29,e[i[30]="REVERSAL_PENDING"]=30,e[i[31]="REFUND_PENDING"]=31,e})(),t})(),n.PhoneNumberToLIDMapping=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pnJid=e.string();break}case 2:{s.lidJid=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PhoneNumberToLIDMapping)return e;var a=new p.proto.PhoneNumberToLIDMapping;return e.pnJid!=null&&(a.pnJid=String(e.pnJid)),e.lidJid!=null&&(a.lidJid=String(e.lidJid)),a},t.toObject=function(e,a){a||(a={});var A={};return e.pnJid!=null&&e.hasOwnProperty("pnJid")&&(A.pnJid=e.pnJid,a.oneofs&&(A._pnJid="pnJid")),e.lidJid!=null&&e.hasOwnProperty("lidJid")&&(A.lidJid=e.lidJid,a.oneofs&&(A._lidJid="lidJid")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PhoneNumberToLIDMapping"},t})(),n.PhotoChange=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.oldPhoto=e.bytes();break}case 2:{s.newPhoto=e.bytes();break}case 3:{s.newPhotoId=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PhotoChange)return e;var a=new p.proto.PhotoChange;return e.oldPhoto!=null&&(typeof e.oldPhoto=="string"?l.base64.decode(e.oldPhoto,a.oldPhoto=l.newBuffer(l.base64.length(e.oldPhoto)),0):e.oldPhoto.length>=0&&(a.oldPhoto=e.oldPhoto)),e.newPhoto!=null&&(typeof e.newPhoto=="string"?l.base64.decode(e.newPhoto,a.newPhoto=l.newBuffer(l.base64.length(e.newPhoto)),0):e.newPhoto.length>=0&&(a.newPhoto=e.newPhoto)),e.newPhotoId!=null&&(a.newPhotoId=e.newPhotoId>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.oldPhoto!=null&&e.hasOwnProperty("oldPhoto")&&(A.oldPhoto=a.bytes===String?l.base64.encode(e.oldPhoto,0,e.oldPhoto.length):a.bytes===Array?Array.prototype.slice.call(e.oldPhoto):e.oldPhoto,a.oneofs&&(A._oldPhoto="oldPhoto")),e.newPhoto!=null&&e.hasOwnProperty("newPhoto")&&(A.newPhoto=a.bytes===String?l.base64.encode(e.newPhoto,0,e.newPhoto.length):a.bytes===Array?Array.prototype.slice.call(e.newPhoto):e.newPhoto,a.oneofs&&(A._newPhoto="newPhoto")),e.newPhotoId!=null&&e.hasOwnProperty("newPhotoId")&&(A.newPhotoId=e.newPhotoId,a.oneofs&&(A._newPhotoId="newPhotoId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PhotoChange"},t})(),n.PinInChat=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}case 2:{s.key=p.proto.MessageKey.decode(e,e.uint32());break}case 3:{s.senderTimestampMs=e.int64();break}case 4:{s.serverTimestampMs=e.int64();break}case 5:{s.messageAddOnContextInfo=p.proto.MessageAddOnContextInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PinInChat)return e;var a=new p.proto.PinInChat;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"UNKNOWN_TYPE":case 0:a.type=0;break;case"PIN_FOR_ALL":case 1:a.type=1;break;case"UNPIN_FOR_ALL":case 2:a.type=2;break}if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.PinInChat.key: object expected");a.key=p.proto.MessageKey.fromObject(e.key)}if(e.senderTimestampMs!=null&&(l.Long?(a.senderTimestampMs=l.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new l.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(l.Long?(a.serverTimestampMs=l.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new l.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),e.messageAddOnContextInfo!=null){if(typeof e.messageAddOnContextInfo!="object")throw TypeError(".proto.PinInChat.messageAddOnContextInfo: object expected");a.messageAddOnContextInfo=p.proto.MessageAddOnContextInfo.fromObject(e.messageAddOnContextInfo)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.PinInChat.Type[e.type]===void 0?e.type:p.proto.PinInChat.Type[e.type]:e.type,a.oneofs&&(A._type="type")),e.key!=null&&e.hasOwnProperty("key")&&(A.key=p.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?se(e.senderTimestampMs):a.longs===Number?ge(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?se(e.serverTimestampMs):a.longs===Number?ge(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),e.messageAddOnContextInfo!=null&&e.hasOwnProperty("messageAddOnContextInfo")&&(A.messageAddOnContextInfo=p.proto.MessageAddOnContextInfo.toObject(e.messageAddOnContextInfo,a),a.oneofs&&(A._messageAddOnContextInfo="messageAddOnContextInfo")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PinInChat"},t.Type=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_TYPE"]=0,e[i[1]="PIN_FOR_ALL"]=1,e[i[2]="UNPIN_FOR_ALL"]=2,e})(),t})(),n.Point=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.xDeprecated=e.int32();break}case 2:{s.yDeprecated=e.int32();break}case 3:{s.x=e.double();break}case 4:{s.y=e.double();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Point)return e;var a=new p.proto.Point;return e.xDeprecated!=null&&(a.xDeprecated=e.xDeprecated|0),e.yDeprecated!=null&&(a.yDeprecated=e.yDeprecated|0),e.x!=null&&(a.x=Number(e.x)),e.y!=null&&(a.y=Number(e.y)),a},t.toObject=function(e,a){a||(a={});var A={};return e.xDeprecated!=null&&e.hasOwnProperty("xDeprecated")&&(A.xDeprecated=e.xDeprecated,a.oneofs&&(A._xDeprecated="xDeprecated")),e.yDeprecated!=null&&e.hasOwnProperty("yDeprecated")&&(A.yDeprecated=e.yDeprecated,a.oneofs&&(A._yDeprecated="yDeprecated")),e.x!=null&&e.hasOwnProperty("x")&&(A.x=a.json&&!isFinite(e.x)?String(e.x):e.x,a.oneofs&&(A._x="x")),e.y!=null&&e.hasOwnProperty("y")&&(A.y=a.json&&!isFinite(e.y)?String(e.y):e.y,a.oneofs&&(A._y="y")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Point"},t})(),n.PollAdditionalMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pollInvalidated=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PollAdditionalMetadata)return e;var a=new p.proto.PollAdditionalMetadata;return e.pollInvalidated!=null&&(a.pollInvalidated=!!e.pollInvalidated),a},t.toObject=function(e,a){a||(a={});var A={};return e.pollInvalidated!=null&&e.hasOwnProperty("pollInvalidated")&&(A.pollInvalidated=e.pollInvalidated,a.oneofs&&(A._pollInvalidated="pollInvalidated")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PollAdditionalMetadata"},t})(),n.PollEncValue=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encPayload=e.bytes();break}case 2:{s.encIv=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PollEncValue)return e;var a=new p.proto.PollEncValue;return e.encPayload!=null&&(typeof e.encPayload=="string"?l.base64.decode(e.encPayload,a.encPayload=l.newBuffer(l.base64.length(e.encPayload)),0):e.encPayload.length>=0&&(a.encPayload=e.encPayload)),e.encIv!=null&&(typeof e.encIv=="string"?l.base64.decode(e.encIv,a.encIv=l.newBuffer(l.base64.length(e.encIv)),0):e.encIv.length>=0&&(a.encIv=e.encIv)),a},t.toObject=function(e,a){a||(a={});var A={};return e.encPayload!=null&&e.hasOwnProperty("encPayload")&&(A.encPayload=a.bytes===String?l.base64.encode(e.encPayload,0,e.encPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encPayload):e.encPayload,a.oneofs&&(A._encPayload="encPayload")),e.encIv!=null&&e.hasOwnProperty("encIv")&&(A.encIv=a.bytes===String?l.base64.encode(e.encIv,0,e.encIv.length):a.bytes===Array?Array.prototype.slice.call(e.encIv):e.encIv,a.oneofs&&(A._encIv="encIv")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PollEncValue"},t})(),n.PollUpdate=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pollUpdateMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.vote=p.proto.Message.PollVoteMessage.decode(e,e.uint32());break}case 3:{s.senderTimestampMs=e.int64();break}case 4:{s.serverTimestampMs=e.int64();break}case 5:{s.unread=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PollUpdate)return e;var a=new p.proto.PollUpdate;if(e.pollUpdateMessageKey!=null){if(typeof e.pollUpdateMessageKey!="object")throw TypeError(".proto.PollUpdate.pollUpdateMessageKey: object expected");a.pollUpdateMessageKey=p.proto.MessageKey.fromObject(e.pollUpdateMessageKey)}if(e.vote!=null){if(typeof e.vote!="object")throw TypeError(".proto.PollUpdate.vote: object expected");a.vote=p.proto.Message.PollVoteMessage.fromObject(e.vote)}return e.senderTimestampMs!=null&&(l.Long?(a.senderTimestampMs=l.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new l.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(l.Long?(a.serverTimestampMs=l.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new l.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),e.unread!=null&&(a.unread=!!e.unread),a},t.toObject=function(e,a){a||(a={});var A={};return e.pollUpdateMessageKey!=null&&e.hasOwnProperty("pollUpdateMessageKey")&&(A.pollUpdateMessageKey=p.proto.MessageKey.toObject(e.pollUpdateMessageKey,a),a.oneofs&&(A._pollUpdateMessageKey="pollUpdateMessageKey")),e.vote!=null&&e.hasOwnProperty("vote")&&(A.vote=p.proto.Message.PollVoteMessage.toObject(e.vote,a),a.oneofs&&(A._vote="vote")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?se(e.senderTimestampMs):a.longs===Number?ge(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?se(e.serverTimestampMs):a.longs===Number?ge(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),e.unread!=null&&e.hasOwnProperty("unread")&&(A.unread=e.unread,a.oneofs&&(A._unread="unread")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PollUpdate"},t})(),n.PreKeyRecordStructure=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.publicKey=e.bytes();break}case 3:{s.privateKey=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PreKeyRecordStructure)return e;var a=new p.proto.PreKeyRecordStructure;return e.id!=null&&(a.id=e.id>>>0),e.publicKey!=null&&(typeof e.publicKey=="string"?l.base64.decode(e.publicKey,a.publicKey=l.newBuffer(l.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.privateKey!=null&&(typeof e.privateKey=="string"?l.base64.decode(e.privateKey,a.privateKey=l.newBuffer(l.base64.length(e.privateKey)),0):e.privateKey.length>=0&&(a.privateKey=e.privateKey)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?l.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.privateKey!=null&&e.hasOwnProperty("privateKey")&&(A.privateKey=a.bytes===String?l.base64.encode(e.privateKey,0,e.privateKey.length):a.bytes===Array?Array.prototype.slice.call(e.privateKey):e.privateKey,a.oneofs&&(A._privateKey="privateKey")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PreKeyRecordStructure"},t})(),n.PreKeySignalMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 5:{s.registrationId=e.uint32();break}case 1:{s.preKeyId=e.uint32();break}case 6:{s.signedPreKeyId=e.uint32();break}case 2:{s.baseKey=e.bytes();break}case 3:{s.identityKey=e.bytes();break}case 4:{s.message=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PreKeySignalMessage)return e;var a=new p.proto.PreKeySignalMessage;return e.registrationId!=null&&(a.registrationId=e.registrationId>>>0),e.preKeyId!=null&&(a.preKeyId=e.preKeyId>>>0),e.signedPreKeyId!=null&&(a.signedPreKeyId=e.signedPreKeyId>>>0),e.baseKey!=null&&(typeof e.baseKey=="string"?l.base64.decode(e.baseKey,a.baseKey=l.newBuffer(l.base64.length(e.baseKey)),0):e.baseKey.length>=0&&(a.baseKey=e.baseKey)),e.identityKey!=null&&(typeof e.identityKey=="string"?l.base64.decode(e.identityKey,a.identityKey=l.newBuffer(l.base64.length(e.identityKey)),0):e.identityKey.length>=0&&(a.identityKey=e.identityKey)),e.message!=null&&(typeof e.message=="string"?l.base64.decode(e.message,a.message=l.newBuffer(l.base64.length(e.message)),0):e.message.length>=0&&(a.message=e.message)),a},t.toObject=function(e,a){a||(a={});var A={};return e.preKeyId!=null&&e.hasOwnProperty("preKeyId")&&(A.preKeyId=e.preKeyId,a.oneofs&&(A._preKeyId="preKeyId")),e.baseKey!=null&&e.hasOwnProperty("baseKey")&&(A.baseKey=a.bytes===String?l.base64.encode(e.baseKey,0,e.baseKey.length):a.bytes===Array?Array.prototype.slice.call(e.baseKey):e.baseKey,a.oneofs&&(A._baseKey="baseKey")),e.identityKey!=null&&e.hasOwnProperty("identityKey")&&(A.identityKey=a.bytes===String?l.base64.encode(e.identityKey,0,e.identityKey.length):a.bytes===Array?Array.prototype.slice.call(e.identityKey):e.identityKey,a.oneofs&&(A._identityKey="identityKey")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=a.bytes===String?l.base64.encode(e.message,0,e.message.length):a.bytes===Array?Array.prototype.slice.call(e.message):e.message,a.oneofs&&(A._message="message")),e.registrationId!=null&&e.hasOwnProperty("registrationId")&&(A.registrationId=e.registrationId,a.oneofs&&(A._registrationId="registrationId")),e.signedPreKeyId!=null&&e.hasOwnProperty("signedPreKeyId")&&(A.signedPreKeyId=e.signedPreKeyId,a.oneofs&&(A._signedPreKeyId="signedPreKeyId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PreKeySignalMessage"},t})(),n.PremiumMessageInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.serverCampaignId=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PremiumMessageInfo)return e;var a=new p.proto.PremiumMessageInfo;return e.serverCampaignId!=null&&(a.serverCampaignId=String(e.serverCampaignId)),a},t.toObject=function(e,a){a||(a={});var A={};return e.serverCampaignId!=null&&e.hasOwnProperty("serverCampaignId")&&(A.serverCampaignId=e.serverCampaignId,a.oneofs&&(A._serverCampaignId="serverCampaignId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PremiumMessageInfo"},t})(),n.PrimaryEphemeralIdentity=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.nonce=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PrimaryEphemeralIdentity)return e;var a=new p.proto.PrimaryEphemeralIdentity;return e.publicKey!=null&&(typeof e.publicKey=="string"?l.base64.decode(e.publicKey,a.publicKey=l.newBuffer(l.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.nonce!=null&&(typeof e.nonce=="string"?l.base64.decode(e.nonce,a.nonce=l.newBuffer(l.base64.length(e.nonce)),0):e.nonce.length>=0&&(a.nonce=e.nonce)),a},t.toObject=function(e,a){a||(a={});var A={};return e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?l.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.nonce!=null&&e.hasOwnProperty("nonce")&&(A.nonce=a.bytes===String?l.base64.encode(e.nonce,0,e.nonce.length):a.bytes===Array?Array.prototype.slice.call(e.nonce):e.nonce,a.oneofs&&(A._nonce="nonce")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PrimaryEphemeralIdentity"},t})(),n.PrivacySystemMessage=(function(){let t={},o=Object.create(t);return o[t[1]="E2EE_MSG"]=1,o[t[2]="NE2EE_SELF"]=2,o[t[3]="NE2EE_OTHER"]=3,o})(),n.ProcessedVideo=(function(){function t(i){if(this.capabilities=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.directPath=e.string();break}case 2:{s.fileSha256=e.bytes();break}case 3:{s.height=e.uint32();break}case 4:{s.width=e.uint32();break}case 5:{s.fileLength=e.uint64();break}case 6:{s.bitrate=e.uint32();break}case 7:{s.quality=e.int32();break}case 8:{s.capabilities&&s.capabilities.length||(s.capabilities=[]),s.capabilities.push(e.string());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ProcessedVideo)return e;var a=new p.proto.ProcessedVideo;switch(e.directPath!=null&&(a.directPath=String(e.directPath)),e.fileSha256!=null&&(typeof e.fileSha256=="string"?l.base64.decode(e.fileSha256,a.fileSha256=l.newBuffer(l.base64.length(e.fileSha256)),0):e.fileSha256.length>=0&&(a.fileSha256=e.fileSha256)),e.height!=null&&(a.height=e.height>>>0),e.width!=null&&(a.width=e.width>>>0),e.fileLength!=null&&(l.Long?(a.fileLength=l.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new l.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),e.bitrate!=null&&(a.bitrate=e.bitrate>>>0),e.quality){default:if(typeof e.quality=="number"){a.quality=e.quality;break}break;case"UNDEFINED":case 0:a.quality=0;break;case"LOW":case 1:a.quality=1;break;case"MID":case 2:a.quality=2;break;case"HIGH":case 3:a.quality=3;break}if(e.capabilities){if(!Array.isArray(e.capabilities))throw TypeError(".proto.ProcessedVideo.capabilities: array expected");a.capabilities=[];for(var A=0;A>>3){case 1:{s.companionEphemeralIdentity=e.bytes();break}case 2:{s.commitment=p.proto.CompanionCommitment.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ProloguePayload)return e;var a=new p.proto.ProloguePayload;if(e.companionEphemeralIdentity!=null&&(typeof e.companionEphemeralIdentity=="string"?l.base64.decode(e.companionEphemeralIdentity,a.companionEphemeralIdentity=l.newBuffer(l.base64.length(e.companionEphemeralIdentity)),0):e.companionEphemeralIdentity.length>=0&&(a.companionEphemeralIdentity=e.companionEphemeralIdentity)),e.commitment!=null){if(typeof e.commitment!="object")throw TypeError(".proto.ProloguePayload.commitment: object expected");a.commitment=p.proto.CompanionCommitment.fromObject(e.commitment)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.companionEphemeralIdentity!=null&&e.hasOwnProperty("companionEphemeralIdentity")&&(A.companionEphemeralIdentity=a.bytes===String?l.base64.encode(e.companionEphemeralIdentity,0,e.companionEphemeralIdentity.length):a.bytes===Array?Array.prototype.slice.call(e.companionEphemeralIdentity):e.companionEphemeralIdentity,a.oneofs&&(A._companionEphemeralIdentity="companionEphemeralIdentity")),e.commitment!=null&&e.hasOwnProperty("commitment")&&(A.commitment=p.proto.CompanionCommitment.toObject(e.commitment,a),a.oneofs&&(A._commitment="commitment")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ProloguePayload"},t})(),n.Pushname=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.string();break}case 2:{s.pushname=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Pushname)return e;var a=new p.proto.Pushname;return e.id!=null&&(a.id=String(e.id)),e.pushname!=null&&(a.pushname=String(e.pushname)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.pushname!=null&&e.hasOwnProperty("pushname")&&(A.pushname=e.pushname,a.oneofs&&(A._pushname="pushname")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Pushname"},t})(),n.QuarantinedMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.originalData=e.bytes();break}case 2:{s.extractedText=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.QuarantinedMessage)return e;var a=new p.proto.QuarantinedMessage;return e.originalData!=null&&(typeof e.originalData=="string"?l.base64.decode(e.originalData,a.originalData=l.newBuffer(l.base64.length(e.originalData)),0):e.originalData.length>=0&&(a.originalData=e.originalData)),e.extractedText!=null&&(a.extractedText=String(e.extractedText)),a},t.toObject=function(e,a){a||(a={});var A={};return e.originalData!=null&&e.hasOwnProperty("originalData")&&(A.originalData=a.bytes===String?l.base64.encode(e.originalData,0,e.originalData.length):a.bytes===Array?Array.prototype.slice.call(e.originalData):e.originalData,a.oneofs&&(A._originalData="originalData")),e.extractedText!=null&&e.hasOwnProperty("extractedText")&&(A.extractedText=e.extractedText,a.oneofs&&(A._extractedText="extractedText")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.QuarantinedMessage"},t})(),n.Reaction=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.key=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.text=e.string();break}case 3:{s.groupingKey=e.string();break}case 4:{s.senderTimestampMs=e.int64();break}case 5:{s.unread=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Reaction)return e;var a=new p.proto.Reaction;if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.Reaction.key: object expected");a.key=p.proto.MessageKey.fromObject(e.key)}return e.text!=null&&(a.text=String(e.text)),e.groupingKey!=null&&(a.groupingKey=String(e.groupingKey)),e.senderTimestampMs!=null&&(l.Long?(a.senderTimestampMs=l.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new l.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.unread!=null&&(a.unread=!!e.unread),a},t.toObject=function(e,a){a||(a={});var A={};return e.key!=null&&e.hasOwnProperty("key")&&(A.key=p.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.text!=null&&e.hasOwnProperty("text")&&(A.text=e.text,a.oneofs&&(A._text="text")),e.groupingKey!=null&&e.hasOwnProperty("groupingKey")&&(A.groupingKey=e.groupingKey,a.oneofs&&(A._groupingKey="groupingKey")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?se(e.senderTimestampMs):a.longs===Number?ge(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.unread!=null&&e.hasOwnProperty("unread")&&(A.unread=e.unread,a.oneofs&&(A._unread="unread")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Reaction"},t})(),n.RecentEmojiWeight=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.emoji=e.string();break}case 2:{s.weight=e.float();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.RecentEmojiWeight)return e;var a=new p.proto.RecentEmojiWeight;return e.emoji!=null&&(a.emoji=String(e.emoji)),e.weight!=null&&(a.weight=Number(e.weight)),a},t.toObject=function(e,a){a||(a={});var A={};return e.emoji!=null&&e.hasOwnProperty("emoji")&&(A.emoji=e.emoji,a.oneofs&&(A._emoji="emoji")),e.weight!=null&&e.hasOwnProperty("weight")&&(A.weight=a.json&&!isFinite(e.weight)?String(e.weight):e.weight,a.oneofs&&(A._weight="weight")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.RecentEmojiWeight"},t})(),n.RecordStructure=(function(){function t(i){if(this.previousSessions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.currentSession=p.proto.SessionStructure.decode(e,e.uint32());break}case 2:{s.previousSessions&&s.previousSessions.length||(s.previousSessions=[]),s.previousSessions.push(p.proto.SessionStructure.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.RecordStructure)return e;var a=new p.proto.RecordStructure;if(e.currentSession!=null){if(typeof e.currentSession!="object")throw TypeError(".proto.RecordStructure.currentSession: object expected");a.currentSession=p.proto.SessionStructure.fromObject(e.currentSession)}if(e.previousSessions){if(!Array.isArray(e.previousSessions))throw TypeError(".proto.RecordStructure.previousSessions: array expected");a.previousSessions=[];for(var A=0;A>>3){case 1:{s.minVersion=e.uint32();break}case 2:{s.maxVersion=e.uint32();break}case 3:{s.notReportableMinVersion=e.uint32();break}case 4:{s.never=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Reportable)return e;var a=new p.proto.Reportable;return e.minVersion!=null&&(a.minVersion=e.minVersion>>>0),e.maxVersion!=null&&(a.maxVersion=e.maxVersion>>>0),e.notReportableMinVersion!=null&&(a.notReportableMinVersion=e.notReportableMinVersion>>>0),e.never!=null&&(a.never=!!e.never),a},t.toObject=function(e,a){a||(a={});var A={};return e.minVersion!=null&&e.hasOwnProperty("minVersion")&&(A.minVersion=e.minVersion,a.oneofs&&(A._minVersion="minVersion")),e.maxVersion!=null&&e.hasOwnProperty("maxVersion")&&(A.maxVersion=e.maxVersion,a.oneofs&&(A._maxVersion="maxVersion")),e.notReportableMinVersion!=null&&e.hasOwnProperty("notReportableMinVersion")&&(A.notReportableMinVersion=e.notReportableMinVersion,a.oneofs&&(A._notReportableMinVersion="notReportableMinVersion")),e.never!=null&&e.hasOwnProperty("never")&&(A.never=e.never,a.oneofs&&(A._never="never")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Reportable"},t})(),n.ReportingTokenInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.reportingTag=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ReportingTokenInfo)return e;var a=new p.proto.ReportingTokenInfo;return e.reportingTag!=null&&(typeof e.reportingTag=="string"?l.base64.decode(e.reportingTag,a.reportingTag=l.newBuffer(l.base64.length(e.reportingTag)),0):e.reportingTag.length>=0&&(a.reportingTag=e.reportingTag)),a},t.toObject=function(e,a){a||(a={});var A={};return e.reportingTag!=null&&e.hasOwnProperty("reportingTag")&&(A.reportingTag=a.bytes===String?l.base64.encode(e.reportingTag,0,e.reportingTag.length):a.bytes===Array?Array.prototype.slice.call(e.reportingTag):e.reportingTag,a.oneofs&&(A._reportingTag="reportingTag")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ReportingTokenInfo"},t})(),n.SenderKeyDistributionMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.iteration=e.uint32();break}case 3:{s.chainKey=e.bytes();break}case 4:{s.signingKey=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SenderKeyDistributionMessage)return e;var a=new p.proto.SenderKeyDistributionMessage;return e.id!=null&&(a.id=e.id>>>0),e.iteration!=null&&(a.iteration=e.iteration>>>0),e.chainKey!=null&&(typeof e.chainKey=="string"?l.base64.decode(e.chainKey,a.chainKey=l.newBuffer(l.base64.length(e.chainKey)),0):e.chainKey.length>=0&&(a.chainKey=e.chainKey)),e.signingKey!=null&&(typeof e.signingKey=="string"?l.base64.decode(e.signingKey,a.signingKey=l.newBuffer(l.base64.length(e.signingKey)),0):e.signingKey.length>=0&&(a.signingKey=e.signingKey)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.iteration!=null&&e.hasOwnProperty("iteration")&&(A.iteration=e.iteration,a.oneofs&&(A._iteration="iteration")),e.chainKey!=null&&e.hasOwnProperty("chainKey")&&(A.chainKey=a.bytes===String?l.base64.encode(e.chainKey,0,e.chainKey.length):a.bytes===Array?Array.prototype.slice.call(e.chainKey):e.chainKey,a.oneofs&&(A._chainKey="chainKey")),e.signingKey!=null&&e.hasOwnProperty("signingKey")&&(A.signingKey=a.bytes===String?l.base64.encode(e.signingKey,0,e.signingKey.length):a.bytes===Array?Array.prototype.slice.call(e.signingKey):e.signingKey,a.oneofs&&(A._signingKey="signingKey")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SenderKeyDistributionMessage"},t})(),n.SenderKeyMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.iteration=e.uint32();break}case 3:{s.ciphertext=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SenderKeyMessage)return e;var a=new p.proto.SenderKeyMessage;return e.id!=null&&(a.id=e.id>>>0),e.iteration!=null&&(a.iteration=e.iteration>>>0),e.ciphertext!=null&&(typeof e.ciphertext=="string"?l.base64.decode(e.ciphertext,a.ciphertext=l.newBuffer(l.base64.length(e.ciphertext)),0):e.ciphertext.length>=0&&(a.ciphertext=e.ciphertext)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.iteration!=null&&e.hasOwnProperty("iteration")&&(A.iteration=e.iteration,a.oneofs&&(A._iteration="iteration")),e.ciphertext!=null&&e.hasOwnProperty("ciphertext")&&(A.ciphertext=a.bytes===String?l.base64.encode(e.ciphertext,0,e.ciphertext.length):a.bytes===Array?Array.prototype.slice.call(e.ciphertext):e.ciphertext,a.oneofs&&(A._ciphertext="ciphertext")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SenderKeyMessage"},t})(),n.SenderKeyRecordStructure=(function(){function t(o){if(this.senderKeyStates=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.senderKeyStates&&r.senderKeyStates.length||(r.senderKeyStates=[]),r.senderKeyStates.push(p.proto.SenderKeyStateStructure.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.SenderKeyRecordStructure)return i;var e=new p.proto.SenderKeyRecordStructure;if(i.senderKeyStates){if(!Array.isArray(i.senderKeyStates))throw TypeError(".proto.SenderKeyRecordStructure.senderKeyStates: array expected");e.senderKeyStates=[];for(var a=0;a>>3){case 1:{s.senderKeyId=e.uint32();break}case 2:{s.senderChainKey=p.proto.SenderKeyStateStructure.SenderChainKey.decode(e,e.uint32());break}case 3:{s.senderSigningKey=p.proto.SenderKeyStateStructure.SenderSigningKey.decode(e,e.uint32());break}case 4:{s.senderMessageKeys&&s.senderMessageKeys.length||(s.senderMessageKeys=[]),s.senderMessageKeys.push(p.proto.SenderKeyStateStructure.SenderMessageKey.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SenderKeyStateStructure)return e;var a=new p.proto.SenderKeyStateStructure;if(e.senderKeyId!=null&&(a.senderKeyId=e.senderKeyId>>>0),e.senderChainKey!=null){if(typeof e.senderChainKey!="object")throw TypeError(".proto.SenderKeyStateStructure.senderChainKey: object expected");a.senderChainKey=p.proto.SenderKeyStateStructure.SenderChainKey.fromObject(e.senderChainKey)}if(e.senderSigningKey!=null){if(typeof e.senderSigningKey!="object")throw TypeError(".proto.SenderKeyStateStructure.senderSigningKey: object expected");a.senderSigningKey=p.proto.SenderKeyStateStructure.SenderSigningKey.fromObject(e.senderSigningKey)}if(e.senderMessageKeys){if(!Array.isArray(e.senderMessageKeys))throw TypeError(".proto.SenderKeyStateStructure.senderMessageKeys: array expected");a.senderMessageKeys=[];for(var A=0;A>>3){case 1:{c.iteration=A.uint32();break}case 2:{c.seed=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SenderKeyStateStructure.SenderChainKey)return A;var r=new p.proto.SenderKeyStateStructure.SenderChainKey;return A.iteration!=null&&(r.iteration=A.iteration>>>0),A.seed!=null&&(typeof A.seed=="string"?l.base64.decode(A.seed,r.seed=l.newBuffer(l.base64.length(A.seed)),0):A.seed.length>=0&&(r.seed=A.seed)),r},i.toObject=function(A,r){r||(r={});var s={};return A.iteration!=null&&A.hasOwnProperty("iteration")&&(s.iteration=A.iteration,r.oneofs&&(s._iteration="iteration")),A.seed!=null&&A.hasOwnProperty("seed")&&(s.seed=r.bytes===String?l.base64.encode(A.seed,0,A.seed.length):r.bytes===Array?Array.prototype.slice.call(A.seed):A.seed,r.oneofs&&(s._seed="seed")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SenderKeyStateStructure.SenderChainKey"},i})(),t.SenderMessageKey=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.iteration=A.uint32();break}case 2:{c.seed=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SenderKeyStateStructure.SenderMessageKey)return A;var r=new p.proto.SenderKeyStateStructure.SenderMessageKey;return A.iteration!=null&&(r.iteration=A.iteration>>>0),A.seed!=null&&(typeof A.seed=="string"?l.base64.decode(A.seed,r.seed=l.newBuffer(l.base64.length(A.seed)),0):A.seed.length>=0&&(r.seed=A.seed)),r},i.toObject=function(A,r){r||(r={});var s={};return A.iteration!=null&&A.hasOwnProperty("iteration")&&(s.iteration=A.iteration,r.oneofs&&(s._iteration="iteration")),A.seed!=null&&A.hasOwnProperty("seed")&&(s.seed=r.bytes===String?l.base64.encode(A.seed,0,A.seed.length):r.bytes===Array?Array.prototype.slice.call(A.seed):A.seed,r.oneofs&&(s._seed="seed")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SenderKeyStateStructure.SenderMessageKey"},i})(),t.SenderSigningKey=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.public=A.bytes();break}case 2:{c.private=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SenderKeyStateStructure.SenderSigningKey)return A;var r=new p.proto.SenderKeyStateStructure.SenderSigningKey;return A.public!=null&&(typeof A.public=="string"?l.base64.decode(A.public,r.public=l.newBuffer(l.base64.length(A.public)),0):A.public.length>=0&&(r.public=A.public)),A.private!=null&&(typeof A.private=="string"?l.base64.decode(A.private,r.private=l.newBuffer(l.base64.length(A.private)),0):A.private.length>=0&&(r.private=A.private)),r},i.toObject=function(A,r){r||(r={});var s={};return A.public!=null&&A.hasOwnProperty("public")&&(s.public=r.bytes===String?l.base64.encode(A.public,0,A.public.length):r.bytes===Array?Array.prototype.slice.call(A.public):A.public,r.oneofs&&(s._public="public")),A.private!=null&&A.hasOwnProperty("private")&&(s.private=r.bytes===String?l.base64.encode(A.private,0,A.private.length):r.bytes===Array?Array.prototype.slice.call(A.private):A.private,r.oneofs&&(s._private="private")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SenderKeyStateStructure.SenderSigningKey"},i})(),t})(),n.ServerErrorReceipt=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.stanzaId=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ServerErrorReceipt)return e;var a=new p.proto.ServerErrorReceipt;return e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),a},t.toObject=function(e,a){a||(a={});var A={};return e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ServerErrorReceipt"},t})(),n.SessionStructure=(function(){function t(i){if(this.receiverChains=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.sessionVersion=e.uint32();break}case 2:{s.localIdentityPublic=e.bytes();break}case 3:{s.remoteIdentityPublic=e.bytes();break}case 4:{s.rootKey=e.bytes();break}case 5:{s.previousCounter=e.uint32();break}case 6:{s.senderChain=p.proto.SessionStructure.Chain.decode(e,e.uint32());break}case 7:{s.receiverChains&&s.receiverChains.length||(s.receiverChains=[]),s.receiverChains.push(p.proto.SessionStructure.Chain.decode(e,e.uint32()));break}case 8:{s.pendingKeyExchange=p.proto.SessionStructure.PendingKeyExchange.decode(e,e.uint32());break}case 9:{s.pendingPreKey=p.proto.SessionStructure.PendingPreKey.decode(e,e.uint32());break}case 10:{s.remoteRegistrationId=e.uint32();break}case 11:{s.localRegistrationId=e.uint32();break}case 12:{s.needsRefresh=e.bool();break}case 13:{s.aliceBaseKey=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SessionStructure)return e;var a=new p.proto.SessionStructure;if(e.sessionVersion!=null&&(a.sessionVersion=e.sessionVersion>>>0),e.localIdentityPublic!=null&&(typeof e.localIdentityPublic=="string"?l.base64.decode(e.localIdentityPublic,a.localIdentityPublic=l.newBuffer(l.base64.length(e.localIdentityPublic)),0):e.localIdentityPublic.length>=0&&(a.localIdentityPublic=e.localIdentityPublic)),e.remoteIdentityPublic!=null&&(typeof e.remoteIdentityPublic=="string"?l.base64.decode(e.remoteIdentityPublic,a.remoteIdentityPublic=l.newBuffer(l.base64.length(e.remoteIdentityPublic)),0):e.remoteIdentityPublic.length>=0&&(a.remoteIdentityPublic=e.remoteIdentityPublic)),e.rootKey!=null&&(typeof e.rootKey=="string"?l.base64.decode(e.rootKey,a.rootKey=l.newBuffer(l.base64.length(e.rootKey)),0):e.rootKey.length>=0&&(a.rootKey=e.rootKey)),e.previousCounter!=null&&(a.previousCounter=e.previousCounter>>>0),e.senderChain!=null){if(typeof e.senderChain!="object")throw TypeError(".proto.SessionStructure.senderChain: object expected");a.senderChain=p.proto.SessionStructure.Chain.fromObject(e.senderChain)}if(e.receiverChains){if(!Array.isArray(e.receiverChains))throw TypeError(".proto.SessionStructure.receiverChains: array expected");a.receiverChains=[];for(var A=0;A>>0),e.localRegistrationId!=null&&(a.localRegistrationId=e.localRegistrationId>>>0),e.needsRefresh!=null&&(a.needsRefresh=!!e.needsRefresh),e.aliceBaseKey!=null&&(typeof e.aliceBaseKey=="string"?l.base64.decode(e.aliceBaseKey,a.aliceBaseKey=l.newBuffer(l.base64.length(e.aliceBaseKey)),0):e.aliceBaseKey.length>=0&&(a.aliceBaseKey=e.aliceBaseKey)),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.receiverChains=[]),e.sessionVersion!=null&&e.hasOwnProperty("sessionVersion")&&(A.sessionVersion=e.sessionVersion,a.oneofs&&(A._sessionVersion="sessionVersion")),e.localIdentityPublic!=null&&e.hasOwnProperty("localIdentityPublic")&&(A.localIdentityPublic=a.bytes===String?l.base64.encode(e.localIdentityPublic,0,e.localIdentityPublic.length):a.bytes===Array?Array.prototype.slice.call(e.localIdentityPublic):e.localIdentityPublic,a.oneofs&&(A._localIdentityPublic="localIdentityPublic")),e.remoteIdentityPublic!=null&&e.hasOwnProperty("remoteIdentityPublic")&&(A.remoteIdentityPublic=a.bytes===String?l.base64.encode(e.remoteIdentityPublic,0,e.remoteIdentityPublic.length):a.bytes===Array?Array.prototype.slice.call(e.remoteIdentityPublic):e.remoteIdentityPublic,a.oneofs&&(A._remoteIdentityPublic="remoteIdentityPublic")),e.rootKey!=null&&e.hasOwnProperty("rootKey")&&(A.rootKey=a.bytes===String?l.base64.encode(e.rootKey,0,e.rootKey.length):a.bytes===Array?Array.prototype.slice.call(e.rootKey):e.rootKey,a.oneofs&&(A._rootKey="rootKey")),e.previousCounter!=null&&e.hasOwnProperty("previousCounter")&&(A.previousCounter=e.previousCounter,a.oneofs&&(A._previousCounter="previousCounter")),e.senderChain!=null&&e.hasOwnProperty("senderChain")&&(A.senderChain=p.proto.SessionStructure.Chain.toObject(e.senderChain,a),a.oneofs&&(A._senderChain="senderChain")),e.receiverChains&&e.receiverChains.length){A.receiverChains=[];for(var r=0;r>>3){case 1:{c.senderRatchetKey=A.bytes();break}case 2:{c.senderRatchetKeyPrivate=A.bytes();break}case 3:{c.chainKey=p.proto.SessionStructure.Chain.ChainKey.decode(A,A.uint32());break}case 4:{c.messageKeys&&c.messageKeys.length||(c.messageKeys=[]),c.messageKeys.push(p.proto.SessionStructure.Chain.MessageKey.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SessionStructure.Chain)return A;var r=new p.proto.SessionStructure.Chain;if(A.senderRatchetKey!=null&&(typeof A.senderRatchetKey=="string"?l.base64.decode(A.senderRatchetKey,r.senderRatchetKey=l.newBuffer(l.base64.length(A.senderRatchetKey)),0):A.senderRatchetKey.length>=0&&(r.senderRatchetKey=A.senderRatchetKey)),A.senderRatchetKeyPrivate!=null&&(typeof A.senderRatchetKeyPrivate=="string"?l.base64.decode(A.senderRatchetKeyPrivate,r.senderRatchetKeyPrivate=l.newBuffer(l.base64.length(A.senderRatchetKeyPrivate)),0):A.senderRatchetKeyPrivate.length>=0&&(r.senderRatchetKeyPrivate=A.senderRatchetKeyPrivate)),A.chainKey!=null){if(typeof A.chainKey!="object")throw TypeError(".proto.SessionStructure.Chain.chainKey: object expected");r.chainKey=p.proto.SessionStructure.Chain.ChainKey.fromObject(A.chainKey)}if(A.messageKeys){if(!Array.isArray(A.messageKeys))throw TypeError(".proto.SessionStructure.Chain.messageKeys: array expected");r.messageKeys=[];for(var s=0;s>>3){case 1:{d.index=s.uint32();break}case 2:{d.key=s.bytes();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.SessionStructure.Chain.ChainKey)return s;var g=new p.proto.SessionStructure.Chain.ChainKey;return s.index!=null&&(g.index=s.index>>>0),s.key!=null&&(typeof s.key=="string"?l.base64.decode(s.key,g.key=l.newBuffer(l.base64.length(s.key)),0):s.key.length>=0&&(g.key=s.key)),g},a.toObject=function(s,g){g||(g={});var c={};return s.index!=null&&s.hasOwnProperty("index")&&(c.index=s.index,g.oneofs&&(c._index="index")),s.key!=null&&s.hasOwnProperty("key")&&(c.key=g.bytes===String?l.base64.encode(s.key,0,s.key.length):g.bytes===Array?Array.prototype.slice.call(s.key):s.key,g.oneofs&&(c._key="key")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.SessionStructure.Chain.ChainKey"},a})(),i.MessageKey=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.index=s.uint32();break}case 2:{d.cipherKey=s.bytes();break}case 3:{d.macKey=s.bytes();break}case 4:{d.iv=s.bytes();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.SessionStructure.Chain.MessageKey)return s;var g=new p.proto.SessionStructure.Chain.MessageKey;return s.index!=null&&(g.index=s.index>>>0),s.cipherKey!=null&&(typeof s.cipherKey=="string"?l.base64.decode(s.cipherKey,g.cipherKey=l.newBuffer(l.base64.length(s.cipherKey)),0):s.cipherKey.length>=0&&(g.cipherKey=s.cipherKey)),s.macKey!=null&&(typeof s.macKey=="string"?l.base64.decode(s.macKey,g.macKey=l.newBuffer(l.base64.length(s.macKey)),0):s.macKey.length>=0&&(g.macKey=s.macKey)),s.iv!=null&&(typeof s.iv=="string"?l.base64.decode(s.iv,g.iv=l.newBuffer(l.base64.length(s.iv)),0):s.iv.length>=0&&(g.iv=s.iv)),g},a.toObject=function(s,g){g||(g={});var c={};return s.index!=null&&s.hasOwnProperty("index")&&(c.index=s.index,g.oneofs&&(c._index="index")),s.cipherKey!=null&&s.hasOwnProperty("cipherKey")&&(c.cipherKey=g.bytes===String?l.base64.encode(s.cipherKey,0,s.cipherKey.length):g.bytes===Array?Array.prototype.slice.call(s.cipherKey):s.cipherKey,g.oneofs&&(c._cipherKey="cipherKey")),s.macKey!=null&&s.hasOwnProperty("macKey")&&(c.macKey=g.bytes===String?l.base64.encode(s.macKey,0,s.macKey.length):g.bytes===Array?Array.prototype.slice.call(s.macKey):s.macKey,g.oneofs&&(c._macKey="macKey")),s.iv!=null&&s.hasOwnProperty("iv")&&(c.iv=g.bytes===String?l.base64.encode(s.iv,0,s.iv.length):g.bytes===Array?Array.prototype.slice.call(s.iv):s.iv,g.oneofs&&(c._iv="iv")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.SessionStructure.Chain.MessageKey"},a})(),i})(),t.PendingKeyExchange=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.sequence=A.uint32();break}case 2:{c.localBaseKey=A.bytes();break}case 3:{c.localBaseKeyPrivate=A.bytes();break}case 4:{c.localRatchetKey=A.bytes();break}case 5:{c.localRatchetKeyPrivate=A.bytes();break}case 7:{c.localIdentityKey=A.bytes();break}case 8:{c.localIdentityKeyPrivate=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SessionStructure.PendingKeyExchange)return A;var r=new p.proto.SessionStructure.PendingKeyExchange;return A.sequence!=null&&(r.sequence=A.sequence>>>0),A.localBaseKey!=null&&(typeof A.localBaseKey=="string"?l.base64.decode(A.localBaseKey,r.localBaseKey=l.newBuffer(l.base64.length(A.localBaseKey)),0):A.localBaseKey.length>=0&&(r.localBaseKey=A.localBaseKey)),A.localBaseKeyPrivate!=null&&(typeof A.localBaseKeyPrivate=="string"?l.base64.decode(A.localBaseKeyPrivate,r.localBaseKeyPrivate=l.newBuffer(l.base64.length(A.localBaseKeyPrivate)),0):A.localBaseKeyPrivate.length>=0&&(r.localBaseKeyPrivate=A.localBaseKeyPrivate)),A.localRatchetKey!=null&&(typeof A.localRatchetKey=="string"?l.base64.decode(A.localRatchetKey,r.localRatchetKey=l.newBuffer(l.base64.length(A.localRatchetKey)),0):A.localRatchetKey.length>=0&&(r.localRatchetKey=A.localRatchetKey)),A.localRatchetKeyPrivate!=null&&(typeof A.localRatchetKeyPrivate=="string"?l.base64.decode(A.localRatchetKeyPrivate,r.localRatchetKeyPrivate=l.newBuffer(l.base64.length(A.localRatchetKeyPrivate)),0):A.localRatchetKeyPrivate.length>=0&&(r.localRatchetKeyPrivate=A.localRatchetKeyPrivate)),A.localIdentityKey!=null&&(typeof A.localIdentityKey=="string"?l.base64.decode(A.localIdentityKey,r.localIdentityKey=l.newBuffer(l.base64.length(A.localIdentityKey)),0):A.localIdentityKey.length>=0&&(r.localIdentityKey=A.localIdentityKey)),A.localIdentityKeyPrivate!=null&&(typeof A.localIdentityKeyPrivate=="string"?l.base64.decode(A.localIdentityKeyPrivate,r.localIdentityKeyPrivate=l.newBuffer(l.base64.length(A.localIdentityKeyPrivate)),0):A.localIdentityKeyPrivate.length>=0&&(r.localIdentityKeyPrivate=A.localIdentityKeyPrivate)),r},i.toObject=function(A,r){r||(r={});var s={};return A.sequence!=null&&A.hasOwnProperty("sequence")&&(s.sequence=A.sequence,r.oneofs&&(s._sequence="sequence")),A.localBaseKey!=null&&A.hasOwnProperty("localBaseKey")&&(s.localBaseKey=r.bytes===String?l.base64.encode(A.localBaseKey,0,A.localBaseKey.length):r.bytes===Array?Array.prototype.slice.call(A.localBaseKey):A.localBaseKey,r.oneofs&&(s._localBaseKey="localBaseKey")),A.localBaseKeyPrivate!=null&&A.hasOwnProperty("localBaseKeyPrivate")&&(s.localBaseKeyPrivate=r.bytes===String?l.base64.encode(A.localBaseKeyPrivate,0,A.localBaseKeyPrivate.length):r.bytes===Array?Array.prototype.slice.call(A.localBaseKeyPrivate):A.localBaseKeyPrivate,r.oneofs&&(s._localBaseKeyPrivate="localBaseKeyPrivate")),A.localRatchetKey!=null&&A.hasOwnProperty("localRatchetKey")&&(s.localRatchetKey=r.bytes===String?l.base64.encode(A.localRatchetKey,0,A.localRatchetKey.length):r.bytes===Array?Array.prototype.slice.call(A.localRatchetKey):A.localRatchetKey,r.oneofs&&(s._localRatchetKey="localRatchetKey")),A.localRatchetKeyPrivate!=null&&A.hasOwnProperty("localRatchetKeyPrivate")&&(s.localRatchetKeyPrivate=r.bytes===String?l.base64.encode(A.localRatchetKeyPrivate,0,A.localRatchetKeyPrivate.length):r.bytes===Array?Array.prototype.slice.call(A.localRatchetKeyPrivate):A.localRatchetKeyPrivate,r.oneofs&&(s._localRatchetKeyPrivate="localRatchetKeyPrivate")),A.localIdentityKey!=null&&A.hasOwnProperty("localIdentityKey")&&(s.localIdentityKey=r.bytes===String?l.base64.encode(A.localIdentityKey,0,A.localIdentityKey.length):r.bytes===Array?Array.prototype.slice.call(A.localIdentityKey):A.localIdentityKey,r.oneofs&&(s._localIdentityKey="localIdentityKey")),A.localIdentityKeyPrivate!=null&&A.hasOwnProperty("localIdentityKeyPrivate")&&(s.localIdentityKeyPrivate=r.bytes===String?l.base64.encode(A.localIdentityKeyPrivate,0,A.localIdentityKeyPrivate.length):r.bytes===Array?Array.prototype.slice.call(A.localIdentityKeyPrivate):A.localIdentityKeyPrivate,r.oneofs&&(s._localIdentityKeyPrivate="localIdentityKeyPrivate")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SessionStructure.PendingKeyExchange"},i})(),t.PendingPreKey=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.preKeyId=A.uint32();break}case 3:{c.signedPreKeyId=A.int32();break}case 2:{c.baseKey=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SessionStructure.PendingPreKey)return A;var r=new p.proto.SessionStructure.PendingPreKey;return A.preKeyId!=null&&(r.preKeyId=A.preKeyId>>>0),A.signedPreKeyId!=null&&(r.signedPreKeyId=A.signedPreKeyId|0),A.baseKey!=null&&(typeof A.baseKey=="string"?l.base64.decode(A.baseKey,r.baseKey=l.newBuffer(l.base64.length(A.baseKey)),0):A.baseKey.length>=0&&(r.baseKey=A.baseKey)),r},i.toObject=function(A,r){r||(r={});var s={};return A.preKeyId!=null&&A.hasOwnProperty("preKeyId")&&(s.preKeyId=A.preKeyId,r.oneofs&&(s._preKeyId="preKeyId")),A.baseKey!=null&&A.hasOwnProperty("baseKey")&&(s.baseKey=r.bytes===String?l.base64.encode(A.baseKey,0,A.baseKey.length):r.bytes===Array?Array.prototype.slice.call(A.baseKey):A.baseKey,r.oneofs&&(s._baseKey="baseKey")),A.signedPreKeyId!=null&&A.hasOwnProperty("signedPreKeyId")&&(s.signedPreKeyId=A.signedPreKeyId,r.oneofs&&(s._signedPreKeyId="signedPreKeyId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SessionStructure.PendingPreKey"},i})(),t})(),n.SessionTransparencyMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.disclaimerText=e.string();break}case 2:{s.hcaId=e.string();break}case 3:{s.sessionTransparencyType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SessionTransparencyMetadata)return e;var a=new p.proto.SessionTransparencyMetadata;switch(e.disclaimerText!=null&&(a.disclaimerText=String(e.disclaimerText)),e.hcaId!=null&&(a.hcaId=String(e.hcaId)),e.sessionTransparencyType){default:if(typeof e.sessionTransparencyType=="number"){a.sessionTransparencyType=e.sessionTransparencyType;break}break;case"UNKNOWN_TYPE":case 0:a.sessionTransparencyType=0;break;case"NY_AI_SAFETY_DISCLAIMER":case 1:a.sessionTransparencyType=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.disclaimerText!=null&&e.hasOwnProperty("disclaimerText")&&(A.disclaimerText=e.disclaimerText,a.oneofs&&(A._disclaimerText="disclaimerText")),e.hcaId!=null&&e.hasOwnProperty("hcaId")&&(A.hcaId=e.hcaId,a.oneofs&&(A._hcaId="hcaId")),e.sessionTransparencyType!=null&&e.hasOwnProperty("sessionTransparencyType")&&(A.sessionTransparencyType=a.enums===String?p.proto.SessionTransparencyType[e.sessionTransparencyType]===void 0?e.sessionTransparencyType:p.proto.SessionTransparencyType[e.sessionTransparencyType]:e.sessionTransparencyType,a.oneofs&&(A._sessionTransparencyType="sessionTransparencyType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SessionTransparencyMetadata"},t})(),n.SessionTransparencyType=(function(){let t={},o=Object.create(t);return o[t[0]="UNKNOWN_TYPE"]=0,o[t[1]="NY_AI_SAFETY_DISCLAIMER"]=1,o})(),n.SignalMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.ratchetKey=e.bytes();break}case 2:{s.counter=e.uint32();break}case 3:{s.previousCounter=e.uint32();break}case 4:{s.ciphertext=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SignalMessage)return e;var a=new p.proto.SignalMessage;return e.ratchetKey!=null&&(typeof e.ratchetKey=="string"?l.base64.decode(e.ratchetKey,a.ratchetKey=l.newBuffer(l.base64.length(e.ratchetKey)),0):e.ratchetKey.length>=0&&(a.ratchetKey=e.ratchetKey)),e.counter!=null&&(a.counter=e.counter>>>0),e.previousCounter!=null&&(a.previousCounter=e.previousCounter>>>0),e.ciphertext!=null&&(typeof e.ciphertext=="string"?l.base64.decode(e.ciphertext,a.ciphertext=l.newBuffer(l.base64.length(e.ciphertext)),0):e.ciphertext.length>=0&&(a.ciphertext=e.ciphertext)),a},t.toObject=function(e,a){a||(a={});var A={};return e.ratchetKey!=null&&e.hasOwnProperty("ratchetKey")&&(A.ratchetKey=a.bytes===String?l.base64.encode(e.ratchetKey,0,e.ratchetKey.length):a.bytes===Array?Array.prototype.slice.call(e.ratchetKey):e.ratchetKey,a.oneofs&&(A._ratchetKey="ratchetKey")),e.counter!=null&&e.hasOwnProperty("counter")&&(A.counter=e.counter,a.oneofs&&(A._counter="counter")),e.previousCounter!=null&&e.hasOwnProperty("previousCounter")&&(A.previousCounter=e.previousCounter,a.oneofs&&(A._previousCounter="previousCounter")),e.ciphertext!=null&&e.hasOwnProperty("ciphertext")&&(A.ciphertext=a.bytes===String?l.base64.encode(e.ciphertext,0,e.ciphertext.length):a.bytes===Array?Array.prototype.slice.call(e.ciphertext):e.ciphertext,a.oneofs&&(A._ciphertext="ciphertext")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SignalMessage"},t})(),n.SignedPreKeyRecordStructure=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.publicKey=e.bytes();break}case 3:{s.privateKey=e.bytes();break}case 4:{s.signature=e.bytes();break}case 5:{s.timestamp=e.fixed64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SignedPreKeyRecordStructure)return e;var a=new p.proto.SignedPreKeyRecordStructure;return e.id!=null&&(a.id=e.id>>>0),e.publicKey!=null&&(typeof e.publicKey=="string"?l.base64.decode(e.publicKey,a.publicKey=l.newBuffer(l.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.privateKey!=null&&(typeof e.privateKey=="string"?l.base64.decode(e.privateKey,a.privateKey=l.newBuffer(l.base64.length(e.privateKey)),0):e.privateKey.length>=0&&(a.privateKey=e.privateKey)),e.signature!=null&&(typeof e.signature=="string"?l.base64.decode(e.signature,a.signature=l.newBuffer(l.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?l.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.privateKey!=null&&e.hasOwnProperty("privateKey")&&(A.privateKey=a.bytes===String?l.base64.encode(e.privateKey,0,e.privateKey.length):a.bytes===Array?Array.prototype.slice.call(e.privateKey):e.privateKey,a.oneofs&&(A._privateKey="privateKey")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?l.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp):a.longs===Number?ge(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SignedPreKeyRecordStructure"},t})(),n.StatusAttribution=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}case 2:{s.actionUrl=e.string();break}case 3:{s.statusReshare=p.proto.StatusAttribution.StatusReshare.decode(e,e.uint32());break}case 4:{s.externalShare=p.proto.StatusAttribution.ExternalShare.decode(e,e.uint32());break}case 5:{s.music=p.proto.StatusAttribution.Music.decode(e,e.uint32());break}case 6:{s.groupStatus=p.proto.StatusAttribution.GroupStatus.decode(e,e.uint32());break}case 7:{s.rlAttribution=p.proto.StatusAttribution.RLAttribution.decode(e,e.uint32());break}case 8:{s.aiCreatedAttribution=p.proto.StatusAttribution.AiCreatedAttribution.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.StatusAttribution)return e;var a=new p.proto.StatusAttribution;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"UNKNOWN":case 0:a.type=0;break;case"RESHARE":case 1:a.type=1;break;case"EXTERNAL_SHARE":case 2:a.type=2;break;case"MUSIC":case 3:a.type=3;break;case"STATUS_MENTION":case 4:a.type=4;break;case"GROUP_STATUS":case 5:a.type=5;break;case"RL_ATTRIBUTION":case 6:a.type=6;break;case"AI_CREATED":case 7:a.type=7;break;case"LAYOUTS":case 8:a.type=8;break}if(e.actionUrl!=null&&(a.actionUrl=String(e.actionUrl)),e.statusReshare!=null){if(typeof e.statusReshare!="object")throw TypeError(".proto.StatusAttribution.statusReshare: object expected");a.statusReshare=p.proto.StatusAttribution.StatusReshare.fromObject(e.statusReshare)}if(e.externalShare!=null){if(typeof e.externalShare!="object")throw TypeError(".proto.StatusAttribution.externalShare: object expected");a.externalShare=p.proto.StatusAttribution.ExternalShare.fromObject(e.externalShare)}if(e.music!=null){if(typeof e.music!="object")throw TypeError(".proto.StatusAttribution.music: object expected");a.music=p.proto.StatusAttribution.Music.fromObject(e.music)}if(e.groupStatus!=null){if(typeof e.groupStatus!="object")throw TypeError(".proto.StatusAttribution.groupStatus: object expected");a.groupStatus=p.proto.StatusAttribution.GroupStatus.fromObject(e.groupStatus)}if(e.rlAttribution!=null){if(typeof e.rlAttribution!="object")throw TypeError(".proto.StatusAttribution.rlAttribution: object expected");a.rlAttribution=p.proto.StatusAttribution.RLAttribution.fromObject(e.rlAttribution)}if(e.aiCreatedAttribution!=null){if(typeof e.aiCreatedAttribution!="object")throw TypeError(".proto.StatusAttribution.aiCreatedAttribution: object expected");a.aiCreatedAttribution=p.proto.StatusAttribution.AiCreatedAttribution.fromObject(e.aiCreatedAttribution)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.StatusAttribution.Type[e.type]===void 0?e.type:p.proto.StatusAttribution.Type[e.type]:e.type,a.oneofs&&(A._type="type")),e.actionUrl!=null&&e.hasOwnProperty("actionUrl")&&(A.actionUrl=e.actionUrl,a.oneofs&&(A._actionUrl="actionUrl")),e.statusReshare!=null&&e.hasOwnProperty("statusReshare")&&(A.statusReshare=p.proto.StatusAttribution.StatusReshare.toObject(e.statusReshare,a),a.oneofs&&(A.attributionData="statusReshare")),e.externalShare!=null&&e.hasOwnProperty("externalShare")&&(A.externalShare=p.proto.StatusAttribution.ExternalShare.toObject(e.externalShare,a),a.oneofs&&(A.attributionData="externalShare")),e.music!=null&&e.hasOwnProperty("music")&&(A.music=p.proto.StatusAttribution.Music.toObject(e.music,a),a.oneofs&&(A.attributionData="music")),e.groupStatus!=null&&e.hasOwnProperty("groupStatus")&&(A.groupStatus=p.proto.StatusAttribution.GroupStatus.toObject(e.groupStatus,a),a.oneofs&&(A.attributionData="groupStatus")),e.rlAttribution!=null&&e.hasOwnProperty("rlAttribution")&&(A.rlAttribution=p.proto.StatusAttribution.RLAttribution.toObject(e.rlAttribution,a),a.oneofs&&(A.attributionData="rlAttribution")),e.aiCreatedAttribution!=null&&e.hasOwnProperty("aiCreatedAttribution")&&(A.aiCreatedAttribution=p.proto.StatusAttribution.AiCreatedAttribution.toObject(e.aiCreatedAttribution,a),a.oneofs&&(A.attributionData="aiCreatedAttribution")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StatusAttribution"},t.AiCreatedAttribution=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.source=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.AiCreatedAttribution)return A;var r=new p.proto.StatusAttribution.AiCreatedAttribution;switch(A.source){default:if(typeof A.source=="number"){r.source=A.source;break}break;case"UNKNOWN":case 0:r.source=0;break;case"STATUS_MIMICRY":case 1:r.source=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.source!=null&&A.hasOwnProperty("source")&&(s.source=r.enums===String?p.proto.StatusAttribution.AiCreatedAttribution.Source[A.source]===void 0?A.source:p.proto.StatusAttribution.AiCreatedAttribution.Source[A.source]:A.source,r.oneofs&&(s._source="source")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.AiCreatedAttribution"},i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="STATUS_MIMICRY"]=1,A})(),i})(),t.ExternalShare=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.actionUrl=A.string();break}case 2:{c.source=A.int32();break}case 3:{c.duration=A.int32();break}case 4:{c.actionFallbackUrl=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.ExternalShare)return A;var r=new p.proto.StatusAttribution.ExternalShare;switch(A.actionUrl!=null&&(r.actionUrl=String(A.actionUrl)),A.source){default:if(typeof A.source=="number"){r.source=A.source;break}break;case"UNKNOWN":case 0:r.source=0;break;case"INSTAGRAM":case 1:r.source=1;break;case"FACEBOOK":case 2:r.source=2;break;case"MESSENGER":case 3:r.source=3;break;case"SPOTIFY":case 4:r.source=4;break;case"YOUTUBE":case 5:r.source=5;break;case"PINTEREST":case 6:r.source=6;break;case"THREADS":case 7:r.source=7;break;case"APPLE_MUSIC":case 8:r.source=8;break;case"SHARECHAT":case 9:r.source=9;break;case"GOOGLE_PHOTOS":case 10:r.source=10;break}return A.duration!=null&&(r.duration=A.duration|0),A.actionFallbackUrl!=null&&(r.actionFallbackUrl=String(A.actionFallbackUrl)),r},i.toObject=function(A,r){r||(r={});var s={};return A.actionUrl!=null&&A.hasOwnProperty("actionUrl")&&(s.actionUrl=A.actionUrl,r.oneofs&&(s._actionUrl="actionUrl")),A.source!=null&&A.hasOwnProperty("source")&&(s.source=r.enums===String?p.proto.StatusAttribution.ExternalShare.Source[A.source]===void 0?A.source:p.proto.StatusAttribution.ExternalShare.Source[A.source]:A.source,r.oneofs&&(s._source="source")),A.duration!=null&&A.hasOwnProperty("duration")&&(s.duration=A.duration,r.oneofs&&(s._duration="duration")),A.actionFallbackUrl!=null&&A.hasOwnProperty("actionFallbackUrl")&&(s.actionFallbackUrl=A.actionFallbackUrl,r.oneofs&&(s._actionFallbackUrl="actionFallbackUrl")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.ExternalShare"},i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="INSTAGRAM"]=1,A[a[2]="FACEBOOK"]=2,A[a[3]="MESSENGER"]=3,A[a[4]="SPOTIFY"]=4,A[a[5]="YOUTUBE"]=5,A[a[6]="PINTEREST"]=6,A[a[7]="THREADS"]=7,A[a[8]="APPLE_MUSIC"]=8,A[a[9]="SHARECHAT"]=9,A[a[10]="GOOGLE_PHOTOS"]=10,A})(),i})(),t.GroupStatus=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.authorJid=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.GroupStatus)return A;var r=new p.proto.StatusAttribution.GroupStatus;return A.authorJid!=null&&(r.authorJid=String(A.authorJid)),r},i.toObject=function(A,r){r||(r={});var s={};return A.authorJid!=null&&A.hasOwnProperty("authorJid")&&(s.authorJid=A.authorJid,r.oneofs&&(s._authorJid="authorJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.GroupStatus"},i})(),t.Music=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.authorName=A.string();break}case 2:{c.songId=A.string();break}case 3:{c.title=A.string();break}case 4:{c.author=A.string();break}case 5:{c.artistAttribution=A.string();break}case 6:{c.isExplicit=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.Music)return A;var r=new p.proto.StatusAttribution.Music;return A.authorName!=null&&(r.authorName=String(A.authorName)),A.songId!=null&&(r.songId=String(A.songId)),A.title!=null&&(r.title=String(A.title)),A.author!=null&&(r.author=String(A.author)),A.artistAttribution!=null&&(r.artistAttribution=String(A.artistAttribution)),A.isExplicit!=null&&(r.isExplicit=!!A.isExplicit),r},i.toObject=function(A,r){r||(r={});var s={};return A.authorName!=null&&A.hasOwnProperty("authorName")&&(s.authorName=A.authorName,r.oneofs&&(s._authorName="authorName")),A.songId!=null&&A.hasOwnProperty("songId")&&(s.songId=A.songId,r.oneofs&&(s._songId="songId")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.author!=null&&A.hasOwnProperty("author")&&(s.author=A.author,r.oneofs&&(s._author="author")),A.artistAttribution!=null&&A.hasOwnProperty("artistAttribution")&&(s.artistAttribution=A.artistAttribution,r.oneofs&&(s._artistAttribution="artistAttribution")),A.isExplicit!=null&&A.hasOwnProperty("isExplicit")&&(s.isExplicit=A.isExplicit,r.oneofs&&(s._isExplicit="isExplicit")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.Music"},i})(),t.RLAttribution=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.source=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.RLAttribution)return A;var r=new p.proto.StatusAttribution.RLAttribution;switch(A.source){default:if(typeof A.source=="number"){r.source=A.source;break}break;case"UNKNOWN":case 0:r.source=0;break;case"RAY_BAN_META_GLASSES":case 1:r.source=1;break;case"OAKLEY_META_GLASSES":case 2:r.source=2;break;case"HYPERNOVA_GLASSES":case 3:r.source=3;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.source!=null&&A.hasOwnProperty("source")&&(s.source=r.enums===String?p.proto.StatusAttribution.RLAttribution.Source[A.source]===void 0?A.source:p.proto.StatusAttribution.RLAttribution.Source[A.source]:A.source,r.oneofs&&(s._source="source")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.RLAttribution"},i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="RAY_BAN_META_GLASSES"]=1,A[a[2]="OAKLEY_META_GLASSES"]=2,A[a[3]="HYPERNOVA_GLASSES"]=3,A})(),i})(),t.StatusReshare=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.source=A.int32();break}case 2:{c.metadata=p.proto.StatusAttribution.StatusReshare.Metadata.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.StatusReshare)return A;var r=new p.proto.StatusAttribution.StatusReshare;switch(A.source){default:if(typeof A.source=="number"){r.source=A.source;break}break;case"UNKNOWN":case 0:r.source=0;break;case"INTERNAL_RESHARE":case 1:r.source=1;break;case"MENTION_RESHARE":case 2:r.source=2;break;case"CHANNEL_RESHARE":case 3:r.source=3;break;case"FORWARD":case 4:r.source=4;break}if(A.metadata!=null){if(typeof A.metadata!="object")throw TypeError(".proto.StatusAttribution.StatusReshare.metadata: object expected");r.metadata=p.proto.StatusAttribution.StatusReshare.Metadata.fromObject(A.metadata)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.source!=null&&A.hasOwnProperty("source")&&(s.source=r.enums===String?p.proto.StatusAttribution.StatusReshare.Source[A.source]===void 0?A.source:p.proto.StatusAttribution.StatusReshare.Source[A.source]:A.source,r.oneofs&&(s._source="source")),A.metadata!=null&&A.hasOwnProperty("metadata")&&(s.metadata=p.proto.StatusAttribution.StatusReshare.Metadata.toObject(A.metadata,r),r.oneofs&&(s._metadata="metadata")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.StatusReshare"},i.Metadata=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.duration=s.int32();break}case 2:{d.channelJid=s.string();break}case 3:{d.channelMessageId=s.int32();break}case 4:{d.hasMultipleReshares=s.bool();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.StatusAttribution.StatusReshare.Metadata)return s;var g=new p.proto.StatusAttribution.StatusReshare.Metadata;return s.duration!=null&&(g.duration=s.duration|0),s.channelJid!=null&&(g.channelJid=String(s.channelJid)),s.channelMessageId!=null&&(g.channelMessageId=s.channelMessageId|0),s.hasMultipleReshares!=null&&(g.hasMultipleReshares=!!s.hasMultipleReshares),g},a.toObject=function(s,g){g||(g={});var c={};return s.duration!=null&&s.hasOwnProperty("duration")&&(c.duration=s.duration,g.oneofs&&(c._duration="duration")),s.channelJid!=null&&s.hasOwnProperty("channelJid")&&(c.channelJid=s.channelJid,g.oneofs&&(c._channelJid="channelJid")),s.channelMessageId!=null&&s.hasOwnProperty("channelMessageId")&&(c.channelMessageId=s.channelMessageId,g.oneofs&&(c._channelMessageId="channelMessageId")),s.hasMultipleReshares!=null&&s.hasOwnProperty("hasMultipleReshares")&&(c.hasMultipleReshares=s.hasMultipleReshares,g.oneofs&&(c._hasMultipleReshares="hasMultipleReshares")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.StatusAttribution.StatusReshare.Metadata"},a})(),i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="INTERNAL_RESHARE"]=1,A[a[2]="MENTION_RESHARE"]=2,A[a[3]="CHANNEL_RESHARE"]=3,A[a[4]="FORWARD"]=4,A})(),i})(),t.Type=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="RESHARE"]=1,e[i[2]="EXTERNAL_SHARE"]=2,e[i[3]="MUSIC"]=3,e[i[4]="STATUS_MENTION"]=4,e[i[5]="GROUP_STATUS"]=5,e[i[6]="RL_ATTRIBUTION"]=6,e[i[7]="AI_CREATED"]=7,e[i[8]="LAYOUTS"]=8,e})(),t})(),n.StatusMentionMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.quotedStatus=p.proto.Message.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.StatusMentionMessage)return e;var a=new p.proto.StatusMentionMessage;if(e.quotedStatus!=null){if(typeof e.quotedStatus!="object")throw TypeError(".proto.StatusMentionMessage.quotedStatus: object expected");a.quotedStatus=p.proto.Message.fromObject(e.quotedStatus)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.quotedStatus!=null&&e.hasOwnProperty("quotedStatus")&&(A.quotedStatus=p.proto.Message.toObject(e.quotedStatus,a),a.oneofs&&(A._quotedStatus="quotedStatus")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StatusMentionMessage"},t})(),n.StatusPSA=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 44:{s.campaignId=e.uint64();break}case 45:{s.campaignExpirationTimestamp=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.StatusPSA)return e;var a=new p.proto.StatusPSA;return e.campaignId!=null&&(l.Long?(a.campaignId=l.Long.fromValue(e.campaignId)).unsigned=!0:typeof e.campaignId=="string"?a.campaignId=parseInt(e.campaignId,10):typeof e.campaignId=="number"?a.campaignId=e.campaignId:typeof e.campaignId=="object"&&(a.campaignId=new l.LongBits(e.campaignId.low>>>0,e.campaignId.high>>>0).toNumber(!0))),e.campaignExpirationTimestamp!=null&&(l.Long?(a.campaignExpirationTimestamp=l.Long.fromValue(e.campaignExpirationTimestamp)).unsigned=!0:typeof e.campaignExpirationTimestamp=="string"?a.campaignExpirationTimestamp=parseInt(e.campaignExpirationTimestamp,10):typeof e.campaignExpirationTimestamp=="number"?a.campaignExpirationTimestamp=e.campaignExpirationTimestamp:typeof e.campaignExpirationTimestamp=="object"&&(a.campaignExpirationTimestamp=new l.LongBits(e.campaignExpirationTimestamp.low>>>0,e.campaignExpirationTimestamp.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};if(a.defaults)if(l.Long){var r=new l.Long(0,0,!0);A.campaignId=a.longs===String?r.toString():a.longs===Number?r.toNumber():r}else A.campaignId=a.longs===String?"0":0;return e.campaignId!=null&&e.hasOwnProperty("campaignId")&&(typeof e.campaignId=="number"?A.campaignId=a.longs===String?String(e.campaignId):e.campaignId:A.campaignId=a.longs===String?se(e.campaignId,!0):a.longs===Number?ge(e.campaignId,!0):e.campaignId),e.campaignExpirationTimestamp!=null&&e.hasOwnProperty("campaignExpirationTimestamp")&&(typeof e.campaignExpirationTimestamp=="number"?A.campaignExpirationTimestamp=a.longs===String?String(e.campaignExpirationTimestamp):e.campaignExpirationTimestamp:A.campaignExpirationTimestamp=a.longs===String?se(e.campaignExpirationTimestamp,!0):a.longs===Number?ge(e.campaignExpirationTimestamp,!0):e.campaignExpirationTimestamp,a.oneofs&&(A._campaignExpirationTimestamp="campaignExpirationTimestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StatusPSA"},t})(),n.StickerMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.url=e.string();break}case 2:{s.fileSha256=e.bytes();break}case 3:{s.fileEncSha256=e.bytes();break}case 4:{s.mediaKey=e.bytes();break}case 5:{s.mimetype=e.string();break}case 6:{s.height=e.uint32();break}case 7:{s.width=e.uint32();break}case 8:{s.directPath=e.string();break}case 9:{s.fileLength=e.uint64();break}case 10:{s.weight=e.float();break}case 11:{s.lastStickerSentTs=e.int64();break}case 12:{s.isLottie=e.bool();break}case 13:{s.imageHash=e.string();break}case 14:{s.isAvatarSticker=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.StickerMetadata)return e;var a=new p.proto.StickerMetadata;return e.url!=null&&(a.url=String(e.url)),e.fileSha256!=null&&(typeof e.fileSha256=="string"?l.base64.decode(e.fileSha256,a.fileSha256=l.newBuffer(l.base64.length(e.fileSha256)),0):e.fileSha256.length>=0&&(a.fileSha256=e.fileSha256)),e.fileEncSha256!=null&&(typeof e.fileEncSha256=="string"?l.base64.decode(e.fileEncSha256,a.fileEncSha256=l.newBuffer(l.base64.length(e.fileEncSha256)),0):e.fileEncSha256.length>=0&&(a.fileEncSha256=e.fileEncSha256)),e.mediaKey!=null&&(typeof e.mediaKey=="string"?l.base64.decode(e.mediaKey,a.mediaKey=l.newBuffer(l.base64.length(e.mediaKey)),0):e.mediaKey.length>=0&&(a.mediaKey=e.mediaKey)),e.mimetype!=null&&(a.mimetype=String(e.mimetype)),e.height!=null&&(a.height=e.height>>>0),e.width!=null&&(a.width=e.width>>>0),e.directPath!=null&&(a.directPath=String(e.directPath)),e.fileLength!=null&&(l.Long?(a.fileLength=l.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new l.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),e.weight!=null&&(a.weight=Number(e.weight)),e.lastStickerSentTs!=null&&(l.Long?(a.lastStickerSentTs=l.Long.fromValue(e.lastStickerSentTs)).unsigned=!1:typeof e.lastStickerSentTs=="string"?a.lastStickerSentTs=parseInt(e.lastStickerSentTs,10):typeof e.lastStickerSentTs=="number"?a.lastStickerSentTs=e.lastStickerSentTs:typeof e.lastStickerSentTs=="object"&&(a.lastStickerSentTs=new l.LongBits(e.lastStickerSentTs.low>>>0,e.lastStickerSentTs.high>>>0).toNumber())),e.isLottie!=null&&(a.isLottie=!!e.isLottie),e.imageHash!=null&&(a.imageHash=String(e.imageHash)),e.isAvatarSticker!=null&&(a.isAvatarSticker=!!e.isAvatarSticker),a},t.toObject=function(e,a){a||(a={});var A={};return e.url!=null&&e.hasOwnProperty("url")&&(A.url=e.url,a.oneofs&&(A._url="url")),e.fileSha256!=null&&e.hasOwnProperty("fileSha256")&&(A.fileSha256=a.bytes===String?l.base64.encode(e.fileSha256,0,e.fileSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileSha256):e.fileSha256,a.oneofs&&(A._fileSha256="fileSha256")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=a.bytes===String?l.base64.encode(e.fileEncSha256,0,e.fileEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileEncSha256):e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),e.mediaKey!=null&&e.hasOwnProperty("mediaKey")&&(A.mediaKey=a.bytes===String?l.base64.encode(e.mediaKey,0,e.mediaKey.length):a.bytes===Array?Array.prototype.slice.call(e.mediaKey):e.mediaKey,a.oneofs&&(A._mediaKey="mediaKey")),e.mimetype!=null&&e.hasOwnProperty("mimetype")&&(A.mimetype=e.mimetype,a.oneofs&&(A._mimetype="mimetype")),e.height!=null&&e.hasOwnProperty("height")&&(A.height=e.height,a.oneofs&&(A._height="height")),e.width!=null&&e.hasOwnProperty("width")&&(A.width=e.width,a.oneofs&&(A._width="width")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.fileLength!=null&&e.hasOwnProperty("fileLength")&&(typeof e.fileLength=="number"?A.fileLength=a.longs===String?String(e.fileLength):e.fileLength:A.fileLength=a.longs===String?se(e.fileLength,!0):a.longs===Number?ge(e.fileLength,!0):e.fileLength,a.oneofs&&(A._fileLength="fileLength")),e.weight!=null&&e.hasOwnProperty("weight")&&(A.weight=a.json&&!isFinite(e.weight)?String(e.weight):e.weight,a.oneofs&&(A._weight="weight")),e.lastStickerSentTs!=null&&e.hasOwnProperty("lastStickerSentTs")&&(typeof e.lastStickerSentTs=="number"?A.lastStickerSentTs=a.longs===String?String(e.lastStickerSentTs):e.lastStickerSentTs:A.lastStickerSentTs=a.longs===String?se(e.lastStickerSentTs):a.longs===Number?ge(e.lastStickerSentTs):e.lastStickerSentTs,a.oneofs&&(A._lastStickerSentTs="lastStickerSentTs")),e.isLottie!=null&&e.hasOwnProperty("isLottie")&&(A.isLottie=e.isLottie,a.oneofs&&(A._isLottie="isLottie")),e.imageHash!=null&&e.hasOwnProperty("imageHash")&&(A.imageHash=e.imageHash,a.oneofs&&(A._imageHash="imageHash")),e.isAvatarSticker!=null&&e.hasOwnProperty("isAvatarSticker")&&(A.isAvatarSticker=e.isAvatarSticker,a.oneofs&&(A._isAvatarSticker="isAvatarSticker")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StickerMetadata"},t})(),n.SyncActionData=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.index=e.bytes();break}case 2:{s.value=p.proto.SyncActionValue.decode(e,e.uint32());break}case 3:{s.padding=e.bytes();break}case 4:{s.version=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncActionData)return e;var a=new p.proto.SyncActionData;if(e.index!=null&&(typeof e.index=="string"?l.base64.decode(e.index,a.index=l.newBuffer(l.base64.length(e.index)),0):e.index.length>=0&&(a.index=e.index)),e.value!=null){if(typeof e.value!="object")throw TypeError(".proto.SyncActionData.value: object expected");a.value=p.proto.SyncActionValue.fromObject(e.value)}return e.padding!=null&&(typeof e.padding=="string"?l.base64.decode(e.padding,a.padding=l.newBuffer(l.base64.length(e.padding)),0):e.padding.length>=0&&(a.padding=e.padding)),e.version!=null&&(a.version=e.version|0),a},t.toObject=function(e,a){a||(a={});var A={};return e.index!=null&&e.hasOwnProperty("index")&&(A.index=a.bytes===String?l.base64.encode(e.index,0,e.index.length):a.bytes===Array?Array.prototype.slice.call(e.index):e.index,a.oneofs&&(A._index="index")),e.value!=null&&e.hasOwnProperty("value")&&(A.value=p.proto.SyncActionValue.toObject(e.value,a),a.oneofs&&(A._value="value")),e.padding!=null&&e.hasOwnProperty("padding")&&(A.padding=a.bytes===String?l.base64.encode(e.padding,0,e.padding.length):a.bytes===Array?Array.prototype.slice.call(e.padding):e.padding,a.oneofs&&(A._padding="padding")),e.version!=null&&e.hasOwnProperty("version")&&(A.version=e.version,a.oneofs&&(A._version="version")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncActionData"},t})(),n.SyncActionValue=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.timestamp=e.int64();break}case 2:{s.starAction=p.proto.SyncActionValue.StarAction.decode(e,e.uint32());break}case 3:{s.contactAction=p.proto.SyncActionValue.ContactAction.decode(e,e.uint32());break}case 4:{s.muteAction=p.proto.SyncActionValue.MuteAction.decode(e,e.uint32());break}case 5:{s.pinAction=p.proto.SyncActionValue.PinAction.decode(e,e.uint32());break}case 7:{s.pushNameSetting=p.proto.SyncActionValue.PushNameSetting.decode(e,e.uint32());break}case 8:{s.quickReplyAction=p.proto.SyncActionValue.QuickReplyAction.decode(e,e.uint32());break}case 11:{s.recentEmojiWeightsAction=p.proto.SyncActionValue.RecentEmojiWeightsAction.decode(e,e.uint32());break}case 14:{s.labelEditAction=p.proto.SyncActionValue.LabelEditAction.decode(e,e.uint32());break}case 15:{s.labelAssociationAction=p.proto.SyncActionValue.LabelAssociationAction.decode(e,e.uint32());break}case 16:{s.localeSetting=p.proto.SyncActionValue.LocaleSetting.decode(e,e.uint32());break}case 17:{s.archiveChatAction=p.proto.SyncActionValue.ArchiveChatAction.decode(e,e.uint32());break}case 18:{s.deleteMessageForMeAction=p.proto.SyncActionValue.DeleteMessageForMeAction.decode(e,e.uint32());break}case 19:{s.keyExpiration=p.proto.SyncActionValue.KeyExpiration.decode(e,e.uint32());break}case 20:{s.markChatAsReadAction=p.proto.SyncActionValue.MarkChatAsReadAction.decode(e,e.uint32());break}case 21:{s.clearChatAction=p.proto.SyncActionValue.ClearChatAction.decode(e,e.uint32());break}case 22:{s.deleteChatAction=p.proto.SyncActionValue.DeleteChatAction.decode(e,e.uint32());break}case 23:{s.unarchiveChatsSetting=p.proto.SyncActionValue.UnarchiveChatsSetting.decode(e,e.uint32());break}case 24:{s.primaryFeature=p.proto.SyncActionValue.PrimaryFeature.decode(e,e.uint32());break}case 26:{s.androidUnsupportedActions=p.proto.SyncActionValue.AndroidUnsupportedActions.decode(e,e.uint32());break}case 27:{s.agentAction=p.proto.SyncActionValue.AgentAction.decode(e,e.uint32());break}case 28:{s.subscriptionAction=p.proto.SyncActionValue.SubscriptionAction.decode(e,e.uint32());break}case 29:{s.userStatusMuteAction=p.proto.SyncActionValue.UserStatusMuteAction.decode(e,e.uint32());break}case 30:{s.timeFormatAction=p.proto.SyncActionValue.TimeFormatAction.decode(e,e.uint32());break}case 31:{s.nuxAction=p.proto.SyncActionValue.NuxAction.decode(e,e.uint32());break}case 32:{s.primaryVersionAction=p.proto.SyncActionValue.PrimaryVersionAction.decode(e,e.uint32());break}case 33:{s.stickerAction=p.proto.SyncActionValue.StickerAction.decode(e,e.uint32());break}case 34:{s.removeRecentStickerAction=p.proto.SyncActionValue.RemoveRecentStickerAction.decode(e,e.uint32());break}case 35:{s.chatAssignment=p.proto.SyncActionValue.ChatAssignmentAction.decode(e,e.uint32());break}case 36:{s.chatAssignmentOpenedStatus=p.proto.SyncActionValue.ChatAssignmentOpenedStatusAction.decode(e,e.uint32());break}case 37:{s.pnForLidChatAction=p.proto.SyncActionValue.PnForLidChatAction.decode(e,e.uint32());break}case 38:{s.marketingMessageAction=p.proto.SyncActionValue.MarketingMessageAction.decode(e,e.uint32());break}case 39:{s.marketingMessageBroadcastAction=p.proto.SyncActionValue.MarketingMessageBroadcastAction.decode(e,e.uint32());break}case 40:{s.externalWebBetaAction=p.proto.SyncActionValue.ExternalWebBetaAction.decode(e,e.uint32());break}case 41:{s.privacySettingRelayAllCalls=p.proto.SyncActionValue.PrivacySettingRelayAllCalls.decode(e,e.uint32());break}case 42:{s.callLogAction=p.proto.SyncActionValue.CallLogAction.decode(e,e.uint32());break}case 43:{s.ugcBot=p.proto.SyncActionValue.UGCBot.decode(e,e.uint32());break}case 44:{s.statusPrivacy=p.proto.SyncActionValue.StatusPrivacyAction.decode(e,e.uint32());break}case 45:{s.botWelcomeRequestAction=p.proto.SyncActionValue.BotWelcomeRequestAction.decode(e,e.uint32());break}case 46:{s.deleteIndividualCallLog=p.proto.SyncActionValue.DeleteIndividualCallLogAction.decode(e,e.uint32());break}case 47:{s.labelReorderingAction=p.proto.SyncActionValue.LabelReorderingAction.decode(e,e.uint32());break}case 48:{s.paymentInfoAction=p.proto.SyncActionValue.PaymentInfoAction.decode(e,e.uint32());break}case 49:{s.customPaymentMethodsAction=p.proto.SyncActionValue.CustomPaymentMethodsAction.decode(e,e.uint32());break}case 50:{s.lockChatAction=p.proto.SyncActionValue.LockChatAction.decode(e,e.uint32());break}case 51:{s.chatLockSettings=p.proto.ChatLockSettings.decode(e,e.uint32());break}case 52:{s.wamoUserIdentifierAction=p.proto.SyncActionValue.WamoUserIdentifierAction.decode(e,e.uint32());break}case 53:{s.privacySettingDisableLinkPreviewsAction=p.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction.decode(e,e.uint32());break}case 54:{s.deviceCapabilities=p.proto.DeviceCapabilities.decode(e,e.uint32());break}case 55:{s.noteEditAction=p.proto.SyncActionValue.NoteEditAction.decode(e,e.uint32());break}case 56:{s.favoritesAction=p.proto.SyncActionValue.FavoritesAction.decode(e,e.uint32());break}case 57:{s.merchantPaymentPartnerAction=p.proto.SyncActionValue.MerchantPaymentPartnerAction.decode(e,e.uint32());break}case 58:{s.waffleAccountLinkStateAction=p.proto.SyncActionValue.WaffleAccountLinkStateAction.decode(e,e.uint32());break}case 59:{s.usernameChatStartMode=p.proto.SyncActionValue.UsernameChatStartModeAction.decode(e,e.uint32());break}case 60:{s.notificationActivitySettingAction=p.proto.SyncActionValue.NotificationActivitySettingAction.decode(e,e.uint32());break}case 61:{s.lidContactAction=p.proto.SyncActionValue.LidContactAction.decode(e,e.uint32());break}case 62:{s.ctwaPerCustomerDataSharingAction=p.proto.SyncActionValue.CtwaPerCustomerDataSharingAction.decode(e,e.uint32());break}case 63:{s.paymentTosAction=p.proto.SyncActionValue.PaymentTosAction.decode(e,e.uint32());break}case 64:{s.privacySettingChannelsPersonalisedRecommendationAction=p.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction.decode(e,e.uint32());break}case 65:{s.businessBroadcastAssociationAction=p.proto.SyncActionValue.BusinessBroadcastAssociationAction.decode(e,e.uint32());break}case 66:{s.detectedOutcomesStatusAction=p.proto.SyncActionValue.DetectedOutcomesStatusAction.decode(e,e.uint32());break}case 68:{s.maibaAiFeaturesControlAction=p.proto.SyncActionValue.MaibaAIFeaturesControlAction.decode(e,e.uint32());break}case 69:{s.businessBroadcastListAction=p.proto.SyncActionValue.BusinessBroadcastListAction.decode(e,e.uint32());break}case 70:{s.musicUserIdAction=p.proto.SyncActionValue.MusicUserIdAction.decode(e,e.uint32());break}case 71:{s.statusPostOptInNotificationPreferencesAction=p.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction.decode(e,e.uint32());break}case 72:{s.avatarUpdatedAction=p.proto.SyncActionValue.AvatarUpdatedAction.decode(e,e.uint32());break}case 74:{s.privateProcessingSettingAction=p.proto.SyncActionValue.PrivateProcessingSettingAction.decode(e,e.uint32());break}case 75:{s.newsletterSavedInterestsAction=p.proto.SyncActionValue.NewsletterSavedInterestsAction.decode(e,e.uint32());break}case 76:{s.aiThreadRenameAction=p.proto.SyncActionValue.AiThreadRenameAction.decode(e,e.uint32());break}case 77:{s.interactiveMessageAction=p.proto.SyncActionValue.InteractiveMessageAction.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncActionValue)return e;var a=new p.proto.SyncActionValue;if(e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),e.starAction!=null){if(typeof e.starAction!="object")throw TypeError(".proto.SyncActionValue.starAction: object expected");a.starAction=p.proto.SyncActionValue.StarAction.fromObject(e.starAction)}if(e.contactAction!=null){if(typeof e.contactAction!="object")throw TypeError(".proto.SyncActionValue.contactAction: object expected");a.contactAction=p.proto.SyncActionValue.ContactAction.fromObject(e.contactAction)}if(e.muteAction!=null){if(typeof e.muteAction!="object")throw TypeError(".proto.SyncActionValue.muteAction: object expected");a.muteAction=p.proto.SyncActionValue.MuteAction.fromObject(e.muteAction)}if(e.pinAction!=null){if(typeof e.pinAction!="object")throw TypeError(".proto.SyncActionValue.pinAction: object expected");a.pinAction=p.proto.SyncActionValue.PinAction.fromObject(e.pinAction)}if(e.pushNameSetting!=null){if(typeof e.pushNameSetting!="object")throw TypeError(".proto.SyncActionValue.pushNameSetting: object expected");a.pushNameSetting=p.proto.SyncActionValue.PushNameSetting.fromObject(e.pushNameSetting)}if(e.quickReplyAction!=null){if(typeof e.quickReplyAction!="object")throw TypeError(".proto.SyncActionValue.quickReplyAction: object expected");a.quickReplyAction=p.proto.SyncActionValue.QuickReplyAction.fromObject(e.quickReplyAction)}if(e.recentEmojiWeightsAction!=null){if(typeof e.recentEmojiWeightsAction!="object")throw TypeError(".proto.SyncActionValue.recentEmojiWeightsAction: object expected");a.recentEmojiWeightsAction=p.proto.SyncActionValue.RecentEmojiWeightsAction.fromObject(e.recentEmojiWeightsAction)}if(e.labelEditAction!=null){if(typeof e.labelEditAction!="object")throw TypeError(".proto.SyncActionValue.labelEditAction: object expected");a.labelEditAction=p.proto.SyncActionValue.LabelEditAction.fromObject(e.labelEditAction)}if(e.labelAssociationAction!=null){if(typeof e.labelAssociationAction!="object")throw TypeError(".proto.SyncActionValue.labelAssociationAction: object expected");a.labelAssociationAction=p.proto.SyncActionValue.LabelAssociationAction.fromObject(e.labelAssociationAction)}if(e.localeSetting!=null){if(typeof e.localeSetting!="object")throw TypeError(".proto.SyncActionValue.localeSetting: object expected");a.localeSetting=p.proto.SyncActionValue.LocaleSetting.fromObject(e.localeSetting)}if(e.archiveChatAction!=null){if(typeof e.archiveChatAction!="object")throw TypeError(".proto.SyncActionValue.archiveChatAction: object expected");a.archiveChatAction=p.proto.SyncActionValue.ArchiveChatAction.fromObject(e.archiveChatAction)}if(e.deleteMessageForMeAction!=null){if(typeof e.deleteMessageForMeAction!="object")throw TypeError(".proto.SyncActionValue.deleteMessageForMeAction: object expected");a.deleteMessageForMeAction=p.proto.SyncActionValue.DeleteMessageForMeAction.fromObject(e.deleteMessageForMeAction)}if(e.keyExpiration!=null){if(typeof e.keyExpiration!="object")throw TypeError(".proto.SyncActionValue.keyExpiration: object expected");a.keyExpiration=p.proto.SyncActionValue.KeyExpiration.fromObject(e.keyExpiration)}if(e.markChatAsReadAction!=null){if(typeof e.markChatAsReadAction!="object")throw TypeError(".proto.SyncActionValue.markChatAsReadAction: object expected");a.markChatAsReadAction=p.proto.SyncActionValue.MarkChatAsReadAction.fromObject(e.markChatAsReadAction)}if(e.clearChatAction!=null){if(typeof e.clearChatAction!="object")throw TypeError(".proto.SyncActionValue.clearChatAction: object expected");a.clearChatAction=p.proto.SyncActionValue.ClearChatAction.fromObject(e.clearChatAction)}if(e.deleteChatAction!=null){if(typeof e.deleteChatAction!="object")throw TypeError(".proto.SyncActionValue.deleteChatAction: object expected");a.deleteChatAction=p.proto.SyncActionValue.DeleteChatAction.fromObject(e.deleteChatAction)}if(e.unarchiveChatsSetting!=null){if(typeof e.unarchiveChatsSetting!="object")throw TypeError(".proto.SyncActionValue.unarchiveChatsSetting: object expected");a.unarchiveChatsSetting=p.proto.SyncActionValue.UnarchiveChatsSetting.fromObject(e.unarchiveChatsSetting)}if(e.primaryFeature!=null){if(typeof e.primaryFeature!="object")throw TypeError(".proto.SyncActionValue.primaryFeature: object expected");a.primaryFeature=p.proto.SyncActionValue.PrimaryFeature.fromObject(e.primaryFeature)}if(e.androidUnsupportedActions!=null){if(typeof e.androidUnsupportedActions!="object")throw TypeError(".proto.SyncActionValue.androidUnsupportedActions: object expected");a.androidUnsupportedActions=p.proto.SyncActionValue.AndroidUnsupportedActions.fromObject(e.androidUnsupportedActions)}if(e.agentAction!=null){if(typeof e.agentAction!="object")throw TypeError(".proto.SyncActionValue.agentAction: object expected");a.agentAction=p.proto.SyncActionValue.AgentAction.fromObject(e.agentAction)}if(e.subscriptionAction!=null){if(typeof e.subscriptionAction!="object")throw TypeError(".proto.SyncActionValue.subscriptionAction: object expected");a.subscriptionAction=p.proto.SyncActionValue.SubscriptionAction.fromObject(e.subscriptionAction)}if(e.userStatusMuteAction!=null){if(typeof e.userStatusMuteAction!="object")throw TypeError(".proto.SyncActionValue.userStatusMuteAction: object expected");a.userStatusMuteAction=p.proto.SyncActionValue.UserStatusMuteAction.fromObject(e.userStatusMuteAction)}if(e.timeFormatAction!=null){if(typeof e.timeFormatAction!="object")throw TypeError(".proto.SyncActionValue.timeFormatAction: object expected");a.timeFormatAction=p.proto.SyncActionValue.TimeFormatAction.fromObject(e.timeFormatAction)}if(e.nuxAction!=null){if(typeof e.nuxAction!="object")throw TypeError(".proto.SyncActionValue.nuxAction: object expected");a.nuxAction=p.proto.SyncActionValue.NuxAction.fromObject(e.nuxAction)}if(e.primaryVersionAction!=null){if(typeof e.primaryVersionAction!="object")throw TypeError(".proto.SyncActionValue.primaryVersionAction: object expected");a.primaryVersionAction=p.proto.SyncActionValue.PrimaryVersionAction.fromObject(e.primaryVersionAction)}if(e.stickerAction!=null){if(typeof e.stickerAction!="object")throw TypeError(".proto.SyncActionValue.stickerAction: object expected");a.stickerAction=p.proto.SyncActionValue.StickerAction.fromObject(e.stickerAction)}if(e.removeRecentStickerAction!=null){if(typeof e.removeRecentStickerAction!="object")throw TypeError(".proto.SyncActionValue.removeRecentStickerAction: object expected");a.removeRecentStickerAction=p.proto.SyncActionValue.RemoveRecentStickerAction.fromObject(e.removeRecentStickerAction)}if(e.chatAssignment!=null){if(typeof e.chatAssignment!="object")throw TypeError(".proto.SyncActionValue.chatAssignment: object expected");a.chatAssignment=p.proto.SyncActionValue.ChatAssignmentAction.fromObject(e.chatAssignment)}if(e.chatAssignmentOpenedStatus!=null){if(typeof e.chatAssignmentOpenedStatus!="object")throw TypeError(".proto.SyncActionValue.chatAssignmentOpenedStatus: object expected");a.chatAssignmentOpenedStatus=p.proto.SyncActionValue.ChatAssignmentOpenedStatusAction.fromObject(e.chatAssignmentOpenedStatus)}if(e.pnForLidChatAction!=null){if(typeof e.pnForLidChatAction!="object")throw TypeError(".proto.SyncActionValue.pnForLidChatAction: object expected");a.pnForLidChatAction=p.proto.SyncActionValue.PnForLidChatAction.fromObject(e.pnForLidChatAction)}if(e.marketingMessageAction!=null){if(typeof e.marketingMessageAction!="object")throw TypeError(".proto.SyncActionValue.marketingMessageAction: object expected");a.marketingMessageAction=p.proto.SyncActionValue.MarketingMessageAction.fromObject(e.marketingMessageAction)}if(e.marketingMessageBroadcastAction!=null){if(typeof e.marketingMessageBroadcastAction!="object")throw TypeError(".proto.SyncActionValue.marketingMessageBroadcastAction: object expected");a.marketingMessageBroadcastAction=p.proto.SyncActionValue.MarketingMessageBroadcastAction.fromObject(e.marketingMessageBroadcastAction)}if(e.externalWebBetaAction!=null){if(typeof e.externalWebBetaAction!="object")throw TypeError(".proto.SyncActionValue.externalWebBetaAction: object expected");a.externalWebBetaAction=p.proto.SyncActionValue.ExternalWebBetaAction.fromObject(e.externalWebBetaAction)}if(e.privacySettingRelayAllCalls!=null){if(typeof e.privacySettingRelayAllCalls!="object")throw TypeError(".proto.SyncActionValue.privacySettingRelayAllCalls: object expected");a.privacySettingRelayAllCalls=p.proto.SyncActionValue.PrivacySettingRelayAllCalls.fromObject(e.privacySettingRelayAllCalls)}if(e.callLogAction!=null){if(typeof e.callLogAction!="object")throw TypeError(".proto.SyncActionValue.callLogAction: object expected");a.callLogAction=p.proto.SyncActionValue.CallLogAction.fromObject(e.callLogAction)}if(e.ugcBot!=null){if(typeof e.ugcBot!="object")throw TypeError(".proto.SyncActionValue.ugcBot: object expected");a.ugcBot=p.proto.SyncActionValue.UGCBot.fromObject(e.ugcBot)}if(e.statusPrivacy!=null){if(typeof e.statusPrivacy!="object")throw TypeError(".proto.SyncActionValue.statusPrivacy: object expected");a.statusPrivacy=p.proto.SyncActionValue.StatusPrivacyAction.fromObject(e.statusPrivacy)}if(e.botWelcomeRequestAction!=null){if(typeof e.botWelcomeRequestAction!="object")throw TypeError(".proto.SyncActionValue.botWelcomeRequestAction: object expected");a.botWelcomeRequestAction=p.proto.SyncActionValue.BotWelcomeRequestAction.fromObject(e.botWelcomeRequestAction)}if(e.deleteIndividualCallLog!=null){if(typeof e.deleteIndividualCallLog!="object")throw TypeError(".proto.SyncActionValue.deleteIndividualCallLog: object expected");a.deleteIndividualCallLog=p.proto.SyncActionValue.DeleteIndividualCallLogAction.fromObject(e.deleteIndividualCallLog)}if(e.labelReorderingAction!=null){if(typeof e.labelReorderingAction!="object")throw TypeError(".proto.SyncActionValue.labelReorderingAction: object expected");a.labelReorderingAction=p.proto.SyncActionValue.LabelReorderingAction.fromObject(e.labelReorderingAction)}if(e.paymentInfoAction!=null){if(typeof e.paymentInfoAction!="object")throw TypeError(".proto.SyncActionValue.paymentInfoAction: object expected");a.paymentInfoAction=p.proto.SyncActionValue.PaymentInfoAction.fromObject(e.paymentInfoAction)}if(e.customPaymentMethodsAction!=null){if(typeof e.customPaymentMethodsAction!="object")throw TypeError(".proto.SyncActionValue.customPaymentMethodsAction: object expected");a.customPaymentMethodsAction=p.proto.SyncActionValue.CustomPaymentMethodsAction.fromObject(e.customPaymentMethodsAction)}if(e.lockChatAction!=null){if(typeof e.lockChatAction!="object")throw TypeError(".proto.SyncActionValue.lockChatAction: object expected");a.lockChatAction=p.proto.SyncActionValue.LockChatAction.fromObject(e.lockChatAction)}if(e.chatLockSettings!=null){if(typeof e.chatLockSettings!="object")throw TypeError(".proto.SyncActionValue.chatLockSettings: object expected");a.chatLockSettings=p.proto.ChatLockSettings.fromObject(e.chatLockSettings)}if(e.wamoUserIdentifierAction!=null){if(typeof e.wamoUserIdentifierAction!="object")throw TypeError(".proto.SyncActionValue.wamoUserIdentifierAction: object expected");a.wamoUserIdentifierAction=p.proto.SyncActionValue.WamoUserIdentifierAction.fromObject(e.wamoUserIdentifierAction)}if(e.privacySettingDisableLinkPreviewsAction!=null){if(typeof e.privacySettingDisableLinkPreviewsAction!="object")throw TypeError(".proto.SyncActionValue.privacySettingDisableLinkPreviewsAction: object expected");a.privacySettingDisableLinkPreviewsAction=p.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction.fromObject(e.privacySettingDisableLinkPreviewsAction)}if(e.deviceCapabilities!=null){if(typeof e.deviceCapabilities!="object")throw TypeError(".proto.SyncActionValue.deviceCapabilities: object expected");a.deviceCapabilities=p.proto.DeviceCapabilities.fromObject(e.deviceCapabilities)}if(e.noteEditAction!=null){if(typeof e.noteEditAction!="object")throw TypeError(".proto.SyncActionValue.noteEditAction: object expected");a.noteEditAction=p.proto.SyncActionValue.NoteEditAction.fromObject(e.noteEditAction)}if(e.favoritesAction!=null){if(typeof e.favoritesAction!="object")throw TypeError(".proto.SyncActionValue.favoritesAction: object expected");a.favoritesAction=p.proto.SyncActionValue.FavoritesAction.fromObject(e.favoritesAction)}if(e.merchantPaymentPartnerAction!=null){if(typeof e.merchantPaymentPartnerAction!="object")throw TypeError(".proto.SyncActionValue.merchantPaymentPartnerAction: object expected");a.merchantPaymentPartnerAction=p.proto.SyncActionValue.MerchantPaymentPartnerAction.fromObject(e.merchantPaymentPartnerAction)}if(e.waffleAccountLinkStateAction!=null){if(typeof e.waffleAccountLinkStateAction!="object")throw TypeError(".proto.SyncActionValue.waffleAccountLinkStateAction: object expected");a.waffleAccountLinkStateAction=p.proto.SyncActionValue.WaffleAccountLinkStateAction.fromObject(e.waffleAccountLinkStateAction)}if(e.usernameChatStartMode!=null){if(typeof e.usernameChatStartMode!="object")throw TypeError(".proto.SyncActionValue.usernameChatStartMode: object expected");a.usernameChatStartMode=p.proto.SyncActionValue.UsernameChatStartModeAction.fromObject(e.usernameChatStartMode)}if(e.notificationActivitySettingAction!=null){if(typeof e.notificationActivitySettingAction!="object")throw TypeError(".proto.SyncActionValue.notificationActivitySettingAction: object expected");a.notificationActivitySettingAction=p.proto.SyncActionValue.NotificationActivitySettingAction.fromObject(e.notificationActivitySettingAction)}if(e.lidContactAction!=null){if(typeof e.lidContactAction!="object")throw TypeError(".proto.SyncActionValue.lidContactAction: object expected");a.lidContactAction=p.proto.SyncActionValue.LidContactAction.fromObject(e.lidContactAction)}if(e.ctwaPerCustomerDataSharingAction!=null){if(typeof e.ctwaPerCustomerDataSharingAction!="object")throw TypeError(".proto.SyncActionValue.ctwaPerCustomerDataSharingAction: object expected");a.ctwaPerCustomerDataSharingAction=p.proto.SyncActionValue.CtwaPerCustomerDataSharingAction.fromObject(e.ctwaPerCustomerDataSharingAction)}if(e.paymentTosAction!=null){if(typeof e.paymentTosAction!="object")throw TypeError(".proto.SyncActionValue.paymentTosAction: object expected");a.paymentTosAction=p.proto.SyncActionValue.PaymentTosAction.fromObject(e.paymentTosAction)}if(e.privacySettingChannelsPersonalisedRecommendationAction!=null){if(typeof e.privacySettingChannelsPersonalisedRecommendationAction!="object")throw TypeError(".proto.SyncActionValue.privacySettingChannelsPersonalisedRecommendationAction: object expected");a.privacySettingChannelsPersonalisedRecommendationAction=p.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction.fromObject(e.privacySettingChannelsPersonalisedRecommendationAction)}if(e.businessBroadcastAssociationAction!=null){if(typeof e.businessBroadcastAssociationAction!="object")throw TypeError(".proto.SyncActionValue.businessBroadcastAssociationAction: object expected");a.businessBroadcastAssociationAction=p.proto.SyncActionValue.BusinessBroadcastAssociationAction.fromObject(e.businessBroadcastAssociationAction)}if(e.detectedOutcomesStatusAction!=null){if(typeof e.detectedOutcomesStatusAction!="object")throw TypeError(".proto.SyncActionValue.detectedOutcomesStatusAction: object expected");a.detectedOutcomesStatusAction=p.proto.SyncActionValue.DetectedOutcomesStatusAction.fromObject(e.detectedOutcomesStatusAction)}if(e.maibaAiFeaturesControlAction!=null){if(typeof e.maibaAiFeaturesControlAction!="object")throw TypeError(".proto.SyncActionValue.maibaAiFeaturesControlAction: object expected");a.maibaAiFeaturesControlAction=p.proto.SyncActionValue.MaibaAIFeaturesControlAction.fromObject(e.maibaAiFeaturesControlAction)}if(e.businessBroadcastListAction!=null){if(typeof e.businessBroadcastListAction!="object")throw TypeError(".proto.SyncActionValue.businessBroadcastListAction: object expected");a.businessBroadcastListAction=p.proto.SyncActionValue.BusinessBroadcastListAction.fromObject(e.businessBroadcastListAction)}if(e.musicUserIdAction!=null){if(typeof e.musicUserIdAction!="object")throw TypeError(".proto.SyncActionValue.musicUserIdAction: object expected");a.musicUserIdAction=p.proto.SyncActionValue.MusicUserIdAction.fromObject(e.musicUserIdAction)}if(e.statusPostOptInNotificationPreferencesAction!=null){if(typeof e.statusPostOptInNotificationPreferencesAction!="object")throw TypeError(".proto.SyncActionValue.statusPostOptInNotificationPreferencesAction: object expected");a.statusPostOptInNotificationPreferencesAction=p.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction.fromObject(e.statusPostOptInNotificationPreferencesAction)}if(e.avatarUpdatedAction!=null){if(typeof e.avatarUpdatedAction!="object")throw TypeError(".proto.SyncActionValue.avatarUpdatedAction: object expected");a.avatarUpdatedAction=p.proto.SyncActionValue.AvatarUpdatedAction.fromObject(e.avatarUpdatedAction)}if(e.privateProcessingSettingAction!=null){if(typeof e.privateProcessingSettingAction!="object")throw TypeError(".proto.SyncActionValue.privateProcessingSettingAction: object expected");a.privateProcessingSettingAction=p.proto.SyncActionValue.PrivateProcessingSettingAction.fromObject(e.privateProcessingSettingAction)}if(e.newsletterSavedInterestsAction!=null){if(typeof e.newsletterSavedInterestsAction!="object")throw TypeError(".proto.SyncActionValue.newsletterSavedInterestsAction: object expected");a.newsletterSavedInterestsAction=p.proto.SyncActionValue.NewsletterSavedInterestsAction.fromObject(e.newsletterSavedInterestsAction)}if(e.aiThreadRenameAction!=null){if(typeof e.aiThreadRenameAction!="object")throw TypeError(".proto.SyncActionValue.aiThreadRenameAction: object expected");a.aiThreadRenameAction=p.proto.SyncActionValue.AiThreadRenameAction.fromObject(e.aiThreadRenameAction)}if(e.interactiveMessageAction!=null){if(typeof e.interactiveMessageAction!="object")throw TypeError(".proto.SyncActionValue.interactiveMessageAction: object expected");a.interactiveMessageAction=p.proto.SyncActionValue.InteractiveMessageAction.fromObject(e.interactiveMessageAction)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp):a.longs===Number?ge(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),e.starAction!=null&&e.hasOwnProperty("starAction")&&(A.starAction=p.proto.SyncActionValue.StarAction.toObject(e.starAction,a),a.oneofs&&(A._starAction="starAction")),e.contactAction!=null&&e.hasOwnProperty("contactAction")&&(A.contactAction=p.proto.SyncActionValue.ContactAction.toObject(e.contactAction,a),a.oneofs&&(A._contactAction="contactAction")),e.muteAction!=null&&e.hasOwnProperty("muteAction")&&(A.muteAction=p.proto.SyncActionValue.MuteAction.toObject(e.muteAction,a),a.oneofs&&(A._muteAction="muteAction")),e.pinAction!=null&&e.hasOwnProperty("pinAction")&&(A.pinAction=p.proto.SyncActionValue.PinAction.toObject(e.pinAction,a),a.oneofs&&(A._pinAction="pinAction")),e.pushNameSetting!=null&&e.hasOwnProperty("pushNameSetting")&&(A.pushNameSetting=p.proto.SyncActionValue.PushNameSetting.toObject(e.pushNameSetting,a),a.oneofs&&(A._pushNameSetting="pushNameSetting")),e.quickReplyAction!=null&&e.hasOwnProperty("quickReplyAction")&&(A.quickReplyAction=p.proto.SyncActionValue.QuickReplyAction.toObject(e.quickReplyAction,a),a.oneofs&&(A._quickReplyAction="quickReplyAction")),e.recentEmojiWeightsAction!=null&&e.hasOwnProperty("recentEmojiWeightsAction")&&(A.recentEmojiWeightsAction=p.proto.SyncActionValue.RecentEmojiWeightsAction.toObject(e.recentEmojiWeightsAction,a),a.oneofs&&(A._recentEmojiWeightsAction="recentEmojiWeightsAction")),e.labelEditAction!=null&&e.hasOwnProperty("labelEditAction")&&(A.labelEditAction=p.proto.SyncActionValue.LabelEditAction.toObject(e.labelEditAction,a),a.oneofs&&(A._labelEditAction="labelEditAction")),e.labelAssociationAction!=null&&e.hasOwnProperty("labelAssociationAction")&&(A.labelAssociationAction=p.proto.SyncActionValue.LabelAssociationAction.toObject(e.labelAssociationAction,a),a.oneofs&&(A._labelAssociationAction="labelAssociationAction")),e.localeSetting!=null&&e.hasOwnProperty("localeSetting")&&(A.localeSetting=p.proto.SyncActionValue.LocaleSetting.toObject(e.localeSetting,a),a.oneofs&&(A._localeSetting="localeSetting")),e.archiveChatAction!=null&&e.hasOwnProperty("archiveChatAction")&&(A.archiveChatAction=p.proto.SyncActionValue.ArchiveChatAction.toObject(e.archiveChatAction,a),a.oneofs&&(A._archiveChatAction="archiveChatAction")),e.deleteMessageForMeAction!=null&&e.hasOwnProperty("deleteMessageForMeAction")&&(A.deleteMessageForMeAction=p.proto.SyncActionValue.DeleteMessageForMeAction.toObject(e.deleteMessageForMeAction,a),a.oneofs&&(A._deleteMessageForMeAction="deleteMessageForMeAction")),e.keyExpiration!=null&&e.hasOwnProperty("keyExpiration")&&(A.keyExpiration=p.proto.SyncActionValue.KeyExpiration.toObject(e.keyExpiration,a),a.oneofs&&(A._keyExpiration="keyExpiration")),e.markChatAsReadAction!=null&&e.hasOwnProperty("markChatAsReadAction")&&(A.markChatAsReadAction=p.proto.SyncActionValue.MarkChatAsReadAction.toObject(e.markChatAsReadAction,a),a.oneofs&&(A._markChatAsReadAction="markChatAsReadAction")),e.clearChatAction!=null&&e.hasOwnProperty("clearChatAction")&&(A.clearChatAction=p.proto.SyncActionValue.ClearChatAction.toObject(e.clearChatAction,a),a.oneofs&&(A._clearChatAction="clearChatAction")),e.deleteChatAction!=null&&e.hasOwnProperty("deleteChatAction")&&(A.deleteChatAction=p.proto.SyncActionValue.DeleteChatAction.toObject(e.deleteChatAction,a),a.oneofs&&(A._deleteChatAction="deleteChatAction")),e.unarchiveChatsSetting!=null&&e.hasOwnProperty("unarchiveChatsSetting")&&(A.unarchiveChatsSetting=p.proto.SyncActionValue.UnarchiveChatsSetting.toObject(e.unarchiveChatsSetting,a),a.oneofs&&(A._unarchiveChatsSetting="unarchiveChatsSetting")),e.primaryFeature!=null&&e.hasOwnProperty("primaryFeature")&&(A.primaryFeature=p.proto.SyncActionValue.PrimaryFeature.toObject(e.primaryFeature,a),a.oneofs&&(A._primaryFeature="primaryFeature")),e.androidUnsupportedActions!=null&&e.hasOwnProperty("androidUnsupportedActions")&&(A.androidUnsupportedActions=p.proto.SyncActionValue.AndroidUnsupportedActions.toObject(e.androidUnsupportedActions,a),a.oneofs&&(A._androidUnsupportedActions="androidUnsupportedActions")),e.agentAction!=null&&e.hasOwnProperty("agentAction")&&(A.agentAction=p.proto.SyncActionValue.AgentAction.toObject(e.agentAction,a),a.oneofs&&(A._agentAction="agentAction")),e.subscriptionAction!=null&&e.hasOwnProperty("subscriptionAction")&&(A.subscriptionAction=p.proto.SyncActionValue.SubscriptionAction.toObject(e.subscriptionAction,a),a.oneofs&&(A._subscriptionAction="subscriptionAction")),e.userStatusMuteAction!=null&&e.hasOwnProperty("userStatusMuteAction")&&(A.userStatusMuteAction=p.proto.SyncActionValue.UserStatusMuteAction.toObject(e.userStatusMuteAction,a),a.oneofs&&(A._userStatusMuteAction="userStatusMuteAction")),e.timeFormatAction!=null&&e.hasOwnProperty("timeFormatAction")&&(A.timeFormatAction=p.proto.SyncActionValue.TimeFormatAction.toObject(e.timeFormatAction,a),a.oneofs&&(A._timeFormatAction="timeFormatAction")),e.nuxAction!=null&&e.hasOwnProperty("nuxAction")&&(A.nuxAction=p.proto.SyncActionValue.NuxAction.toObject(e.nuxAction,a),a.oneofs&&(A._nuxAction="nuxAction")),e.primaryVersionAction!=null&&e.hasOwnProperty("primaryVersionAction")&&(A.primaryVersionAction=p.proto.SyncActionValue.PrimaryVersionAction.toObject(e.primaryVersionAction,a),a.oneofs&&(A._primaryVersionAction="primaryVersionAction")),e.stickerAction!=null&&e.hasOwnProperty("stickerAction")&&(A.stickerAction=p.proto.SyncActionValue.StickerAction.toObject(e.stickerAction,a),a.oneofs&&(A._stickerAction="stickerAction")),e.removeRecentStickerAction!=null&&e.hasOwnProperty("removeRecentStickerAction")&&(A.removeRecentStickerAction=p.proto.SyncActionValue.RemoveRecentStickerAction.toObject(e.removeRecentStickerAction,a),a.oneofs&&(A._removeRecentStickerAction="removeRecentStickerAction")),e.chatAssignment!=null&&e.hasOwnProperty("chatAssignment")&&(A.chatAssignment=p.proto.SyncActionValue.ChatAssignmentAction.toObject(e.chatAssignment,a),a.oneofs&&(A._chatAssignment="chatAssignment")),e.chatAssignmentOpenedStatus!=null&&e.hasOwnProperty("chatAssignmentOpenedStatus")&&(A.chatAssignmentOpenedStatus=p.proto.SyncActionValue.ChatAssignmentOpenedStatusAction.toObject(e.chatAssignmentOpenedStatus,a),a.oneofs&&(A._chatAssignmentOpenedStatus="chatAssignmentOpenedStatus")),e.pnForLidChatAction!=null&&e.hasOwnProperty("pnForLidChatAction")&&(A.pnForLidChatAction=p.proto.SyncActionValue.PnForLidChatAction.toObject(e.pnForLidChatAction,a),a.oneofs&&(A._pnForLidChatAction="pnForLidChatAction")),e.marketingMessageAction!=null&&e.hasOwnProperty("marketingMessageAction")&&(A.marketingMessageAction=p.proto.SyncActionValue.MarketingMessageAction.toObject(e.marketingMessageAction,a),a.oneofs&&(A._marketingMessageAction="marketingMessageAction")),e.marketingMessageBroadcastAction!=null&&e.hasOwnProperty("marketingMessageBroadcastAction")&&(A.marketingMessageBroadcastAction=p.proto.SyncActionValue.MarketingMessageBroadcastAction.toObject(e.marketingMessageBroadcastAction,a),a.oneofs&&(A._marketingMessageBroadcastAction="marketingMessageBroadcastAction")),e.externalWebBetaAction!=null&&e.hasOwnProperty("externalWebBetaAction")&&(A.externalWebBetaAction=p.proto.SyncActionValue.ExternalWebBetaAction.toObject(e.externalWebBetaAction,a),a.oneofs&&(A._externalWebBetaAction="externalWebBetaAction")),e.privacySettingRelayAllCalls!=null&&e.hasOwnProperty("privacySettingRelayAllCalls")&&(A.privacySettingRelayAllCalls=p.proto.SyncActionValue.PrivacySettingRelayAllCalls.toObject(e.privacySettingRelayAllCalls,a),a.oneofs&&(A._privacySettingRelayAllCalls="privacySettingRelayAllCalls")),e.callLogAction!=null&&e.hasOwnProperty("callLogAction")&&(A.callLogAction=p.proto.SyncActionValue.CallLogAction.toObject(e.callLogAction,a),a.oneofs&&(A._callLogAction="callLogAction")),e.ugcBot!=null&&e.hasOwnProperty("ugcBot")&&(A.ugcBot=p.proto.SyncActionValue.UGCBot.toObject(e.ugcBot,a),a.oneofs&&(A._ugcBot="ugcBot")),e.statusPrivacy!=null&&e.hasOwnProperty("statusPrivacy")&&(A.statusPrivacy=p.proto.SyncActionValue.StatusPrivacyAction.toObject(e.statusPrivacy,a),a.oneofs&&(A._statusPrivacy="statusPrivacy")),e.botWelcomeRequestAction!=null&&e.hasOwnProperty("botWelcomeRequestAction")&&(A.botWelcomeRequestAction=p.proto.SyncActionValue.BotWelcomeRequestAction.toObject(e.botWelcomeRequestAction,a),a.oneofs&&(A._botWelcomeRequestAction="botWelcomeRequestAction")),e.deleteIndividualCallLog!=null&&e.hasOwnProperty("deleteIndividualCallLog")&&(A.deleteIndividualCallLog=p.proto.SyncActionValue.DeleteIndividualCallLogAction.toObject(e.deleteIndividualCallLog,a),a.oneofs&&(A._deleteIndividualCallLog="deleteIndividualCallLog")),e.labelReorderingAction!=null&&e.hasOwnProperty("labelReorderingAction")&&(A.labelReorderingAction=p.proto.SyncActionValue.LabelReorderingAction.toObject(e.labelReorderingAction,a),a.oneofs&&(A._labelReorderingAction="labelReorderingAction")),e.paymentInfoAction!=null&&e.hasOwnProperty("paymentInfoAction")&&(A.paymentInfoAction=p.proto.SyncActionValue.PaymentInfoAction.toObject(e.paymentInfoAction,a),a.oneofs&&(A._paymentInfoAction="paymentInfoAction")),e.customPaymentMethodsAction!=null&&e.hasOwnProperty("customPaymentMethodsAction")&&(A.customPaymentMethodsAction=p.proto.SyncActionValue.CustomPaymentMethodsAction.toObject(e.customPaymentMethodsAction,a),a.oneofs&&(A._customPaymentMethodsAction="customPaymentMethodsAction")),e.lockChatAction!=null&&e.hasOwnProperty("lockChatAction")&&(A.lockChatAction=p.proto.SyncActionValue.LockChatAction.toObject(e.lockChatAction,a),a.oneofs&&(A._lockChatAction="lockChatAction")),e.chatLockSettings!=null&&e.hasOwnProperty("chatLockSettings")&&(A.chatLockSettings=p.proto.ChatLockSettings.toObject(e.chatLockSettings,a),a.oneofs&&(A._chatLockSettings="chatLockSettings")),e.wamoUserIdentifierAction!=null&&e.hasOwnProperty("wamoUserIdentifierAction")&&(A.wamoUserIdentifierAction=p.proto.SyncActionValue.WamoUserIdentifierAction.toObject(e.wamoUserIdentifierAction,a),a.oneofs&&(A._wamoUserIdentifierAction="wamoUserIdentifierAction")),e.privacySettingDisableLinkPreviewsAction!=null&&e.hasOwnProperty("privacySettingDisableLinkPreviewsAction")&&(A.privacySettingDisableLinkPreviewsAction=p.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction.toObject(e.privacySettingDisableLinkPreviewsAction,a),a.oneofs&&(A._privacySettingDisableLinkPreviewsAction="privacySettingDisableLinkPreviewsAction")),e.deviceCapabilities!=null&&e.hasOwnProperty("deviceCapabilities")&&(A.deviceCapabilities=p.proto.DeviceCapabilities.toObject(e.deviceCapabilities,a),a.oneofs&&(A._deviceCapabilities="deviceCapabilities")),e.noteEditAction!=null&&e.hasOwnProperty("noteEditAction")&&(A.noteEditAction=p.proto.SyncActionValue.NoteEditAction.toObject(e.noteEditAction,a),a.oneofs&&(A._noteEditAction="noteEditAction")),e.favoritesAction!=null&&e.hasOwnProperty("favoritesAction")&&(A.favoritesAction=p.proto.SyncActionValue.FavoritesAction.toObject(e.favoritesAction,a),a.oneofs&&(A._favoritesAction="favoritesAction")),e.merchantPaymentPartnerAction!=null&&e.hasOwnProperty("merchantPaymentPartnerAction")&&(A.merchantPaymentPartnerAction=p.proto.SyncActionValue.MerchantPaymentPartnerAction.toObject(e.merchantPaymentPartnerAction,a),a.oneofs&&(A._merchantPaymentPartnerAction="merchantPaymentPartnerAction")),e.waffleAccountLinkStateAction!=null&&e.hasOwnProperty("waffleAccountLinkStateAction")&&(A.waffleAccountLinkStateAction=p.proto.SyncActionValue.WaffleAccountLinkStateAction.toObject(e.waffleAccountLinkStateAction,a),a.oneofs&&(A._waffleAccountLinkStateAction="waffleAccountLinkStateAction")),e.usernameChatStartMode!=null&&e.hasOwnProperty("usernameChatStartMode")&&(A.usernameChatStartMode=p.proto.SyncActionValue.UsernameChatStartModeAction.toObject(e.usernameChatStartMode,a),a.oneofs&&(A._usernameChatStartMode="usernameChatStartMode")),e.notificationActivitySettingAction!=null&&e.hasOwnProperty("notificationActivitySettingAction")&&(A.notificationActivitySettingAction=p.proto.SyncActionValue.NotificationActivitySettingAction.toObject(e.notificationActivitySettingAction,a),a.oneofs&&(A._notificationActivitySettingAction="notificationActivitySettingAction")),e.lidContactAction!=null&&e.hasOwnProperty("lidContactAction")&&(A.lidContactAction=p.proto.SyncActionValue.LidContactAction.toObject(e.lidContactAction,a),a.oneofs&&(A._lidContactAction="lidContactAction")),e.ctwaPerCustomerDataSharingAction!=null&&e.hasOwnProperty("ctwaPerCustomerDataSharingAction")&&(A.ctwaPerCustomerDataSharingAction=p.proto.SyncActionValue.CtwaPerCustomerDataSharingAction.toObject(e.ctwaPerCustomerDataSharingAction,a),a.oneofs&&(A._ctwaPerCustomerDataSharingAction="ctwaPerCustomerDataSharingAction")),e.paymentTosAction!=null&&e.hasOwnProperty("paymentTosAction")&&(A.paymentTosAction=p.proto.SyncActionValue.PaymentTosAction.toObject(e.paymentTosAction,a),a.oneofs&&(A._paymentTosAction="paymentTosAction")),e.privacySettingChannelsPersonalisedRecommendationAction!=null&&e.hasOwnProperty("privacySettingChannelsPersonalisedRecommendationAction")&&(A.privacySettingChannelsPersonalisedRecommendationAction=p.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction.toObject(e.privacySettingChannelsPersonalisedRecommendationAction,a),a.oneofs&&(A._privacySettingChannelsPersonalisedRecommendationAction="privacySettingChannelsPersonalisedRecommendationAction")),e.businessBroadcastAssociationAction!=null&&e.hasOwnProperty("businessBroadcastAssociationAction")&&(A.businessBroadcastAssociationAction=p.proto.SyncActionValue.BusinessBroadcastAssociationAction.toObject(e.businessBroadcastAssociationAction,a),a.oneofs&&(A._businessBroadcastAssociationAction="businessBroadcastAssociationAction")),e.detectedOutcomesStatusAction!=null&&e.hasOwnProperty("detectedOutcomesStatusAction")&&(A.detectedOutcomesStatusAction=p.proto.SyncActionValue.DetectedOutcomesStatusAction.toObject(e.detectedOutcomesStatusAction,a),a.oneofs&&(A._detectedOutcomesStatusAction="detectedOutcomesStatusAction")),e.maibaAiFeaturesControlAction!=null&&e.hasOwnProperty("maibaAiFeaturesControlAction")&&(A.maibaAiFeaturesControlAction=p.proto.SyncActionValue.MaibaAIFeaturesControlAction.toObject(e.maibaAiFeaturesControlAction,a),a.oneofs&&(A._maibaAiFeaturesControlAction="maibaAiFeaturesControlAction")),e.businessBroadcastListAction!=null&&e.hasOwnProperty("businessBroadcastListAction")&&(A.businessBroadcastListAction=p.proto.SyncActionValue.BusinessBroadcastListAction.toObject(e.businessBroadcastListAction,a),a.oneofs&&(A._businessBroadcastListAction="businessBroadcastListAction")),e.musicUserIdAction!=null&&e.hasOwnProperty("musicUserIdAction")&&(A.musicUserIdAction=p.proto.SyncActionValue.MusicUserIdAction.toObject(e.musicUserIdAction,a),a.oneofs&&(A._musicUserIdAction="musicUserIdAction")),e.statusPostOptInNotificationPreferencesAction!=null&&e.hasOwnProperty("statusPostOptInNotificationPreferencesAction")&&(A.statusPostOptInNotificationPreferencesAction=p.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction.toObject(e.statusPostOptInNotificationPreferencesAction,a),a.oneofs&&(A._statusPostOptInNotificationPreferencesAction="statusPostOptInNotificationPreferencesAction")),e.avatarUpdatedAction!=null&&e.hasOwnProperty("avatarUpdatedAction")&&(A.avatarUpdatedAction=p.proto.SyncActionValue.AvatarUpdatedAction.toObject(e.avatarUpdatedAction,a),a.oneofs&&(A._avatarUpdatedAction="avatarUpdatedAction")),e.privateProcessingSettingAction!=null&&e.hasOwnProperty("privateProcessingSettingAction")&&(A.privateProcessingSettingAction=p.proto.SyncActionValue.PrivateProcessingSettingAction.toObject(e.privateProcessingSettingAction,a),a.oneofs&&(A._privateProcessingSettingAction="privateProcessingSettingAction")),e.newsletterSavedInterestsAction!=null&&e.hasOwnProperty("newsletterSavedInterestsAction")&&(A.newsletterSavedInterestsAction=p.proto.SyncActionValue.NewsletterSavedInterestsAction.toObject(e.newsletterSavedInterestsAction,a),a.oneofs&&(A._newsletterSavedInterestsAction="newsletterSavedInterestsAction")),e.aiThreadRenameAction!=null&&e.hasOwnProperty("aiThreadRenameAction")&&(A.aiThreadRenameAction=p.proto.SyncActionValue.AiThreadRenameAction.toObject(e.aiThreadRenameAction,a),a.oneofs&&(A._aiThreadRenameAction="aiThreadRenameAction")),e.interactiveMessageAction!=null&&e.hasOwnProperty("interactiveMessageAction")&&(A.interactiveMessageAction=p.proto.SyncActionValue.InteractiveMessageAction.toObject(e.interactiveMessageAction,a),a.oneofs&&(A._interactiveMessageAction="interactiveMessageAction")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncActionValue"},t.AgentAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}case 2:{c.deviceID=A.int32();break}case 3:{c.isDeleted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.AgentAction)return A;var r=new p.proto.SyncActionValue.AgentAction;return A.name!=null&&(r.name=String(A.name)),A.deviceID!=null&&(r.deviceID=A.deviceID|0),A.isDeleted!=null&&(r.isDeleted=!!A.isDeleted),r},i.toObject=function(A,r){r||(r={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.deviceID!=null&&A.hasOwnProperty("deviceID")&&(s.deviceID=A.deviceID,r.oneofs&&(s._deviceID="deviceID")),A.isDeleted!=null&&A.hasOwnProperty("isDeleted")&&(s.isDeleted=A.isDeleted,r.oneofs&&(s._isDeleted="isDeleted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.AgentAction"},i})(),t.AiThreadRenameAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.newTitle=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.AiThreadRenameAction)return A;var r=new p.proto.SyncActionValue.AiThreadRenameAction;return A.newTitle!=null&&(r.newTitle=String(A.newTitle)),r},i.toObject=function(A,r){r||(r={});var s={};return A.newTitle!=null&&A.hasOwnProperty("newTitle")&&(s.newTitle=A.newTitle,r.oneofs&&(s._newTitle="newTitle")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.AiThreadRenameAction"},i})(),t.AndroidUnsupportedActions=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.allowed=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.AndroidUnsupportedActions)return A;var r=new p.proto.SyncActionValue.AndroidUnsupportedActions;return A.allowed!=null&&(r.allowed=!!A.allowed),r},i.toObject=function(A,r){r||(r={});var s={};return A.allowed!=null&&A.hasOwnProperty("allowed")&&(s.allowed=A.allowed,r.oneofs&&(s._allowed="allowed")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.AndroidUnsupportedActions"},i})(),t.ArchiveChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.archived=A.bool();break}case 2:{c.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ArchiveChatAction)return A;var r=new p.proto.SyncActionValue.ArchiveChatAction;if(A.archived!=null&&(r.archived=!!A.archived),A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.ArchiveChatAction.messageRange: object expected");r.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.archived!=null&&A.hasOwnProperty("archived")&&(s.archived=A.archived,r.oneofs&&(s._archived="archived")),A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,r),r.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ArchiveChatAction"},i})(),t.AvatarUpdatedAction=(function(){function i(a){if(this.recentAvatarStickers=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.eventType=A.int32();break}case 2:{c.recentAvatarStickers&&c.recentAvatarStickers.length||(c.recentAvatarStickers=[]),c.recentAvatarStickers.push(p.proto.SyncActionValue.StickerAction.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.AvatarUpdatedAction)return A;var r=new p.proto.SyncActionValue.AvatarUpdatedAction;switch(A.eventType){default:if(typeof A.eventType=="number"){r.eventType=A.eventType;break}break;case"UPDATED":case 0:r.eventType=0;break;case"CREATED":case 1:r.eventType=1;break;case"DELETED":case 2:r.eventType=2;break}if(A.recentAvatarStickers){if(!Array.isArray(A.recentAvatarStickers))throw TypeError(".proto.SyncActionValue.AvatarUpdatedAction.recentAvatarStickers: array expected");r.recentAvatarStickers=[];for(var s=0;s>>3){case 1:{c.isSent=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.BotWelcomeRequestAction)return A;var r=new p.proto.SyncActionValue.BotWelcomeRequestAction;return A.isSent!=null&&(r.isSent=!!A.isSent),r},i.toObject=function(A,r){r||(r={});var s={};return A.isSent!=null&&A.hasOwnProperty("isSent")&&(s.isSent=A.isSent,r.oneofs&&(s._isSent="isSent")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.BotWelcomeRequestAction"},i})(),t.BroadcastListParticipant=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.lidJid=A.string();break}case 2:{c.pnJid=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.BroadcastListParticipant)return A;var r=new p.proto.SyncActionValue.BroadcastListParticipant;return A.lidJid!=null&&(r.lidJid=String(A.lidJid)),A.pnJid!=null&&(r.pnJid=String(A.pnJid)),r},i.toObject=function(A,r){r||(r={});var s={};return r.defaults&&(s.lidJid=""),A.lidJid!=null&&A.hasOwnProperty("lidJid")&&(s.lidJid=A.lidJid),A.pnJid!=null&&A.hasOwnProperty("pnJid")&&(s.pnJid=A.pnJid,r.oneofs&&(s._pnJid="pnJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.BroadcastListParticipant"},i})(),t.BusinessBroadcastAssociationAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.deleted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.BusinessBroadcastAssociationAction)return A;var r=new p.proto.SyncActionValue.BusinessBroadcastAssociationAction;return A.deleted!=null&&(r.deleted=!!A.deleted),r},i.toObject=function(A,r){r||(r={});var s={};return A.deleted!=null&&A.hasOwnProperty("deleted")&&(s.deleted=A.deleted,r.oneofs&&(s._deleted="deleted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.BusinessBroadcastAssociationAction"},i})(),t.BusinessBroadcastListAction=(function(){function i(a){if(this.participants=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.deleted=A.bool();break}case 2:{c.participants&&c.participants.length||(c.participants=[]),c.participants.push(p.proto.SyncActionValue.BroadcastListParticipant.decode(A,A.uint32()));break}case 3:{c.listName=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.BusinessBroadcastListAction)return A;var r=new p.proto.SyncActionValue.BusinessBroadcastListAction;if(A.deleted!=null&&(r.deleted=!!A.deleted),A.participants){if(!Array.isArray(A.participants))throw TypeError(".proto.SyncActionValue.BusinessBroadcastListAction.participants: array expected");r.participants=[];for(var s=0;s>>3){case 1:{c.callLogRecord=p.proto.CallLogRecord.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.CallLogAction)return A;var r=new p.proto.SyncActionValue.CallLogAction;if(A.callLogRecord!=null){if(typeof A.callLogRecord!="object")throw TypeError(".proto.SyncActionValue.CallLogAction.callLogRecord: object expected");r.callLogRecord=p.proto.CallLogRecord.fromObject(A.callLogRecord)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.callLogRecord!=null&&A.hasOwnProperty("callLogRecord")&&(s.callLogRecord=p.proto.CallLogRecord.toObject(A.callLogRecord,r),r.oneofs&&(s._callLogRecord="callLogRecord")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.CallLogAction"},i})(),t.ChatAssignmentAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.deviceAgentID=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ChatAssignmentAction)return A;var r=new p.proto.SyncActionValue.ChatAssignmentAction;return A.deviceAgentID!=null&&(r.deviceAgentID=String(A.deviceAgentID)),r},i.toObject=function(A,r){r||(r={});var s={};return A.deviceAgentID!=null&&A.hasOwnProperty("deviceAgentID")&&(s.deviceAgentID=A.deviceAgentID,r.oneofs&&(s._deviceAgentID="deviceAgentID")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ChatAssignmentAction"},i})(),t.ChatAssignmentOpenedStatusAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.chatOpened=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ChatAssignmentOpenedStatusAction)return A;var r=new p.proto.SyncActionValue.ChatAssignmentOpenedStatusAction;return A.chatOpened!=null&&(r.chatOpened=!!A.chatOpened),r},i.toObject=function(A,r){r||(r={});var s={};return A.chatOpened!=null&&A.hasOwnProperty("chatOpened")&&(s.chatOpened=A.chatOpened,r.oneofs&&(s._chatOpened="chatOpened")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ChatAssignmentOpenedStatusAction"},i})(),t.ClearChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ClearChatAction)return A;var r=new p.proto.SyncActionValue.ClearChatAction;if(A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.ClearChatAction.messageRange: object expected");r.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,r),r.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ClearChatAction"},i})(),t.ContactAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.fullName=A.string();break}case 2:{c.firstName=A.string();break}case 3:{c.lidJid=A.string();break}case 4:{c.saveOnPrimaryAddressbook=A.bool();break}case 5:{c.pnJid=A.string();break}case 6:{c.username=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ContactAction)return A;var r=new p.proto.SyncActionValue.ContactAction;return A.fullName!=null&&(r.fullName=String(A.fullName)),A.firstName!=null&&(r.firstName=String(A.firstName)),A.lidJid!=null&&(r.lidJid=String(A.lidJid)),A.saveOnPrimaryAddressbook!=null&&(r.saveOnPrimaryAddressbook=!!A.saveOnPrimaryAddressbook),A.pnJid!=null&&(r.pnJid=String(A.pnJid)),A.username!=null&&(r.username=String(A.username)),r},i.toObject=function(A,r){r||(r={});var s={};return A.fullName!=null&&A.hasOwnProperty("fullName")&&(s.fullName=A.fullName,r.oneofs&&(s._fullName="fullName")),A.firstName!=null&&A.hasOwnProperty("firstName")&&(s.firstName=A.firstName,r.oneofs&&(s._firstName="firstName")),A.lidJid!=null&&A.hasOwnProperty("lidJid")&&(s.lidJid=A.lidJid,r.oneofs&&(s._lidJid="lidJid")),A.saveOnPrimaryAddressbook!=null&&A.hasOwnProperty("saveOnPrimaryAddressbook")&&(s.saveOnPrimaryAddressbook=A.saveOnPrimaryAddressbook,r.oneofs&&(s._saveOnPrimaryAddressbook="saveOnPrimaryAddressbook")),A.pnJid!=null&&A.hasOwnProperty("pnJid")&&(s.pnJid=A.pnJid,r.oneofs&&(s._pnJid="pnJid")),A.username!=null&&A.hasOwnProperty("username")&&(s.username=A.username,r.oneofs&&(s._username="username")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ContactAction"},i})(),t.CtwaPerCustomerDataSharingAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isCtwaPerCustomerDataSharingEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.CtwaPerCustomerDataSharingAction)return A;var r=new p.proto.SyncActionValue.CtwaPerCustomerDataSharingAction;return A.isCtwaPerCustomerDataSharingEnabled!=null&&(r.isCtwaPerCustomerDataSharingEnabled=!!A.isCtwaPerCustomerDataSharingEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.isCtwaPerCustomerDataSharingEnabled!=null&&A.hasOwnProperty("isCtwaPerCustomerDataSharingEnabled")&&(s.isCtwaPerCustomerDataSharingEnabled=A.isCtwaPerCustomerDataSharingEnabled,r.oneofs&&(s._isCtwaPerCustomerDataSharingEnabled="isCtwaPerCustomerDataSharingEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.CtwaPerCustomerDataSharingAction"},i})(),t.CustomPaymentMethod=(function(){function i(e){if(this.metadata=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.credentialId=a.string();break}case 2:{g.country=a.string();break}case 3:{g.type=a.string();break}case 4:{g.metadata&&g.metadata.length||(g.metadata=[]),g.metadata.push(p.proto.SyncActionValue.CustomPaymentMethodMetadata.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.CustomPaymentMethod)return a;var A=new p.proto.SyncActionValue.CustomPaymentMethod;if(a.credentialId!=null&&(A.credentialId=String(a.credentialId)),a.country!=null&&(A.country=String(a.country)),a.type!=null&&(A.type=String(a.type)),a.metadata){if(!Array.isArray(a.metadata))throw TypeError(".proto.SyncActionValue.CustomPaymentMethod.metadata: array expected");A.metadata=[];for(var r=0;r>>3){case 1:{g.key=a.string();break}case 2:{g.value=a.string();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.CustomPaymentMethodMetadata)return a;var A=new p.proto.SyncActionValue.CustomPaymentMethodMetadata;return a.key!=null&&(A.key=String(a.key)),a.value!=null&&(A.value=String(a.value)),A},i.toObject=function(a,A){A||(A={});var r={};return A.defaults&&(r.key="",r.value=""),a.key!=null&&a.hasOwnProperty("key")&&(r.key=a.key),a.value!=null&&a.hasOwnProperty("value")&&(r.value=a.value),r},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.SyncActionValue.CustomPaymentMethodMetadata"},i})(),t.CustomPaymentMethodsAction=(function(){function i(e){if(this.customPaymentMethods=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.customPaymentMethods&&g.customPaymentMethods.length||(g.customPaymentMethods=[]),g.customPaymentMethods.push(p.proto.SyncActionValue.CustomPaymentMethod.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.CustomPaymentMethodsAction)return a;var A=new p.proto.SyncActionValue.CustomPaymentMethodsAction;if(a.customPaymentMethods){if(!Array.isArray(a.customPaymentMethods))throw TypeError(".proto.SyncActionValue.CustomPaymentMethodsAction.customPaymentMethods: array expected");A.customPaymentMethods=[];for(var r=0;r>>3){case 1:{c.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.DeleteChatAction)return A;var r=new p.proto.SyncActionValue.DeleteChatAction;if(A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.DeleteChatAction.messageRange: object expected");r.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,r),r.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DeleteChatAction"},i})(),t.DeleteIndividualCallLogAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.peerJid=A.string();break}case 2:{c.isIncoming=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.DeleteIndividualCallLogAction)return A;var r=new p.proto.SyncActionValue.DeleteIndividualCallLogAction;return A.peerJid!=null&&(r.peerJid=String(A.peerJid)),A.isIncoming!=null&&(r.isIncoming=!!A.isIncoming),r},i.toObject=function(A,r){r||(r={});var s={};return A.peerJid!=null&&A.hasOwnProperty("peerJid")&&(s.peerJid=A.peerJid,r.oneofs&&(s._peerJid="peerJid")),A.isIncoming!=null&&A.hasOwnProperty("isIncoming")&&(s.isIncoming=A.isIncoming,r.oneofs&&(s._isIncoming="isIncoming")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DeleteIndividualCallLogAction"},i})(),t.DeleteMessageForMeAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.deleteMedia=A.bool();break}case 2:{c.messageTimestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.DeleteMessageForMeAction)return A;var r=new p.proto.SyncActionValue.DeleteMessageForMeAction;return A.deleteMedia!=null&&(r.deleteMedia=!!A.deleteMedia),A.messageTimestamp!=null&&(l.Long?(r.messageTimestamp=l.Long.fromValue(A.messageTimestamp)).unsigned=!1:typeof A.messageTimestamp=="string"?r.messageTimestamp=parseInt(A.messageTimestamp,10):typeof A.messageTimestamp=="number"?r.messageTimestamp=A.messageTimestamp:typeof A.messageTimestamp=="object"&&(r.messageTimestamp=new l.LongBits(A.messageTimestamp.low>>>0,A.messageTimestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.deleteMedia!=null&&A.hasOwnProperty("deleteMedia")&&(s.deleteMedia=A.deleteMedia,r.oneofs&&(s._deleteMedia="deleteMedia")),A.messageTimestamp!=null&&A.hasOwnProperty("messageTimestamp")&&(typeof A.messageTimestamp=="number"?s.messageTimestamp=r.longs===String?String(A.messageTimestamp):A.messageTimestamp:s.messageTimestamp=r.longs===String?se(A.messageTimestamp):r.longs===Number?ge(A.messageTimestamp):A.messageTimestamp,r.oneofs&&(s._messageTimestamp="messageTimestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DeleteMessageForMeAction"},i})(),t.DetectedOutcomesStatusAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.DetectedOutcomesStatusAction)return A;var r=new p.proto.SyncActionValue.DetectedOutcomesStatusAction;return A.isEnabled!=null&&(r.isEnabled=!!A.isEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.isEnabled!=null&&A.hasOwnProperty("isEnabled")&&(s.isEnabled=A.isEnabled,r.oneofs&&(s._isEnabled="isEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DetectedOutcomesStatusAction"},i})(),t.ExternalWebBetaAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isOptIn=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ExternalWebBetaAction)return A;var r=new p.proto.SyncActionValue.ExternalWebBetaAction;return A.isOptIn!=null&&(r.isOptIn=!!A.isOptIn),r},i.toObject=function(A,r){r||(r={});var s={};return A.isOptIn!=null&&A.hasOwnProperty("isOptIn")&&(s.isOptIn=A.isOptIn,r.oneofs&&(s._isOptIn="isOptIn")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ExternalWebBetaAction"},i})(),t.FavoritesAction=(function(){function i(e){if(this.favorites=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.favorites&&g.favorites.length||(g.favorites=[]),g.favorites.push(p.proto.SyncActionValue.FavoritesAction.Favorite.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.FavoritesAction)return a;var A=new p.proto.SyncActionValue.FavoritesAction;if(a.favorites){if(!Array.isArray(a.favorites))throw TypeError(".proto.SyncActionValue.FavoritesAction.favorites: array expected");A.favorites=[];for(var r=0;r>>3){case 1:{I.id=r.string();break}default:r.skipType(d&7);break}}return I},e.fromObject=function(r){if(r instanceof p.proto.SyncActionValue.FavoritesAction.Favorite)return r;var s=new p.proto.SyncActionValue.FavoritesAction.Favorite;return r.id!=null&&(s.id=String(r.id)),s},e.toObject=function(r,s){s||(s={});var g={};return r.id!=null&&r.hasOwnProperty("id")&&(g.id=r.id,s.oneofs&&(g._id="id")),g},e.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},e.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/proto.SyncActionValue.FavoritesAction.Favorite"},e})(),i})(),t.InteractiveMessageAction=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.type=a.int32();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.InteractiveMessageAction)return a;var A=new p.proto.SyncActionValue.InteractiveMessageAction;switch(a.type){default:if(typeof a.type=="number"){A.type=a.type;break}break;case"DISABLE_CTA":case 1:A.type=1;break}return A},i.toObject=function(a,A){A||(A={});var r={};return A.defaults&&(r.type=A.enums===String?"DISABLE_CTA":1),a.type!=null&&a.hasOwnProperty("type")&&(r.type=A.enums===String?p.proto.SyncActionValue.InteractiveMessageAction.InteractiveMessageActionMode[a.type]===void 0?a.type:p.proto.SyncActionValue.InteractiveMessageAction.InteractiveMessageActionMode[a.type]:a.type),r},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.SyncActionValue.InteractiveMessageAction"},i.InteractiveMessageActionMode=(function(){let e={},a=Object.create(e);return a[e[1]="DISABLE_CTA"]=1,a})(),i})(),t.KeyExpiration=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.expiredKeyEpoch=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.KeyExpiration)return A;var r=new p.proto.SyncActionValue.KeyExpiration;return A.expiredKeyEpoch!=null&&(r.expiredKeyEpoch=A.expiredKeyEpoch|0),r},i.toObject=function(A,r){r||(r={});var s={};return A.expiredKeyEpoch!=null&&A.hasOwnProperty("expiredKeyEpoch")&&(s.expiredKeyEpoch=A.expiredKeyEpoch,r.oneofs&&(s._expiredKeyEpoch="expiredKeyEpoch")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.KeyExpiration"},i})(),t.LabelAssociationAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.labeled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.LabelAssociationAction)return A;var r=new p.proto.SyncActionValue.LabelAssociationAction;return A.labeled!=null&&(r.labeled=!!A.labeled),r},i.toObject=function(A,r){r||(r={});var s={};return A.labeled!=null&&A.hasOwnProperty("labeled")&&(s.labeled=A.labeled,r.oneofs&&(s._labeled="labeled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LabelAssociationAction"},i})(),t.LabelEditAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}case 2:{c.color=A.int32();break}case 3:{c.predefinedId=A.int32();break}case 4:{c.deleted=A.bool();break}case 5:{c.orderIndex=A.int32();break}case 6:{c.isActive=A.bool();break}case 7:{c.type=A.int32();break}case 8:{c.isImmutable=A.bool();break}case 9:{c.muteEndTimeMs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.LabelEditAction)return A;var r=new p.proto.SyncActionValue.LabelEditAction;switch(A.name!=null&&(r.name=String(A.name)),A.color!=null&&(r.color=A.color|0),A.predefinedId!=null&&(r.predefinedId=A.predefinedId|0),A.deleted!=null&&(r.deleted=!!A.deleted),A.orderIndex!=null&&(r.orderIndex=A.orderIndex|0),A.isActive!=null&&(r.isActive=!!A.isActive),A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"NONE":case 0:r.type=0;break;case"UNREAD":case 1:r.type=1;break;case"GROUPS":case 2:r.type=2;break;case"FAVORITES":case 3:r.type=3;break;case"PREDEFINED":case 4:r.type=4;break;case"CUSTOM":case 5:r.type=5;break;case"COMMUNITY":case 6:r.type=6;break;case"SERVER_ASSIGNED":case 7:r.type=7;break;case"DRAFTED":case 8:r.type=8;break;case"AI_HANDOFF":case 9:r.type=9;break}return A.isImmutable!=null&&(r.isImmutable=!!A.isImmutable),A.muteEndTimeMs!=null&&(l.Long?(r.muteEndTimeMs=l.Long.fromValue(A.muteEndTimeMs)).unsigned=!1:typeof A.muteEndTimeMs=="string"?r.muteEndTimeMs=parseInt(A.muteEndTimeMs,10):typeof A.muteEndTimeMs=="number"?r.muteEndTimeMs=A.muteEndTimeMs:typeof A.muteEndTimeMs=="object"&&(r.muteEndTimeMs=new l.LongBits(A.muteEndTimeMs.low>>>0,A.muteEndTimeMs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.color!=null&&A.hasOwnProperty("color")&&(s.color=A.color,r.oneofs&&(s._color="color")),A.predefinedId!=null&&A.hasOwnProperty("predefinedId")&&(s.predefinedId=A.predefinedId,r.oneofs&&(s._predefinedId="predefinedId")),A.deleted!=null&&A.hasOwnProperty("deleted")&&(s.deleted=A.deleted,r.oneofs&&(s._deleted="deleted")),A.orderIndex!=null&&A.hasOwnProperty("orderIndex")&&(s.orderIndex=A.orderIndex,r.oneofs&&(s._orderIndex="orderIndex")),A.isActive!=null&&A.hasOwnProperty("isActive")&&(s.isActive=A.isActive,r.oneofs&&(s._isActive="isActive")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.SyncActionValue.LabelEditAction.ListType[A.type]===void 0?A.type:p.proto.SyncActionValue.LabelEditAction.ListType[A.type]:A.type,r.oneofs&&(s._type="type")),A.isImmutable!=null&&A.hasOwnProperty("isImmutable")&&(s.isImmutable=A.isImmutable,r.oneofs&&(s._isImmutable="isImmutable")),A.muteEndTimeMs!=null&&A.hasOwnProperty("muteEndTimeMs")&&(typeof A.muteEndTimeMs=="number"?s.muteEndTimeMs=r.longs===String?String(A.muteEndTimeMs):A.muteEndTimeMs:s.muteEndTimeMs=r.longs===String?se(A.muteEndTimeMs):r.longs===Number?ge(A.muteEndTimeMs):A.muteEndTimeMs,r.oneofs&&(s._muteEndTimeMs="muteEndTimeMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LabelEditAction"},i.ListType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="UNREAD"]=1,A[a[2]="GROUPS"]=2,A[a[3]="FAVORITES"]=3,A[a[4]="PREDEFINED"]=4,A[a[5]="CUSTOM"]=5,A[a[6]="COMMUNITY"]=6,A[a[7]="SERVER_ASSIGNED"]=7,A[a[8]="DRAFTED"]=8,A[a[9]="AI_HANDOFF"]=9,A})(),i})(),t.LabelReorderingAction=(function(){function i(e){if(this.sortedLabelIds=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{if(g.sortedLabelIds&&g.sortedLabelIds.length||(g.sortedLabelIds=[]),(c&7)===2)for(var I=a.uint32()+a.pos;a.pos>>3){case 1:{c.fullName=A.string();break}case 2:{c.firstName=A.string();break}case 3:{c.username=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.LidContactAction)return A;var r=new p.proto.SyncActionValue.LidContactAction;return A.fullName!=null&&(r.fullName=String(A.fullName)),A.firstName!=null&&(r.firstName=String(A.firstName)),A.username!=null&&(r.username=String(A.username)),r},i.toObject=function(A,r){r||(r={});var s={};return A.fullName!=null&&A.hasOwnProperty("fullName")&&(s.fullName=A.fullName,r.oneofs&&(s._fullName="fullName")),A.firstName!=null&&A.hasOwnProperty("firstName")&&(s.firstName=A.firstName,r.oneofs&&(s._firstName="firstName")),A.username!=null&&A.hasOwnProperty("username")&&(s.username=A.username,r.oneofs&&(s._username="username")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LidContactAction"},i})(),t.LocaleSetting=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.locale=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.LocaleSetting)return A;var r=new p.proto.SyncActionValue.LocaleSetting;return A.locale!=null&&(r.locale=String(A.locale)),r},i.toObject=function(A,r){r||(r={});var s={};return A.locale!=null&&A.hasOwnProperty("locale")&&(s.locale=A.locale,r.oneofs&&(s._locale="locale")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LocaleSetting"},i})(),t.LockChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.locked=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.LockChatAction)return A;var r=new p.proto.SyncActionValue.LockChatAction;return A.locked!=null&&(r.locked=!!A.locked),r},i.toObject=function(A,r){r||(r={});var s={};return A.locked!=null&&A.hasOwnProperty("locked")&&(s.locked=A.locked,r.oneofs&&(s._locked="locked")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LockChatAction"},i})(),t.MaibaAIFeaturesControlAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.aiFeatureStatus=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MaibaAIFeaturesControlAction)return A;var r=new p.proto.SyncActionValue.MaibaAIFeaturesControlAction;switch(A.aiFeatureStatus){default:if(typeof A.aiFeatureStatus=="number"){r.aiFeatureStatus=A.aiFeatureStatus;break}break;case"ENABLED":case 0:r.aiFeatureStatus=0;break;case"ENABLED_HAS_LEARNING":case 1:r.aiFeatureStatus=1;break;case"DISABLED":case 2:r.aiFeatureStatus=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.aiFeatureStatus!=null&&A.hasOwnProperty("aiFeatureStatus")&&(s.aiFeatureStatus=r.enums===String?p.proto.SyncActionValue.MaibaAIFeaturesControlAction.MaibaAIFeatureStatus[A.aiFeatureStatus]===void 0?A.aiFeatureStatus:p.proto.SyncActionValue.MaibaAIFeaturesControlAction.MaibaAIFeatureStatus[A.aiFeatureStatus]:A.aiFeatureStatus,r.oneofs&&(s._aiFeatureStatus="aiFeatureStatus")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MaibaAIFeaturesControlAction"},i.MaibaAIFeatureStatus=(function(){let a={},A=Object.create(a);return A[a[0]="ENABLED"]=0,A[a[1]="ENABLED_HAS_LEARNING"]=1,A[a[2]="DISABLED"]=2,A})(),i})(),t.MarkChatAsReadAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.read=A.bool();break}case 2:{c.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MarkChatAsReadAction)return A;var r=new p.proto.SyncActionValue.MarkChatAsReadAction;if(A.read!=null&&(r.read=!!A.read),A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.MarkChatAsReadAction.messageRange: object expected");r.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.read!=null&&A.hasOwnProperty("read")&&(s.read=A.read,r.oneofs&&(s._read="read")),A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,r),r.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MarkChatAsReadAction"},i})(),t.MarketingMessageAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}case 2:{c.message=A.string();break}case 3:{c.type=A.int32();break}case 4:{c.createdAt=A.int64();break}case 5:{c.lastSentAt=A.int64();break}case 6:{c.isDeleted=A.bool();break}case 7:{c.mediaId=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MarketingMessageAction)return A;var r=new p.proto.SyncActionValue.MarketingMessageAction;switch(A.name!=null&&(r.name=String(A.name)),A.message!=null&&(r.message=String(A.message)),A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"PERSONALIZED":case 0:r.type=0;break}return A.createdAt!=null&&(l.Long?(r.createdAt=l.Long.fromValue(A.createdAt)).unsigned=!1:typeof A.createdAt=="string"?r.createdAt=parseInt(A.createdAt,10):typeof A.createdAt=="number"?r.createdAt=A.createdAt:typeof A.createdAt=="object"&&(r.createdAt=new l.LongBits(A.createdAt.low>>>0,A.createdAt.high>>>0).toNumber())),A.lastSentAt!=null&&(l.Long?(r.lastSentAt=l.Long.fromValue(A.lastSentAt)).unsigned=!1:typeof A.lastSentAt=="string"?r.lastSentAt=parseInt(A.lastSentAt,10):typeof A.lastSentAt=="number"?r.lastSentAt=A.lastSentAt:typeof A.lastSentAt=="object"&&(r.lastSentAt=new l.LongBits(A.lastSentAt.low>>>0,A.lastSentAt.high>>>0).toNumber())),A.isDeleted!=null&&(r.isDeleted=!!A.isDeleted),A.mediaId!=null&&(r.mediaId=String(A.mediaId)),r},i.toObject=function(A,r){r||(r={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.message!=null&&A.hasOwnProperty("message")&&(s.message=A.message,r.oneofs&&(s._message="message")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.SyncActionValue.MarketingMessageAction.MarketingMessagePrototypeType[A.type]===void 0?A.type:p.proto.SyncActionValue.MarketingMessageAction.MarketingMessagePrototypeType[A.type]:A.type,r.oneofs&&(s._type="type")),A.createdAt!=null&&A.hasOwnProperty("createdAt")&&(typeof A.createdAt=="number"?s.createdAt=r.longs===String?String(A.createdAt):A.createdAt:s.createdAt=r.longs===String?se(A.createdAt):r.longs===Number?ge(A.createdAt):A.createdAt,r.oneofs&&(s._createdAt="createdAt")),A.lastSentAt!=null&&A.hasOwnProperty("lastSentAt")&&(typeof A.lastSentAt=="number"?s.lastSentAt=r.longs===String?String(A.lastSentAt):A.lastSentAt:s.lastSentAt=r.longs===String?se(A.lastSentAt):r.longs===Number?ge(A.lastSentAt):A.lastSentAt,r.oneofs&&(s._lastSentAt="lastSentAt")),A.isDeleted!=null&&A.hasOwnProperty("isDeleted")&&(s.isDeleted=A.isDeleted,r.oneofs&&(s._isDeleted="isDeleted")),A.mediaId!=null&&A.hasOwnProperty("mediaId")&&(s.mediaId=A.mediaId,r.oneofs&&(s._mediaId="mediaId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MarketingMessageAction"},i.MarketingMessagePrototypeType=(function(){let a={},A=Object.create(a);return A[a[0]="PERSONALIZED"]=0,A})(),i})(),t.MarketingMessageBroadcastAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.repliedCount=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MarketingMessageBroadcastAction)return A;var r=new p.proto.SyncActionValue.MarketingMessageBroadcastAction;return A.repliedCount!=null&&(r.repliedCount=A.repliedCount|0),r},i.toObject=function(A,r){r||(r={});var s={};return A.repliedCount!=null&&A.hasOwnProperty("repliedCount")&&(s.repliedCount=A.repliedCount,r.oneofs&&(s._repliedCount="repliedCount")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MarketingMessageBroadcastAction"},i})(),t.MerchantPaymentPartnerAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.status=A.int32();break}case 2:{c.country=A.string();break}case 3:{c.gatewayName=A.string();break}case 4:{c.credentialId=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MerchantPaymentPartnerAction)return A;var r=new p.proto.SyncActionValue.MerchantPaymentPartnerAction;switch(A.status){default:if(typeof A.status=="number"){r.status=A.status;break}break;case"ACTIVE":case 0:r.status=0;break;case"INACTIVE":case 1:r.status=1;break}return A.country!=null&&(r.country=String(A.country)),A.gatewayName!=null&&(r.gatewayName=String(A.gatewayName)),A.credentialId!=null&&(r.credentialId=String(A.credentialId)),r},i.toObject=function(A,r){r||(r={});var s={};return r.defaults&&(s.status=r.enums===String?"ACTIVE":0,s.country=""),A.status!=null&&A.hasOwnProperty("status")&&(s.status=r.enums===String?p.proto.SyncActionValue.MerchantPaymentPartnerAction.Status[A.status]===void 0?A.status:p.proto.SyncActionValue.MerchantPaymentPartnerAction.Status[A.status]:A.status),A.country!=null&&A.hasOwnProperty("country")&&(s.country=A.country),A.gatewayName!=null&&A.hasOwnProperty("gatewayName")&&(s.gatewayName=A.gatewayName,r.oneofs&&(s._gatewayName="gatewayName")),A.credentialId!=null&&A.hasOwnProperty("credentialId")&&(s.credentialId=A.credentialId,r.oneofs&&(s._credentialId="credentialId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MerchantPaymentPartnerAction"},i.Status=(function(){let a={},A=Object.create(a);return A[a[0]="ACTIVE"]=0,A[a[1]="INACTIVE"]=1,A})(),i})(),t.MusicUserIdAction=(function(){function i(a){if(this.musicUserIdMap={},a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.musicUserId=A.string();break}case 2:{c.musicUserIdMap===l.emptyObject&&(c.musicUserIdMap={});var f=A.uint32()+A.pos;for(I="",d="";A.pos>>3){case 1:I=A.string();break;case 2:d=A.string();break;default:A.skipType(Q&7);break}}c.musicUserIdMap[I]=d;break}default:A.skipType(B&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MusicUserIdAction)return A;var r=new p.proto.SyncActionValue.MusicUserIdAction;if(A.musicUserId!=null&&(r.musicUserId=String(A.musicUserId)),A.musicUserIdMap){if(typeof A.musicUserIdMap!="object")throw TypeError(".proto.SyncActionValue.MusicUserIdAction.musicUserIdMap: object expected");r.musicUserIdMap={};for(var s=Object.keys(A.musicUserIdMap),g=0;g>>3){case 1:{c.muted=A.bool();break}case 2:{c.muteEndTimestamp=A.int64();break}case 3:{c.autoMuted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MuteAction)return A;var r=new p.proto.SyncActionValue.MuteAction;return A.muted!=null&&(r.muted=!!A.muted),A.muteEndTimestamp!=null&&(l.Long?(r.muteEndTimestamp=l.Long.fromValue(A.muteEndTimestamp)).unsigned=!1:typeof A.muteEndTimestamp=="string"?r.muteEndTimestamp=parseInt(A.muteEndTimestamp,10):typeof A.muteEndTimestamp=="number"?r.muteEndTimestamp=A.muteEndTimestamp:typeof A.muteEndTimestamp=="object"&&(r.muteEndTimestamp=new l.LongBits(A.muteEndTimestamp.low>>>0,A.muteEndTimestamp.high>>>0).toNumber())),A.autoMuted!=null&&(r.autoMuted=!!A.autoMuted),r},i.toObject=function(A,r){r||(r={});var s={};return A.muted!=null&&A.hasOwnProperty("muted")&&(s.muted=A.muted,r.oneofs&&(s._muted="muted")),A.muteEndTimestamp!=null&&A.hasOwnProperty("muteEndTimestamp")&&(typeof A.muteEndTimestamp=="number"?s.muteEndTimestamp=r.longs===String?String(A.muteEndTimestamp):A.muteEndTimestamp:s.muteEndTimestamp=r.longs===String?se(A.muteEndTimestamp):r.longs===Number?ge(A.muteEndTimestamp):A.muteEndTimestamp,r.oneofs&&(s._muteEndTimestamp="muteEndTimestamp")),A.autoMuted!=null&&A.hasOwnProperty("autoMuted")&&(s.autoMuted=A.autoMuted,r.oneofs&&(s._autoMuted="autoMuted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MuteAction"},i})(),t.NewsletterSavedInterestsAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.newsletterSavedInterests=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.NewsletterSavedInterestsAction)return A;var r=new p.proto.SyncActionValue.NewsletterSavedInterestsAction;return A.newsletterSavedInterests!=null&&(r.newsletterSavedInterests=String(A.newsletterSavedInterests)),r},i.toObject=function(A,r){r||(r={});var s={};return A.newsletterSavedInterests!=null&&A.hasOwnProperty("newsletterSavedInterests")&&(s.newsletterSavedInterests=A.newsletterSavedInterests,r.oneofs&&(s._newsletterSavedInterests="newsletterSavedInterests")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NewsletterSavedInterestsAction"},i})(),t.NoteEditAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.type=A.int32();break}case 2:{c.chatJid=A.string();break}case 3:{c.createdAt=A.int64();break}case 4:{c.deleted=A.bool();break}case 5:{c.unstructuredContent=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.NoteEditAction)return A;var r=new p.proto.SyncActionValue.NoteEditAction;switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNSTRUCTURED":case 1:r.type=1;break;case"STRUCTURED":case 2:r.type=2;break}return A.chatJid!=null&&(r.chatJid=String(A.chatJid)),A.createdAt!=null&&(l.Long?(r.createdAt=l.Long.fromValue(A.createdAt)).unsigned=!1:typeof A.createdAt=="string"?r.createdAt=parseInt(A.createdAt,10):typeof A.createdAt=="number"?r.createdAt=A.createdAt:typeof A.createdAt=="object"&&(r.createdAt=new l.LongBits(A.createdAt.low>>>0,A.createdAt.high>>>0).toNumber())),A.deleted!=null&&(r.deleted=!!A.deleted),A.unstructuredContent!=null&&(r.unstructuredContent=String(A.unstructuredContent)),r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.SyncActionValue.NoteEditAction.NoteType[A.type]===void 0?A.type:p.proto.SyncActionValue.NoteEditAction.NoteType[A.type]:A.type,r.oneofs&&(s._type="type")),A.chatJid!=null&&A.hasOwnProperty("chatJid")&&(s.chatJid=A.chatJid,r.oneofs&&(s._chatJid="chatJid")),A.createdAt!=null&&A.hasOwnProperty("createdAt")&&(typeof A.createdAt=="number"?s.createdAt=r.longs===String?String(A.createdAt):A.createdAt:s.createdAt=r.longs===String?se(A.createdAt):r.longs===Number?ge(A.createdAt):A.createdAt,r.oneofs&&(s._createdAt="createdAt")),A.deleted!=null&&A.hasOwnProperty("deleted")&&(s.deleted=A.deleted,r.oneofs&&(s._deleted="deleted")),A.unstructuredContent!=null&&A.hasOwnProperty("unstructuredContent")&&(s.unstructuredContent=A.unstructuredContent,r.oneofs&&(s._unstructuredContent="unstructuredContent")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NoteEditAction"},i.NoteType=(function(){let a={},A=Object.create(a);return A[a[1]="UNSTRUCTURED"]=1,A[a[2]="STRUCTURED"]=2,A})(),i})(),t.NotificationActivitySettingAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.notificationActivitySetting=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.NotificationActivitySettingAction)return A;var r=new p.proto.SyncActionValue.NotificationActivitySettingAction;switch(A.notificationActivitySetting){default:if(typeof A.notificationActivitySetting=="number"){r.notificationActivitySetting=A.notificationActivitySetting;break}break;case"DEFAULT_ALL_MESSAGES":case 0:r.notificationActivitySetting=0;break;case"ALL_MESSAGES":case 1:r.notificationActivitySetting=1;break;case"HIGHLIGHTS":case 2:r.notificationActivitySetting=2;break;case"DEFAULT_HIGHLIGHTS":case 3:r.notificationActivitySetting=3;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.notificationActivitySetting!=null&&A.hasOwnProperty("notificationActivitySetting")&&(s.notificationActivitySetting=r.enums===String?p.proto.SyncActionValue.NotificationActivitySettingAction.NotificationActivitySetting[A.notificationActivitySetting]===void 0?A.notificationActivitySetting:p.proto.SyncActionValue.NotificationActivitySettingAction.NotificationActivitySetting[A.notificationActivitySetting]:A.notificationActivitySetting,r.oneofs&&(s._notificationActivitySetting="notificationActivitySetting")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NotificationActivitySettingAction"},i.NotificationActivitySetting=(function(){let a={},A=Object.create(a);return A[a[0]="DEFAULT_ALL_MESSAGES"]=0,A[a[1]="ALL_MESSAGES"]=1,A[a[2]="HIGHLIGHTS"]=2,A[a[3]="DEFAULT_HIGHLIGHTS"]=3,A})(),i})(),t.NuxAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.acknowledged=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.NuxAction)return A;var r=new p.proto.SyncActionValue.NuxAction;return A.acknowledged!=null&&(r.acknowledged=!!A.acknowledged),r},i.toObject=function(A,r){r||(r={});var s={};return A.acknowledged!=null&&A.hasOwnProperty("acknowledged")&&(s.acknowledged=A.acknowledged,r.oneofs&&(s._acknowledged="acknowledged")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NuxAction"},i})(),t.PaymentInfoAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.cpi=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PaymentInfoAction)return A;var r=new p.proto.SyncActionValue.PaymentInfoAction;return A.cpi!=null&&(r.cpi=String(A.cpi)),r},i.toObject=function(A,r){r||(r={});var s={};return A.cpi!=null&&A.hasOwnProperty("cpi")&&(s.cpi=A.cpi,r.oneofs&&(s._cpi="cpi")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PaymentInfoAction"},i})(),t.PaymentTosAction=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.paymentNotice=a.int32();break}case 2:{g.accepted=a.bool();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.PaymentTosAction)return a;var A=new p.proto.SyncActionValue.PaymentTosAction;switch(a.paymentNotice){default:if(typeof a.paymentNotice=="number"){A.paymentNotice=a.paymentNotice;break}break;case"BR_PAY_PRIVACY_POLICY":case 0:A.paymentNotice=0;break}return a.accepted!=null&&(A.accepted=!!a.accepted),A},i.toObject=function(a,A){A||(A={});var r={};return A.defaults&&(r.paymentNotice=A.enums===String?"BR_PAY_PRIVACY_POLICY":0,r.accepted=!1),a.paymentNotice!=null&&a.hasOwnProperty("paymentNotice")&&(r.paymentNotice=A.enums===String?p.proto.SyncActionValue.PaymentTosAction.PaymentNotice[a.paymentNotice]===void 0?a.paymentNotice:p.proto.SyncActionValue.PaymentTosAction.PaymentNotice[a.paymentNotice]:a.paymentNotice),a.accepted!=null&&a.hasOwnProperty("accepted")&&(r.accepted=a.accepted),r},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.SyncActionValue.PaymentTosAction"},i.PaymentNotice=(function(){let e={},a=Object.create(e);return a[e[0]="BR_PAY_PRIVACY_POLICY"]=0,a})(),i})(),t.PinAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.pinned=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PinAction)return A;var r=new p.proto.SyncActionValue.PinAction;return A.pinned!=null&&(r.pinned=!!A.pinned),r},i.toObject=function(A,r){r||(r={});var s={};return A.pinned!=null&&A.hasOwnProperty("pinned")&&(s.pinned=A.pinned,r.oneofs&&(s._pinned="pinned")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PinAction"},i})(),t.PnForLidChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.pnJid=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PnForLidChatAction)return A;var r=new p.proto.SyncActionValue.PnForLidChatAction;return A.pnJid!=null&&(r.pnJid=String(A.pnJid)),r},i.toObject=function(A,r){r||(r={});var s={};return A.pnJid!=null&&A.hasOwnProperty("pnJid")&&(s.pnJid=A.pnJid,r.oneofs&&(s._pnJid="pnJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PnForLidChatAction"},i})(),t.PrimaryFeature=(function(){function i(e){if(this.flags=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.flags&&g.flags.length||(g.flags=[]),g.flags.push(a.string());break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.PrimaryFeature)return a;var A=new p.proto.SyncActionValue.PrimaryFeature;if(a.flags){if(!Array.isArray(a.flags))throw TypeError(".proto.SyncActionValue.PrimaryFeature.flags: array expected");A.flags=[];for(var r=0;r>>3){case 1:{c.version=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PrimaryVersionAction)return A;var r=new p.proto.SyncActionValue.PrimaryVersionAction;return A.version!=null&&(r.version=String(A.version)),r},i.toObject=function(A,r){r||(r={});var s={};return A.version!=null&&A.hasOwnProperty("version")&&(s.version=A.version,r.oneofs&&(s._version="version")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrimaryVersionAction"},i})(),t.PrivacySettingChannelsPersonalisedRecommendationAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isUserOptedOut=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction)return A;var r=new p.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction;return A.isUserOptedOut!=null&&(r.isUserOptedOut=!!A.isUserOptedOut),r},i.toObject=function(A,r){r||(r={});var s={};return A.isUserOptedOut!=null&&A.hasOwnProperty("isUserOptedOut")&&(s.isUserOptedOut=A.isUserOptedOut,r.oneofs&&(s._isUserOptedOut="isUserOptedOut")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction"},i})(),t.PrivacySettingDisableLinkPreviewsAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isPreviewsDisabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction)return A;var r=new p.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction;return A.isPreviewsDisabled!=null&&(r.isPreviewsDisabled=!!A.isPreviewsDisabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.isPreviewsDisabled!=null&&A.hasOwnProperty("isPreviewsDisabled")&&(s.isPreviewsDisabled=A.isPreviewsDisabled,r.oneofs&&(s._isPreviewsDisabled="isPreviewsDisabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction"},i})(),t.PrivacySettingRelayAllCalls=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PrivacySettingRelayAllCalls)return A;var r=new p.proto.SyncActionValue.PrivacySettingRelayAllCalls;return A.isEnabled!=null&&(r.isEnabled=!!A.isEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.isEnabled!=null&&A.hasOwnProperty("isEnabled")&&(s.isEnabled=A.isEnabled,r.oneofs&&(s._isEnabled="isEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivacySettingRelayAllCalls"},i})(),t.PrivateProcessingSettingAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.privateProcessingStatus=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PrivateProcessingSettingAction)return A;var r=new p.proto.SyncActionValue.PrivateProcessingSettingAction;switch(A.privateProcessingStatus){default:if(typeof A.privateProcessingStatus=="number"){r.privateProcessingStatus=A.privateProcessingStatus;break}break;case"UNDEFINED":case 0:r.privateProcessingStatus=0;break;case"ENABLED":case 1:r.privateProcessingStatus=1;break;case"DISABLED":case 2:r.privateProcessingStatus=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.privateProcessingStatus!=null&&A.hasOwnProperty("privateProcessingStatus")&&(s.privateProcessingStatus=r.enums===String?p.proto.SyncActionValue.PrivateProcessingSettingAction.PrivateProcessingStatus[A.privateProcessingStatus]===void 0?A.privateProcessingStatus:p.proto.SyncActionValue.PrivateProcessingSettingAction.PrivateProcessingStatus[A.privateProcessingStatus]:A.privateProcessingStatus,r.oneofs&&(s._privateProcessingStatus="privateProcessingStatus")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivateProcessingSettingAction"},i.PrivateProcessingStatus=(function(){let a={},A=Object.create(a);return A[a[0]="UNDEFINED"]=0,A[a[1]="ENABLED"]=1,A[a[2]="DISABLED"]=2,A})(),i})(),t.PushNameSetting=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PushNameSetting)return A;var r=new p.proto.SyncActionValue.PushNameSetting;return A.name!=null&&(r.name=String(A.name)),r},i.toObject=function(A,r){r||(r={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PushNameSetting"},i})(),t.QuickReplyAction=(function(){function i(a){if(this.keywords=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.shortcut=A.string();break}case 2:{c.message=A.string();break}case 3:{c.keywords&&c.keywords.length||(c.keywords=[]),c.keywords.push(A.string());break}case 4:{c.count=A.int32();break}case 5:{c.deleted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.QuickReplyAction)return A;var r=new p.proto.SyncActionValue.QuickReplyAction;if(A.shortcut!=null&&(r.shortcut=String(A.shortcut)),A.message!=null&&(r.message=String(A.message)),A.keywords){if(!Array.isArray(A.keywords))throw TypeError(".proto.SyncActionValue.QuickReplyAction.keywords: array expected");r.keywords=[];for(var s=0;s>>3){case 1:{g.weights&&g.weights.length||(g.weights=[]),g.weights.push(p.proto.RecentEmojiWeight.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.RecentEmojiWeightsAction)return a;var A=new p.proto.SyncActionValue.RecentEmojiWeightsAction;if(a.weights){if(!Array.isArray(a.weights))throw TypeError(".proto.SyncActionValue.RecentEmojiWeightsAction.weights: array expected");A.weights=[];for(var r=0;r>>3){case 1:{c.lastStickerSentTs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.RemoveRecentStickerAction)return A;var r=new p.proto.SyncActionValue.RemoveRecentStickerAction;return A.lastStickerSentTs!=null&&(l.Long?(r.lastStickerSentTs=l.Long.fromValue(A.lastStickerSentTs)).unsigned=!1:typeof A.lastStickerSentTs=="string"?r.lastStickerSentTs=parseInt(A.lastStickerSentTs,10):typeof A.lastStickerSentTs=="number"?r.lastStickerSentTs=A.lastStickerSentTs:typeof A.lastStickerSentTs=="object"&&(r.lastStickerSentTs=new l.LongBits(A.lastStickerSentTs.low>>>0,A.lastStickerSentTs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.lastStickerSentTs!=null&&A.hasOwnProperty("lastStickerSentTs")&&(typeof A.lastStickerSentTs=="number"?s.lastStickerSentTs=r.longs===String?String(A.lastStickerSentTs):A.lastStickerSentTs:s.lastStickerSentTs=r.longs===String?se(A.lastStickerSentTs):r.longs===Number?ge(A.lastStickerSentTs):A.lastStickerSentTs,r.oneofs&&(s._lastStickerSentTs="lastStickerSentTs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.RemoveRecentStickerAction"},i})(),t.StarAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.starred=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.StarAction)return A;var r=new p.proto.SyncActionValue.StarAction;return A.starred!=null&&(r.starred=!!A.starred),r},i.toObject=function(A,r){r||(r={});var s={};return A.starred!=null&&A.hasOwnProperty("starred")&&(s.starred=A.starred,r.oneofs&&(s._starred="starred")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.StarAction"},i})(),t.StatusPostOptInNotificationPreferencesAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.enabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction)return A;var r=new p.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction;return A.enabled!=null&&(r.enabled=!!A.enabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.enabled!=null&&A.hasOwnProperty("enabled")&&(s.enabled=A.enabled,r.oneofs&&(s._enabled="enabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction"},i})(),t.StatusPrivacyAction=(function(){function i(a){if(this.userJid=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.mode=A.int32();break}case 2:{c.userJid&&c.userJid.length||(c.userJid=[]),c.userJid.push(A.string());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.StatusPrivacyAction)return A;var r=new p.proto.SyncActionValue.StatusPrivacyAction;switch(A.mode){default:if(typeof A.mode=="number"){r.mode=A.mode;break}break;case"ALLOW_LIST":case 0:r.mode=0;break;case"DENY_LIST":case 1:r.mode=1;break;case"CONTACTS":case 2:r.mode=2;break;case"CLOSE_FRIENDS":case 3:r.mode=3;break}if(A.userJid){if(!Array.isArray(A.userJid))throw TypeError(".proto.SyncActionValue.StatusPrivacyAction.userJid: array expected");r.userJid=[];for(var s=0;s>>3){case 1:{c.url=A.string();break}case 2:{c.fileEncSha256=A.bytes();break}case 3:{c.mediaKey=A.bytes();break}case 4:{c.mimetype=A.string();break}case 5:{c.height=A.uint32();break}case 6:{c.width=A.uint32();break}case 7:{c.directPath=A.string();break}case 8:{c.fileLength=A.uint64();break}case 9:{c.isFavorite=A.bool();break}case 10:{c.deviceIdHint=A.uint32();break}case 11:{c.isLottie=A.bool();break}case 12:{c.imageHash=A.string();break}case 13:{c.isAvatarSticker=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.StickerAction)return A;var r=new p.proto.SyncActionValue.StickerAction;return A.url!=null&&(r.url=String(A.url)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.height!=null&&(r.height=A.height>>>0),A.width!=null&&(r.width=A.width>>>0),A.directPath!=null&&(r.directPath=String(A.directPath)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.isFavorite!=null&&(r.isFavorite=!!A.isFavorite),A.deviceIdHint!=null&&(r.deviceIdHint=A.deviceIdHint>>>0),A.isLottie!=null&&(r.isLottie=!!A.isLottie),A.imageHash!=null&&(r.imageHash=String(A.imageHash)),A.isAvatarSticker!=null&&(r.isAvatarSticker=!!A.isAvatarSticker),r},i.toObject=function(A,r){r||(r={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=A.height,r.oneofs&&(s._height="height")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=A.width,r.oneofs&&(s._width="width")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.isFavorite!=null&&A.hasOwnProperty("isFavorite")&&(s.isFavorite=A.isFavorite,r.oneofs&&(s._isFavorite="isFavorite")),A.deviceIdHint!=null&&A.hasOwnProperty("deviceIdHint")&&(s.deviceIdHint=A.deviceIdHint,r.oneofs&&(s._deviceIdHint="deviceIdHint")),A.isLottie!=null&&A.hasOwnProperty("isLottie")&&(s.isLottie=A.isLottie,r.oneofs&&(s._isLottie="isLottie")),A.imageHash!=null&&A.hasOwnProperty("imageHash")&&(s.imageHash=A.imageHash,r.oneofs&&(s._imageHash="imageHash")),A.isAvatarSticker!=null&&A.hasOwnProperty("isAvatarSticker")&&(s.isAvatarSticker=A.isAvatarSticker,r.oneofs&&(s._isAvatarSticker="isAvatarSticker")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.StickerAction"},i})(),t.SubscriptionAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isDeactivated=A.bool();break}case 2:{c.isAutoRenewing=A.bool();break}case 3:{c.expirationDate=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.SubscriptionAction)return A;var r=new p.proto.SyncActionValue.SubscriptionAction;return A.isDeactivated!=null&&(r.isDeactivated=!!A.isDeactivated),A.isAutoRenewing!=null&&(r.isAutoRenewing=!!A.isAutoRenewing),A.expirationDate!=null&&(l.Long?(r.expirationDate=l.Long.fromValue(A.expirationDate)).unsigned=!1:typeof A.expirationDate=="string"?r.expirationDate=parseInt(A.expirationDate,10):typeof A.expirationDate=="number"?r.expirationDate=A.expirationDate:typeof A.expirationDate=="object"&&(r.expirationDate=new l.LongBits(A.expirationDate.low>>>0,A.expirationDate.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.isDeactivated!=null&&A.hasOwnProperty("isDeactivated")&&(s.isDeactivated=A.isDeactivated,r.oneofs&&(s._isDeactivated="isDeactivated")),A.isAutoRenewing!=null&&A.hasOwnProperty("isAutoRenewing")&&(s.isAutoRenewing=A.isAutoRenewing,r.oneofs&&(s._isAutoRenewing="isAutoRenewing")),A.expirationDate!=null&&A.hasOwnProperty("expirationDate")&&(typeof A.expirationDate=="number"?s.expirationDate=r.longs===String?String(A.expirationDate):A.expirationDate:s.expirationDate=r.longs===String?se(A.expirationDate):r.longs===Number?ge(A.expirationDate):A.expirationDate,r.oneofs&&(s._expirationDate="expirationDate")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.SubscriptionAction"},i})(),t.SyncActionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.timestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.SyncActionMessage)return A;var r=new p.proto.SyncActionValue.SyncActionMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.SyncActionValue.SyncActionMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return A.timestamp!=null&&(l.Long?(r.timestamp=l.Long.fromValue(A.timestamp)).unsigned=!1:typeof A.timestamp=="string"?r.timestamp=parseInt(A.timestamp,10):typeof A.timestamp=="number"?r.timestamp=A.timestamp:typeof A.timestamp=="object"&&(r.timestamp=new l.LongBits(A.timestamp.low>>>0,A.timestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.timestamp!=null&&A.hasOwnProperty("timestamp")&&(typeof A.timestamp=="number"?s.timestamp=r.longs===String?String(A.timestamp):A.timestamp:s.timestamp=r.longs===String?se(A.timestamp):r.longs===Number?ge(A.timestamp):A.timestamp,r.oneofs&&(s._timestamp="timestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.SyncActionMessage"},i})(),t.SyncActionMessageRange=(function(){function i(a){if(this.messages=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.lastMessageTimestamp=A.int64();break}case 2:{c.lastSystemMessageTimestamp=A.int64();break}case 3:{c.messages&&c.messages.length||(c.messages=[]),c.messages.push(p.proto.SyncActionValue.SyncActionMessage.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.SyncActionMessageRange)return A;var r=new p.proto.SyncActionValue.SyncActionMessageRange;if(A.lastMessageTimestamp!=null&&(l.Long?(r.lastMessageTimestamp=l.Long.fromValue(A.lastMessageTimestamp)).unsigned=!1:typeof A.lastMessageTimestamp=="string"?r.lastMessageTimestamp=parseInt(A.lastMessageTimestamp,10):typeof A.lastMessageTimestamp=="number"?r.lastMessageTimestamp=A.lastMessageTimestamp:typeof A.lastMessageTimestamp=="object"&&(r.lastMessageTimestamp=new l.LongBits(A.lastMessageTimestamp.low>>>0,A.lastMessageTimestamp.high>>>0).toNumber())),A.lastSystemMessageTimestamp!=null&&(l.Long?(r.lastSystemMessageTimestamp=l.Long.fromValue(A.lastSystemMessageTimestamp)).unsigned=!1:typeof A.lastSystemMessageTimestamp=="string"?r.lastSystemMessageTimestamp=parseInt(A.lastSystemMessageTimestamp,10):typeof A.lastSystemMessageTimestamp=="number"?r.lastSystemMessageTimestamp=A.lastSystemMessageTimestamp:typeof A.lastSystemMessageTimestamp=="object"&&(r.lastSystemMessageTimestamp=new l.LongBits(A.lastSystemMessageTimestamp.low>>>0,A.lastSystemMessageTimestamp.high>>>0).toNumber())),A.messages){if(!Array.isArray(A.messages))throw TypeError(".proto.SyncActionValue.SyncActionMessageRange.messages: array expected");r.messages=[];for(var s=0;s>>3){case 1:{c.isTwentyFourHourFormatEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.TimeFormatAction)return A;var r=new p.proto.SyncActionValue.TimeFormatAction;return A.isTwentyFourHourFormatEnabled!=null&&(r.isTwentyFourHourFormatEnabled=!!A.isTwentyFourHourFormatEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.isTwentyFourHourFormatEnabled!=null&&A.hasOwnProperty("isTwentyFourHourFormatEnabled")&&(s.isTwentyFourHourFormatEnabled=A.isTwentyFourHourFormatEnabled,r.oneofs&&(s._isTwentyFourHourFormatEnabled="isTwentyFourHourFormatEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.TimeFormatAction"},i})(),t.UGCBot=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.definition=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.UGCBot)return A;var r=new p.proto.SyncActionValue.UGCBot;return A.definition!=null&&(typeof A.definition=="string"?l.base64.decode(A.definition,r.definition=l.newBuffer(l.base64.length(A.definition)),0):A.definition.length>=0&&(r.definition=A.definition)),r},i.toObject=function(A,r){r||(r={});var s={};return A.definition!=null&&A.hasOwnProperty("definition")&&(s.definition=r.bytes===String?l.base64.encode(A.definition,0,A.definition.length):r.bytes===Array?Array.prototype.slice.call(A.definition):A.definition,r.oneofs&&(s._definition="definition")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UGCBot"},i})(),t.UnarchiveChatsSetting=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.unarchiveChats=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.UnarchiveChatsSetting)return A;var r=new p.proto.SyncActionValue.UnarchiveChatsSetting;return A.unarchiveChats!=null&&(r.unarchiveChats=!!A.unarchiveChats),r},i.toObject=function(A,r){r||(r={});var s={};return A.unarchiveChats!=null&&A.hasOwnProperty("unarchiveChats")&&(s.unarchiveChats=A.unarchiveChats,r.oneofs&&(s._unarchiveChats="unarchiveChats")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UnarchiveChatsSetting"},i})(),t.UserStatusMuteAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.muted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.UserStatusMuteAction)return A;var r=new p.proto.SyncActionValue.UserStatusMuteAction;return A.muted!=null&&(r.muted=!!A.muted),r},i.toObject=function(A,r){r||(r={});var s={};return A.muted!=null&&A.hasOwnProperty("muted")&&(s.muted=A.muted,r.oneofs&&(s._muted="muted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UserStatusMuteAction"},i})(),t.UsernameChatStartModeAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.chatStartMode=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.UsernameChatStartModeAction)return A;var r=new p.proto.SyncActionValue.UsernameChatStartModeAction;switch(A.chatStartMode){default:if(typeof A.chatStartMode=="number"){r.chatStartMode=A.chatStartMode;break}break;case"LID":case 1:r.chatStartMode=1;break;case"PN":case 2:r.chatStartMode=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.chatStartMode!=null&&A.hasOwnProperty("chatStartMode")&&(s.chatStartMode=r.enums===String?p.proto.SyncActionValue.UsernameChatStartModeAction.ChatStartMode[A.chatStartMode]===void 0?A.chatStartMode:p.proto.SyncActionValue.UsernameChatStartModeAction.ChatStartMode[A.chatStartMode]:A.chatStartMode,r.oneofs&&(s._chatStartMode="chatStartMode")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UsernameChatStartModeAction"},i.ChatStartMode=(function(){let a={},A=Object.create(a);return A[a[1]="LID"]=1,A[a[2]="PN"]=2,A})(),i})(),t.WaffleAccountLinkStateAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 2:{c.linkState=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.WaffleAccountLinkStateAction)return A;var r=new p.proto.SyncActionValue.WaffleAccountLinkStateAction;switch(A.linkState){default:if(typeof A.linkState=="number"){r.linkState=A.linkState;break}break;case"ACTIVE":case 0:r.linkState=0;break;case"PAUSED":case 1:r.linkState=1;break;case"UNLINKED":case 2:r.linkState=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.linkState!=null&&A.hasOwnProperty("linkState")&&(s.linkState=r.enums===String?p.proto.SyncActionValue.WaffleAccountLinkStateAction.AccountLinkState[A.linkState]===void 0?A.linkState:p.proto.SyncActionValue.WaffleAccountLinkStateAction.AccountLinkState[A.linkState]:A.linkState,r.oneofs&&(s._linkState="linkState")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.WaffleAccountLinkStateAction"},i.AccountLinkState=(function(){let a={},A=Object.create(a);return A[a[0]="ACTIVE"]=0,A[a[1]="PAUSED"]=1,A[a[2]="UNLINKED"]=2,A})(),i})(),t.WamoUserIdentifierAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.identifier=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.WamoUserIdentifierAction)return A;var r=new p.proto.SyncActionValue.WamoUserIdentifierAction;return A.identifier!=null&&(r.identifier=String(A.identifier)),r},i.toObject=function(A,r){r||(r={});var s={};return A.identifier!=null&&A.hasOwnProperty("identifier")&&(s.identifier=A.identifier,r.oneofs&&(s._identifier="identifier")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.WamoUserIdentifierAction"},i})(),t})(),n.SyncdIndex=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.blob=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdIndex)return e;var a=new p.proto.SyncdIndex;return e.blob!=null&&(typeof e.blob=="string"?l.base64.decode(e.blob,a.blob=l.newBuffer(l.base64.length(e.blob)),0):e.blob.length>=0&&(a.blob=e.blob)),a},t.toObject=function(e,a){a||(a={});var A={};return e.blob!=null&&e.hasOwnProperty("blob")&&(A.blob=a.bytes===String?l.base64.encode(e.blob,0,e.blob.length):a.bytes===Array?Array.prototype.slice.call(e.blob):e.blob,a.oneofs&&(A._blob="blob")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdIndex"},t})(),n.SyncdMutation=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.operation=e.int32();break}case 2:{s.record=p.proto.SyncdRecord.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdMutation)return e;var a=new p.proto.SyncdMutation;switch(e.operation){default:if(typeof e.operation=="number"){a.operation=e.operation;break}break;case"SET":case 0:a.operation=0;break;case"REMOVE":case 1:a.operation=1;break}if(e.record!=null){if(typeof e.record!="object")throw TypeError(".proto.SyncdMutation.record: object expected");a.record=p.proto.SyncdRecord.fromObject(e.record)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.operation!=null&&e.hasOwnProperty("operation")&&(A.operation=a.enums===String?p.proto.SyncdMutation.SyncdOperation[e.operation]===void 0?e.operation:p.proto.SyncdMutation.SyncdOperation[e.operation]:e.operation,a.oneofs&&(A._operation="operation")),e.record!=null&&e.hasOwnProperty("record")&&(A.record=p.proto.SyncdRecord.toObject(e.record,a),a.oneofs&&(A._record="record")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdMutation"},t.SyncdOperation=(function(){let i={},e=Object.create(i);return e[i[0]="SET"]=0,e[i[1]="REMOVE"]=1,e})(),t})(),n.SyncdMutations=(function(){function t(o){if(this.mutations=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.mutations&&r.mutations.length||(r.mutations=[]),r.mutations.push(p.proto.SyncdMutation.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.SyncdMutations)return i;var e=new p.proto.SyncdMutations;if(i.mutations){if(!Array.isArray(i.mutations))throw TypeError(".proto.SyncdMutations.mutations: array expected");e.mutations=[];for(var a=0;a>>3){case 1:{s.version=p.proto.SyncdVersion.decode(e,e.uint32());break}case 2:{s.mutations&&s.mutations.length||(s.mutations=[]),s.mutations.push(p.proto.SyncdMutation.decode(e,e.uint32()));break}case 3:{s.externalMutations=p.proto.ExternalBlobReference.decode(e,e.uint32());break}case 4:{s.snapshotMac=e.bytes();break}case 5:{s.patchMac=e.bytes();break}case 6:{s.keyId=p.proto.KeyId.decode(e,e.uint32());break}case 7:{s.exitCode=p.proto.ExitCode.decode(e,e.uint32());break}case 8:{s.deviceIndex=e.uint32();break}case 9:{s.clientDebugData=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdPatch)return e;var a=new p.proto.SyncdPatch;if(e.version!=null){if(typeof e.version!="object")throw TypeError(".proto.SyncdPatch.version: object expected");a.version=p.proto.SyncdVersion.fromObject(e.version)}if(e.mutations){if(!Array.isArray(e.mutations))throw TypeError(".proto.SyncdPatch.mutations: array expected");a.mutations=[];for(var A=0;A=0&&(a.snapshotMac=e.snapshotMac)),e.patchMac!=null&&(typeof e.patchMac=="string"?l.base64.decode(e.patchMac,a.patchMac=l.newBuffer(l.base64.length(e.patchMac)),0):e.patchMac.length>=0&&(a.patchMac=e.patchMac)),e.keyId!=null){if(typeof e.keyId!="object")throw TypeError(".proto.SyncdPatch.keyId: object expected");a.keyId=p.proto.KeyId.fromObject(e.keyId)}if(e.exitCode!=null){if(typeof e.exitCode!="object")throw TypeError(".proto.SyncdPatch.exitCode: object expected");a.exitCode=p.proto.ExitCode.fromObject(e.exitCode)}return e.deviceIndex!=null&&(a.deviceIndex=e.deviceIndex>>>0),e.clientDebugData!=null&&(typeof e.clientDebugData=="string"?l.base64.decode(e.clientDebugData,a.clientDebugData=l.newBuffer(l.base64.length(e.clientDebugData)),0):e.clientDebugData.length>=0&&(a.clientDebugData=e.clientDebugData)),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.mutations=[]),e.version!=null&&e.hasOwnProperty("version")&&(A.version=p.proto.SyncdVersion.toObject(e.version,a),a.oneofs&&(A._version="version")),e.mutations&&e.mutations.length){A.mutations=[];for(var r=0;r>>3){case 1:{s.index=p.proto.SyncdIndex.decode(e,e.uint32());break}case 2:{s.value=p.proto.SyncdValue.decode(e,e.uint32());break}case 3:{s.keyId=p.proto.KeyId.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdRecord)return e;var a=new p.proto.SyncdRecord;if(e.index!=null){if(typeof e.index!="object")throw TypeError(".proto.SyncdRecord.index: object expected");a.index=p.proto.SyncdIndex.fromObject(e.index)}if(e.value!=null){if(typeof e.value!="object")throw TypeError(".proto.SyncdRecord.value: object expected");a.value=p.proto.SyncdValue.fromObject(e.value)}if(e.keyId!=null){if(typeof e.keyId!="object")throw TypeError(".proto.SyncdRecord.keyId: object expected");a.keyId=p.proto.KeyId.fromObject(e.keyId)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.index!=null&&e.hasOwnProperty("index")&&(A.index=p.proto.SyncdIndex.toObject(e.index,a),a.oneofs&&(A._index="index")),e.value!=null&&e.hasOwnProperty("value")&&(A.value=p.proto.SyncdValue.toObject(e.value,a),a.oneofs&&(A._value="value")),e.keyId!=null&&e.hasOwnProperty("keyId")&&(A.keyId=p.proto.KeyId.toObject(e.keyId,a),a.oneofs&&(A._keyId="keyId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdRecord"},t})(),n.SyncdSnapshot=(function(){function t(i){if(this.records=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.version=p.proto.SyncdVersion.decode(e,e.uint32());break}case 2:{s.records&&s.records.length||(s.records=[]),s.records.push(p.proto.SyncdRecord.decode(e,e.uint32()));break}case 3:{s.mac=e.bytes();break}case 4:{s.keyId=p.proto.KeyId.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdSnapshot)return e;var a=new p.proto.SyncdSnapshot;if(e.version!=null){if(typeof e.version!="object")throw TypeError(".proto.SyncdSnapshot.version: object expected");a.version=p.proto.SyncdVersion.fromObject(e.version)}if(e.records){if(!Array.isArray(e.records))throw TypeError(".proto.SyncdSnapshot.records: array expected");a.records=[];for(var A=0;A=0&&(a.mac=e.mac)),e.keyId!=null){if(typeof e.keyId!="object")throw TypeError(".proto.SyncdSnapshot.keyId: object expected");a.keyId=p.proto.KeyId.fromObject(e.keyId)}return a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.records=[]),e.version!=null&&e.hasOwnProperty("version")&&(A.version=p.proto.SyncdVersion.toObject(e.version,a),a.oneofs&&(A._version="version")),e.records&&e.records.length){A.records=[];for(var r=0;r>>3){case 1:{s.blob=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdValue)return e;var a=new p.proto.SyncdValue;return e.blob!=null&&(typeof e.blob=="string"?l.base64.decode(e.blob,a.blob=l.newBuffer(l.base64.length(e.blob)),0):e.blob.length>=0&&(a.blob=e.blob)),a},t.toObject=function(e,a){a||(a={});var A={};return e.blob!=null&&e.hasOwnProperty("blob")&&(A.blob=a.bytes===String?l.base64.encode(e.blob,0,e.blob.length):a.bytes===Array?Array.prototype.slice.call(e.blob):e.blob,a.oneofs&&(A._blob="blob")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdValue"},t})(),n.SyncdVersion=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.version=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdVersion)return e;var a=new p.proto.SyncdVersion;return e.version!=null&&(l.Long?(a.version=l.Long.fromValue(e.version)).unsigned=!0:typeof e.version=="string"?a.version=parseInt(e.version,10):typeof e.version=="number"?a.version=e.version:typeof e.version=="object"&&(a.version=new l.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};return e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?A.version=a.longs===String?String(e.version):e.version:A.version=a.longs===String?se(e.version,!0):a.longs===Number?ge(e.version,!0):e.version,a.oneofs&&(A._version="version")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdVersion"},t})(),n.TapLinkAction=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.title=e.string();break}case 2:{s.tapUrl=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.TapLinkAction)return e;var a=new p.proto.TapLinkAction;return e.title!=null&&(a.title=String(e.title)),e.tapUrl!=null&&(a.tapUrl=String(e.tapUrl)),a},t.toObject=function(e,a){a||(a={});var A={};return e.title!=null&&e.hasOwnProperty("title")&&(A.title=e.title,a.oneofs&&(A._title="title")),e.tapUrl!=null&&e.hasOwnProperty("tapUrl")&&(A.tapUrl=e.tapUrl,a.oneofs&&(A._tapUrl="tapUrl")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.TapLinkAction"},t})(),n.TemplateButton=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 4:{s.index=e.uint32();break}case 1:{s.quickReplyButton=p.proto.TemplateButton.QuickReplyButton.decode(e,e.uint32());break}case 2:{s.urlButton=p.proto.TemplateButton.URLButton.decode(e,e.uint32());break}case 3:{s.callButton=p.proto.TemplateButton.CallButton.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.TemplateButton)return e;var a=new p.proto.TemplateButton;if(e.index!=null&&(a.index=e.index>>>0),e.quickReplyButton!=null){if(typeof e.quickReplyButton!="object")throw TypeError(".proto.TemplateButton.quickReplyButton: object expected");a.quickReplyButton=p.proto.TemplateButton.QuickReplyButton.fromObject(e.quickReplyButton)}if(e.urlButton!=null){if(typeof e.urlButton!="object")throw TypeError(".proto.TemplateButton.urlButton: object expected");a.urlButton=p.proto.TemplateButton.URLButton.fromObject(e.urlButton)}if(e.callButton!=null){if(typeof e.callButton!="object")throw TypeError(".proto.TemplateButton.callButton: object expected");a.callButton=p.proto.TemplateButton.CallButton.fromObject(e.callButton)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.quickReplyButton!=null&&e.hasOwnProperty("quickReplyButton")&&(A.quickReplyButton=p.proto.TemplateButton.QuickReplyButton.toObject(e.quickReplyButton,a),a.oneofs&&(A.button="quickReplyButton")),e.urlButton!=null&&e.hasOwnProperty("urlButton")&&(A.urlButton=p.proto.TemplateButton.URLButton.toObject(e.urlButton,a),a.oneofs&&(A.button="urlButton")),e.callButton!=null&&e.hasOwnProperty("callButton")&&(A.callButton=p.proto.TemplateButton.CallButton.toObject(e.callButton,a),a.oneofs&&(A.button="callButton")),e.index!=null&&e.hasOwnProperty("index")&&(A.index=e.index,a.oneofs&&(A._index="index")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.TemplateButton"},t.CallButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=p.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}case 2:{c.phoneNumber=p.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.TemplateButton.CallButton)return A;var r=new p.proto.TemplateButton.CallButton;if(A.displayText!=null){if(typeof A.displayText!="object")throw TypeError(".proto.TemplateButton.CallButton.displayText: object expected");r.displayText=p.proto.Message.HighlyStructuredMessage.fromObject(A.displayText)}if(A.phoneNumber!=null){if(typeof A.phoneNumber!="object")throw TypeError(".proto.TemplateButton.CallButton.phoneNumber: object expected");r.phoneNumber=p.proto.Message.HighlyStructuredMessage.fromObject(A.phoneNumber)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=p.proto.Message.HighlyStructuredMessage.toObject(A.displayText,r),r.oneofs&&(s._displayText="displayText")),A.phoneNumber!=null&&A.hasOwnProperty("phoneNumber")&&(s.phoneNumber=p.proto.Message.HighlyStructuredMessage.toObject(A.phoneNumber,r),r.oneofs&&(s._phoneNumber="phoneNumber")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.TemplateButton.CallButton"},i})(),t.QuickReplyButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=p.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}case 2:{c.id=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.TemplateButton.QuickReplyButton)return A;var r=new p.proto.TemplateButton.QuickReplyButton;if(A.displayText!=null){if(typeof A.displayText!="object")throw TypeError(".proto.TemplateButton.QuickReplyButton.displayText: object expected");r.displayText=p.proto.Message.HighlyStructuredMessage.fromObject(A.displayText)}return A.id!=null&&(r.id=String(A.id)),r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=p.proto.Message.HighlyStructuredMessage.toObject(A.displayText,r),r.oneofs&&(s._displayText="displayText")),A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,r.oneofs&&(s._id="id")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.TemplateButton.QuickReplyButton"},i})(),t.URLButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=p.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}case 2:{c.url=p.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.TemplateButton.URLButton)return A;var r=new p.proto.TemplateButton.URLButton;if(A.displayText!=null){if(typeof A.displayText!="object")throw TypeError(".proto.TemplateButton.URLButton.displayText: object expected");r.displayText=p.proto.Message.HighlyStructuredMessage.fromObject(A.displayText)}if(A.url!=null){if(typeof A.url!="object")throw TypeError(".proto.TemplateButton.URLButton.url: object expected");r.url=p.proto.Message.HighlyStructuredMessage.fromObject(A.url)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=p.proto.Message.HighlyStructuredMessage.toObject(A.displayText,r),r.oneofs&&(s._displayText="displayText")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=p.proto.Message.HighlyStructuredMessage.toObject(A.url,r),r.oneofs&&(s._url="url")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.TemplateButton.URLButton"},i})(),t})(),n.ThreadID=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.threadType=e.int32();break}case 2:{s.threadKey=p.proto.MessageKey.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ThreadID)return e;var a=new p.proto.ThreadID;switch(e.threadType){default:if(typeof e.threadType=="number"){a.threadType=e.threadType;break}break;case"UNKNOWN":case 0:a.threadType=0;break;case"VIEW_REPLIES":case 1:a.threadType=1;break;case"AI_THREAD":case 2:a.threadType=2;break}if(e.threadKey!=null){if(typeof e.threadKey!="object")throw TypeError(".proto.ThreadID.threadKey: object expected");a.threadKey=p.proto.MessageKey.fromObject(e.threadKey)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.threadType!=null&&e.hasOwnProperty("threadType")&&(A.threadType=a.enums===String?p.proto.ThreadID.ThreadType[e.threadType]===void 0?e.threadType:p.proto.ThreadID.ThreadType[e.threadType]:e.threadType,a.oneofs&&(A._threadType="threadType")),e.threadKey!=null&&e.hasOwnProperty("threadKey")&&(A.threadKey=p.proto.MessageKey.toObject(e.threadKey,a),a.oneofs&&(A._threadKey="threadKey")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ThreadID"},t.ThreadType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="VIEW_REPLIES"]=1,e[i[2]="AI_THREAD"]=2,e})(),t})(),n.UrlTrackingMap=(function(){function t(o){if(this.urlTrackingMapElements=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.urlTrackingMapElements&&r.urlTrackingMapElements.length||(r.urlTrackingMapElements=[]),r.urlTrackingMapElements.push(p.proto.UrlTrackingMap.UrlTrackingMapElement.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.UrlTrackingMap)return i;var e=new p.proto.UrlTrackingMap;if(i.urlTrackingMapElements){if(!Array.isArray(i.urlTrackingMapElements))throw TypeError(".proto.UrlTrackingMap.urlTrackingMapElements: array expected");e.urlTrackingMapElements=[];for(var a=0;a>>3){case 1:{g.originalUrl=a.string();break}case 2:{g.unconsentedUsersUrl=a.string();break}case 3:{g.consentedUsersUrl=a.string();break}case 4:{g.cardIndex=a.uint32();break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof p.proto.UrlTrackingMap.UrlTrackingMapElement)return a;var A=new p.proto.UrlTrackingMap.UrlTrackingMapElement;return a.originalUrl!=null&&(A.originalUrl=String(a.originalUrl)),a.unconsentedUsersUrl!=null&&(A.unconsentedUsersUrl=String(a.unconsentedUsersUrl)),a.consentedUsersUrl!=null&&(A.consentedUsersUrl=String(a.consentedUsersUrl)),a.cardIndex!=null&&(A.cardIndex=a.cardIndex>>>0),A},o.toObject=function(a,A){A||(A={});var r={};return a.originalUrl!=null&&a.hasOwnProperty("originalUrl")&&(r.originalUrl=a.originalUrl,A.oneofs&&(r._originalUrl="originalUrl")),a.unconsentedUsersUrl!=null&&a.hasOwnProperty("unconsentedUsersUrl")&&(r.unconsentedUsersUrl=a.unconsentedUsersUrl,A.oneofs&&(r._unconsentedUsersUrl="unconsentedUsersUrl")),a.consentedUsersUrl!=null&&a.hasOwnProperty("consentedUsersUrl")&&(r.consentedUsersUrl=a.consentedUsersUrl,A.oneofs&&(r._consentedUsersUrl="consentedUsersUrl")),a.cardIndex!=null&&a.hasOwnProperty("cardIndex")&&(r.cardIndex=a.cardIndex,A.oneofs&&(r._cardIndex="cardIndex")),r},o.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.UrlTrackingMap.UrlTrackingMapElement"},o})(),t})(),n.UserPassword=(function(){function t(i){if(this.transformerArg=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encoding=e.int32();break}case 2:{s.transformer=e.int32();break}case 3:{s.transformerArg&&s.transformerArg.length||(s.transformerArg=[]),s.transformerArg.push(p.proto.UserPassword.TransformerArg.decode(e,e.uint32()));break}case 4:{s.transformedData=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.UserPassword)return e;var a=new p.proto.UserPassword;switch(e.encoding){default:if(typeof e.encoding=="number"){a.encoding=e.encoding;break}break;case"UTF8":case 0:a.encoding=0;break;case"UTF8_BROKEN":case 1:a.encoding=1;break}switch(e.transformer){default:if(typeof e.transformer=="number"){a.transformer=e.transformer;break}break;case"NONE":case 0:a.transformer=0;break;case"PBKDF2_HMAC_SHA512":case 1:a.transformer=1;break;case"PBKDF2_HMAC_SHA384":case 2:a.transformer=2;break}if(e.transformerArg){if(!Array.isArray(e.transformerArg))throw TypeError(".proto.UserPassword.transformerArg: array expected");a.transformerArg=[];for(var A=0;A=0&&(a.transformedData=e.transformedData)),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.transformerArg=[]),e.encoding!=null&&e.hasOwnProperty("encoding")&&(A.encoding=a.enums===String?p.proto.UserPassword.Encoding[e.encoding]===void 0?e.encoding:p.proto.UserPassword.Encoding[e.encoding]:e.encoding,a.oneofs&&(A._encoding="encoding")),e.transformer!=null&&e.hasOwnProperty("transformer")&&(A.transformer=a.enums===String?p.proto.UserPassword.Transformer[e.transformer]===void 0?e.transformer:p.proto.UserPassword.Transformer[e.transformer]:e.transformer,a.oneofs&&(A._transformer="transformer")),e.transformerArg&&e.transformerArg.length){A.transformerArg=[];for(var r=0;r>>3){case 1:{c.key=A.string();break}case 2:{c.value=p.proto.UserPassword.TransformerArg.Value.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.UserPassword.TransformerArg)return A;var r=new p.proto.UserPassword.TransformerArg;if(A.key!=null&&(r.key=String(A.key)),A.value!=null){if(typeof A.value!="object")throw TypeError(".proto.UserPassword.TransformerArg.value: object expected");r.value=p.proto.UserPassword.TransformerArg.Value.fromObject(A.value)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=A.key,r.oneofs&&(s._key="key")),A.value!=null&&A.hasOwnProperty("value")&&(s.value=p.proto.UserPassword.TransformerArg.Value.toObject(A.value,r),r.oneofs&&(s._value="value")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.UserPassword.TransformerArg"},i.Value=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.asBlob=s.bytes();break}case 2:{d.asUnsignedInteger=s.uint32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.UserPassword.TransformerArg.Value)return s;var g=new p.proto.UserPassword.TransformerArg.Value;return s.asBlob!=null&&(typeof s.asBlob=="string"?l.base64.decode(s.asBlob,g.asBlob=l.newBuffer(l.base64.length(s.asBlob)),0):s.asBlob.length>=0&&(g.asBlob=s.asBlob)),s.asUnsignedInteger!=null&&(g.asUnsignedInteger=s.asUnsignedInteger>>>0),g},a.toObject=function(s,g){g||(g={});var c={};return s.asBlob!=null&&s.hasOwnProperty("asBlob")&&(c.asBlob=g.bytes===String?l.base64.encode(s.asBlob,0,s.asBlob.length):g.bytes===Array?Array.prototype.slice.call(s.asBlob):s.asBlob,g.oneofs&&(c.value="asBlob")),s.asUnsignedInteger!=null&&s.hasOwnProperty("asUnsignedInteger")&&(c.asUnsignedInteger=s.asUnsignedInteger,g.oneofs&&(c.value="asUnsignedInteger")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.UserPassword.TransformerArg.Value"},a})(),i})(),t})(),n.UserReceipt=(function(){function t(i){if(this.pendingDeviceJid=[],this.deliveredDeviceJid=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.userJid=e.string();break}case 2:{s.receiptTimestamp=e.int64();break}case 3:{s.readTimestamp=e.int64();break}case 4:{s.playedTimestamp=e.int64();break}case 5:{s.pendingDeviceJid&&s.pendingDeviceJid.length||(s.pendingDeviceJid=[]),s.pendingDeviceJid.push(e.string());break}case 6:{s.deliveredDeviceJid&&s.deliveredDeviceJid.length||(s.deliveredDeviceJid=[]),s.deliveredDeviceJid.push(e.string());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.UserReceipt)return e;var a=new p.proto.UserReceipt;if(e.userJid!=null&&(a.userJid=String(e.userJid)),e.receiptTimestamp!=null&&(l.Long?(a.receiptTimestamp=l.Long.fromValue(e.receiptTimestamp)).unsigned=!1:typeof e.receiptTimestamp=="string"?a.receiptTimestamp=parseInt(e.receiptTimestamp,10):typeof e.receiptTimestamp=="number"?a.receiptTimestamp=e.receiptTimestamp:typeof e.receiptTimestamp=="object"&&(a.receiptTimestamp=new l.LongBits(e.receiptTimestamp.low>>>0,e.receiptTimestamp.high>>>0).toNumber())),e.readTimestamp!=null&&(l.Long?(a.readTimestamp=l.Long.fromValue(e.readTimestamp)).unsigned=!1:typeof e.readTimestamp=="string"?a.readTimestamp=parseInt(e.readTimestamp,10):typeof e.readTimestamp=="number"?a.readTimestamp=e.readTimestamp:typeof e.readTimestamp=="object"&&(a.readTimestamp=new l.LongBits(e.readTimestamp.low>>>0,e.readTimestamp.high>>>0).toNumber())),e.playedTimestamp!=null&&(l.Long?(a.playedTimestamp=l.Long.fromValue(e.playedTimestamp)).unsigned=!1:typeof e.playedTimestamp=="string"?a.playedTimestamp=parseInt(e.playedTimestamp,10):typeof e.playedTimestamp=="number"?a.playedTimestamp=e.playedTimestamp:typeof e.playedTimestamp=="object"&&(a.playedTimestamp=new l.LongBits(e.playedTimestamp.low>>>0,e.playedTimestamp.high>>>0).toNumber())),e.pendingDeviceJid){if(!Array.isArray(e.pendingDeviceJid))throw TypeError(".proto.UserReceipt.pendingDeviceJid: array expected");a.pendingDeviceJid=[];for(var A=0;A>>3){case 1:{s.details=e.bytes();break}case 2:{s.signature=e.bytes();break}case 3:{s.serverSignature=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.VerifiedNameCertificate)return e;var a=new p.proto.VerifiedNameCertificate;return e.details!=null&&(typeof e.details=="string"?l.base64.decode(e.details,a.details=l.newBuffer(l.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.signature!=null&&(typeof e.signature=="string"?l.base64.decode(e.signature,a.signature=l.newBuffer(l.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),e.serverSignature!=null&&(typeof e.serverSignature=="string"?l.base64.decode(e.serverSignature,a.serverSignature=l.newBuffer(l.base64.length(e.serverSignature)),0):e.serverSignature.length>=0&&(a.serverSignature=e.serverSignature)),a},t.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?l.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?l.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),e.serverSignature!=null&&e.hasOwnProperty("serverSignature")&&(A.serverSignature=a.bytes===String?l.base64.encode(e.serverSignature,0,e.serverSignature.length):a.bytes===Array?Array.prototype.slice.call(e.serverSignature):e.serverSignature,a.oneofs&&(A._serverSignature="serverSignature")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.VerifiedNameCertificate"},t.Details=(function(){function i(a){if(this.localizedNames=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.serial=A.uint64();break}case 2:{c.issuer=A.string();break}case 4:{c.verifiedName=A.string();break}case 8:{c.localizedNames&&c.localizedNames.length||(c.localizedNames=[]),c.localizedNames.push(p.proto.LocalizedName.decode(A,A.uint32()));break}case 10:{c.issueTime=A.uint64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.VerifiedNameCertificate.Details)return A;var r=new p.proto.VerifiedNameCertificate.Details;if(A.serial!=null&&(l.Long?(r.serial=l.Long.fromValue(A.serial)).unsigned=!0:typeof A.serial=="string"?r.serial=parseInt(A.serial,10):typeof A.serial=="number"?r.serial=A.serial:typeof A.serial=="object"&&(r.serial=new l.LongBits(A.serial.low>>>0,A.serial.high>>>0).toNumber(!0))),A.issuer!=null&&(r.issuer=String(A.issuer)),A.verifiedName!=null&&(r.verifiedName=String(A.verifiedName)),A.localizedNames){if(!Array.isArray(A.localizedNames))throw TypeError(".proto.VerifiedNameCertificate.Details.localizedNames: array expected");r.localizedNames=[];for(var s=0;s>>0,A.issueTime.high>>>0).toNumber(!0))),r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.localizedNames=[]),A.serial!=null&&A.hasOwnProperty("serial")&&(typeof A.serial=="number"?s.serial=r.longs===String?String(A.serial):A.serial:s.serial=r.longs===String?se(A.serial,!0):r.longs===Number?ge(A.serial,!0):A.serial,r.oneofs&&(s._serial="serial")),A.issuer!=null&&A.hasOwnProperty("issuer")&&(s.issuer=A.issuer,r.oneofs&&(s._issuer="issuer")),A.verifiedName!=null&&A.hasOwnProperty("verifiedName")&&(s.verifiedName=A.verifiedName,r.oneofs&&(s._verifiedName="verifiedName")),A.localizedNames&&A.localizedNames.length){s.localizedNames=[];for(var g=0;g>>3){case 1:{s.filename=e.string();break}case 2:{s.opacity=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.WallpaperSettings)return e;var a=new p.proto.WallpaperSettings;return e.filename!=null&&(a.filename=String(e.filename)),e.opacity!=null&&(a.opacity=e.opacity>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.filename!=null&&e.hasOwnProperty("filename")&&(A.filename=e.filename,a.oneofs&&(A._filename="filename")),e.opacity!=null&&e.hasOwnProperty("opacity")&&(A.opacity=e.opacity,a.oneofs&&(A._opacity="opacity")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.WallpaperSettings"},t})(),n.WebFeatures=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.labelsDisplay=e.int32();break}case 2:{s.voipIndividualOutgoing=e.int32();break}case 3:{s.groupsV3=e.int32();break}case 4:{s.groupsV3Create=e.int32();break}case 5:{s.changeNumberV2=e.int32();break}case 6:{s.queryStatusV3Thumbnail=e.int32();break}case 7:{s.liveLocations=e.int32();break}case 8:{s.queryVname=e.int32();break}case 9:{s.voipIndividualIncoming=e.int32();break}case 10:{s.quickRepliesQuery=e.int32();break}case 11:{s.payments=e.int32();break}case 12:{s.stickerPackQuery=e.int32();break}case 13:{s.liveLocationsFinal=e.int32();break}case 14:{s.labelsEdit=e.int32();break}case 15:{s.mediaUpload=e.int32();break}case 18:{s.mediaUploadRichQuickReplies=e.int32();break}case 19:{s.vnameV2=e.int32();break}case 20:{s.videoPlaybackUrl=e.int32();break}case 21:{s.statusRanking=e.int32();break}case 22:{s.voipIndividualVideo=e.int32();break}case 23:{s.thirdPartyStickers=e.int32();break}case 24:{s.frequentlyForwardedSetting=e.int32();break}case 25:{s.groupsV4JoinPermission=e.int32();break}case 26:{s.recentStickers=e.int32();break}case 27:{s.catalog=e.int32();break}case 28:{s.starredStickers=e.int32();break}case 29:{s.voipGroupCall=e.int32();break}case 30:{s.templateMessage=e.int32();break}case 31:{s.templateMessageInteractivity=e.int32();break}case 32:{s.ephemeralMessages=e.int32();break}case 33:{s.e2ENotificationSync=e.int32();break}case 34:{s.recentStickersV2=e.int32();break}case 36:{s.recentStickersV3=e.int32();break}case 37:{s.userNotice=e.int32();break}case 39:{s.support=e.int32();break}case 40:{s.groupUiiCleanup=e.int32();break}case 41:{s.groupDogfoodingInternalOnly=e.int32();break}case 42:{s.settingsSync=e.int32();break}case 43:{s.archiveV2=e.int32();break}case 44:{s.ephemeralAllowGroupMembers=e.int32();break}case 45:{s.ephemeral24HDuration=e.int32();break}case 46:{s.mdForceUpgrade=e.int32();break}case 47:{s.disappearingMode=e.int32();break}case 48:{s.externalMdOptInAvailable=e.int32();break}case 49:{s.noDeleteMessageTimeLimit=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.WebFeatures)return e;var a=new p.proto.WebFeatures;switch(e.labelsDisplay){default:if(typeof e.labelsDisplay=="number"){a.labelsDisplay=e.labelsDisplay;break}break;case"NOT_STARTED":case 0:a.labelsDisplay=0;break;case"FORCE_UPGRADE":case 1:a.labelsDisplay=1;break;case"DEVELOPMENT":case 2:a.labelsDisplay=2;break;case"PRODUCTION":case 3:a.labelsDisplay=3;break}switch(e.voipIndividualOutgoing){default:if(typeof e.voipIndividualOutgoing=="number"){a.voipIndividualOutgoing=e.voipIndividualOutgoing;break}break;case"NOT_STARTED":case 0:a.voipIndividualOutgoing=0;break;case"FORCE_UPGRADE":case 1:a.voipIndividualOutgoing=1;break;case"DEVELOPMENT":case 2:a.voipIndividualOutgoing=2;break;case"PRODUCTION":case 3:a.voipIndividualOutgoing=3;break}switch(e.groupsV3){default:if(typeof e.groupsV3=="number"){a.groupsV3=e.groupsV3;break}break;case"NOT_STARTED":case 0:a.groupsV3=0;break;case"FORCE_UPGRADE":case 1:a.groupsV3=1;break;case"DEVELOPMENT":case 2:a.groupsV3=2;break;case"PRODUCTION":case 3:a.groupsV3=3;break}switch(e.groupsV3Create){default:if(typeof e.groupsV3Create=="number"){a.groupsV3Create=e.groupsV3Create;break}break;case"NOT_STARTED":case 0:a.groupsV3Create=0;break;case"FORCE_UPGRADE":case 1:a.groupsV3Create=1;break;case"DEVELOPMENT":case 2:a.groupsV3Create=2;break;case"PRODUCTION":case 3:a.groupsV3Create=3;break}switch(e.changeNumberV2){default:if(typeof e.changeNumberV2=="number"){a.changeNumberV2=e.changeNumberV2;break}break;case"NOT_STARTED":case 0:a.changeNumberV2=0;break;case"FORCE_UPGRADE":case 1:a.changeNumberV2=1;break;case"DEVELOPMENT":case 2:a.changeNumberV2=2;break;case"PRODUCTION":case 3:a.changeNumberV2=3;break}switch(e.queryStatusV3Thumbnail){default:if(typeof e.queryStatusV3Thumbnail=="number"){a.queryStatusV3Thumbnail=e.queryStatusV3Thumbnail;break}break;case"NOT_STARTED":case 0:a.queryStatusV3Thumbnail=0;break;case"FORCE_UPGRADE":case 1:a.queryStatusV3Thumbnail=1;break;case"DEVELOPMENT":case 2:a.queryStatusV3Thumbnail=2;break;case"PRODUCTION":case 3:a.queryStatusV3Thumbnail=3;break}switch(e.liveLocations){default:if(typeof e.liveLocations=="number"){a.liveLocations=e.liveLocations;break}break;case"NOT_STARTED":case 0:a.liveLocations=0;break;case"FORCE_UPGRADE":case 1:a.liveLocations=1;break;case"DEVELOPMENT":case 2:a.liveLocations=2;break;case"PRODUCTION":case 3:a.liveLocations=3;break}switch(e.queryVname){default:if(typeof e.queryVname=="number"){a.queryVname=e.queryVname;break}break;case"NOT_STARTED":case 0:a.queryVname=0;break;case"FORCE_UPGRADE":case 1:a.queryVname=1;break;case"DEVELOPMENT":case 2:a.queryVname=2;break;case"PRODUCTION":case 3:a.queryVname=3;break}switch(e.voipIndividualIncoming){default:if(typeof e.voipIndividualIncoming=="number"){a.voipIndividualIncoming=e.voipIndividualIncoming;break}break;case"NOT_STARTED":case 0:a.voipIndividualIncoming=0;break;case"FORCE_UPGRADE":case 1:a.voipIndividualIncoming=1;break;case"DEVELOPMENT":case 2:a.voipIndividualIncoming=2;break;case"PRODUCTION":case 3:a.voipIndividualIncoming=3;break}switch(e.quickRepliesQuery){default:if(typeof e.quickRepliesQuery=="number"){a.quickRepliesQuery=e.quickRepliesQuery;break}break;case"NOT_STARTED":case 0:a.quickRepliesQuery=0;break;case"FORCE_UPGRADE":case 1:a.quickRepliesQuery=1;break;case"DEVELOPMENT":case 2:a.quickRepliesQuery=2;break;case"PRODUCTION":case 3:a.quickRepliesQuery=3;break}switch(e.payments){default:if(typeof e.payments=="number"){a.payments=e.payments;break}break;case"NOT_STARTED":case 0:a.payments=0;break;case"FORCE_UPGRADE":case 1:a.payments=1;break;case"DEVELOPMENT":case 2:a.payments=2;break;case"PRODUCTION":case 3:a.payments=3;break}switch(e.stickerPackQuery){default:if(typeof e.stickerPackQuery=="number"){a.stickerPackQuery=e.stickerPackQuery;break}break;case"NOT_STARTED":case 0:a.stickerPackQuery=0;break;case"FORCE_UPGRADE":case 1:a.stickerPackQuery=1;break;case"DEVELOPMENT":case 2:a.stickerPackQuery=2;break;case"PRODUCTION":case 3:a.stickerPackQuery=3;break}switch(e.liveLocationsFinal){default:if(typeof e.liveLocationsFinal=="number"){a.liveLocationsFinal=e.liveLocationsFinal;break}break;case"NOT_STARTED":case 0:a.liveLocationsFinal=0;break;case"FORCE_UPGRADE":case 1:a.liveLocationsFinal=1;break;case"DEVELOPMENT":case 2:a.liveLocationsFinal=2;break;case"PRODUCTION":case 3:a.liveLocationsFinal=3;break}switch(e.labelsEdit){default:if(typeof e.labelsEdit=="number"){a.labelsEdit=e.labelsEdit;break}break;case"NOT_STARTED":case 0:a.labelsEdit=0;break;case"FORCE_UPGRADE":case 1:a.labelsEdit=1;break;case"DEVELOPMENT":case 2:a.labelsEdit=2;break;case"PRODUCTION":case 3:a.labelsEdit=3;break}switch(e.mediaUpload){default:if(typeof e.mediaUpload=="number"){a.mediaUpload=e.mediaUpload;break}break;case"NOT_STARTED":case 0:a.mediaUpload=0;break;case"FORCE_UPGRADE":case 1:a.mediaUpload=1;break;case"DEVELOPMENT":case 2:a.mediaUpload=2;break;case"PRODUCTION":case 3:a.mediaUpload=3;break}switch(e.mediaUploadRichQuickReplies){default:if(typeof e.mediaUploadRichQuickReplies=="number"){a.mediaUploadRichQuickReplies=e.mediaUploadRichQuickReplies;break}break;case"NOT_STARTED":case 0:a.mediaUploadRichQuickReplies=0;break;case"FORCE_UPGRADE":case 1:a.mediaUploadRichQuickReplies=1;break;case"DEVELOPMENT":case 2:a.mediaUploadRichQuickReplies=2;break;case"PRODUCTION":case 3:a.mediaUploadRichQuickReplies=3;break}switch(e.vnameV2){default:if(typeof e.vnameV2=="number"){a.vnameV2=e.vnameV2;break}break;case"NOT_STARTED":case 0:a.vnameV2=0;break;case"FORCE_UPGRADE":case 1:a.vnameV2=1;break;case"DEVELOPMENT":case 2:a.vnameV2=2;break;case"PRODUCTION":case 3:a.vnameV2=3;break}switch(e.videoPlaybackUrl){default:if(typeof e.videoPlaybackUrl=="number"){a.videoPlaybackUrl=e.videoPlaybackUrl;break}break;case"NOT_STARTED":case 0:a.videoPlaybackUrl=0;break;case"FORCE_UPGRADE":case 1:a.videoPlaybackUrl=1;break;case"DEVELOPMENT":case 2:a.videoPlaybackUrl=2;break;case"PRODUCTION":case 3:a.videoPlaybackUrl=3;break}switch(e.statusRanking){default:if(typeof e.statusRanking=="number"){a.statusRanking=e.statusRanking;break}break;case"NOT_STARTED":case 0:a.statusRanking=0;break;case"FORCE_UPGRADE":case 1:a.statusRanking=1;break;case"DEVELOPMENT":case 2:a.statusRanking=2;break;case"PRODUCTION":case 3:a.statusRanking=3;break}switch(e.voipIndividualVideo){default:if(typeof e.voipIndividualVideo=="number"){a.voipIndividualVideo=e.voipIndividualVideo;break}break;case"NOT_STARTED":case 0:a.voipIndividualVideo=0;break;case"FORCE_UPGRADE":case 1:a.voipIndividualVideo=1;break;case"DEVELOPMENT":case 2:a.voipIndividualVideo=2;break;case"PRODUCTION":case 3:a.voipIndividualVideo=3;break}switch(e.thirdPartyStickers){default:if(typeof e.thirdPartyStickers=="number"){a.thirdPartyStickers=e.thirdPartyStickers;break}break;case"NOT_STARTED":case 0:a.thirdPartyStickers=0;break;case"FORCE_UPGRADE":case 1:a.thirdPartyStickers=1;break;case"DEVELOPMENT":case 2:a.thirdPartyStickers=2;break;case"PRODUCTION":case 3:a.thirdPartyStickers=3;break}switch(e.frequentlyForwardedSetting){default:if(typeof e.frequentlyForwardedSetting=="number"){a.frequentlyForwardedSetting=e.frequentlyForwardedSetting;break}break;case"NOT_STARTED":case 0:a.frequentlyForwardedSetting=0;break;case"FORCE_UPGRADE":case 1:a.frequentlyForwardedSetting=1;break;case"DEVELOPMENT":case 2:a.frequentlyForwardedSetting=2;break;case"PRODUCTION":case 3:a.frequentlyForwardedSetting=3;break}switch(e.groupsV4JoinPermission){default:if(typeof e.groupsV4JoinPermission=="number"){a.groupsV4JoinPermission=e.groupsV4JoinPermission;break}break;case"NOT_STARTED":case 0:a.groupsV4JoinPermission=0;break;case"FORCE_UPGRADE":case 1:a.groupsV4JoinPermission=1;break;case"DEVELOPMENT":case 2:a.groupsV4JoinPermission=2;break;case"PRODUCTION":case 3:a.groupsV4JoinPermission=3;break}switch(e.recentStickers){default:if(typeof e.recentStickers=="number"){a.recentStickers=e.recentStickers;break}break;case"NOT_STARTED":case 0:a.recentStickers=0;break;case"FORCE_UPGRADE":case 1:a.recentStickers=1;break;case"DEVELOPMENT":case 2:a.recentStickers=2;break;case"PRODUCTION":case 3:a.recentStickers=3;break}switch(e.catalog){default:if(typeof e.catalog=="number"){a.catalog=e.catalog;break}break;case"NOT_STARTED":case 0:a.catalog=0;break;case"FORCE_UPGRADE":case 1:a.catalog=1;break;case"DEVELOPMENT":case 2:a.catalog=2;break;case"PRODUCTION":case 3:a.catalog=3;break}switch(e.starredStickers){default:if(typeof e.starredStickers=="number"){a.starredStickers=e.starredStickers;break}break;case"NOT_STARTED":case 0:a.starredStickers=0;break;case"FORCE_UPGRADE":case 1:a.starredStickers=1;break;case"DEVELOPMENT":case 2:a.starredStickers=2;break;case"PRODUCTION":case 3:a.starredStickers=3;break}switch(e.voipGroupCall){default:if(typeof e.voipGroupCall=="number"){a.voipGroupCall=e.voipGroupCall;break}break;case"NOT_STARTED":case 0:a.voipGroupCall=0;break;case"FORCE_UPGRADE":case 1:a.voipGroupCall=1;break;case"DEVELOPMENT":case 2:a.voipGroupCall=2;break;case"PRODUCTION":case 3:a.voipGroupCall=3;break}switch(e.templateMessage){default:if(typeof e.templateMessage=="number"){a.templateMessage=e.templateMessage;break}break;case"NOT_STARTED":case 0:a.templateMessage=0;break;case"FORCE_UPGRADE":case 1:a.templateMessage=1;break;case"DEVELOPMENT":case 2:a.templateMessage=2;break;case"PRODUCTION":case 3:a.templateMessage=3;break}switch(e.templateMessageInteractivity){default:if(typeof e.templateMessageInteractivity=="number"){a.templateMessageInteractivity=e.templateMessageInteractivity;break}break;case"NOT_STARTED":case 0:a.templateMessageInteractivity=0;break;case"FORCE_UPGRADE":case 1:a.templateMessageInteractivity=1;break;case"DEVELOPMENT":case 2:a.templateMessageInteractivity=2;break;case"PRODUCTION":case 3:a.templateMessageInteractivity=3;break}switch(e.ephemeralMessages){default:if(typeof e.ephemeralMessages=="number"){a.ephemeralMessages=e.ephemeralMessages;break}break;case"NOT_STARTED":case 0:a.ephemeralMessages=0;break;case"FORCE_UPGRADE":case 1:a.ephemeralMessages=1;break;case"DEVELOPMENT":case 2:a.ephemeralMessages=2;break;case"PRODUCTION":case 3:a.ephemeralMessages=3;break}switch(e.e2ENotificationSync){default:if(typeof e.e2ENotificationSync=="number"){a.e2ENotificationSync=e.e2ENotificationSync;break}break;case"NOT_STARTED":case 0:a.e2ENotificationSync=0;break;case"FORCE_UPGRADE":case 1:a.e2ENotificationSync=1;break;case"DEVELOPMENT":case 2:a.e2ENotificationSync=2;break;case"PRODUCTION":case 3:a.e2ENotificationSync=3;break}switch(e.recentStickersV2){default:if(typeof e.recentStickersV2=="number"){a.recentStickersV2=e.recentStickersV2;break}break;case"NOT_STARTED":case 0:a.recentStickersV2=0;break;case"FORCE_UPGRADE":case 1:a.recentStickersV2=1;break;case"DEVELOPMENT":case 2:a.recentStickersV2=2;break;case"PRODUCTION":case 3:a.recentStickersV2=3;break}switch(e.recentStickersV3){default:if(typeof e.recentStickersV3=="number"){a.recentStickersV3=e.recentStickersV3;break}break;case"NOT_STARTED":case 0:a.recentStickersV3=0;break;case"FORCE_UPGRADE":case 1:a.recentStickersV3=1;break;case"DEVELOPMENT":case 2:a.recentStickersV3=2;break;case"PRODUCTION":case 3:a.recentStickersV3=3;break}switch(e.userNotice){default:if(typeof e.userNotice=="number"){a.userNotice=e.userNotice;break}break;case"NOT_STARTED":case 0:a.userNotice=0;break;case"FORCE_UPGRADE":case 1:a.userNotice=1;break;case"DEVELOPMENT":case 2:a.userNotice=2;break;case"PRODUCTION":case 3:a.userNotice=3;break}switch(e.support){default:if(typeof e.support=="number"){a.support=e.support;break}break;case"NOT_STARTED":case 0:a.support=0;break;case"FORCE_UPGRADE":case 1:a.support=1;break;case"DEVELOPMENT":case 2:a.support=2;break;case"PRODUCTION":case 3:a.support=3;break}switch(e.groupUiiCleanup){default:if(typeof e.groupUiiCleanup=="number"){a.groupUiiCleanup=e.groupUiiCleanup;break}break;case"NOT_STARTED":case 0:a.groupUiiCleanup=0;break;case"FORCE_UPGRADE":case 1:a.groupUiiCleanup=1;break;case"DEVELOPMENT":case 2:a.groupUiiCleanup=2;break;case"PRODUCTION":case 3:a.groupUiiCleanup=3;break}switch(e.groupDogfoodingInternalOnly){default:if(typeof e.groupDogfoodingInternalOnly=="number"){a.groupDogfoodingInternalOnly=e.groupDogfoodingInternalOnly;break}break;case"NOT_STARTED":case 0:a.groupDogfoodingInternalOnly=0;break;case"FORCE_UPGRADE":case 1:a.groupDogfoodingInternalOnly=1;break;case"DEVELOPMENT":case 2:a.groupDogfoodingInternalOnly=2;break;case"PRODUCTION":case 3:a.groupDogfoodingInternalOnly=3;break}switch(e.settingsSync){default:if(typeof e.settingsSync=="number"){a.settingsSync=e.settingsSync;break}break;case"NOT_STARTED":case 0:a.settingsSync=0;break;case"FORCE_UPGRADE":case 1:a.settingsSync=1;break;case"DEVELOPMENT":case 2:a.settingsSync=2;break;case"PRODUCTION":case 3:a.settingsSync=3;break}switch(e.archiveV2){default:if(typeof e.archiveV2=="number"){a.archiveV2=e.archiveV2;break}break;case"NOT_STARTED":case 0:a.archiveV2=0;break;case"FORCE_UPGRADE":case 1:a.archiveV2=1;break;case"DEVELOPMENT":case 2:a.archiveV2=2;break;case"PRODUCTION":case 3:a.archiveV2=3;break}switch(e.ephemeralAllowGroupMembers){default:if(typeof e.ephemeralAllowGroupMembers=="number"){a.ephemeralAllowGroupMembers=e.ephemeralAllowGroupMembers;break}break;case"NOT_STARTED":case 0:a.ephemeralAllowGroupMembers=0;break;case"FORCE_UPGRADE":case 1:a.ephemeralAllowGroupMembers=1;break;case"DEVELOPMENT":case 2:a.ephemeralAllowGroupMembers=2;break;case"PRODUCTION":case 3:a.ephemeralAllowGroupMembers=3;break}switch(e.ephemeral24HDuration){default:if(typeof e.ephemeral24HDuration=="number"){a.ephemeral24HDuration=e.ephemeral24HDuration;break}break;case"NOT_STARTED":case 0:a.ephemeral24HDuration=0;break;case"FORCE_UPGRADE":case 1:a.ephemeral24HDuration=1;break;case"DEVELOPMENT":case 2:a.ephemeral24HDuration=2;break;case"PRODUCTION":case 3:a.ephemeral24HDuration=3;break}switch(e.mdForceUpgrade){default:if(typeof e.mdForceUpgrade=="number"){a.mdForceUpgrade=e.mdForceUpgrade;break}break;case"NOT_STARTED":case 0:a.mdForceUpgrade=0;break;case"FORCE_UPGRADE":case 1:a.mdForceUpgrade=1;break;case"DEVELOPMENT":case 2:a.mdForceUpgrade=2;break;case"PRODUCTION":case 3:a.mdForceUpgrade=3;break}switch(e.disappearingMode){default:if(typeof e.disappearingMode=="number"){a.disappearingMode=e.disappearingMode;break}break;case"NOT_STARTED":case 0:a.disappearingMode=0;break;case"FORCE_UPGRADE":case 1:a.disappearingMode=1;break;case"DEVELOPMENT":case 2:a.disappearingMode=2;break;case"PRODUCTION":case 3:a.disappearingMode=3;break}switch(e.externalMdOptInAvailable){default:if(typeof e.externalMdOptInAvailable=="number"){a.externalMdOptInAvailable=e.externalMdOptInAvailable;break}break;case"NOT_STARTED":case 0:a.externalMdOptInAvailable=0;break;case"FORCE_UPGRADE":case 1:a.externalMdOptInAvailable=1;break;case"DEVELOPMENT":case 2:a.externalMdOptInAvailable=2;break;case"PRODUCTION":case 3:a.externalMdOptInAvailable=3;break}switch(e.noDeleteMessageTimeLimit){default:if(typeof e.noDeleteMessageTimeLimit=="number"){a.noDeleteMessageTimeLimit=e.noDeleteMessageTimeLimit;break}break;case"NOT_STARTED":case 0:a.noDeleteMessageTimeLimit=0;break;case"FORCE_UPGRADE":case 1:a.noDeleteMessageTimeLimit=1;break;case"DEVELOPMENT":case 2:a.noDeleteMessageTimeLimit=2;break;case"PRODUCTION":case 3:a.noDeleteMessageTimeLimit=3;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.labelsDisplay!=null&&e.hasOwnProperty("labelsDisplay")&&(A.labelsDisplay=a.enums===String?p.proto.WebFeatures.Flag[e.labelsDisplay]===void 0?e.labelsDisplay:p.proto.WebFeatures.Flag[e.labelsDisplay]:e.labelsDisplay,a.oneofs&&(A._labelsDisplay="labelsDisplay")),e.voipIndividualOutgoing!=null&&e.hasOwnProperty("voipIndividualOutgoing")&&(A.voipIndividualOutgoing=a.enums===String?p.proto.WebFeatures.Flag[e.voipIndividualOutgoing]===void 0?e.voipIndividualOutgoing:p.proto.WebFeatures.Flag[e.voipIndividualOutgoing]:e.voipIndividualOutgoing,a.oneofs&&(A._voipIndividualOutgoing="voipIndividualOutgoing")),e.groupsV3!=null&&e.hasOwnProperty("groupsV3")&&(A.groupsV3=a.enums===String?p.proto.WebFeatures.Flag[e.groupsV3]===void 0?e.groupsV3:p.proto.WebFeatures.Flag[e.groupsV3]:e.groupsV3,a.oneofs&&(A._groupsV3="groupsV3")),e.groupsV3Create!=null&&e.hasOwnProperty("groupsV3Create")&&(A.groupsV3Create=a.enums===String?p.proto.WebFeatures.Flag[e.groupsV3Create]===void 0?e.groupsV3Create:p.proto.WebFeatures.Flag[e.groupsV3Create]:e.groupsV3Create,a.oneofs&&(A._groupsV3Create="groupsV3Create")),e.changeNumberV2!=null&&e.hasOwnProperty("changeNumberV2")&&(A.changeNumberV2=a.enums===String?p.proto.WebFeatures.Flag[e.changeNumberV2]===void 0?e.changeNumberV2:p.proto.WebFeatures.Flag[e.changeNumberV2]:e.changeNumberV2,a.oneofs&&(A._changeNumberV2="changeNumberV2")),e.queryStatusV3Thumbnail!=null&&e.hasOwnProperty("queryStatusV3Thumbnail")&&(A.queryStatusV3Thumbnail=a.enums===String?p.proto.WebFeatures.Flag[e.queryStatusV3Thumbnail]===void 0?e.queryStatusV3Thumbnail:p.proto.WebFeatures.Flag[e.queryStatusV3Thumbnail]:e.queryStatusV3Thumbnail,a.oneofs&&(A._queryStatusV3Thumbnail="queryStatusV3Thumbnail")),e.liveLocations!=null&&e.hasOwnProperty("liveLocations")&&(A.liveLocations=a.enums===String?p.proto.WebFeatures.Flag[e.liveLocations]===void 0?e.liveLocations:p.proto.WebFeatures.Flag[e.liveLocations]:e.liveLocations,a.oneofs&&(A._liveLocations="liveLocations")),e.queryVname!=null&&e.hasOwnProperty("queryVname")&&(A.queryVname=a.enums===String?p.proto.WebFeatures.Flag[e.queryVname]===void 0?e.queryVname:p.proto.WebFeatures.Flag[e.queryVname]:e.queryVname,a.oneofs&&(A._queryVname="queryVname")),e.voipIndividualIncoming!=null&&e.hasOwnProperty("voipIndividualIncoming")&&(A.voipIndividualIncoming=a.enums===String?p.proto.WebFeatures.Flag[e.voipIndividualIncoming]===void 0?e.voipIndividualIncoming:p.proto.WebFeatures.Flag[e.voipIndividualIncoming]:e.voipIndividualIncoming,a.oneofs&&(A._voipIndividualIncoming="voipIndividualIncoming")),e.quickRepliesQuery!=null&&e.hasOwnProperty("quickRepliesQuery")&&(A.quickRepliesQuery=a.enums===String?p.proto.WebFeatures.Flag[e.quickRepliesQuery]===void 0?e.quickRepliesQuery:p.proto.WebFeatures.Flag[e.quickRepliesQuery]:e.quickRepliesQuery,a.oneofs&&(A._quickRepliesQuery="quickRepliesQuery")),e.payments!=null&&e.hasOwnProperty("payments")&&(A.payments=a.enums===String?p.proto.WebFeatures.Flag[e.payments]===void 0?e.payments:p.proto.WebFeatures.Flag[e.payments]:e.payments,a.oneofs&&(A._payments="payments")),e.stickerPackQuery!=null&&e.hasOwnProperty("stickerPackQuery")&&(A.stickerPackQuery=a.enums===String?p.proto.WebFeatures.Flag[e.stickerPackQuery]===void 0?e.stickerPackQuery:p.proto.WebFeatures.Flag[e.stickerPackQuery]:e.stickerPackQuery,a.oneofs&&(A._stickerPackQuery="stickerPackQuery")),e.liveLocationsFinal!=null&&e.hasOwnProperty("liveLocationsFinal")&&(A.liveLocationsFinal=a.enums===String?p.proto.WebFeatures.Flag[e.liveLocationsFinal]===void 0?e.liveLocationsFinal:p.proto.WebFeatures.Flag[e.liveLocationsFinal]:e.liveLocationsFinal,a.oneofs&&(A._liveLocationsFinal="liveLocationsFinal")),e.labelsEdit!=null&&e.hasOwnProperty("labelsEdit")&&(A.labelsEdit=a.enums===String?p.proto.WebFeatures.Flag[e.labelsEdit]===void 0?e.labelsEdit:p.proto.WebFeatures.Flag[e.labelsEdit]:e.labelsEdit,a.oneofs&&(A._labelsEdit="labelsEdit")),e.mediaUpload!=null&&e.hasOwnProperty("mediaUpload")&&(A.mediaUpload=a.enums===String?p.proto.WebFeatures.Flag[e.mediaUpload]===void 0?e.mediaUpload:p.proto.WebFeatures.Flag[e.mediaUpload]:e.mediaUpload,a.oneofs&&(A._mediaUpload="mediaUpload")),e.mediaUploadRichQuickReplies!=null&&e.hasOwnProperty("mediaUploadRichQuickReplies")&&(A.mediaUploadRichQuickReplies=a.enums===String?p.proto.WebFeatures.Flag[e.mediaUploadRichQuickReplies]===void 0?e.mediaUploadRichQuickReplies:p.proto.WebFeatures.Flag[e.mediaUploadRichQuickReplies]:e.mediaUploadRichQuickReplies,a.oneofs&&(A._mediaUploadRichQuickReplies="mediaUploadRichQuickReplies")),e.vnameV2!=null&&e.hasOwnProperty("vnameV2")&&(A.vnameV2=a.enums===String?p.proto.WebFeatures.Flag[e.vnameV2]===void 0?e.vnameV2:p.proto.WebFeatures.Flag[e.vnameV2]:e.vnameV2,a.oneofs&&(A._vnameV2="vnameV2")),e.videoPlaybackUrl!=null&&e.hasOwnProperty("videoPlaybackUrl")&&(A.videoPlaybackUrl=a.enums===String?p.proto.WebFeatures.Flag[e.videoPlaybackUrl]===void 0?e.videoPlaybackUrl:p.proto.WebFeatures.Flag[e.videoPlaybackUrl]:e.videoPlaybackUrl,a.oneofs&&(A._videoPlaybackUrl="videoPlaybackUrl")),e.statusRanking!=null&&e.hasOwnProperty("statusRanking")&&(A.statusRanking=a.enums===String?p.proto.WebFeatures.Flag[e.statusRanking]===void 0?e.statusRanking:p.proto.WebFeatures.Flag[e.statusRanking]:e.statusRanking,a.oneofs&&(A._statusRanking="statusRanking")),e.voipIndividualVideo!=null&&e.hasOwnProperty("voipIndividualVideo")&&(A.voipIndividualVideo=a.enums===String?p.proto.WebFeatures.Flag[e.voipIndividualVideo]===void 0?e.voipIndividualVideo:p.proto.WebFeatures.Flag[e.voipIndividualVideo]:e.voipIndividualVideo,a.oneofs&&(A._voipIndividualVideo="voipIndividualVideo")),e.thirdPartyStickers!=null&&e.hasOwnProperty("thirdPartyStickers")&&(A.thirdPartyStickers=a.enums===String?p.proto.WebFeatures.Flag[e.thirdPartyStickers]===void 0?e.thirdPartyStickers:p.proto.WebFeatures.Flag[e.thirdPartyStickers]:e.thirdPartyStickers,a.oneofs&&(A._thirdPartyStickers="thirdPartyStickers")),e.frequentlyForwardedSetting!=null&&e.hasOwnProperty("frequentlyForwardedSetting")&&(A.frequentlyForwardedSetting=a.enums===String?p.proto.WebFeatures.Flag[e.frequentlyForwardedSetting]===void 0?e.frequentlyForwardedSetting:p.proto.WebFeatures.Flag[e.frequentlyForwardedSetting]:e.frequentlyForwardedSetting,a.oneofs&&(A._frequentlyForwardedSetting="frequentlyForwardedSetting")),e.groupsV4JoinPermission!=null&&e.hasOwnProperty("groupsV4JoinPermission")&&(A.groupsV4JoinPermission=a.enums===String?p.proto.WebFeatures.Flag[e.groupsV4JoinPermission]===void 0?e.groupsV4JoinPermission:p.proto.WebFeatures.Flag[e.groupsV4JoinPermission]:e.groupsV4JoinPermission,a.oneofs&&(A._groupsV4JoinPermission="groupsV4JoinPermission")),e.recentStickers!=null&&e.hasOwnProperty("recentStickers")&&(A.recentStickers=a.enums===String?p.proto.WebFeatures.Flag[e.recentStickers]===void 0?e.recentStickers:p.proto.WebFeatures.Flag[e.recentStickers]:e.recentStickers,a.oneofs&&(A._recentStickers="recentStickers")),e.catalog!=null&&e.hasOwnProperty("catalog")&&(A.catalog=a.enums===String?p.proto.WebFeatures.Flag[e.catalog]===void 0?e.catalog:p.proto.WebFeatures.Flag[e.catalog]:e.catalog,a.oneofs&&(A._catalog="catalog")),e.starredStickers!=null&&e.hasOwnProperty("starredStickers")&&(A.starredStickers=a.enums===String?p.proto.WebFeatures.Flag[e.starredStickers]===void 0?e.starredStickers:p.proto.WebFeatures.Flag[e.starredStickers]:e.starredStickers,a.oneofs&&(A._starredStickers="starredStickers")),e.voipGroupCall!=null&&e.hasOwnProperty("voipGroupCall")&&(A.voipGroupCall=a.enums===String?p.proto.WebFeatures.Flag[e.voipGroupCall]===void 0?e.voipGroupCall:p.proto.WebFeatures.Flag[e.voipGroupCall]:e.voipGroupCall,a.oneofs&&(A._voipGroupCall="voipGroupCall")),e.templateMessage!=null&&e.hasOwnProperty("templateMessage")&&(A.templateMessage=a.enums===String?p.proto.WebFeatures.Flag[e.templateMessage]===void 0?e.templateMessage:p.proto.WebFeatures.Flag[e.templateMessage]:e.templateMessage,a.oneofs&&(A._templateMessage="templateMessage")),e.templateMessageInteractivity!=null&&e.hasOwnProperty("templateMessageInteractivity")&&(A.templateMessageInteractivity=a.enums===String?p.proto.WebFeatures.Flag[e.templateMessageInteractivity]===void 0?e.templateMessageInteractivity:p.proto.WebFeatures.Flag[e.templateMessageInteractivity]:e.templateMessageInteractivity,a.oneofs&&(A._templateMessageInteractivity="templateMessageInteractivity")),e.ephemeralMessages!=null&&e.hasOwnProperty("ephemeralMessages")&&(A.ephemeralMessages=a.enums===String?p.proto.WebFeatures.Flag[e.ephemeralMessages]===void 0?e.ephemeralMessages:p.proto.WebFeatures.Flag[e.ephemeralMessages]:e.ephemeralMessages,a.oneofs&&(A._ephemeralMessages="ephemeralMessages")),e.e2ENotificationSync!=null&&e.hasOwnProperty("e2ENotificationSync")&&(A.e2ENotificationSync=a.enums===String?p.proto.WebFeatures.Flag[e.e2ENotificationSync]===void 0?e.e2ENotificationSync:p.proto.WebFeatures.Flag[e.e2ENotificationSync]:e.e2ENotificationSync,a.oneofs&&(A._e2ENotificationSync="e2ENotificationSync")),e.recentStickersV2!=null&&e.hasOwnProperty("recentStickersV2")&&(A.recentStickersV2=a.enums===String?p.proto.WebFeatures.Flag[e.recentStickersV2]===void 0?e.recentStickersV2:p.proto.WebFeatures.Flag[e.recentStickersV2]:e.recentStickersV2,a.oneofs&&(A._recentStickersV2="recentStickersV2")),e.recentStickersV3!=null&&e.hasOwnProperty("recentStickersV3")&&(A.recentStickersV3=a.enums===String?p.proto.WebFeatures.Flag[e.recentStickersV3]===void 0?e.recentStickersV3:p.proto.WebFeatures.Flag[e.recentStickersV3]:e.recentStickersV3,a.oneofs&&(A._recentStickersV3="recentStickersV3")),e.userNotice!=null&&e.hasOwnProperty("userNotice")&&(A.userNotice=a.enums===String?p.proto.WebFeatures.Flag[e.userNotice]===void 0?e.userNotice:p.proto.WebFeatures.Flag[e.userNotice]:e.userNotice,a.oneofs&&(A._userNotice="userNotice")),e.support!=null&&e.hasOwnProperty("support")&&(A.support=a.enums===String?p.proto.WebFeatures.Flag[e.support]===void 0?e.support:p.proto.WebFeatures.Flag[e.support]:e.support,a.oneofs&&(A._support="support")),e.groupUiiCleanup!=null&&e.hasOwnProperty("groupUiiCleanup")&&(A.groupUiiCleanup=a.enums===String?p.proto.WebFeatures.Flag[e.groupUiiCleanup]===void 0?e.groupUiiCleanup:p.proto.WebFeatures.Flag[e.groupUiiCleanup]:e.groupUiiCleanup,a.oneofs&&(A._groupUiiCleanup="groupUiiCleanup")),e.groupDogfoodingInternalOnly!=null&&e.hasOwnProperty("groupDogfoodingInternalOnly")&&(A.groupDogfoodingInternalOnly=a.enums===String?p.proto.WebFeatures.Flag[e.groupDogfoodingInternalOnly]===void 0?e.groupDogfoodingInternalOnly:p.proto.WebFeatures.Flag[e.groupDogfoodingInternalOnly]:e.groupDogfoodingInternalOnly,a.oneofs&&(A._groupDogfoodingInternalOnly="groupDogfoodingInternalOnly")),e.settingsSync!=null&&e.hasOwnProperty("settingsSync")&&(A.settingsSync=a.enums===String?p.proto.WebFeatures.Flag[e.settingsSync]===void 0?e.settingsSync:p.proto.WebFeatures.Flag[e.settingsSync]:e.settingsSync,a.oneofs&&(A._settingsSync="settingsSync")),e.archiveV2!=null&&e.hasOwnProperty("archiveV2")&&(A.archiveV2=a.enums===String?p.proto.WebFeatures.Flag[e.archiveV2]===void 0?e.archiveV2:p.proto.WebFeatures.Flag[e.archiveV2]:e.archiveV2,a.oneofs&&(A._archiveV2="archiveV2")),e.ephemeralAllowGroupMembers!=null&&e.hasOwnProperty("ephemeralAllowGroupMembers")&&(A.ephemeralAllowGroupMembers=a.enums===String?p.proto.WebFeatures.Flag[e.ephemeralAllowGroupMembers]===void 0?e.ephemeralAllowGroupMembers:p.proto.WebFeatures.Flag[e.ephemeralAllowGroupMembers]:e.ephemeralAllowGroupMembers,a.oneofs&&(A._ephemeralAllowGroupMembers="ephemeralAllowGroupMembers")),e.ephemeral24HDuration!=null&&e.hasOwnProperty("ephemeral24HDuration")&&(A.ephemeral24HDuration=a.enums===String?p.proto.WebFeatures.Flag[e.ephemeral24HDuration]===void 0?e.ephemeral24HDuration:p.proto.WebFeatures.Flag[e.ephemeral24HDuration]:e.ephemeral24HDuration,a.oneofs&&(A._ephemeral24HDuration="ephemeral24HDuration")),e.mdForceUpgrade!=null&&e.hasOwnProperty("mdForceUpgrade")&&(A.mdForceUpgrade=a.enums===String?p.proto.WebFeatures.Flag[e.mdForceUpgrade]===void 0?e.mdForceUpgrade:p.proto.WebFeatures.Flag[e.mdForceUpgrade]:e.mdForceUpgrade,a.oneofs&&(A._mdForceUpgrade="mdForceUpgrade")),e.disappearingMode!=null&&e.hasOwnProperty("disappearingMode")&&(A.disappearingMode=a.enums===String?p.proto.WebFeatures.Flag[e.disappearingMode]===void 0?e.disappearingMode:p.proto.WebFeatures.Flag[e.disappearingMode]:e.disappearingMode,a.oneofs&&(A._disappearingMode="disappearingMode")),e.externalMdOptInAvailable!=null&&e.hasOwnProperty("externalMdOptInAvailable")&&(A.externalMdOptInAvailable=a.enums===String?p.proto.WebFeatures.Flag[e.externalMdOptInAvailable]===void 0?e.externalMdOptInAvailable:p.proto.WebFeatures.Flag[e.externalMdOptInAvailable]:e.externalMdOptInAvailable,a.oneofs&&(A._externalMdOptInAvailable="externalMdOptInAvailable")),e.noDeleteMessageTimeLimit!=null&&e.hasOwnProperty("noDeleteMessageTimeLimit")&&(A.noDeleteMessageTimeLimit=a.enums===String?p.proto.WebFeatures.Flag[e.noDeleteMessageTimeLimit]===void 0?e.noDeleteMessageTimeLimit:p.proto.WebFeatures.Flag[e.noDeleteMessageTimeLimit]:e.noDeleteMessageTimeLimit,a.oneofs&&(A._noDeleteMessageTimeLimit="noDeleteMessageTimeLimit")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.WebFeatures"},t.Flag=(function(){let i={},e=Object.create(i);return e[i[0]="NOT_STARTED"]=0,e[i[1]="FORCE_UPGRADE"]=1,e[i[2]="DEVELOPMENT"]=2,e[i[3]="PRODUCTION"]=3,e})(),t})(),n.WebLinkRenderConfig=(function(){let t={},o=Object.create(t);return o[t[0]="WEBVIEW"]=0,o[t[1]="SYSTEM"]=1,o})(),n.WebMessageInfo=(function(){function t(i){if(this.messageStubParameters=[],this.labels=[],this.userReceipt=[],this.reactions=[],this.pollUpdates=[],this.eventResponses=[],this.statusMentions=[],this.messageAddOns=[],this.statusMentionSources=[],this.supportAiCitations=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.key=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.message=p.proto.Message.decode(e,e.uint32());break}case 3:{s.messageTimestamp=e.uint64();break}case 4:{s.status=e.int32();break}case 5:{s.participant=e.string();break}case 6:{s.messageC2STimestamp=e.uint64();break}case 16:{s.ignore=e.bool();break}case 17:{s.starred=e.bool();break}case 18:{s.broadcast=e.bool();break}case 19:{s.pushName=e.string();break}case 20:{s.mediaCiphertextSha256=e.bytes();break}case 21:{s.multicast=e.bool();break}case 22:{s.urlText=e.bool();break}case 23:{s.urlNumber=e.bool();break}case 24:{s.messageStubType=e.int32();break}case 25:{s.clearMedia=e.bool();break}case 26:{s.messageStubParameters&&s.messageStubParameters.length||(s.messageStubParameters=[]),s.messageStubParameters.push(e.string());break}case 27:{s.duration=e.uint32();break}case 28:{s.labels&&s.labels.length||(s.labels=[]),s.labels.push(e.string());break}case 29:{s.paymentInfo=p.proto.PaymentInfo.decode(e,e.uint32());break}case 30:{s.finalLiveLocation=p.proto.Message.LiveLocationMessage.decode(e,e.uint32());break}case 31:{s.quotedPaymentInfo=p.proto.PaymentInfo.decode(e,e.uint32());break}case 32:{s.ephemeralStartTimestamp=e.uint64();break}case 33:{s.ephemeralDuration=e.uint32();break}case 34:{s.ephemeralOffToOn=e.bool();break}case 35:{s.ephemeralOutOfSync=e.bool();break}case 36:{s.bizPrivacyStatus=e.int32();break}case 37:{s.verifiedBizName=e.string();break}case 38:{s.mediaData=p.proto.MediaData.decode(e,e.uint32());break}case 39:{s.photoChange=p.proto.PhotoChange.decode(e,e.uint32());break}case 40:{s.userReceipt&&s.userReceipt.length||(s.userReceipt=[]),s.userReceipt.push(p.proto.UserReceipt.decode(e,e.uint32()));break}case 41:{s.reactions&&s.reactions.length||(s.reactions=[]),s.reactions.push(p.proto.Reaction.decode(e,e.uint32()));break}case 42:{s.quotedStickerData=p.proto.MediaData.decode(e,e.uint32());break}case 43:{s.futureproofData=e.bytes();break}case 44:{s.statusPsa=p.proto.StatusPSA.decode(e,e.uint32());break}case 45:{s.pollUpdates&&s.pollUpdates.length||(s.pollUpdates=[]),s.pollUpdates.push(p.proto.PollUpdate.decode(e,e.uint32()));break}case 46:{s.pollAdditionalMetadata=p.proto.PollAdditionalMetadata.decode(e,e.uint32());break}case 47:{s.agentId=e.string();break}case 48:{s.statusAlreadyViewed=e.bool();break}case 49:{s.messageSecret=e.bytes();break}case 50:{s.keepInChat=p.proto.KeepInChat.decode(e,e.uint32());break}case 51:{s.originalSelfAuthorUserJidString=e.string();break}case 52:{s.revokeMessageTimestamp=e.uint64();break}case 54:{s.pinInChat=p.proto.PinInChat.decode(e,e.uint32());break}case 55:{s.premiumMessageInfo=p.proto.PremiumMessageInfo.decode(e,e.uint32());break}case 56:{s.is1PBizBotMessage=e.bool();break}case 57:{s.isGroupHistoryMessage=e.bool();break}case 58:{s.botMessageInvokerJid=e.string();break}case 59:{s.commentMetadata=p.proto.CommentMetadata.decode(e,e.uint32());break}case 61:{s.eventResponses&&s.eventResponses.length||(s.eventResponses=[]),s.eventResponses.push(p.proto.EventResponse.decode(e,e.uint32()));break}case 62:{s.reportingTokenInfo=p.proto.ReportingTokenInfo.decode(e,e.uint32());break}case 63:{s.newsletterServerId=e.uint64();break}case 64:{s.eventAdditionalMetadata=p.proto.EventAdditionalMetadata.decode(e,e.uint32());break}case 65:{s.isMentionedInStatus=e.bool();break}case 66:{s.statusMentions&&s.statusMentions.length||(s.statusMentions=[]),s.statusMentions.push(e.string());break}case 67:{s.targetMessageId=p.proto.MessageKey.decode(e,e.uint32());break}case 68:{s.messageAddOns&&s.messageAddOns.length||(s.messageAddOns=[]),s.messageAddOns.push(p.proto.MessageAddOn.decode(e,e.uint32()));break}case 69:{s.statusMentionMessageInfo=p.proto.StatusMentionMessage.decode(e,e.uint32());break}case 70:{s.isSupportAiMessage=e.bool();break}case 71:{s.statusMentionSources&&s.statusMentionSources.length||(s.statusMentionSources=[]),s.statusMentionSources.push(e.string());break}case 72:{s.supportAiCitations&&s.supportAiCitations.length||(s.supportAiCitations=[]),s.supportAiCitations.push(p.proto.Citation.decode(e,e.uint32()));break}case 73:{s.botTargetId=e.string();break}case 74:{s.groupHistoryIndividualMessageInfo=p.proto.GroupHistoryIndividualMessageInfo.decode(e,e.uint32());break}case 75:{s.groupHistoryBundleInfo=p.proto.GroupHistoryBundleInfo.decode(e,e.uint32());break}case 76:{s.interactiveMessageAdditionalMetadata=p.proto.InteractiveMessageAdditionalMetadata.decode(e,e.uint32());break}case 77:{s.quarantinedMessage=p.proto.QuarantinedMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.WebMessageInfo)return e;var a=new p.proto.WebMessageInfo;if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.WebMessageInfo.key: object expected");a.key=p.proto.MessageKey.fromObject(e.key)}if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.WebMessageInfo.message: object expected");a.message=p.proto.Message.fromObject(e.message)}switch(e.messageTimestamp!=null&&(l.Long?(a.messageTimestamp=l.Long.fromValue(e.messageTimestamp)).unsigned=!0:typeof e.messageTimestamp=="string"?a.messageTimestamp=parseInt(e.messageTimestamp,10):typeof e.messageTimestamp=="number"?a.messageTimestamp=e.messageTimestamp:typeof e.messageTimestamp=="object"&&(a.messageTimestamp=new l.LongBits(e.messageTimestamp.low>>>0,e.messageTimestamp.high>>>0).toNumber(!0))),e.status){default:if(typeof e.status=="number"){a.status=e.status;break}break;case"ERROR":case 0:a.status=0;break;case"PENDING":case 1:a.status=1;break;case"SERVER_ACK":case 2:a.status=2;break;case"DELIVERY_ACK":case 3:a.status=3;break;case"READ":case 4:a.status=4;break;case"PLAYED":case 5:a.status=5;break}switch(e.participant!=null&&(a.participant=String(e.participant)),e.messageC2STimestamp!=null&&(l.Long?(a.messageC2STimestamp=l.Long.fromValue(e.messageC2STimestamp)).unsigned=!0:typeof e.messageC2STimestamp=="string"?a.messageC2STimestamp=parseInt(e.messageC2STimestamp,10):typeof e.messageC2STimestamp=="number"?a.messageC2STimestamp=e.messageC2STimestamp:typeof e.messageC2STimestamp=="object"&&(a.messageC2STimestamp=new l.LongBits(e.messageC2STimestamp.low>>>0,e.messageC2STimestamp.high>>>0).toNumber(!0))),e.ignore!=null&&(a.ignore=!!e.ignore),e.starred!=null&&(a.starred=!!e.starred),e.broadcast!=null&&(a.broadcast=!!e.broadcast),e.pushName!=null&&(a.pushName=String(e.pushName)),e.mediaCiphertextSha256!=null&&(typeof e.mediaCiphertextSha256=="string"?l.base64.decode(e.mediaCiphertextSha256,a.mediaCiphertextSha256=l.newBuffer(l.base64.length(e.mediaCiphertextSha256)),0):e.mediaCiphertextSha256.length>=0&&(a.mediaCiphertextSha256=e.mediaCiphertextSha256)),e.multicast!=null&&(a.multicast=!!e.multicast),e.urlText!=null&&(a.urlText=!!e.urlText),e.urlNumber!=null&&(a.urlNumber=!!e.urlNumber),e.messageStubType){default:if(typeof e.messageStubType=="number"){a.messageStubType=e.messageStubType;break}break;case"UNKNOWN":case 0:a.messageStubType=0;break;case"REVOKE":case 1:a.messageStubType=1;break;case"CIPHERTEXT":case 2:a.messageStubType=2;break;case"FUTUREPROOF":case 3:a.messageStubType=3;break;case"NON_VERIFIED_TRANSITION":case 4:a.messageStubType=4;break;case"UNVERIFIED_TRANSITION":case 5:a.messageStubType=5;break;case"VERIFIED_TRANSITION":case 6:a.messageStubType=6;break;case"VERIFIED_LOW_UNKNOWN":case 7:a.messageStubType=7;break;case"VERIFIED_HIGH":case 8:a.messageStubType=8;break;case"VERIFIED_INITIAL_UNKNOWN":case 9:a.messageStubType=9;break;case"VERIFIED_INITIAL_LOW":case 10:a.messageStubType=10;break;case"VERIFIED_INITIAL_HIGH":case 11:a.messageStubType=11;break;case"VERIFIED_TRANSITION_ANY_TO_NONE":case 12:a.messageStubType=12;break;case"VERIFIED_TRANSITION_ANY_TO_HIGH":case 13:a.messageStubType=13;break;case"VERIFIED_TRANSITION_HIGH_TO_LOW":case 14:a.messageStubType=14;break;case"VERIFIED_TRANSITION_HIGH_TO_UNKNOWN":case 15:a.messageStubType=15;break;case"VERIFIED_TRANSITION_UNKNOWN_TO_LOW":case 16:a.messageStubType=16;break;case"VERIFIED_TRANSITION_LOW_TO_UNKNOWN":case 17:a.messageStubType=17;break;case"VERIFIED_TRANSITION_NONE_TO_LOW":case 18:a.messageStubType=18;break;case"VERIFIED_TRANSITION_NONE_TO_UNKNOWN":case 19:a.messageStubType=19;break;case"GROUP_CREATE":case 20:a.messageStubType=20;break;case"GROUP_CHANGE_SUBJECT":case 21:a.messageStubType=21;break;case"GROUP_CHANGE_ICON":case 22:a.messageStubType=22;break;case"GROUP_CHANGE_INVITE_LINK":case 23:a.messageStubType=23;break;case"GROUP_CHANGE_DESCRIPTION":case 24:a.messageStubType=24;break;case"GROUP_CHANGE_RESTRICT":case 25:a.messageStubType=25;break;case"GROUP_CHANGE_ANNOUNCE":case 26:a.messageStubType=26;break;case"GROUP_PARTICIPANT_ADD":case 27:a.messageStubType=27;break;case"GROUP_PARTICIPANT_REMOVE":case 28:a.messageStubType=28;break;case"GROUP_PARTICIPANT_PROMOTE":case 29:a.messageStubType=29;break;case"GROUP_PARTICIPANT_DEMOTE":case 30:a.messageStubType=30;break;case"GROUP_PARTICIPANT_INVITE":case 31:a.messageStubType=31;break;case"GROUP_PARTICIPANT_LEAVE":case 32:a.messageStubType=32;break;case"GROUP_PARTICIPANT_CHANGE_NUMBER":case 33:a.messageStubType=33;break;case"BROADCAST_CREATE":case 34:a.messageStubType=34;break;case"BROADCAST_ADD":case 35:a.messageStubType=35;break;case"BROADCAST_REMOVE":case 36:a.messageStubType=36;break;case"GENERIC_NOTIFICATION":case 37:a.messageStubType=37;break;case"E2E_IDENTITY_CHANGED":case 38:a.messageStubType=38;break;case"E2E_ENCRYPTED":case 39:a.messageStubType=39;break;case"CALL_MISSED_VOICE":case 40:a.messageStubType=40;break;case"CALL_MISSED_VIDEO":case 41:a.messageStubType=41;break;case"INDIVIDUAL_CHANGE_NUMBER":case 42:a.messageStubType=42;break;case"GROUP_DELETE":case 43:a.messageStubType=43;break;case"GROUP_ANNOUNCE_MODE_MESSAGE_BOUNCE":case 44:a.messageStubType=44;break;case"CALL_MISSED_GROUP_VOICE":case 45:a.messageStubType=45;break;case"CALL_MISSED_GROUP_VIDEO":case 46:a.messageStubType=46;break;case"PAYMENT_CIPHERTEXT":case 47:a.messageStubType=47;break;case"PAYMENT_FUTUREPROOF":case 48:a.messageStubType=48;break;case"PAYMENT_TRANSACTION_STATUS_UPDATE_FAILED":case 49:a.messageStubType=49;break;case"PAYMENT_TRANSACTION_STATUS_UPDATE_REFUNDED":case 50:a.messageStubType=50;break;case"PAYMENT_TRANSACTION_STATUS_UPDATE_REFUND_FAILED":case 51:a.messageStubType=51;break;case"PAYMENT_TRANSACTION_STATUS_RECEIVER_PENDING_SETUP":case 52:a.messageStubType=52;break;case"PAYMENT_TRANSACTION_STATUS_RECEIVER_SUCCESS_AFTER_HICCUP":case 53:a.messageStubType=53;break;case"PAYMENT_ACTION_ACCOUNT_SETUP_REMINDER":case 54:a.messageStubType=54;break;case"PAYMENT_ACTION_SEND_PAYMENT_REMINDER":case 55:a.messageStubType=55;break;case"PAYMENT_ACTION_SEND_PAYMENT_INVITATION":case 56:a.messageStubType=56;break;case"PAYMENT_ACTION_REQUEST_DECLINED":case 57:a.messageStubType=57;break;case"PAYMENT_ACTION_REQUEST_EXPIRED":case 58:a.messageStubType=58;break;case"PAYMENT_ACTION_REQUEST_CANCELLED":case 59:a.messageStubType=59;break;case"BIZ_VERIFIED_TRANSITION_TOP_TO_BOTTOM":case 60:a.messageStubType=60;break;case"BIZ_VERIFIED_TRANSITION_BOTTOM_TO_TOP":case 61:a.messageStubType=61;break;case"BIZ_INTRO_TOP":case 62:a.messageStubType=62;break;case"BIZ_INTRO_BOTTOM":case 63:a.messageStubType=63;break;case"BIZ_NAME_CHANGE":case 64:a.messageStubType=64;break;case"BIZ_MOVE_TO_CONSUMER_APP":case 65:a.messageStubType=65;break;case"BIZ_TWO_TIER_MIGRATION_TOP":case 66:a.messageStubType=66;break;case"BIZ_TWO_TIER_MIGRATION_BOTTOM":case 67:a.messageStubType=67;break;case"OVERSIZED":case 68:a.messageStubType=68;break;case"GROUP_CHANGE_NO_FREQUENTLY_FORWARDED":case 69:a.messageStubType=69;break;case"GROUP_V4_ADD_INVITE_SENT":case 70:a.messageStubType=70;break;case"GROUP_PARTICIPANT_ADD_REQUEST_JOIN":case 71:a.messageStubType=71;break;case"CHANGE_EPHEMERAL_SETTING":case 72:a.messageStubType=72;break;case"E2E_DEVICE_CHANGED":case 73:a.messageStubType=73;break;case"VIEWED_ONCE":case 74:a.messageStubType=74;break;case"E2E_ENCRYPTED_NOW":case 75:a.messageStubType=75;break;case"BLUE_MSG_BSP_FB_TO_BSP_PREMISE":case 76:a.messageStubType=76;break;case"BLUE_MSG_BSP_FB_TO_SELF_FB":case 77:a.messageStubType=77;break;case"BLUE_MSG_BSP_FB_TO_SELF_PREMISE":case 78:a.messageStubType=78;break;case"BLUE_MSG_BSP_FB_UNVERIFIED":case 79:a.messageStubType=79;break;case"BLUE_MSG_BSP_FB_UNVERIFIED_TO_SELF_PREMISE_VERIFIED":case 80:a.messageStubType=80;break;case"BLUE_MSG_BSP_FB_VERIFIED":case 81:a.messageStubType=81;break;case"BLUE_MSG_BSP_FB_VERIFIED_TO_SELF_PREMISE_UNVERIFIED":case 82:a.messageStubType=82;break;case"BLUE_MSG_BSP_PREMISE_TO_SELF_PREMISE":case 83:a.messageStubType=83;break;case"BLUE_MSG_BSP_PREMISE_UNVERIFIED":case 84:a.messageStubType=84;break;case"BLUE_MSG_BSP_PREMISE_UNVERIFIED_TO_SELF_PREMISE_VERIFIED":case 85:a.messageStubType=85;break;case"BLUE_MSG_BSP_PREMISE_VERIFIED":case 86:a.messageStubType=86;break;case"BLUE_MSG_BSP_PREMISE_VERIFIED_TO_SELF_PREMISE_UNVERIFIED":case 87:a.messageStubType=87;break;case"BLUE_MSG_CONSUMER_TO_BSP_FB_UNVERIFIED":case 88:a.messageStubType=88;break;case"BLUE_MSG_CONSUMER_TO_BSP_PREMISE_UNVERIFIED":case 89:a.messageStubType=89;break;case"BLUE_MSG_CONSUMER_TO_SELF_FB_UNVERIFIED":case 90:a.messageStubType=90;break;case"BLUE_MSG_CONSUMER_TO_SELF_PREMISE_UNVERIFIED":case 91:a.messageStubType=91;break;case"BLUE_MSG_SELF_FB_TO_BSP_PREMISE":case 92:a.messageStubType=92;break;case"BLUE_MSG_SELF_FB_TO_SELF_PREMISE":case 93:a.messageStubType=93;break;case"BLUE_MSG_SELF_FB_UNVERIFIED":case 94:a.messageStubType=94;break;case"BLUE_MSG_SELF_FB_UNVERIFIED_TO_SELF_PREMISE_VERIFIED":case 95:a.messageStubType=95;break;case"BLUE_MSG_SELF_FB_VERIFIED":case 96:a.messageStubType=96;break;case"BLUE_MSG_SELF_FB_VERIFIED_TO_SELF_PREMISE_UNVERIFIED":case 97:a.messageStubType=97;break;case"BLUE_MSG_SELF_PREMISE_TO_BSP_PREMISE":case 98:a.messageStubType=98;break;case"BLUE_MSG_SELF_PREMISE_UNVERIFIED":case 99:a.messageStubType=99;break;case"BLUE_MSG_SELF_PREMISE_VERIFIED":case 100:a.messageStubType=100;break;case"BLUE_MSG_TO_BSP_FB":case 101:a.messageStubType=101;break;case"BLUE_MSG_TO_CONSUMER":case 102:a.messageStubType=102;break;case"BLUE_MSG_TO_SELF_FB":case 103:a.messageStubType=103;break;case"BLUE_MSG_UNVERIFIED_TO_BSP_FB_VERIFIED":case 104:a.messageStubType=104;break;case"BLUE_MSG_UNVERIFIED_TO_BSP_PREMISE_VERIFIED":case 105:a.messageStubType=105;break;case"BLUE_MSG_UNVERIFIED_TO_SELF_FB_VERIFIED":case 106:a.messageStubType=106;break;case"BLUE_MSG_UNVERIFIED_TO_VERIFIED":case 107:a.messageStubType=107;break;case"BLUE_MSG_VERIFIED_TO_BSP_FB_UNVERIFIED":case 108:a.messageStubType=108;break;case"BLUE_MSG_VERIFIED_TO_BSP_PREMISE_UNVERIFIED":case 109:a.messageStubType=109;break;case"BLUE_MSG_VERIFIED_TO_SELF_FB_UNVERIFIED":case 110:a.messageStubType=110;break;case"BLUE_MSG_VERIFIED_TO_UNVERIFIED":case 111:a.messageStubType=111;break;case"BLUE_MSG_BSP_FB_UNVERIFIED_TO_BSP_PREMISE_VERIFIED":case 112:a.messageStubType=112;break;case"BLUE_MSG_BSP_FB_UNVERIFIED_TO_SELF_FB_VERIFIED":case 113:a.messageStubType=113;break;case"BLUE_MSG_BSP_FB_VERIFIED_TO_BSP_PREMISE_UNVERIFIED":case 114:a.messageStubType=114;break;case"BLUE_MSG_BSP_FB_VERIFIED_TO_SELF_FB_UNVERIFIED":case 115:a.messageStubType=115;break;case"BLUE_MSG_SELF_FB_UNVERIFIED_TO_BSP_PREMISE_VERIFIED":case 116:a.messageStubType=116;break;case"BLUE_MSG_SELF_FB_VERIFIED_TO_BSP_PREMISE_UNVERIFIED":case 117:a.messageStubType=117;break;case"E2E_IDENTITY_UNAVAILABLE":case 118:a.messageStubType=118;break;case"GROUP_CREATING":case 119:a.messageStubType=119;break;case"GROUP_CREATE_FAILED":case 120:a.messageStubType=120;break;case"GROUP_BOUNCED":case 121:a.messageStubType=121;break;case"BLOCK_CONTACT":case 122:a.messageStubType=122;break;case"EPHEMERAL_SETTING_NOT_APPLIED":case 123:a.messageStubType=123;break;case"SYNC_FAILED":case 124:a.messageStubType=124;break;case"SYNCING":case 125:a.messageStubType=125;break;case"BIZ_PRIVACY_MODE_INIT_FB":case 126:a.messageStubType=126;break;case"BIZ_PRIVACY_MODE_INIT_BSP":case 127:a.messageStubType=127;break;case"BIZ_PRIVACY_MODE_TO_FB":case 128:a.messageStubType=128;break;case"BIZ_PRIVACY_MODE_TO_BSP":case 129:a.messageStubType=129;break;case"DISAPPEARING_MODE":case 130:a.messageStubType=130;break;case"E2E_DEVICE_FETCH_FAILED":case 131:a.messageStubType=131;break;case"ADMIN_REVOKE":case 132:a.messageStubType=132;break;case"GROUP_INVITE_LINK_GROWTH_LOCKED":case 133:a.messageStubType=133;break;case"COMMUNITY_LINK_PARENT_GROUP":case 134:a.messageStubType=134;break;case"COMMUNITY_LINK_SIBLING_GROUP":case 135:a.messageStubType=135;break;case"COMMUNITY_LINK_SUB_GROUP":case 136:a.messageStubType=136;break;case"COMMUNITY_UNLINK_PARENT_GROUP":case 137:a.messageStubType=137;break;case"COMMUNITY_UNLINK_SIBLING_GROUP":case 138:a.messageStubType=138;break;case"COMMUNITY_UNLINK_SUB_GROUP":case 139:a.messageStubType=139;break;case"GROUP_PARTICIPANT_ACCEPT":case 140:a.messageStubType=140;break;case"GROUP_PARTICIPANT_LINKED_GROUP_JOIN":case 141:a.messageStubType=141;break;case"COMMUNITY_CREATE":case 142:a.messageStubType=142;break;case"EPHEMERAL_KEEP_IN_CHAT":case 143:a.messageStubType=143;break;case"GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST":case 144:a.messageStubType=144;break;case"GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE":case 145:a.messageStubType=145;break;case"INTEGRITY_UNLINK_PARENT_GROUP":case 146:a.messageStubType=146;break;case"COMMUNITY_PARTICIPANT_PROMOTE":case 147:a.messageStubType=147;break;case"COMMUNITY_PARTICIPANT_DEMOTE":case 148:a.messageStubType=148;break;case"COMMUNITY_PARENT_GROUP_DELETED":case 149:a.messageStubType=149;break;case"COMMUNITY_LINK_PARENT_GROUP_MEMBERSHIP_APPROVAL":case 150:a.messageStubType=150;break;case"GROUP_PARTICIPANT_JOINED_GROUP_AND_PARENT_GROUP":case 151:a.messageStubType=151;break;case"MASKED_THREAD_CREATED":case 152:a.messageStubType=152;break;case"MASKED_THREAD_UNMASKED":case 153:a.messageStubType=153;break;case"BIZ_CHAT_ASSIGNMENT":case 154:a.messageStubType=154;break;case"CHAT_PSA":case 155:a.messageStubType=155;break;case"CHAT_POLL_CREATION_MESSAGE":case 156:a.messageStubType=156;break;case"CAG_MASKED_THREAD_CREATED":case 157:a.messageStubType=157;break;case"COMMUNITY_PARENT_GROUP_SUBJECT_CHANGED":case 158:a.messageStubType=158;break;case"CAG_INVITE_AUTO_ADD":case 159:a.messageStubType=159;break;case"BIZ_CHAT_ASSIGNMENT_UNASSIGN":case 160:a.messageStubType=160;break;case"CAG_INVITE_AUTO_JOINED":case 161:a.messageStubType=161;break;case"SCHEDULED_CALL_START_MESSAGE":case 162:a.messageStubType=162;break;case"COMMUNITY_INVITE_RICH":case 163:a.messageStubType=163;break;case"COMMUNITY_INVITE_AUTO_ADD_RICH":case 164:a.messageStubType=164;break;case"SUB_GROUP_INVITE_RICH":case 165:a.messageStubType=165;break;case"SUB_GROUP_PARTICIPANT_ADD_RICH":case 166:a.messageStubType=166;break;case"COMMUNITY_LINK_PARENT_GROUP_RICH":case 167:a.messageStubType=167;break;case"COMMUNITY_PARTICIPANT_ADD_RICH":case 168:a.messageStubType=168;break;case"SILENCED_UNKNOWN_CALLER_AUDIO":case 169:a.messageStubType=169;break;case"SILENCED_UNKNOWN_CALLER_VIDEO":case 170:a.messageStubType=170;break;case"GROUP_MEMBER_ADD_MODE":case 171:a.messageStubType=171;break;case"GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD":case 172:a.messageStubType=172;break;case"COMMUNITY_CHANGE_DESCRIPTION":case 173:a.messageStubType=173;break;case"SENDER_INVITE":case 174:a.messageStubType=174;break;case"RECEIVER_INVITE":case 175:a.messageStubType=175;break;case"COMMUNITY_ALLOW_MEMBER_ADDED_GROUPS":case 176:a.messageStubType=176;break;case"PINNED_MESSAGE_IN_CHAT":case 177:a.messageStubType=177;break;case"PAYMENT_INVITE_SETUP_INVITER":case 178:a.messageStubType=178;break;case"PAYMENT_INVITE_SETUP_INVITEE_RECEIVE_ONLY":case 179:a.messageStubType=179;break;case"PAYMENT_INVITE_SETUP_INVITEE_SEND_AND_RECEIVE":case 180:a.messageStubType=180;break;case"LINKED_GROUP_CALL_START":case 181:a.messageStubType=181;break;case"REPORT_TO_ADMIN_ENABLED_STATUS":case 182:a.messageStubType=182;break;case"EMPTY_SUBGROUP_CREATE":case 183:a.messageStubType=183;break;case"SCHEDULED_CALL_CANCEL":case 184:a.messageStubType=184;break;case"SUBGROUP_ADMIN_TRIGGERED_AUTO_ADD_RICH":case 185:a.messageStubType=185;break;case"GROUP_CHANGE_RECENT_HISTORY_SHARING":case 186:a.messageStubType=186;break;case"PAID_MESSAGE_SERVER_CAMPAIGN_ID":case 187:a.messageStubType=187;break;case"GENERAL_CHAT_CREATE":case 188:a.messageStubType=188;break;case"GENERAL_CHAT_ADD":case 189:a.messageStubType=189;break;case"GENERAL_CHAT_AUTO_ADD_DISABLED":case 190:a.messageStubType=190;break;case"SUGGESTED_SUBGROUP_ANNOUNCE":case 191:a.messageStubType=191;break;case"BIZ_BOT_1P_MESSAGING_ENABLED":case 192:a.messageStubType=192;break;case"CHANGE_USERNAME":case 193:a.messageStubType=193;break;case"BIZ_COEX_PRIVACY_INIT_SELF":case 194:a.messageStubType=194;break;case"BIZ_COEX_PRIVACY_TRANSITION_SELF":case 195:a.messageStubType=195;break;case"SUPPORT_AI_EDUCATION":case 196:a.messageStubType=196;break;case"BIZ_BOT_3P_MESSAGING_ENABLED":case 197:a.messageStubType=197;break;case"REMINDER_SETUP_MESSAGE":case 198:a.messageStubType=198;break;case"REMINDER_SENT_MESSAGE":case 199:a.messageStubType=199;break;case"REMINDER_CANCEL_MESSAGE":case 200:a.messageStubType=200;break;case"BIZ_COEX_PRIVACY_INIT":case 201:a.messageStubType=201;break;case"BIZ_COEX_PRIVACY_TRANSITION":case 202:a.messageStubType=202;break;case"GROUP_DEACTIVATED":case 203:a.messageStubType=203;break;case"COMMUNITY_DEACTIVATE_SIBLING_GROUP":case 204:a.messageStubType=204;break;case"EVENT_UPDATED":case 205:a.messageStubType=205;break;case"EVENT_CANCELED":case 206:a.messageStubType=206;break;case"COMMUNITY_OWNER_UPDATED":case 207:a.messageStubType=207;break;case"COMMUNITY_SUB_GROUP_VISIBILITY_HIDDEN":case 208:a.messageStubType=208;break;case"CAPI_GROUP_NE2EE_SYSTEM_MESSAGE":case 209:a.messageStubType=209;break;case"STATUS_MENTION":case 210:a.messageStubType=210;break;case"USER_CONTROLS_SYSTEM_MESSAGE":case 211:a.messageStubType=211;break;case"SUPPORT_SYSTEM_MESSAGE":case 212:a.messageStubType=212;break;case"CHANGE_LID":case 213:a.messageStubType=213;break;case"BIZ_CUSTOMER_3PD_DATA_SHARING_OPT_IN_MESSAGE":case 214:a.messageStubType=214;break;case"BIZ_CUSTOMER_3PD_DATA_SHARING_OPT_OUT_MESSAGE":case 215:a.messageStubType=215;break;case"CHANGE_LIMIT_SHARING":case 216:a.messageStubType=216;break;case"GROUP_MEMBER_LINK_MODE":case 217:a.messageStubType=217;break;case"BIZ_AUTOMATICALLY_LABELED_CHAT_SYSTEM_MESSAGE":case 218:a.messageStubType=218;break;case"PHONE_NUMBER_HIDING_CHAT_DEPRECATED_MESSAGE":case 219:a.messageStubType=219;break;case"QUARANTINED_MESSAGE":case 220:a.messageStubType=220;break;case"GROUP_MEMBER_SHARE_GROUP_HISTORY_MODE":case 221:a.messageStubType=221;break}if(e.clearMedia!=null&&(a.clearMedia=!!e.clearMedia),e.messageStubParameters){if(!Array.isArray(e.messageStubParameters))throw TypeError(".proto.WebMessageInfo.messageStubParameters: array expected");a.messageStubParameters=[];for(var A=0;A>>0),e.labels){if(!Array.isArray(e.labels))throw TypeError(".proto.WebMessageInfo.labels: array expected");a.labels=[];for(var A=0;A>>0,e.ephemeralStartTimestamp.high>>>0).toNumber(!0))),e.ephemeralDuration!=null&&(a.ephemeralDuration=e.ephemeralDuration>>>0),e.ephemeralOffToOn!=null&&(a.ephemeralOffToOn=!!e.ephemeralOffToOn),e.ephemeralOutOfSync!=null&&(a.ephemeralOutOfSync=!!e.ephemeralOutOfSync),e.bizPrivacyStatus){default:if(typeof e.bizPrivacyStatus=="number"){a.bizPrivacyStatus=e.bizPrivacyStatus;break}break;case"E2EE":case 0:a.bizPrivacyStatus=0;break;case"FB":case 2:a.bizPrivacyStatus=2;break;case"BSP":case 1:a.bizPrivacyStatus=1;break;case"BSP_AND_FB":case 3:a.bizPrivacyStatus=3;break}if(e.verifiedBizName!=null&&(a.verifiedBizName=String(e.verifiedBizName)),e.mediaData!=null){if(typeof e.mediaData!="object")throw TypeError(".proto.WebMessageInfo.mediaData: object expected");a.mediaData=p.proto.MediaData.fromObject(e.mediaData)}if(e.photoChange!=null){if(typeof e.photoChange!="object")throw TypeError(".proto.WebMessageInfo.photoChange: object expected");a.photoChange=p.proto.PhotoChange.fromObject(e.photoChange)}if(e.userReceipt){if(!Array.isArray(e.userReceipt))throw TypeError(".proto.WebMessageInfo.userReceipt: array expected");a.userReceipt=[];for(var A=0;A=0&&(a.futureproofData=e.futureproofData)),e.statusPsa!=null){if(typeof e.statusPsa!="object")throw TypeError(".proto.WebMessageInfo.statusPsa: object expected");a.statusPsa=p.proto.StatusPSA.fromObject(e.statusPsa)}if(e.pollUpdates){if(!Array.isArray(e.pollUpdates))throw TypeError(".proto.WebMessageInfo.pollUpdates: array expected");a.pollUpdates=[];for(var A=0;A=0&&(a.messageSecret=e.messageSecret)),e.keepInChat!=null){if(typeof e.keepInChat!="object")throw TypeError(".proto.WebMessageInfo.keepInChat: object expected");a.keepInChat=p.proto.KeepInChat.fromObject(e.keepInChat)}if(e.originalSelfAuthorUserJidString!=null&&(a.originalSelfAuthorUserJidString=String(e.originalSelfAuthorUserJidString)),e.revokeMessageTimestamp!=null&&(l.Long?(a.revokeMessageTimestamp=l.Long.fromValue(e.revokeMessageTimestamp)).unsigned=!0:typeof e.revokeMessageTimestamp=="string"?a.revokeMessageTimestamp=parseInt(e.revokeMessageTimestamp,10):typeof e.revokeMessageTimestamp=="number"?a.revokeMessageTimestamp=e.revokeMessageTimestamp:typeof e.revokeMessageTimestamp=="object"&&(a.revokeMessageTimestamp=new l.LongBits(e.revokeMessageTimestamp.low>>>0,e.revokeMessageTimestamp.high>>>0).toNumber(!0))),e.pinInChat!=null){if(typeof e.pinInChat!="object")throw TypeError(".proto.WebMessageInfo.pinInChat: object expected");a.pinInChat=p.proto.PinInChat.fromObject(e.pinInChat)}if(e.premiumMessageInfo!=null){if(typeof e.premiumMessageInfo!="object")throw TypeError(".proto.WebMessageInfo.premiumMessageInfo: object expected");a.premiumMessageInfo=p.proto.PremiumMessageInfo.fromObject(e.premiumMessageInfo)}if(e.is1PBizBotMessage!=null&&(a.is1PBizBotMessage=!!e.is1PBizBotMessage),e.isGroupHistoryMessage!=null&&(a.isGroupHistoryMessage=!!e.isGroupHistoryMessage),e.botMessageInvokerJid!=null&&(a.botMessageInvokerJid=String(e.botMessageInvokerJid)),e.commentMetadata!=null){if(typeof e.commentMetadata!="object")throw TypeError(".proto.WebMessageInfo.commentMetadata: object expected");a.commentMetadata=p.proto.CommentMetadata.fromObject(e.commentMetadata)}if(e.eventResponses){if(!Array.isArray(e.eventResponses))throw TypeError(".proto.WebMessageInfo.eventResponses: array expected");a.eventResponses=[];for(var A=0;A>>0,e.newsletterServerId.high>>>0).toNumber(!0))),e.eventAdditionalMetadata!=null){if(typeof e.eventAdditionalMetadata!="object")throw TypeError(".proto.WebMessageInfo.eventAdditionalMetadata: object expected");a.eventAdditionalMetadata=p.proto.EventAdditionalMetadata.fromObject(e.eventAdditionalMetadata)}if(e.isMentionedInStatus!=null&&(a.isMentionedInStatus=!!e.isMentionedInStatus),e.statusMentions){if(!Array.isArray(e.statusMentions))throw TypeError(".proto.WebMessageInfo.statusMentions: array expected");a.statusMentions=[];for(var A=0;A>>3){case 2:{s.timestamp=e.uint64();break}case 3:{s.unreadChats=e.uint32();break}case 4:{s.notifyMessageCount=e.uint32();break}case 5:{s.notifyMessages&&s.notifyMessages.length||(s.notifyMessages=[]),s.notifyMessages.push(p.proto.WebMessageInfo.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.WebNotificationsInfo)return e;var a=new p.proto.WebNotificationsInfo;if(e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!0:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber(!0))),e.unreadChats!=null&&(a.unreadChats=e.unreadChats>>>0),e.notifyMessageCount!=null&&(a.notifyMessageCount=e.notifyMessageCount>>>0),e.notifyMessages){if(!Array.isArray(e.notifyMessages))throw TypeError(".proto.WebNotificationsInfo.notifyMessages: array expected");a.notifyMessages=[];for(var A=0;ABa.hasSubscribers||IB.hasSubscribers,k9=new Set,R9=typeof process=="object"&&process?process:{},V2e=(n,t,o,i)=>{typeof R9.emitWarning=="function"?R9.emitWarning(n,t,o,i):console.error(`[${o}] ${t}: ${n}`)},W2e=n=>!k9.has(n),Lc=n=>!!n&&n===Math.floor(n)&&n>0&&isFinite(n),v9=n=>Lc(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?xw:null:null,xw=class extends Array{constructor(n){super(n),this.fill(0)}},Z2e=class lB{heap;length;static#e=!1;static create(t){let o=v9(t);if(!o)return[];lB.#e=!0;let i=new lB(t,o);return lB.#e=!1,i}constructor(t,o){if(!lB.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new o(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Mg=class P9{#e;#A;#t;#r;#g;#a;#n;#i;get perf(){return this.#i}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#I;#l;#o;#s;#c;#p;#d;#h;#E;#C;#f;#B;#y;#S;#Q;#m;#u;#b;#R;static unsafeExposeInternals(t){return{starts:t.#y,ttls:t.#S,autopurgeTimers:t.#Q,sizes:t.#B,keyMap:t.#o,keyList:t.#s,valList:t.#c,next:t.#p,prev:t.#d,get head(){return t.#h},get tail(){return t.#E},free:t.#C,isBackgroundFetch:o=>t.#G(o),backgroundFetch:(o,i,e,a)=>t.#K(o,i,e,a),moveToTail:o=>t.#x(o),indexes:o=>t.#P(o),rindexes:o=>t.#N(o),isStale:o=>t.#M(o)}}get max(){return this.#e}get maxSize(){return this.#A}get calculatedSize(){return this.#l}get size(){return this.#I}get fetchMethod(){return this.#a}get memoMethod(){return this.#n}get dispose(){return this.#t}get onInsert(){return this.#r}get disposeAfter(){return this.#g}constructor(t){let{max:o=0,ttl:i,ttlResolution:e=1,ttlAutopurge:a,updateAgeOnGet:A,updateAgeOnHas:r,allowStale:s,dispose:g,onInsert:c,disposeAfter:I,noDisposeOnSet:d,noUpdateTTL:B,maxSize:f=0,maxEntrySize:Q=0,sizeCalculation:y,fetchMethod:m,memoMethod:_,noDeleteOnFetchRejection:T,noDeleteOnStaleGet:R,allowStaleOnFetchRejection:F,allowStaleOnFetchAbort:K,ignoreFetchAbort:L,backgroundFetchSize:q=1,perf:z}=t;if(this.backgroundFetchSize=q,z!==void 0&&typeof z?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#i=z??z2e,o!==0&&!Lc(o))throw new TypeError("max option must be a nonnegative integer");let j=o?v9(o):Array;if(!j)throw new Error("invalid max value: "+o);if(this.#e=o,this.#A=f,this.maxEntrySize=Q||this.#A,this.sizeCalculation=y,this.sizeCalculation){if(!this.#A&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(_!==void 0&&typeof _!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#n=_,m!==void 0&&typeof m!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#a=m,this.#u=!!m,this.#o=new Map,this.#s=Array.from({length:o}).fill(void 0),this.#c=Array.from({length:o}).fill(void 0),this.#p=new j(o),this.#d=new j(o),this.#h=0,this.#E=0,this.#C=Z2e.create(o),this.#I=0,this.#l=0,typeof g=="function"&&(this.#t=g),typeof c=="function"&&(this.#r=c),typeof I=="function"?(this.#g=I,this.#f=[]):(this.#g=void 0,this.#f=void 0),this.#m=!!this.#t,this.#R=!!this.#r,this.#b=!!this.#g,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!B,this.noDeleteOnFetchRejection=!!T,this.allowStaleOnFetchRejection=!!F,this.allowStaleOnFetchAbort=!!K,this.ignoreFetchAbort=!!L,this.maxEntrySize!==0){if(this.#A!==0&&!Lc(this.#A))throw new TypeError("maxSize must be a positive integer if specified");if(!Lc(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!s,this.noDeleteOnStaleGet=!!R,this.updateAgeOnGet=!!A,this.updateAgeOnHas=!!r,this.ttlResolution=Lc(e)||e===0?e:1,this.ttlAutopurge=!!a,this.ttl=i||0,this.ttl){if(!Lc(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#e===0&&this.ttl===0&&this.#A===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#A){let P="LRU_CACHE_UNBOUNDED";W2e(P)&&(k9.add(P),V2e("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",P,P9))}}getRemainingTTL(t){return this.#o.has(t)?1/0:0}#D(){let t=new xw(this.#e),o=new xw(this.#e);this.#S=t,this.#y=o;let i=this.ttlAutopurge?Array.from({length:this.#e}):void 0;this.#Q=i,this.#k=(s,g,c=this.#i.now())=>{o[s]=g!==0?c:0,t[s]=g,e(s,g)},this.#w=s=>{o[s]=t[s]!==0?this.#i.now():0,e(s,t[s])};let e=this.ttlAutopurge?(s,g)=>{if(i?.[s]&&(clearTimeout(i[s]),i[s]=void 0),g&&g!==0&&i){let c=setTimeout(()=>{this.#M(s)?(this.#J(this.#s[s],"expire"),i[s]=void 0):e(s,r(s))},g+1);c.unref&&c.unref(),i[s]=c}}:()=>{};this.#T=(s,g)=>{if(t[g]){let c=t[g],I=o[g];if(!c||!I)return;s.ttl=c,s.start=I,s.now=a||A();let d=s.now-I;s.remainingTTL=c-d}};let a=0,A=()=>{let s=this.#i.now();if(this.ttlResolution>0){a=s;let g=setTimeout(()=>a=0,this.ttlResolution);g.unref&&g.unref()}return s};this.getRemainingTTL=s=>{let g=this.#o.get(s);return g===void 0?0:r(g)};let r=s=>{let g=t[s],c=o[s];if(!g||!c)return 1/0;let I=(a||A())-c;return g-I};this.#M=s=>{let g=o[s],c=t[s];return!!c&&!!g&&(a||A())-g>c}}#w=()=>{};#T=()=>{};#k=()=>{};#M=()=>!1;#L(){let t=new xw(this.#e);this.#l=0,this.#B=t,this.#_=o=>{this.#l-=t[o],t[o]=0},this.#v=(o,i,e,a)=>{if(!Lc(e)){if(this.#G(i))return this.backgroundFetchSize;if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(e=a(i,o),!Lc(e))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.")}return e},this.#U=(o,i,e)=>{if(t[o]=i,this.#A){let a=this.#A-t[o];for(;this.#l>a;)this.#q(!0)}this.#l+=t[o],e&&(e.entrySize=i,e.totalCalculatedSize=this.#l)}}#_=t=>{};#U=(t,o,i)=>{};#v=(t,o,i,e)=>{if(i||e)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#P({allowStale:t=this.allowStale}={}){if(this.#I)for(let o=this.#E;this.#Y(o)&&((t||!this.#M(o))&&(yield o),o!==this.#h);)o=this.#d[o]}*#N({allowStale:t=this.allowStale}={}){if(this.#I)for(let o=this.#h;this.#Y(o)&&((t||!this.#M(o))&&(yield o),o!==this.#E);)o=this.#p[o]}#Y(t){return t!==void 0&&this.#o.get(this.#s[t])===t}*entries(){for(let t of this.#P())this.#c[t]!==void 0&&this.#s[t]!==void 0&&!this.#G(this.#c[t])&&(yield[this.#s[t],this.#c[t]])}*rentries(){for(let t of this.#N())this.#c[t]!==void 0&&this.#s[t]!==void 0&&!this.#G(this.#c[t])&&(yield[this.#s[t],this.#c[t]])}*keys(){for(let t of this.#P()){let o=this.#s[t];o!==void 0&&!this.#G(this.#c[t])&&(yield o)}}*rkeys(){for(let t of this.#N()){let o=this.#s[t];o!==void 0&&!this.#G(this.#c[t])&&(yield o)}}*values(){for(let t of this.#P())this.#c[t]!==void 0&&!this.#G(this.#c[t])&&(yield this.#c[t])}*rvalues(){for(let t of this.#N())this.#c[t]!==void 0&&!this.#G(this.#c[t])&&(yield this.#c[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,o={}){for(let i of this.#P()){let e=this.#c[i],a=this.#G(e)?e.__staleWhileFetching:e;if(a!==void 0&&t(a,this.#s[i],this))return this.#j(this.#s[i],o)}}forEach(t,o=this){for(let i of this.#P()){let e=this.#c[i],a=this.#G(e)?e.__staleWhileFetching:e;a!==void 0&&t.call(o,a,this.#s[i],this)}}rforEach(t,o=this){for(let i of this.#N()){let e=this.#c[i],a=this.#G(e)?e.__staleWhileFetching:e;a!==void 0&&t.call(o,a,this.#s[i],this)}}purgeStale(){let t=!1;for(let o of this.#N({allowStale:!0}))this.#M(o)&&(this.#J(this.#s[o],"expire"),t=!0);return t}info(t){let o=this.#o.get(t);if(o===void 0)return;let i=this.#c[o],e=this.#G(i)?i.__staleWhileFetching:i;if(e===void 0)return;let a={value:e};if(this.#S&&this.#y){let A=this.#S[o],r=this.#y[o];if(A&&r){let s=A-(this.#i.now()-r);a.ttl=s,a.start=Date.now()}}return this.#B&&(a.size=this.#B[o]),a}dump(){let t=[];for(let o of this.#P({allowStale:!0})){let i=this.#s[o],e=this.#c[o],a=this.#G(e)?e.__staleWhileFetching:e;if(a===void 0||i===void 0)continue;let A={value:a};if(this.#S&&this.#y){A.ttl=this.#S[o];let r=this.#i.now()-this.#y[o];A.start=Math.floor(Date.now()-r)}this.#B&&(A.size=this.#B[o]),t.unshift([i,A])}return t}load(t){this.clear();for(let[o,i]of t){if(i.start){let e=Date.now()-i.start;i.start=this.#i.now()-e}this.#H(o,i.value,i)}}set(t,o,i={}){let{status:e=Ba.hasSubscribers?{}:void 0}=i;i.status=e,e&&(e.op="set",e.key=t,o!==void 0&&(e.value=o),e.cache=this);let a=this.#H(t,o,i);return e&&Ba.hasSubscribers&&Ba.publish(e),a}#H(t,o,i,e){let{ttl:a=this.ttl,start:A,noDisposeOnSet:r=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:g}=i,c=this.#G(o);if(o===void 0)return g&&(g.set="deleted"),this.delete(t),this;let{noUpdateTTL:I=this.noUpdateTTL}=i;g&&!c&&(g.value=o);let d=this.#v(t,o,i.size||0,s,g);if(this.maxEntrySize&&d>this.maxEntrySize)return this.#J(t,"set"),g&&(g.set="miss",g.maxEntrySizeExceeded=!0),this;let B=this.#I===0?void 0:this.#o.get(t);if(B===void 0)B=this.#I===0?this.#E:this.#C.length!==0?this.#C.pop():this.#I===this.#e?this.#q(!1):this.#I,this.#s[B]=t,this.#c[B]=o,this.#o.set(t,B),this.#p[this.#E]=B,this.#d[B]=this.#E,this.#E=B,this.#I++,this.#U(B,d,g),g&&(g.set="add"),I=!1,this.#R&&!c&&this.#r?.(o,t,"add");else{this.#x(B);let f=this.#c[B];if(o!==f){if(!r)if(this.#G(f)){f!==e&&f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:Q}=f;Q!==void 0&&Q!==o&&(this.#m&&this.#t?.(Q,t,"set"),this.#b&&this.#f?.push([Q,t,"set"]))}else this.#m&&this.#t?.(f,t,"set"),this.#b&&this.#f?.push([f,t,"set"]);if(this.#_(B),this.#U(B,d,g),this.#c[B]=o,!c){let Q=f&&this.#G(f)?f.__staleWhileFetching:f,y=Q===void 0?"add":o!==Q?"replace":"update";g&&(g.set=y,Q!==void 0&&(g.oldValue=Q)),this.#R&&this.onInsert?.(o,t,y)}}else c||(g&&(g.set="update"),this.#R&&this.onInsert?.(o,t,"update"))}if(a!==0&&!this.#S&&this.#D(),this.#S&&(I||this.#k(B,a,A),g&&this.#T(g,B)),!r&&this.#b&&this.#f){let f=this.#f,Q;for(;Q=f?.shift();)this.#g?.(...Q)}return this}pop(){try{for(;this.#I;){let t=this.#c[this.#h];if(this.#q(!0),this.#G(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#b&&this.#f){let t=this.#f,o;for(;o=t?.shift();)this.#g?.(...o)}}}#q(t){let o=this.#h,i=this.#s[o],e=this.#c[o],a=this.#G(e);a&&e.__abortController.abort(new Error("evicted"));let A=a?e.__staleWhileFetching:e;return(this.#m||this.#b)&&A!==void 0&&(this.#m&&this.#t?.(A,i,"evict"),this.#b&&this.#f?.push([A,i,"evict"])),this.#_(o),this.#Q?.[o]&&(clearTimeout(this.#Q[o]),this.#Q[o]=void 0),t&&(this.#s[o]=void 0,this.#c[o]=void 0,this.#C.push(o)),this.#I===1?(this.#h=this.#E=0,this.#C.length=0):this.#h=this.#p[o],this.#o.delete(i),this.#I--,o}has(t,o={}){let{status:i=Ba.hasSubscribers?{}:void 0}=o;o.status=i,i&&(i.op="has",i.key=t,i.cache=this);let e=this.#z(t,o);return Ba.hasSubscribers&&Ba.publish(i),e}#z(t,o={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:e}=o,a=this.#o.get(t);if(a!==void 0){let A=this.#c[a];if(this.#G(A)&&A.__staleWhileFetching===void 0)return!1;if(this.#M(a))e&&(e.has="stale",this.#T(e,a));else return i&&this.#w(a),e&&(e.has="hit",this.#T(e,a)),!0}else e&&(e.has="miss");return!1}peek(t,o={}){let{status:i=sF()?{}:void 0}=o;i&&(i.op="peek",i.key=t,i.cache=this),o.status=i;let e=this.#F(t,o);return Ba.hasSubscribers&&Ba.publish(i),e}#F(t,o){let{status:i,allowStale:e=this.allowStale}=o,a=this.#o.get(t);if(a===void 0||!e&&this.#M(a)){i&&(i.peek=a===void 0?"miss":"stale");return}let A=this.#c[a],r=this.#G(A)?A.__staleWhileFetching:A;return i&&(r!==void 0?(i.peek="hit",i.value=r):i.peek="miss"),r}#K(t,o,i,e){let a=o===void 0?void 0:this.#c[o];if(this.#G(a))return a;let A=new AbortController,{signal:r}=i;r?.addEventListener("abort",()=>A.abort(r.reason),{signal:A.signal});let s={signal:A.signal,options:i,context:e},g=(Q,y=!1)=>{let{aborted:m}=A.signal,_=i.ignoreFetchAbort&&Q!==void 0,T=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&Q!==void 0);if(i.status&&(m&&!y?(i.status.fetchAborted=!0,i.status.fetchError=A.signal.reason,_&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),m&&!_&&!y)return I(A.signal.reason,T);let R=B,F=this.#c[o];return(F===B||F===void 0&&_&&y)&&(Q===void 0?R.__staleWhileFetching!==void 0?this.#c[o]=R.__staleWhileFetching:this.#J(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#H(t,Q,s.options,R))),Q},c=Q=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=Q),I(Q,!1)),I=(Q,y)=>{let{aborted:m}=A.signal,_=m&&i.allowStaleOnFetchAbort,T=_||i.allowStaleOnFetchRejection,R=T||i.noDeleteOnFetchRejection,F=B;if(this.#c[o]===B&&(!R||!y&&F.__staleWhileFetching===void 0?this.#J(t,"fetch"):_||(this.#c[o]=F.__staleWhileFetching)),T)return i.status&&F.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),F.__staleWhileFetching;if(F.__returned===F)throw Q},d=(Q,y)=>{let m=this.#a?.(t,a,s);A.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(Q(void 0),i.allowStaleOnFetchAbort&&(Q=_=>g(_,!0)))}),m&&m instanceof Promise?m.then(_=>Q(_===void 0?void 0:_),y):m!==void 0&&Q(m)};i.status&&(i.status.fetchDispatched=!0);let B=new Promise(d).then(g,c),f=Object.assign(B,{__abortController:A,__staleWhileFetching:a,__returned:void 0});return o===void 0?(this.#H(t,f,{...s.options,status:void 0}),o=this.#o.get(t)):this.#c[o]=f,f}#G(t){if(!this.#u)return!1;let o=t;return!!o&&o instanceof Promise&&o.hasOwnProperty("__staleWhileFetching")&&o.__abortController instanceof AbortController}fetch(t,o={}){let i=IB.hasSubscribers,{status:e=sF()?{}:void 0}=o;o.status=e,e&&o.context&&(e.context=o.context);let a=this.#$(t,o);return e&&i&&(e.trace=!0,IB.tracePromise(()=>a,e).catch(()=>{})),a}async#$(t,o={}){let{allowStale:i=this.allowStale,updateAgeOnGet:e=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:A=this.ttl,noDisposeOnSet:r=this.noDisposeOnSet,size:s=0,sizeCalculation:g=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:B=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:Q,forceRefresh:y=!1,status:m,signal:_}=o;if(m&&(m.op="fetch",m.key=t,y&&(m.forceRefresh=!0),m.cache=this),!this.#u)return m&&(m.fetch="get"),this.#j(t,{allowStale:i,updateAgeOnGet:e,noDeleteOnStaleGet:a,status:m});let T={allowStale:i,updateAgeOnGet:e,noDeleteOnStaleGet:a,ttl:A,noDisposeOnSet:r,size:s,sizeCalculation:g,noUpdateTTL:c,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:f,ignoreFetchAbort:B,status:m,signal:_},R=this.#o.get(t);if(R===void 0){m&&(m.fetch="miss");let F=this.#K(t,R,T,Q);return F.__returned=F}else{let F=this.#c[R];if(this.#G(F)){let z=i&&F.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",z&&(m.returnedStale=!0)),z?F.__staleWhileFetching:F.__returned=F}let K=this.#M(R);if(!y&&!K)return m&&(m.fetch="hit"),this.#x(R),e&&this.#w(R),m&&this.#T(m,R),F;let L=this.#K(t,R,T,Q),q=L.__staleWhileFetching!==void 0&&i;return m&&(m.fetch=K?"stale":"refresh",q&&K&&(m.returnedStale=!0)),q?L.__staleWhileFetching:L.__returned=L}}forceFetch(t,o={}){let i=IB.hasSubscribers,{status:e=sF()?{}:void 0}=o;o.status=e,e&&o.context&&(e.context=o.context);let a=this.#Ae(t,o);return e&&i&&(e.trace=!0,IB.tracePromise(()=>a,e).catch(()=>{})),a}async#Ae(t,o={}){let i=await this.#$(t,o);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,o={}){let{status:i=Ba.hasSubscribers?{}:void 0}=o;o.status=i,i&&(i.op="memo",i.key=t,o.context&&(i.context=o.context),i.cache=this);let e=this.#te(t,o);return i&&(i.value=e),Ba.hasSubscribers&&Ba.publish(i),e}#te(t,o={}){let i=this.#n;if(!i)throw new Error("no memoMethod provided to constructor");let{context:e,status:a,forceRefresh:A,...r}=o;a&&A&&(a.forceRefresh=!0);let s=this.#j(t,r),g=A||s===void 0;if(a&&(a.memo=g?"miss":"hit",g||(a.value=s)),!g)return s;let c=i(t,s,{options:r,context:e});return a&&(a.value=c),this.#H(t,c,r),c}get(t,o={}){let{status:i=Ba.hasSubscribers?{}:void 0}=o;o.status=i,i&&(i.op="get",i.key=t,i.cache=this);let e=this.#j(t,o);return i&&(e!==void 0&&(i.value=e),Ba.hasSubscribers&&Ba.publish(i)),e}#j(t,o={}){let{allowStale:i=this.allowStale,updateAgeOnGet:e=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:A}=o,r=this.#o.get(t);if(r===void 0){A&&(A.get="miss");return}let s=this.#c[r],g=this.#G(s);return A&&this.#T(A,r),this.#M(r)?g?(A&&(A.get="stale-fetching"),i&&s.__staleWhileFetching!==void 0?(A&&(A.returnedStale=!0),s.__staleWhileFetching):void 0):(a||this.#J(t,"expire"),A&&(A.get="stale"),i?(A&&(A.returnedStale=!0),s):void 0):(A&&(A.get=g?"fetching":"hit"),this.#x(r),e&&this.#w(r),g?s.__staleWhileFetching:s)}#X(t,o){this.#d[o]=t,this.#p[t]=o}#x(t){t!==this.#E&&(t===this.#h?this.#h=this.#p[t]:this.#X(this.#d[t],this.#p[t]),this.#X(this.#E,t),this.#E=t)}delete(t){return this.#J(t,"delete")}#J(t,o){Ba.hasSubscribers&&Ba.publish({op:"delete",delete:o,key:t,cache:this});let i=!1;if(this.#I!==0){let e=this.#o.get(t);if(e!==void 0)if(this.#Q?.[e]&&(clearTimeout(this.#Q[e]),this.#Q[e]=void 0),i=!0,this.#I===1)this.#V(o);else{this.#_(e);let a=this.#c[e];if(this.#G(a)?a.__abortController.abort(new Error("deleted")):(this.#m||this.#b)&&(this.#m&&this.#t?.(a,t,o),this.#b&&this.#f?.push([a,t,o])),this.#o.delete(t),this.#s[e]=void 0,this.#c[e]=void 0,e===this.#E)this.#E=this.#d[e];else if(e===this.#h)this.#h=this.#p[e];else{let A=this.#d[e];this.#p[A]=this.#p[e];let r=this.#p[e];this.#d[r]=this.#d[e]}this.#I--,this.#C.push(e)}}if(this.#b&&this.#f?.length){let e=this.#f,a;for(;a=e?.shift();)this.#g?.(...a)}return i}clear(){return this.#V("delete")}#V(t){for(let o of this.#N({allowStale:!0})){let i=this.#c[o];if(this.#G(i))i.__abortController.abort(new Error("deleted"));else{let e=this.#s[o];this.#m&&this.#t?.(i,e,t),this.#b&&this.#f?.push([i,e,t])}}if(this.#o.clear(),this.#c.fill(void 0),this.#s.fill(void 0),this.#S&&this.#y){this.#S.fill(0),this.#y.fill(0);for(let o of this.#Q??[])o!==void 0&&clearTimeout(o);this.#Q?.fill(void 0)}if(this.#B&&this.#B.fill(0),this.#h=0,this.#E=0,this.#C.length=0,this.#l=0,this.#I=0,this.#b&&this.#f){let o=this.#f,i;for(;i=o?.shift();)this.#g?.(...i)}}};var oD=Je(Lr(),1);import{createHash as kUe,randomBytes as SB}from"crypto";var NX=["critical_block","critical_unblock_low","regular_high","regular_low","regular"];var IfA=Je(Lr(),1),na;(function(n){n[n.Connecting=0]="Connecting",n[n.AwaitingInitialSync=1]="AwaitingInitialSync",n[n.Syncing=2]="Syncing",n[n.Online=3]="Online"})(na||(na={}));var Hc;(function(n){n.BIZ_COMMERCE_VIOLATION_ALCOHOL="BIZ_COMMERCE_VIOLATION_ALCOHOL",n.BIZ_COMMERCE_VIOLATION_ADULT="BIZ_COMMERCE_VIOLATION_ADULT",n.BIZ_COMMERCE_VIOLATION_ANIMALS="BIZ_COMMERCE_VIOLATION_ANIMALS",n.BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS="BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS",n.BIZ_COMMERCE_VIOLATION_DATING="BIZ_COMMERCE_VIOLATION_DATING",n.BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS="BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS",n.BIZ_COMMERCE_VIOLATION_DRUGS="BIZ_COMMERCE_VIOLATION_DRUGS",n.BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC="BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC",n.BIZ_COMMERCE_VIOLATION_GAMBLING="BIZ_COMMERCE_VIOLATION_GAMBLING",n.BIZ_COMMERCE_VIOLATION_HEALTHCARE="BIZ_COMMERCE_VIOLATION_HEALTHCARE",n.BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY="BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY",n.BIZ_COMMERCE_VIOLATION_SUPPLEMENTS="BIZ_COMMERCE_VIOLATION_SUPPLEMENTS",n.BIZ_COMMERCE_VIOLATION_TOBACCO="BIZ_COMMERCE_VIOLATION_TOBACCO",n.BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT="BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT",n.BIZ_COMMERCE_VIOLATION_WEAPONS="BIZ_COMMERCE_VIOLATION_WEAPONS",n.BIZ_QUALITY="BIZ_QUALITY",n.DEFAULT="DEFAULT",n.WEB_COMPANION_ONLY="WEB_COMPANION_ONLY"})(Hc||(Hc={}));var RX;(function(n){n.NONE="NONE",n.FIRST_WARNING="FIRST_WARNING",n.SECOND_WARNING="SECOND_WARNING",n.CAPPED="CAPPED"})(RX||(RX={}));var kX;(function(n){n.NOT_ELIGIBLE="NOT_ELIGIBLE",n.NOT_ACTIVE="NOT_ACTIVE",n.ACTIVE="ACTIVE",n.ACTIVE_UPGRADE_AVAILABLE="ACTIVE_UPGRADE_AVAILABLE"})(kX||(kX={}));var vX;(function(n){n.NOT_ELIGIBLE="NOT_ELIGIBLE",n.ELIGIBLE="ELIGIBLE",n.ACTIVE_IN_CURRENT_CYCLE="ACTIVE_IN_CURRENT_CYCLE",n.EXHAUSTED="EXHAUSTED"})(vX||(vX={}));var TA=oe.WebMessageInfo.StubType,th=oe.WebMessageInfo.Status,dB;(function(n){n.PN="pn",n.LID="lid"})(dB||(dB={}));var fa;(function(n){n.xwa2_newsletter_create="xwa2_newsletter_create",n.xwa2_newsletter_subscribers="xwa2_newsletter_subscribers",n.xwa2_newsletter_view="xwa2_newsletter_view",n.xwa2_newsletter_metadata="xwa2_newsletter",n.xwa2_newsletter_admin_count="xwa2_newsletter_admin",n.xwa2_newsletter_mute_v2="xwa2_newsletter_mute_v2",n.xwa2_newsletter_unmute_v2="xwa2_newsletter_unmute_v2",n.xwa2_newsletter_follow="xwa2_newsletter_follow",n.xwa2_newsletter_unfollow="xwa2_newsletter_unfollow",n.xwa2_newsletter_join_v2="xwa2_newsletter_join_v2",n.xwa2_newsletter_leave_v2="xwa2_newsletter_leave_v2",n.xwa2_newsletter_change_owner="xwa2_newsletter_change_owner",n.xwa2_newsletter_demote="xwa2_newsletter_demote",n.xwa2_newsletter_delete_v2="xwa2_newsletter_delete_v2",n.xwa2_fetch_account_reachout_timelock="xwa2_fetch_account_reachout_timelock",n.xwa2_message_capping_info="xwa2_message_capping_info"})(fa||(fa={}));var sa;(function(n){n.CREATE="8823471724422422",n.UPDATE_METADATA="24250201037901610",n.METADATA="6563316087068696",n.SUBSCRIBERS="9783111038412085",n.FOLLOW="24404358912487870",n.UNFOLLOW="9767147403369991",n.MUTE="29766401636284406",n.UNMUTE="9864994326891137",n.ADMIN_COUNT="7130823597031706",n.CHANGE_OWNER="7341777602580933",n.DEMOTE="6551828931592903",n.DELETE="30062808666639665",n.REACHOUT_TIMELOCK="23983697327930364",n.MESSAGE_CAPPING_INFO="24503548349331633"})(sa||(sa={}));var $t;(function(n){n[n.connectionClosed=428]="connectionClosed",n[n.connectionLost=408]="connectionLost",n[n.connectionReplaced=440]="connectionReplaced",n[n.timedOut=408]="timedOut",n[n.loggedOut=401]="loggedOut",n[n.badSession=500]="badSession",n[n.restartRequired=515]="restartRequired",n[n.multideviceMismatch=411]="multideviceMismatch",n[n.forbidden=403]="forbidden",n[n.unavailableService=503]="unavailableService"})($t||($t={}));var hB={};Pr(hB,{DOUBLE_BYTE_TOKENS:()=>PX,SINGLE_BYTE_TOKENS:()=>GX,TAGS:()=>gUe,TOKEN_MAP:()=>BF});var gUe={LIST_EMPTY:0,DICTIONARY_0:236,DICTIONARY_1:237,DICTIONARY_2:238,DICTIONARY_3:239,INTEROP_JID:245,FB_JID:246,AD_JID:247,LIST_8:248,LIST_16:249,JID_PAIR:250,HEX_8:251,BINARY_8:252,BINARY_20:253,BINARY_32:254,NIBBLE_8:255,PACKED_MAX:127},PX=[["read-self","active","fbns","protocol","reaction","screen_width","heartbeat","deviceid","2:47DEQpj8","uploadfieldstat","voip_settings","retry","priority","longitude","conflict","false","ig_professional","replaced","preaccept","cover_photo","uncompressed","encopt","ppic","04","passive","status-revoke-drop","keygen","540","offer","rate","opus","latitude","w:gp2","ver","4","business_profile","medium","sender","prev_v_id","email","website","invited","sign_credential","05","transport","skey","reason","peer_abtest_bucket","America/Sao_Paulo","appid","refresh","100","06","404","101","104","107","102","109","103","member_add_mode","105","transaction-id","110","106","outgoing","108","111","tokens","followers","ig_handle","self_pid","tue","dec","thu","joinable","peer_pid","mon","features","wed","peer_device_presence","pn","delete","07","fri","audio_duration","admin","connected","delta","rcat","disable","collection","08","480","sat","phash","all","invite","accept","critical_unblock_low","group_update","signed_credential","blinded_credential","eph_setting","net","09","background_location","refresh_id","Asia/Kolkata","privacy_mode_ts","account_sync","voip_payload_type","service_areas","acs_public_key","v_id","0a","fallback_class","relay","actual_actors","metadata","w:biz","5","connected-limit","notice","0b","host_storage","fb_page","subject","privatestats","invis","groupadd","010","note.m4r","uuid","0c","8000","sun","372","1020","stage","1200","720","canonical","fb","011","video_duration","0d","1140","superadmin","012","Opening.m4r","keystore_attestation","dleq_proof","013","timestamp","ab_key","w:sync:app:state","0e","vertical","600","p_v_id","6","likes","014","500","1260","creator","0f","rte","destination","group","group_info","syncd_anti_tampering_fatal_exception_enabled","015","dl_bw","Asia/Jakarta","vp8/h.264","online","1320","fb:multiway","10","timeout","016","nse_retry","urn:xmpp:whatsapp:dirty","017","a_v_id","web_shops_chat_header_button_enabled","nse_call","inactive-upgrade","none","web","groups","2250","mms_hot_content_timespan_in_seconds","contact_blacklist","nse_read","suspended_group_deletion_notification","binary_version","018","https://www.whatsapp.com/otp/copy/","reg_push","shops_hide_catalog_attachment_entrypoint","server_sync",".","ephemeral_messages_allowed_values","019","mms_vcache_aggregation_enabled","iphone","America/Argentina/Buenos_Aires","01a","mms_vcard_autodownload_size_kb","nse_ver","shops_header_dropdown_menu_item","dhash","catalog_status","communities_mvp_new_iqs_serverprop","blocklist","default","11","ephemeral_messages_enabled","01b","original_dimensions","8","mms4_media_retry_notification_encryption_enabled","mms4_server_error_receipt_encryption_enabled","original_image_url","sync","multiway","420","companion_enc_static","shops_profile_drawer_entrypoint","01c","vcard_as_document_size_kb","status_video_max_duration","request_image_url","01d","regular_high","s_t","abt","share_ext_min_preliminary_image_quality","01e","32","syncd_key_rotation_enabled","data_namespace","md_downgrade_read_receipts2","patch","polltype","ephemeral_messages_setting","userrate","15","partial_pjpeg_bw_threshold","played-self","catalog_exists","01f","mute_v2"],["reject","dirty","announcement","020","13","9","status_video_max_bitrate","fb:thrift_iq","offline_batch","022","full","ctwa_first_business_reply_logging","h.264","smax_id","group_description_length","https://www.whatsapp.com/otp/code","status_image_max_edge","smb_upsell_business_profile_enabled","021","web_upgrade_to_md_modal","14","023","s_o","smaller_video_thumbs_status_enabled","media_max_autodownload","960","blocking_status","peer_msg","joinable_group_call_client_version","group_call_video_maximization_enabled","return_snapshot","high","America/Mexico_City","entry_point_block_logging_enabled","pop","024","1050","16","1380","one_tap_calling_in_group_chat_size","regular_low","inline_joinable_education_enabled","hq_image_max_edge","locked","America/Bogota","smb_biztools_deeplink_enabled","status_image_quality","1088","025","payments_upi_intent_transaction_limit","voip","w:g2","027","md_pin_chat_enabled","026","multi_scan_pjpeg_download_enabled","shops_product_grid","transaction_id","ctwa_context_enabled","20","fna","hq_image_quality","alt_jpeg_doc_detection_quality","group_call_max_participants","pkey","America/Belem","image_max_kbytes","web_cart_v1_1_order_message_changes_enabled","ctwa_context_enterprise_enabled","urn:xmpp:whatsapp:account","840","Asia/Kuala_Lumpur","max_participants","video_remux_after_repair_enabled","stella_addressbook_restriction_type","660","900","780","context_menu_ios13_enabled","mute-state","ref","payments_request_messages","029","frskmsg","vcard_max_size_kb","sample_buffer_gif_player_enabled","match_last_seen","510","4983","video_max_bitrate","028","w:comms:chat","17","frequently_forwarded_max","groups_privacy_blacklist","Asia/Karachi","02a","web_download_document_thumb_mms_enabled","02b","hist_sync","biz_block_reasons_version","1024","18","web_is_direct_connection_for_plm_transparent","view_once_write","file_max_size","paid_convo_id","online_privacy_setting","video_max_edge","view_once_read","enhanced_storage_management","multi_scan_pjpeg_encoding_enabled","ctwa_context_forward_enabled","video_transcode_downgrade_enable","template_doc_mime_types","hq_image_bw_threshold","30","body","u_aud_limit_sil_restarts_ctrl","other","participating","w:biz:directory","1110","vp8","4018","meta","doc_detection_image_max_edge","image_quality","1170","02c","smb_upsell_chat_banner_enabled","key_expiry_time_second","pid","stella_interop_enabled","19","linked_device_max_count","md_device_sync_enabled","02d","02e","360","enhanced_block_enabled","ephemeral_icon_in_forwarding","paid_convo_status","gif_provider","project_name","server-error","canonical_url_validation_enabled","wallpapers_v2","syncd_clear_chat_delete_chat_enabled","medianotify","02f","shops_required_tos_version","vote","reset_skey_on_id_change","030","image_max_edge","multicast_limit_global","ul_bw","21","25","5000","poll","570","22","031","1280","WhatsApp","032","bloks_shops_enabled","50","upload_host_switching_enabled","web_ctwa_context_compose_enabled","ptt_forwarded_features_enabled","unblocked","partial_pjpeg_enabled","fbid:devices","height","ephemeral_group_query_ts","group_join_permissions","order","033","alt_jpeg_status_quality","migrate","popular-bank","win_uwp_deprecation_killswitch_enabled","web_download_status_thumb_mms_enabled","blocking","url_text","035","web_forwarding_limit_to_groups","1600","val","1000","syncd_msg_date_enabled","bank-ref-id","max_subject","payments_web_enabled","web_upload_document_thumb_mms_enabled","size","request","ephemeral","24","receipt_agg","ptt_remember_play_position","sampling_weight","enc_rekey","mute_always","037","034","23","036","action","click_to_chat_qr_enabled","width","disabled","038","md_blocklist_v2","played_self_enabled","web_buttons_message_enabled","flow_id","clear","450","fbid:thread","bloks_session_state","America/Lima","attachment_picker_refresh","download_host_switching_enabled","1792","u_aud_limit_sil_restarts_test2","custom_urls","device_fanout","optimistic_upload","2000","key_cipher_suite","web_smb_upsell_in_biz_profile_enabled","e","039","siri_post_status_shortcut","pair-device","lg","lc","stream_attribution_url","model","mspjpeg_phash_gen","catalog_send_all","new_multi_vcards_ui","share_biz_vcard_enabled","-","clean","200","md_blocklist_v2_server","03b","03a","web_md_migration_experience","ptt_conversation_waveform","u_aud_limit_sil_restarts_test1"],["64","ptt_playback_speed_enabled","web_product_list_message_enabled","paid_convo_ts","27","manufacturer","psp-routing","grp_uii_cleanup","ptt_draft_enabled","03c","business_initiated","web_catalog_products_onoff","web_upload_link_thumb_mms_enabled","03e","mediaretry","35","hfm_string_changes","28","America/Fortaleza","max_keys","md_mhfs_days","streaming_upload_chunk_size","5541","040","03d","2675","03f","...","512","mute","48","041","alt_jpeg_quality","60","042","md_smb_quick_reply","5183","c","1343","40","1230","043","044","mms_cat_v1_forward_hot_override_enabled","user_notice","ptt_waveform_send","047","Asia/Calcutta","250","md_privacy_v2","31","29","128","md_messaging_enabled","046","crypto","690","045","enc_iv","75","failure","ptt_oot_playback","AIzaSyDR5yfaG7OG8sMTUj8kfQEb8T9pN8BM6Lk","w","048","2201","web_large_files_ui","Asia/Makassar","812","status_collapse_muted","1334","257","2HP4dm","049","patches","1290","43cY6T","America/Caracas","web_sticker_maker","campaign","ptt_pausable_enabled","33","42","attestation","biz","04b","query_linked","s","125","04a","810","availability","1411","responsiveness_v2_m1","catalog_not_created","34","America/Santiago","1465","enc_p","04d","status_info","04f","key_version","..","04c","04e","md_group_notification","1598","1215","web_cart_enabled","37","630","1920","2394","-1","vcard","38","elapsed","36","828","peer","pricing_category","1245","invalid","stella_ios_enabled","2687","45","1528","39","u_is_redial_audio_1104_ctrl","1025","1455","58","2524","2603","054","bsp_system_message_enabled","web_pip_redesign","051","verify_apps","1974","1272","1322","1755","052","70","050","1063","1135","1361","80","1096","1828","1851","1251","1921","key_config_id","1254","1566","1252","2525","critical_block","1669","max_available","w:auth:backup:token","product","2530","870","1022","participant_uuid","web_cart_on_off","1255","1432","1867","41","1415","1440","240","1204","1608","1690","1846","1483","1687","1749","69","url_number","053","1325","1040","365","59","Asia/Riyadh","1177","test_recommended","057","1612","43","1061","1518","1635","055","1034","1375","750","1430","event_code","1682","503","55","865","78","1309","1365","44","America/Guayaquil","535","LIMITED","1377","1613","1420","1599","1822","05a","1681","password","1111","1214","1376","1478","47","1082","4282","Europe/Istanbul","1307","46","058","1124","256","rate-overlimit","retail","u_a_socket_err_fix_succ_test","1292","1370","1388","520","861","psa","regular","1181","1766","05b","1183","1213","1304","1537"],["1724","profile_picture","1071","1314","1605","407","990","1710","746","pricing_model","056","059","061","1119","6027","65","877","1607","05d","917","seen","1516","49","470","973","1037","1350","1394","1480","1796","keys","794","1536","1594","2378","1333","1524","1825","116","309","52","808","827","909","495","1660","361","957","google","1357","1565","1967","996","1775","586","736","1052","1670","bank","177","1416","2194","2222","1454","1839","1275","53","997","1629","6028","smba","1378","1410","05c","1849","727","create","1559","536","1106","1310","1944","670","1297","1316","1762","en","1148","1295","1551","1853","1890","1208","1784","7200","05f","178","1283","1332","381","643","1056","1238","2024","2387","179","981","1547","1705","05e","290","903","1069","1285","2436","062","251","560","582","719","56","1700","2321","325","448","613","777","791","51","488","902","Asia/Almaty","is_hidden","1398","1527","1893","1999","2367","2642","237","busy","065","067","233","590","993","1511","54","723","860","363","487","522","605","995","1321","1691","1865","2447","2462","NON_TRANSACTIONAL","433","871","432","1004","1207","2032","2050","2379","2446","279","636","703","904","248","370","691","700","1068","1655","2334","060","063","364","533","534","567","1191","1210","1473","1827","069","701","2531","514","prev_dhash","064","496","790","1046","1139","1505","1521","1108","207","544","637","final","1173","1293","1694","1939","1951","1993","2353","2515","504","601","857","modify","spam_request","p_121_aa_1101_test4","866","1427","1502","1638","1744","2153","068","382","725","1704","1864","1990","2003","Asia/Dubai","508","531","1387","1474","1632","2307","2386","819","2014","066","387","1468","1706","2186","2261","471","728","1147","1372","1961"]],GX=["","xmlstreamstart","xmlstreamend","s.whatsapp.net","type","participant","from","receipt","id","notification","disappearing_mode","status","jid","broadcast","user","devices","device_hash","to","offline","message","result","class","xmlns","duration","notify","iq","t","ack","g.us","enc","urn:xmpp:whatsapp:push","presence","config_value","picture","verified_name","config_code","key-index-list","contact","mediatype","routing_info","edge_routing","get","read","urn:xmpp:ping","fallback_hostname","0","chatstate","business_hours_config","unavailable","download_buckets","skmsg","verified_level","composing","handshake","device-list","media","text","fallback_ip4","media_conn","device","creation","location","config","item","fallback_ip6","count","w:profile:picture","image","business","2","hostname","call-creator","display_name","relaylatency","platform","abprops","success","msg","offline_preview","prop","key-index","v","day_of_week","pkmsg","version","1","ping","w:p","download","video","set","specific_hours","props","primary","unknown","hash","commerce_experience","last","subscribe","max_buckets","call","profile","member_since_text","close_time","call-id","sticker","mode","participants","value","query","profile_options","open_time","code","list","host","ts","contacts","upload","lid","preview","update","usync","w:stats","delivery","auth_ttl","context","fail","cart_enabled","appdata","category","atn","direct_connection","decrypt-fail","relay_id","mmg-fallback.whatsapp.net","target","available","name","last_id","mmg.whatsapp.net","categories","401","is_new","index","tctoken","ip4","token_id","latency","recipient","edit","ip6","add","thumbnail-document","26","paused","true","identity","stream:error","key","sidelist","background","audio","3","thumbnail-image","biz-cover-photo","cat","gcm","thumbnail-video","error","auth","deny","serial","in","registration","thumbnail-link","remove","00","gif","thumbnail-gif","tag","capability","multicast","item-not-found","description","business_hours","config_expo_key","md-app-state","expiration","fallback","ttl","300","md-msg-hist","device_orientation","out","w:m","open_24h","side_list","token","inactive","01","document","te2","played","encrypt","msgr","hide","direct_path","12","state","not-authorized","url","terminate","signature","status-revoke-delay","02","te","linked_accounts","trusted_contact","timezone","ptt","kyc-id","privacy_token","readreceipts","appointment_only","address","expected_ts","privacy","7","android","interactive","device-identity","enabled","attribute_padding","1080","03","screen_height"],BF={};for(let[n,t]of GX.entries())BF[t]={index:n};for(let[n,t]of PX.entries())for(let[o,i]of t.entries())BF[i]={dict:n,index:o};var OA="@s.whatsapp.net";var FX="0@c.us";var jt;(function(n){n[n.WHATSAPP=0]="WHATSAPP",n[n.LID=1]="LID",n[n.HOSTED=128]="HOSTED",n[n.HOSTED_LID=129]="HOSTED_LID"})(jt||(jt={}));var LX=(n,t)=>{switch(t){case jt.LID:return"lid";case jt.HOSTED:return"hosted";case jt.HOSTED_LID:return"hosted.lid";case jt.WHATSAPP:default:return n}},Cr=(n,t,o,i)=>`${n||""}${i?`_${i}`:""}${o?`:${o}`:""}@${t}`,yA=n=>{let t=typeof n=="string"?n.indexOf("@"):-1;if(t<0)return;let o=n.slice(t+1),i=n.slice(0,t),[e,a]=i.split(":"),[A,r]=e.split("_"),s=jt.WHATSAPP;return o==="lid"?s=jt.LID:o==="hosted"?s=jt.HOSTED:o==="hosted.lid"?s=jt.HOSTED_LID:r&&(s=parseInt(r)),{server:o,user:A,domainType:s,device:a?+a:void 0}},Tt=(n,t)=>yA(n)?.user===yA(t)?.user,rh=n=>n?.endsWith("@bot"),_t=n=>n?.endsWith("@s.whatsapp.net"),qA=n=>n?.endsWith("@lid"),EB=n=>n?.endsWith("@broadcast"),Ur=n=>n?.endsWith("@g.us"),Tg=n=>n==="status@broadcast",Kc=n=>n?.endsWith("@newsletter"),ur=n=>n?.endsWith("@hosted"),ga=n=>n?.endsWith("@hosted.lid"),cUe=/^1313555\d{4}$|^131655500\d{2}$/,UX=n=>n&&cUe.test(n.split("@")[0])&&n.endsWith("@c.us"),uA=n=>{let t=yA(n);if(!t)return"";let{user:o,server:i}=t;return Cr(o,i==="c.us"?"s.whatsapp.net":i)},HX=(n,t)=>{let i=yA(n)?.device||0,{server:e,user:a}=yA(t);return Cr(a,e,i)};var KX=(n,t=hB,o=[0])=>{let i=xX(n,t,o);return Buffer.from(i)},xX=({tag:n,attrs:t,content:o},i,e)=>{let{TAGS:a,TOKEN_MAP:A}=i,r=L=>e.push(L&255),s=(L,q,z=!1)=>{for(let j=0;j>P*8&255)}},g=L=>{for(let q of L)e.push(q)},c=L=>{g([L>>8&255,L&255])},I=L=>g([L>>16&15,L>>8&255,L&255]),d=L=>{if(L>=4294967296)throw new Error("string too large to encode: "+L);L>=1<<20?(r(a.BINARY_32),s(L,4)):L>=256?(r(a.BINARY_20),I(L)):(r(a.BINARY_8),r(L))},B=L=>{let q=Buffer.from(L,"utf-8");d(q.length),g(q)},f=({domainType:L,device:q,user:z,server:j})=>{typeof q<"u"?(r(a.AD_JID),r(L||0),r(q||0),R(z)):(r(a.JID_PAIR),z.length?R(z):r(a.LIST_EMPTY),R(j))},Q=L=>{switch(L){case"-":return 10;case".":return 11;case"\0":return 15;default:if(L>="0"&&L<="9")return L.charCodeAt(0)-48;throw new Error(`invalid byte for nibble "${L}"`)}},y=L=>{if(L>="0"&&L<="9")return L.charCodeAt(0)-48;if(L>="A"&&L<="F")return 10+L.charCodeAt(0)-65;if(L>="a"&&L<="f")return 10+L.charCodeAt(0)-97;if(L==="\0")return 15;throw new Error(`Invalid hex char "${L}"`)},m=(L,q)=>{if(L.length>a.PACKED_MAX)throw new Error("Too many bytes to pack");r(q==="nibble"?a.NIBBLE_8:a.HEX_8);let z=Math.ceil(L.length/2);L.length%2!==0&&(z|=128),r(z);let j=q==="nibble"?Q:y,P=(U,N)=>j(U)<<4|j(N),J=Math.floor(L.length/2);for(let U=0;U{if(!L||L.length>a.PACKED_MAX)return!1;for(let q of L)if(!(q>="0"&&q<="9")&&q!=="-"&&q!==".")return!1;return!0},T=L=>{if(!L||L.length>a.PACKED_MAX)return!1;for(let q of L)if(!(q>="0"&&q<="9")&&!(q>="A"&&q<="F"))return!1;return!0},R=L=>{if(L==null){r(a.LIST_EMPTY);return}if(L===""){B(L);return}let q=A[L];if(q)typeof q.dict=="number"&&r(a.DICTIONARY_0+q.dict),r(q.index);else if(_(L))m(L,"nibble");else if(T(L))m(L,"hex");else{let z=yA(L);z?f(z):B(L)}},F=L=>{L===0?r(a.LIST_EMPTY):L<256?g([a.LIST_8,L]):(r(a.LIST_16),c(L))};if(!n)throw new Error("Invalid node: tag cannot be undefined");let K=Object.keys(t||{}).filter(L=>typeof t[L]<"u"&&t[L]!==null);F(2*K.length+1+(typeof o<"u"?1:0)),R(n);for(let L of K)typeof t[L]=="string"&&(R(L),R(t[L]));if(typeof o=="string")R(o);else if(Buffer.isBuffer(o)||o instanceof Uint8Array)d(o.length),g(o);else if(Array.isArray(o)){let L=o.filter(q=>q&&(q.tag||Buffer.isBuffer(q)||q instanceof Uint8Array||typeof q=="string"));F(L.length);for(let q of L)xX(q,i,e)}else if(!(typeof o>"u"))throw new Error(`invalid children for header "${n}": ${o} (${typeof o})`);return e};import{promisify as IUe}from"util";import{inflate as lUe}from"zlib";var pUe=IUe(lUe),dUe=async n=>(2&n.readUInt8()?n=await pUe(n.slice(1)):n=n.slice(1),n),YX=(n,t,o={index:0})=>{let{DOUBLE_BYTE_TOKENS:i,SINGLE_BYTE_TOKENS:e,TAGS:a}=t,A=k=>{if(o.index+k>n.length)throw new Error("end of stream")},r=()=>{let k=n[o.index];return o.index+=1,k},s=()=>(A(1),r()),g=k=>{A(k);let V=n.slice(o.index,o.index+k);return o.index+=k,V},c=k=>g(k).toString("utf-8"),I=(k,V=!1)=>{A(k);let Ae=0;for(let ie=0;ie(A(3),((r()&15)<<16)+(r()<<8)+r()),B=k=>{if(k>=0&&k<16)return k<10?48+k:65+k-10;throw new Error("invalid hex: "+k)},f=k=>{if(k>=0&&k<=9)return 48+k;switch(k){case 10:return 45;case 11:return 46;case 15:return 0;default:throw new Error("invalid nibble: "+k)}},Q=(k,V)=>{if(k===a.NIBBLE_8)return f(V);if(k===a.HEX_8)return B(V);throw new Error("unknown tag: "+k)},y=k=>{let V=s(),Ae="";for(let ie=0;ie<(V&127);ie++){let De=s();Ae+=String.fromCharCode(Q(k,(De&240)>>4)),Ae+=String.fromCharCode(Q(k,De&15))}return V>>7!==0&&(Ae=Ae.slice(0,-1)),Ae},m=k=>k===a.LIST_EMPTY||k===a.LIST_8||k===a.LIST_16,_=k=>{switch(k){case a.LIST_EMPTY:return 0;case a.LIST_8:return s();case a.LIST_16:return I(2);default:throw new Error("invalid tag for list size: "+k)}},T=()=>{let k=L(s()),V=L(s());if(V)return(k||"")+"@"+V;throw new Error("invalid jid pair: "+k+", "+V)},R=()=>{let k=s(),V=Number(k),Ae=s(),ie=L(s()),De="s.whatsapp.net";return V===jt.LID?De="lid":V===jt.HOSTED?De="hosted":V===jt.HOSTED_LID&&(De="hosted.lid"),Cr(ie,De,Ae)},F=()=>{let k=L(s()),V=I(2),Ae=L(s());return`${k}:${V}@${Ae}`},K=()=>{let k=L(s()),V=I(2),Ae=I(2),ie="interop",De=o.index;try{ie=L(s())}catch{o.index=De}return`${Ae}-${k}:${V}@${ie}`},L=k=>{if(k>=1&&k{let V=[],Ae=_(k);for(let ie=0;ie{let Ae=i[k];if(!Ae)throw new Error(`Invalid double token dict (${k})`);let ie=Ae[V];if(typeof ie>"u")throw new Error(`Invalid double token (${V})`);return ie},j=_(s()),P=L(s());if(!j||!P.length)throw new Error("invalid node");let J={},U;if(j===0||!P)throw new Error("invalid node");let N=j-1>>1;for(let k=0;k{let t=await dUe(n);return YX(t,hB)};var qX=Je(Lr(),1);var JX=new WeakMap,kA=(n,t)=>{if(!n||!Array.isArray(n.content))return[];let o=JX.get(n);if(!o){o=new Map;for(let i of n.content){let e=o.get(i.tag);e||o.set(i.tag,e=[]),e.push(i)}JX.set(n,o)}return o.get(t)||[]},le=(n,t)=>kA(n,t)[0],ys=({content:n})=>Array.isArray(n)?n:[],Qa=(n,t)=>{let o=le(n,t)?.content;if(Buffer.isBuffer(o)||o instanceof Uint8Array)return o},YA=(n,t)=>{let o=le(n,t)?.content;if(Buffer.isBuffer(o)||o instanceof Uint8Array)return Buffer.from(o).toString("utf-8");if(typeof o=="string")return o},xc=(n,t,o)=>{let i=Qa(n,t);if(i)return hUe(i,o)},Li=n=>{let t=le(n,"error");if(t)throw new qX.Boom(t.attrs.text||"Unknown error",{data:+t.attrs.code})},fF=(n,t)=>kA(n,t).reduce((e,{attrs:a})=>(typeof a.name=="string"?e[a.name]=a.value||a.config_value:e[a.config_code]=a.value||a.config_value,e),{});function hUe(n,t){let o=0;for(let i=0;i" ".repeat(n);function _n(n,t=0){if(!n)return n;if(typeof n=="string")return Vw(t)+n;if(n instanceof Uint8Array)return Vw(t)+Buffer.from(n).toString("hex");if(Array.isArray(n))return n.map(a=>Vw(t+1)+_n(a,t+1)).join(` +${B}`:dt(m),s,g),I||await this.#a.markSeen(A)}catch(_){this.#I.error?.("[dsh-weixin] failed to send the safe error reply:",_)}}}async#_(t,o,i,e){this.#c?.throwIfAborted();let a=this.#d.get(i),A=e.claimedReplyMessageId===o;if(!a||a!==e||a.submitting)return A&&(!a||a!==e)?this.#N(t,o):this.#T(t,o,i,{releaseMessageId:!1});if(this.#a.hasSeen(o))return;await this.#a.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString();let r=Fr(fl(t)),s=Fr(t?.context_token)??void 0,g=Fr(t?.run_id)??void 0;if(!r||Ew(t)){await this.#F(e.actor,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002"),s,g);return}let c=this.#d.get(i);if(!c||c!==e||c.submitting){if(A&&(!c||c!==e)){await this.#F(e.actor,hw(),s,g);return}return this.#T(t,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.contextToken=s,c.runId=g,c.needsPresentation){try{await this.#P(c)}catch{this.#i.lastError=w("\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002"),this.#I.error?.("[dsh-weixin] failed to retry an interaction question"),c.interaction.reconnect?.();return}let d=this.#d.get(i);if(!d||d!==e||d.submitting){if(A&&(!d||d!==e)){await this.#F(e.actor,hw(),s,g).catch(()=>{});return}return this.#T(t,o,i,{releaseMessageId:!1,alreadyRecorded:!0})}}let I=c.questions[c.index];if(I){if(c.answers.push(Ei(I,r)),c.index+=1,c.index{});return}if(this.#d.get(i)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#i.lastError=w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002"),this.#I.error?.("[dsh-weixin] failed to answer a Harness interaction"),await this.#F(c.actor,w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002"),c.contextToken,c.runId).catch(()=>{})}}}async#U(t,{key:o,actor:i,contextToken:e,runId:a}){if(t?.kind==="approval")return this.#B.handleRequested(t,{key:o,actor:i,send:c=>this.#F(i,c,e,a)});if(t?.kind!=="question")return;let A=t?.payload?.questions,r=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t?.rpcId!="string"||typeof r!="string"||typeof t.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!di(c))){this.#I.warn?.("[dsh-weixin] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"Weixin safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#F(i,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002"),e,a).catch(()=>{});return}let s=this.#d.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#P(s);return}if(this.#h.has(r))return;if(s){await t.respond({ok:!1,error:{code:"cancelled",message:"Weixin is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,questions:A,answers:[],index:0,contextToken:e,runId:a,queue:null,claimedReplyMessageId:null,presentationPromise:null,submitting:!1,needsPresentation:!0};this.#d.set(o,g),this.#h.set(r,o),await this.#P(g)}async#v(t){if(t?.kind==="approval"){await this.#B.handleResolved(t);return}let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#h.get(o);i&&this.#H(i,o)}#P(t){if(!t.needsPresentation)return Promise.resolve();if(t.presentationPromise)return t.presentationPromise;let o=t.questions[t.index];if(!o)return Promise.resolve();let i=this.#F(t.actor,hi(o,t.index,t.questions.length),t.contextToken,t.runId).then(()=>{t.needsPresentation=!1}).finally(()=>{t.presentationPromise===i&&(t.presentationPromise=null)});return t.presentationPromise=i,i}async#N(t,o){this.#a.hasSeen(o)||(await this.#a.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),await this.#F(Fr(t?.from_user_id),hw(),Fr(t?.context_token)??void 0,Fr(t?.run_id)??void 0).catch(()=>{}))}#Y(t,o){let i=this.#d.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#d.delete(t),this.#h.delete(i.interactionId),i)}#H(t,o){return this.#Y(t,o)!==null}async#q(t){let o=this.#Y(t);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Weixin interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#I.warn?.("[dsh-weixin] failed to cancel a pending Harness interaction")}}async#z(t,o,i){if(this.#c?.aborted)return;this.#i.lastError=i?.message??String(i);let e=tt(this.#i,i);this.#I.error?.(`[dsh-weixin] failed to process an interaction reply [${e.referenceId}]:`,i),this.#a.hasSeen(o)||await this.#a.markSeen(o).catch(()=>{}),await this.#F(Fr(t?.from_user_id),dt(e),Fr(t?.context_token)??void 0,Fr(t?.run_id)??void 0).catch(()=>{})}async#F(t,o,i,e){await this.#Ae();let a=[],A=MZ(o,this.#o);for(let r=0;r{}).then(t);return this.#b=o.catch(()=>{}),o}async#$(t,o){let i=Fr(t);if(!i||this.#R||this.#c?.aborted||Date.now(){if(e!==this.#u||this.#R)return!1;let a=this.#S;if(!a){let A=await this.#e.getConfig({baseUrl:this.#A,token:this.#t,toUserId:i,contextToken:o,signal:this.#c});if(a=Fr(A?.typingTicket),!a)return this.#D=Date.now()+RG,!1;if(e!==this.#u||this.#R)return!1;this.#S=a,this.#D=0}return this.#Q=i,await this.#e.sendTyping({baseUrl:this.#A,token:this.#t,toUserId:i,typingTicket:a,status:1,signal:this.#c}),e!==this.#u||this.#R?!1:(this.#w=!1,this.#D=0,this.#te(e),!0)})}catch(a){return e===this.#u&&(this.#j(),this.#w=!!(this.#Q&&this.#S),this.#D=Date.now()+RG),!this.#c?.aborted&&!this.#R&&this.#I.warn?.("[dsh-weixin] typing indicator failed:",a),!1}}async#Ae({signal:t=AbortSignal.timeout(5e3)}={}){++this.#u,this.#j();let o=this.#Q,i=this.#S,e=this.#w;if(this.#Q=null,typeof this.#e.sendTyping!="function")return!1;try{return await this.#G(async()=>{if(!o||!i)return!1;try{await this.#e.sendTyping({baseUrl:this.#A,token:this.#t,toUserId:o,typingTicket:i,status:2,signal:t})}finally{e&&this.#S===i&&(this.#S=null),this.#w=!1}return!0})}catch(a){return t?.aborted||this.#I.warn?.("[dsh-weixin] typing cancellation failed:",a),!1}}#te(t){if(this.#j(),t!==this.#u||!this.#Q||this.#R)return;let o=setTimeout(()=>{this.#m===o&&(this.#m=null),this.#G(async()=>t!==this.#u||!this.#Q||this.#R?!1:(await this.#e.sendTyping({baseUrl:this.#A,token:this.#t,toUserId:this.#Q,typingTicket:this.#S,status:1,signal:this.#c}),!0)).then(i=>{i&&this.#te(t)}).catch(i=>{t===this.#u&&(this.#w=!!(this.#Q&&this.#S),this.#D=Date.now()+RG,!this.#c?.aborted&&!this.#R&&this.#I.warn?.("[dsh-weixin] typing keepalive failed:",i))})},this.#s);o.unref?.(),this.#m=o}#j(){this.#m&&clearTimeout(this.#m),this.#m=null}#X(t,o,i){return this.#d.has(t)||this.#B.hasPending(t)?Promise.resolve(!1):this.#$(o,i)}async#x(t,o,i,e,a,A){let r=(g,c)=>this.#e[g]({baseUrl:this.#A,token:this.#t,toUserId:t,file:c,contextToken:e,runId:a,signal:this.#c}),s=await bo({artifacts:i,baseReceipt:A,deliveryId:o,aggregatePresentation:A?"weixin-text-and-files":"weixin-files",channelKey:"weixin",signal:this.#c,sendImage:typeof this.#e.sendImage=="function"?g=>r("sendImage",g):void 0,sendFile:typeof this.#e.sendFile=="function"?g=>r("sendFile",g):void 0,onFailure:(g,c)=>tt(this.#i,c,{userMessage:TLe(g?.fileName,c),reason:c?.code}),sendFailureNotice:(g,c,I)=>this.#F(t,dt(I),e,a),logger:this.#I});return this.#i.artifactsSent=(this.#i.artifactsSent??0)+s.artifactsSent,this.#i.artifactSendErrors=(this.#i.artifactSendErrors??0)+s.artifactSendErrors,{receipt:s.receipt,userVisible:s.userVisible,artifactSendErrors:s.artifactSendErrors}}};var NLe=Object.freeze([250,1e3,3e3]),RLe=new Set(["harness-connect-failed","harness-timeout","harness-auth-required","harness-proxy-auth-required","harness-loopback-forbidden","harness-host-untrusted","harness-request-forbidden","harness-api-not-found","harness-http-failed","harness-response-invalid","harness-rpc-rejected"]);function kLe(n){if(n===void 0)return[...NLe];if(!Array.isArray(n))throw new TypeError("startRetryDelaysMs must be an array");return n.map(t=>{if(!Number.isFinite(t)||t<0)throw new TypeError("startRetryDelaysMs must contain non-negative delays");return t})}function vLe(n){return n instanceof _A?n.code==="network-error"||n.code==="timeout"?!0:n.code==="http-error"&&(n.status===408||n.status===425||n.status===429||n.status>=500):!1}function PLe(n,t){let o=new Error(`Weixin runtime failed during ${n}`,{cause:t});return o.name="WeixinRuntimeStartError",o.code=n,o}function GLe(n){let t=RLe.has(n?.code)?n.code:"harness-check-unknown-failed";return PLe(t,n)}function UZ(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let a=setTimeout(()=>{t?.removeEventListener("abort",A),o()},n),A=()=>{clearTimeout(a),t?.removeEventListener("abort",A),i(t.reason??new DOMException("Aborted","AbortError"))};t?.addEventListener("abort",A,{once:!0})})}function FLe(n){if(!Array.isArray(n)||n.length<2)return Array.isArray(n)?n:[];let t=["seq","create_time_ms"].find(o=>n.every(i=>typeof i?.[o]=="number"&&Number.isFinite(i[o])||typeof i?.[o]=="string"&&i[o].trim()&&Number.isFinite(Number(i[o]))));return t?n.map((o,i)=>({message:o,index:i,order:Number(o[t])})).sort((o,i)=>o.order-i.order||o.index-i.index).map(({message:o})=>o):n}function LLe(){return{startedAt:null,ready:!1,weixinConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastError:null,...kG()}}var rB=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o=LLe();#s=null;#c=null;#p=null;#d=null;constructor({api:t,config:o,token:i,harness:e,state:a,contextEnhancement:A,logger:r=console,replyTimeoutMs:s=6e5,maxMessageChars:g=Bl,startRetryDelaysMs:c}){if(!t||!o||!i||!e||!a)throw new TypeError("WeixinRuntime requires API, account, token, Harness, and state");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,this.#I=g,this.#l=kLe(c)}get status(){return structuredClone(this.#o)}async start(){return this.#o.ready&&this.#p?this.status:this.#d?this.#d:(this.#d=this.#h().finally(()=>{this.#d=null}),this.#d)}async#h(){await this.stop(),this.#o.startedAt=new Date().toISOString(),this.#o.weixinConnectionState="connecting",this.#o.lastError=null;try{try{await this.#r.ensureRunning()}catch(o){throw GLe(o)}this.#o.harnessReachable=!0,await this.#E(),this.#c=new AbortController;let t=this.#c.signal;return this.#s=new uw({api:this.#e,baseUrl:this.#A.baseUrl,token:this.#t,ownerUserId:this.#A.ownerUserId,harness:this.#r,state:this.#g,contextEnhancement:this.#a,status:this.#o,logger:this.#n,replyTimeoutMs:this.#i,maxMessageChars:this.#I,signal:t}),this.#o.ready=!0,this.#o.weixinConnectionState="connected",this.#o.lastCheckedAt=Date.now(),this.#p=this.#C(t).catch(o=>{t.aborted||(this.#o.ready=!1,this.#o.weixinConnectionState="failed",this.#o.lastError=o?.message??String(o),this.#n.error?.(`[dsh-weixin] account ${this.#A.botId} monitor stopped:`,o))}),this.status}catch(t){throw this.#c?.abort(),this.#c=null,this.#s=null,this.#o.ready=!1,this.#o.weixinConnectionState="failed",this.#o.lastError=t?.message??String(t),t}}async#E(){for(let t=0;;t+=1)try{return await this.#e.notifyStart({baseUrl:this.#A.baseUrl,token:this.#t})}catch(o){let i=this.#l[t];if(i===void 0||!vLe(o))throw o;this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} start request failed; retrying in ${i}ms:`,o),await UZ(i)}}async#C(t){let o=0;for(;!t.aborted;)try{let i=await this.#e.getUpdates({baseUrl:this.#A.baseUrl,token:this.#t,getUpdatesBuf:this.#g.getUpdatesBuf(),signal:t});if(t.aborted)return;if(i?.ret!==void 0&&i.ret!==0||i?.errcode!==void 0&&i.errcode!==0){let a=i.errcode??i.ret;throw new _A(a===-14?"stale-token":"updates-rejected",a===-14?w("\u5FAE\u4FE1\u767B\u5F55\u51ED\u636E\u5DF2\u5931\u6548\uFF0C\u8BF7\u79FB\u9664\u8D26\u53F7\u540E\u91CD\u65B0\u626B\u7801\u3002"):w("\u5FAE\u4FE1\u6D88\u606F\u540C\u6B65\u8BF7\u6C42\u88AB\u62D2\u7EDD\u3002"))}o=0,this.#o.ready=!0,this.#o.weixinConnectionState="connected",this.#o.lastCheckedAt=Date.now(),this.#o.lastError=null;for(let a of FLe(i?.msgs))this.#s.accept(a).catch(A=>{t.aborted||this.#n.error?.(`[dsh-weixin] account ${this.#A.botId} message handling failed:`,A)});typeof i?.get_updates_buf=="string"&&i.get_updates_buf&&await this.#g.setGetUpdatesBuf(i.get_updates_buf)}catch(i){if(t.aborted)return;if(o+=1,this.#o.lastError=i?.message??String(i),this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} poll failed (${o}/3):`,i),i instanceof _A&&i.code==="stale-token"||o>=3)throw i;await UZ(Math.min(2e3*2**(o-1),1e4),t)}}async stop(){let t=this.#p,o=this.#s,i=!!(this.#c||t||this.#o.ready);if(this.#c?.abort(),this.#c=null,this.#p=null,await o?.close?.(),await t?.catch(()=>{}),await o?.waitForIdle(),this.#s=null,i)try{await this.#e.notifyStop({baseUrl:this.#A.baseUrl,token:this.#t,signal:AbortSignal.timeout(1e4)})}catch(e){this.#n.warn?.(`[dsh-weixin] account ${this.#A.botId} stop notification failed:`,e)}return this.#o.ready=!1,this.#o.weixinConnectionState="idle",this.status}async sendConnectionTest(t){let o=SE(this.#g),i=typeof o?.toUserId=="string"&&o.toUserId.trim()?o.toUserId.trim():typeof this.#A.ownerUserId=="string"&&this.#A.ownerUserId.trim()?this.#A.ownerUserId.trim():null;if(!i)throw Ir(w("\u5FAE\u4FE1\u673A\u5668\u4EBA"));if(!this.#o.ready||!this.#c)throw new Error("Weixin runtime is not connected");return await this.#e.sendText({baseUrl:this.#A.baseUrl,token:this.#t,toUserId:i,text:t,signal:this.#c.signal}),{sent:!0}}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.toUserId=="string"?t.route.toUserId.trim():"";if(t?.kind!=="user"||!e){let a=new TypeError("Invalid Weixin proactive delivery target");throw a.code="invalid-target",a}if(!this.#o.ready||!this.#c){let a=new Error("Weixin runtime is not connected");throw a.code="bot-not-connected",a}return i?.throwIfAborted(),await this.#e.sendText({baseUrl:this.#A.baseUrl,token:this.#t,toUserId:e,text:o,signal:i??this.#c.signal}),{sent:!0}}};var HZ=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function ULe(n){if(!Array.isArray(n)||n.length===0)return[...HZ];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...HZ]}var Bw=class{#e;#A;#t;#r;#g;#a;#n;#i=null;#I=null;#l=0;#o=!1;#s=!1;#c;#p;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=t,this.#A=o,this.#t=i,this.#r=ULe(e),this.#g=Number.isFinite(a)&&a>=0?a:15e3,this.#a=A,this.#n=r,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#s||this.#o?this:(this.#s=!0,this.#d(0),this)}async close(){this.#o||(this.#o=!0,this.#i!==null&&this.#n(this.#i),this.#i=null,await this.#I?.catch(()=>{}),this.#p?.(null),this.#p=null)}#d(t){this.#o||(this.#i=this.#a(()=>{this.#i=null,this.#h()},t),this.#i?.unref?.())}async#h(){if(this.#o||this.#I)return;let t=this.#E();this.#I=t;try{await t}finally{this.#I===t&&(this.#I=null)}}async#E(){try{if(await this.#A.ensureRunning(),this.#o)return;let t=await this.#e.initialize();if(this.#o)return;this.#p?.(t),this.#p=null;let{configured:o,connected:i}=t.totals;if(iRa(n),B=xLe(t),f=await new e(B.config).load(),Q=Ql(t.workspace??process.cwd()),y=o.WorkspaceStore??ea,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=f.list();await m.reconcile(_.map(k=>k.botId)),await Promise.all(_.map(k=>m.ensure(k.botId,{defaultAgentPreset:t.agentPreset})));let T=typeof f.remove=="function"?Pa(f,{workspaces:m}):f,R=new Map,L=k=>Ql(B.accounts,k,"state.json"),U=async k=>{let V=R.get(k);return V||(V=await new a(L(k)).load(),R.set(k,V)),V},F=Ua(n,o.commandExecutor),{controlExecutor:q,sessionMaintenanceExecutor:z,fileIngressExecutor:j}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),P=new A({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...F?{commandExecutor:F}:{},...q?{controlExecutor:q}:{},...z?{sessionMaintenanceExecutor:z}:{},...j?{fileIngressExecutor:j}:{}}),J=new r({api:g,credentials:n.credentials,configStore:T,logger:I,createRuntime:async({botId:k,config:V,token:Ae})=>{let ie=await U(k);await m.ensure(k,{defaultAgentPreset:t.agentPreset});let De=Ga(P,{botId:k,workspaces:m,state:ie,agentPresetCatalog:d});return new s({api:g,config:V,token:Ae,harness:De.harness,state:De.state,contextEnhancement:{botId:k,getSettings:()=>m.contextEnhancementFor(k)},replyTimeoutMs:t.replyTimeoutMs??6e5,maxMessageChars:t.maxMessageChars??Bl,logger:{error:(...fe)=>I.error?.(`[${k}]`,...fe),warn:(...fe)=>I.warn?.(`[${k}]`,...fe),info:(...fe)=>I.info?.(`[${k}]`,...fe),debug:(...fe)=>I.debug?.(`[${k}]`,...fe)}})},deleteState:async({botId:k})=>{let V=R.get(k);if(R.delete(k),V&&typeof V.remove=="function")await V.remove();else try{await HLe(L(k))}catch(Ae){if(Ae?.code!=="ENOENT")throw Ae}}}),H=Fa(J,{workspaces:m,stateFor:U,agentPresetCatalog:d}),N=c({controller:H,harness:P,logger:I,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:H,deliveryAdapter:La({channel:"weixin",workspaces:m,coreController:J,stateFor:U}),ready:N.ready,async close(){await N.close(),await H.close(),P.stopManagedProcess()}}}import YLe from"qrcode";var KZ="/weixin",Sr=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",submitVerification:"provision.verify",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),xZ=Object.freeze(Object.values(Sr));function YZ(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function jd(n,t){return YZ(n)&&Object.keys(n).every(o=>t.includes(o))}function fw(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function jLe(n,t){return YZ(t)?n===Sr.status?jd(t,[])?null:"connection.status does not accept fields.":n===Sr.beginProvisioning?jd(t,["locale"])&&(t.locale===void 0||t.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Sr.pollProvisioning,Sr.cancelProvisioning].includes(n)?jd(t,["attemptId"])&&fw(t.attemptId)?null:`${n} requires an attemptId.`:n===Sr.submitVerification?jd(t,["attemptId","verifyCode"])&&fw(t.attemptId)&&typeof t.verifyCode=="string"&&/^\d{4,8}$/.test(t.verifyCode)?null:"provision.verify requires an attemptId and a 4-to-8-digit code.":n===Sr.reconnectBot?jd(t,["botId","sendTest"])&&fw(t.botId)&&(t.sendTest===void 0||t.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Sr.deleteBot?jd(t,["botId","confirm"])&&fw(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Sr.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Sr.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===Sr.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown Weixin endpoint.":"Payload must be an object."}function Qw(n){return{ok:!1,error:{code:"bad-request",message:n}}}function iB(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function JLe(){return{ok:!1,error:{code:"weixin-operation-failed",message:"\u5FAE\u4FE1\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}async function qLe(n){return YLe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function yw(n,t){return!n||!n.verificationUrl?n:{...n,qrCodeDataUrl:await t(n.verificationUrl)}}async function Jd(n,t){let o=structuredClone(n);return o.provisioning&&(o.provisioning=await yw(o.provisioning,t)),o}function zLe(n){if(!n||typeof n.status!="function"||typeof n.startProvisioning!="function"||typeof n.registrationStatus!="function"||typeof n.submitVerification!="function"||typeof n.cancelProvisioning!="function"||typeof n.reconnectBot!="function"||typeof n.deleteBot!="function")throw new TypeError("A complete Weixin controller is required")}function jZ(n,{encodeQr:t=qLe}={}){zLe(n);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return iB();if(!xZ.includes(e))return Qw("Unknown Weixin endpoint.");let r=jLe(e,a);if(r)return Qw(r);try{let s;if(e===Sr.status)s=await Jd(await n.status(),i);else if(e===Sr.beginProvisioning){let g=await n.startProvisioning();if(A?.aborted)return await n.cancelProvisioning(g.attemptId),iB();s=await yw(g,i)}else if(e===Sr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return Qw("The provisioning attempt no longer exists.");s=await yw(g,i)}else if(e===Sr.submitVerification)s=await yw(await n.submitVerification(a.attemptId,a.verifyCode),i);else if(e===Sr.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return Qw("The provisioning attempt no longer exists.")}else if(e===Sr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return iB();let c;if(a.sendTest===!0)if(!g?.bots?.some(d=>d?.botId===a.botId&&d?.connected===!0)||typeof n.sendConnectionTest!="function")c=ir(Ir("\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=ir()}catch(d){c=ir(d)}s=await Jd({...g,...c?{testMessage:c}:{}},i)}else if(e===Sr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await Jd(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===Sr.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>Jd(g,i))}else if(e===Sr.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await Jd(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else s=await Jd(await n.deleteBot(a.botId),i);return A?.aborted?iB():{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?iB():g?{ok:!1,error:g}:JLe()}}}function mw(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(KZ,jZ(t,o),{authority:hr(i)})}async function JZ(n,t={}){if(t?.controller)return mw(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await PG(n,t,t.internals),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=mw(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-weixin: close account connections"),e}import{rm as uZe,unlink as BZe}from"node:fs/promises";import{homedir as fZe}from"node:os";import{join as uE,resolve as Xg}from"node:path";import{createHash as VLe}from"node:crypto";import{mkdir as WLe,readFile as ZLe,rename as XLe,unlink as $Le,writeFile as e2e}from"node:fs/promises";import{dirname as A2e}from"node:path";var GG=Object.freeze({version:2,bots:Object.freeze([])}),qZ=/^whatsapp_[a-f0-9]{24}$/,t2e=/^[a-f0-9-]{36}$/,r2e=/^[1-9]\d{4,14}$/,zd=Object.freeze({selfOnly:"self-only",privateAllowlist:"private-allowlist",open:"open"});function qd(n){return typeof n=="string"&&n.trim()?n.trim():null}function Sw(n){let t=qd(n)?.toLowerCase();return/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(t??"")?t:null}function FG(n){let t=Sw(n);if(!t)throw new TypeError("A valid WhatsApp account JID is required");return`whatsapp_${VLe("sha256").update(t).digest("hex").slice(0,24)}`}function LG(n){let t=Sw(n)?.split("@")[0]??"";return t?t.length<=7?`${t.slice(0,2)}\u2022\u2022\u2022${t.slice(-2)}`:`${t.slice(0,4)}\u2022\u2022\u2022\u2022${t.slice(-4)}`:w("WhatsApp\u8D26\u53F7")}function a2e(n){if(n===void 0)return Object.freeze([]);if(!Array.isArray(n))throw new TypeError("allowedNumbers must be an array of WhatsApp phone numbers");let t=n.map(o=>{let i=typeof o=="string"?o.trim().replace(/^\+/,""):"";if(!r2e.test(i))throw new TypeError("allowedNumbers contains an invalid WhatsApp phone number");return i});return Object.freeze([...new Set(t)])}function wg(n={}){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("WhatsApp access policy must be an object");let t=n.accessMode??zd.selfOnly;if(!Object.values(zd).includes(t))throw new TypeError("WhatsApp accessMode is invalid");return Object.freeze({accessMode:t,allowedNumbers:a2e(n.allowedNumbers)})}var ww=class{#e;#A=GG;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=this.#g(JSON.parse(await ZLe(this.#e,"utf8")));if(!t)throw new Error("dsh-im WhatsApp config contains invalid account data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=GG}return this}list(){return structuredClone(this.#A.bots)}get(t){let o=this.#A.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByAccountJid(t){let o=Sw(t),i=this.#A.bots.find(e=>e.accountJid===o);return i?structuredClone(i):null}async save(t){let o=this.#r(t);if(!o)throw new Error("Refusing to persist incomplete WhatsApp account data");return this.#a(i=>{let e=i.find(r=>r.accountJid===o.accountJid&&r.botId!==o.botId),a=i.find(r=>r.authDirectory===o.authDirectory&&r.botId!==o.botId);if(e||a)throw new Error("Duplicate WhatsApp account identity");let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!qZ.test(t))throw new TypeError("Invalid WhatsApp bot id");return this.#a(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await $Le(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=GG});this.#t=t.then(()=>{},()=>{}),await t}#r(t){if(!t||typeof t!="object")return null;let o=Sw(t.accountJid),i=qd(t.botId),e=qd(t.authDirectory),a=qd(t.name);if(!o||!i||!e||!a||!qZ.test(i)||!t2e.test(e)||FG(o)!==i)return null;let A;try{A=wg(t)}catch{return null}return Object.freeze({botId:i,accountJid:o,authDirectory:e,name:a,createdAt:qd(t.createdAt)??new Date().toISOString(),connectedAt:qd(t.connectedAt),...A})}#g(t){if(!t||t.version!==2||!Array.isArray(t.bots))return null;let o=t.bots.map(A=>this.#r(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.accountJid)||a.has(A.authDirectory))return null;i.add(A.botId),e.add(A.accountJid),a.add(A.authDirectory)}return Object.freeze({version:2,bots:Object.freeze(o)})}async#a(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:2,bots:Object.freeze(e)});await this.#n(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#n(t){await WLe(A2e(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await e2e(o,`${JSON.stringify(t,null,2)} +`,{encoding:"utf8",mode:384}),await XLe(o,this.#e)}};var Dw=class extends lr{constructor(t){super({...t,rpcIdPrefix:"whatsapp",logPrefix:"dsh-whatsapp"})}};var Ow=class extends As{};import{randomUUID as i2e}from"node:crypto";var zZ=new Set(["starting","pending","connecting"]),bw=new Set(["connected","failed","cancelled"]),o2e=6e4;function Nc(n,t){return Object.freeze({code:n,message:t})}function Mw(n){return n?{attemptId:n.id,status:n.state,qrRevision:n.qrRevision,pollIntervalMs:1e3,...n.qrValue?{qrValue:n.qrValue}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.botId?{botId:n.botId}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}var oB=class{#e;#A;#t;#r;#g;#a;#n;#i=new Map;#I=new Map;#l=new Map;#o=new Map;#s=null;#c=0;#p=!1;constructor({configStore:t,authPath:o,createSession:i,createRuntime:e,deleteAuth:a=async()=>{},deleteState:A=async()=>{},logger:r=console}){if(!t||typeof t.list!="function"||typeof t.save!="function"||typeof t.remove!="function")throw new TypeError("WhatsappController requires a config store");if(typeof o!="function"||typeof i!="function"||typeof e!="function")throw new TypeError("WhatsappController dependencies are incomplete");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r}async initialize(){if(this.#p)return this.status();for(let t of this.#e.list())await this.#f(t.botId,async()=>{if(!(this.#p||this.#i.get(t.botId)?.status?.ready))try{await this.#E(t),this.#I.delete(t.botId)}catch(o){this.#I.set(t.botId,Nc(o?.code==="relink-required"?"relink-required":"connection-failed",o?.code==="relink-required"?w("WhatsApp \u5173\u8054\u8BBE\u5907\u5DF2\u5931\u6548\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002"):w("WhatsApp \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"))),this.#n.warn?.(`[dsh-im:whatsapp] bot ${t.botId} failed to initialize`)}finally{this.#B()}});return this.status()}async startProvisioning(){if(this.#p)throw new Error("WhatsApp controller is closed");this.#s&&await this.cancelProvisioning(this.#s);let t,o,i=!1,e=new Promise((r,s)=>{t=()=>{i||(i=!0,r())},o=g=>{i||(i=!0,s(g))}}),a=i2e(),A={id:a,state:"starting",authDirectory:a,createdAt:Date.now(),expiresAt:null,qrRevision:0,qrValue:null,controller:new AbortController,session:null,task:null,error:null,botId:null};this.#l.set(a,A),this.#s=a,this.#B();try{let r=await this.#t({authDir:this.#A(A.authDirectory),signal:A.controller.signal,logger:this.#n,onQr:s=>{A.controller.signal.aborted||bw.has(A.state)||typeof s!="string"||!s||(A.qrValue=s,A.qrRevision+=1,A.expiresAt=Date.now()+o2e,A.state="pending",this.#B(),t())}});return A.session=r,A.task=r.ready.then(s=>this.#d(A,s)).catch(s=>this.#h(A,s,o)),await e,Mw(A)}catch(r){throw await this.#h(A,r,o),r}}registrationStatus(t){return Mw(this.#l.get(t))}async cancelProvisioning(t){let o=this.#l.get(t);return o?(bw.has(o.state)||(o.controller.abort(),await o.session?.close().catch(()=>{}),await o.task?.catch(()=>{}),bw.has(o.state)||(o.state="cancelled",o.error=Nc("cancelled",w("\u626B\u7801\u63A5\u5165\u5DF2\u53D6\u6D88\u3002"))),await this.#g(o.authDirectory).catch(()=>{})),this.#s===o.id&&(this.#s=null),this.#B(),Mw(o)):null}async reconnectBot(t){let o=this.#e.get(t);if(!o)throw new Error("Unknown WhatsApp bot");return await this.#f(t,async()=>{try{await this.#E(o),this.#I.delete(t)}catch(i){throw this.#I.set(t,Nc(i?.code==="relink-required"?"relink-required":"connection-failed",i?.code==="relink-required"?w("WhatsApp \u5173\u8054\u8BBE\u5907\u5DF2\u5931\u6548\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002"):w("WhatsApp \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),i}finally{this.#B()}}),this.status()}async sendConnectionTest(t){let o=this.#e.get(t);if(!o)throw new Error("Unknown WhatsApp bot");return this.#f(t,async()=>{let i=this.#i.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw e.code="test-target-unavailable",e}return i.sendConnectionTest(ba(`${o.name}\uFF08${LG(o.accountJid)}\uFF09`,w("WhatsApp\u673A\u5668\u4EBA")))})}async sendProactiveText(t,o,i,e={}){if(!this.#e.get(t))throw new Error("Unknown WhatsApp bot");return this.#f(t,async()=>{let A=this.#i.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async setAccessPolicy(t,o){if(this.#p)throw new Error("WhatsApp controller is closed");let i=wg(o);return await this.#f(t,async()=>{if(this.#p)throw new Error("WhatsApp controller is closed");let e=this.#e.get(t);if(!e)throw new Error("Unknown WhatsApp bot");let a=await this.#e.save({...e,...i});this.#i.get(t)?.setAccessPolicy?.(a),this.#B()}),this.status()}async deleteBot(t){let o=this.#e.get(t);if(!o)throw new Error("Unknown WhatsApp bot");return await this.#f(t,async()=>{await this.#C(t);try{await this.#e.remove(t)}catch(i){throw await this.#E(o).catch(()=>{}),i}await Promise.allSettled([this.#g(o.authDirectory),this.#a({botId:t,config:o})]),this.#I.delete(t),this.#B()}),this.status()}status(){let t=this.#e.list().map(e=>{let a=this.#i.get(e.botId)?.status??null,A=a?.ready===!0&&a.connectionState==="connected"&&a.harnessReachable===!0,r=A?"connected":a?.connectionState==="connecting"?"connecting":this.#I.has(e.botId)||a?.connectionState==="failed"?"error":"offline";return{botId:e.botId,state:r,connected:A,configured:!0,bot:{name:e.name,idMasked:LG(e.accountJid)},health:{status:A?"healthy":r==="error"?"error":"offline",summary:A?w("WhatsApp Web \u5173\u8054\u8BBE\u5907\u8FD0\u884C\u6B63\u5E38"):r==="error"?w("WhatsApp \u8FDE\u63A5\u672A\u5C31\u7EEA"):w("WhatsApp \u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},lastMessageError:Vr(a?.lastMessageError),accessPolicy:wg(e),error:structuredClone(this.#I.get(e.botId)??null)}}),o=t.filter(e=>e.connected).length,i=this.#s?this.#l.get(this.#s):null;return{schemaVersion:1,revision:this.#c,state:i&&zZ.has(i.state)?"provisioning":t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o},...i&&zZ.has(i.state)?{provisioning:Mw(i)}:{}}}async close(){this.#p||(this.#p=!0,this.#s&&await this.cancelProvisioning(this.#s),await Promise.allSettled([...this.#o.values()]),await Promise.allSettled([...this.#i.keys()].map(t=>this.#C(t))))}async#d(t,o){if(t.controller.signal.aborted||this.#p)return;t.state="connecting",t.qrValue=null,t.expiresAt=null,this.#B();let i=FG(o.accountJid);t.botId=i,await t.session?.close();let e=this.#e.get(i),a={botId:i,accountJid:o.accountJid,authDirectory:t.authDirectory,name:o.name,createdAt:e?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString(),accessMode:e?.accessMode,allowedNumbers:e?.allowedNumbers};try{if(t.controller.signal.aborted||this.#p)throw Object.assign(new Error,{name:"AbortError"});if(await this.#e.save(a),t.controller.signal.aborted||this.#p)throw Object.assign(new Error,{name:"AbortError"});try{await this.#E(a),this.#I.delete(i)}catch{this.#I.set(i,Nc("connection-failed",w("WhatsApp \u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#n.warn?.(`[dsh-im:whatsapp] bot ${i} did not reconnect after QR binding`)}e?.authDirectory&&e.authDirectory!==a.authDirectory&&await this.#g(e.authDirectory).catch(()=>{}),t.state="connected",t.error=null}catch(A){t.controller.signal.aborted||this.#p||A?.name==="AbortError"?(await this.#C(i),e?await this.#e.save(e).catch(()=>{}):await this.#e.remove(i).catch(()=>null)&&await this.#a({botId:i,config:a}).catch(s=>{this.#n.warn?.("[dsh-im:whatsapp] cancelled bot state cleanup failed:",s)}),await this.#g(t.authDirectory).catch(()=>{}),e&&await this.#E(e).catch(()=>{}),t.state="cancelled",t.error=Nc("cancelled",w("\u626B\u7801\u63A5\u5165\u5DF2\u53D6\u6D88\u3002"))):(await this.#g(t.authDirectory).catch(()=>{}),t.state="failed",t.error=Nc("activation-failed",w("WhatsApp \u5DF2\u626B\u7801\uFF0C\u4F46\u65E0\u6CD5\u4FDD\u5B58\u5173\u8054\u8BBE\u5907\u3002")),this.#n.error?.("[dsh-im:whatsapp] unable to persist linked-device session"))}finally{this.#s===t.id&&(this.#s=null),this.#B()}}async#h(t,o,i=()=>{}){bw.has(t.state)||(t.controller.signal.aborted||o?.name==="AbortError"?(t.state="cancelled",t.error=Nc("cancelled",w("\u626B\u7801\u63A5\u5165\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=Nc("qr-connect-failed",w("\u65E0\u6CD5\u8FDE\u63A5 WhatsApp\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"))),this.#s===t.id&&(this.#s=null),await t.session?.close().catch(()=>{}),await this.#g(t.authDirectory).catch(()=>{}),this.#B(),i(o))}async#E(t){if(this.#p)throw new Error("WhatsApp controller is closed");if(await this.#C(t.botId),this.#p)throw new Error("WhatsApp controller is closed");let o=await this.#r({botId:t.botId,config:t,authDir:this.#A(t.authDirectory)});if(!o||typeof o.start!="function"||typeof o.stop!="function")throw new TypeError("createRuntime returned an invalid WhatsApp runtime");this.#i.set(t.botId,o);try{await o.start()}catch(i){throw await o.stop().catch(()=>{}),this.#i.delete(t.botId),i}}async#C(t){let o=this.#i.get(t);this.#i.delete(t),await o?.stop().catch(()=>{})}#f(t,o){let a=(this.#o.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#o.get(t)===a&&this.#o.delete(t)});return this.#o.set(t,a),a}#B(){this.#c+=1}};import{createHash as tZe,randomBytes as Fce}from"node:crypto";var v=Je(Sm(),1),D=v.default.Reader,G=v.default.Writer,l=v.default.util,p=v.default.roots.default||(v.default.roots.default={});function se(n,t){if(typeof n=="string")return n;if(typeof n=="number")return String(n);if(n&&typeof n.low=="number"&&typeof n.high=="number"){let o=BigInt(n.low>>>0),e=BigInt(n.high>>>0)<<32n|o;return!t&&n.high<0?(e-(1n<<64n)).toString():e.toString()}return String(n)}function ge(n,t){if(typeof n=="number")return n;if(typeof n=="string")return Number(n);if(n&&typeof n.low=="number"&&typeof n.high=="number"){let o=BigInt(n.low>>>0),e=BigInt(n.high>>>0)<<32n|o;return!t&&n.high<0?Number(e-(1n<<64n)):Number(e)}return Number(n)}var oe=p.proto=(()=>{let n={};return n.ADVDeviceIdentity=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.rawId=e.uint32();break}case 2:{s.timestamp=e.uint64();break}case 3:{s.keyIndex=e.uint32();break}case 4:{s.accountType=e.int32();break}case 5:{s.deviceType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ADVDeviceIdentity)return e;var a=new p.proto.ADVDeviceIdentity;switch(e.rawId!=null&&(a.rawId=e.rawId>>>0),e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!0:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber(!0))),e.keyIndex!=null&&(a.keyIndex=e.keyIndex>>>0),e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"E2EE":case 0:a.accountType=0;break;case"HOSTED":case 1:a.accountType=1;break}switch(e.deviceType){default:if(typeof e.deviceType=="number"){a.deviceType=e.deviceType;break}break;case"E2EE":case 0:a.deviceType=0;break;case"HOSTED":case 1:a.deviceType=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.rawId!=null&&e.hasOwnProperty("rawId")&&(A.rawId=e.rawId,a.oneofs&&(A._rawId="rawId")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp,!0):a.longs===Number?ge(e.timestamp,!0):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),e.keyIndex!=null&&e.hasOwnProperty("keyIndex")&&(A.keyIndex=e.keyIndex,a.oneofs&&(A._keyIndex="keyIndex")),e.accountType!=null&&e.hasOwnProperty("accountType")&&(A.accountType=a.enums===String?p.proto.ADVEncryptionType[e.accountType]===void 0?e.accountType:p.proto.ADVEncryptionType[e.accountType]:e.accountType,a.oneofs&&(A._accountType="accountType")),e.deviceType!=null&&e.hasOwnProperty("deviceType")&&(A.deviceType=a.enums===String?p.proto.ADVEncryptionType[e.deviceType]===void 0?e.deviceType:p.proto.ADVEncryptionType[e.deviceType]:e.deviceType,a.oneofs&&(A._deviceType="deviceType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVDeviceIdentity"},t})(),n.ADVEncryptionType=(function(){let t={},o=Object.create(t);return o[t[0]="E2EE"]=0,o[t[1]="HOSTED"]=1,o})(),n.ADVKeyIndexList=(function(){function t(i){if(this.validIndexes=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.rawId=e.uint32();break}case 2:{s.timestamp=e.uint64();break}case 3:{s.currentIndex=e.uint32();break}case 4:{if(s.validIndexes&&s.validIndexes.length||(s.validIndexes=[]),(g&7)===2)for(var c=e.uint32()+e.pos;e.pos>>0),e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!0:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber(!0))),e.currentIndex!=null&&(a.currentIndex=e.currentIndex>>>0),e.validIndexes){if(!Array.isArray(e.validIndexes))throw TypeError(".proto.ADVKeyIndexList.validIndexes: array expected");a.validIndexes=[];for(var A=0;A>>0}switch(e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"E2EE":case 0:a.accountType=0;break;case"HOSTED":case 1:a.accountType=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.validIndexes=[]),e.rawId!=null&&e.hasOwnProperty("rawId")&&(A.rawId=e.rawId,a.oneofs&&(A._rawId="rawId")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp,!0):a.longs===Number?ge(e.timestamp,!0):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),e.currentIndex!=null&&e.hasOwnProperty("currentIndex")&&(A.currentIndex=e.currentIndex,a.oneofs&&(A._currentIndex="currentIndex")),e.validIndexes&&e.validIndexes.length){A.validIndexes=[];for(var r=0;r>>3){case 1:{s.details=e.bytes();break}case 2:{s.accountSignatureKey=e.bytes();break}case 3:{s.accountSignature=e.bytes();break}case 4:{s.deviceSignature=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ADVSignedDeviceIdentity)return e;var a=new p.proto.ADVSignedDeviceIdentity;return e.details!=null&&(typeof e.details=="string"?l.base64.decode(e.details,a.details=l.newBuffer(l.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.accountSignatureKey!=null&&(typeof e.accountSignatureKey=="string"?l.base64.decode(e.accountSignatureKey,a.accountSignatureKey=l.newBuffer(l.base64.length(e.accountSignatureKey)),0):e.accountSignatureKey.length>=0&&(a.accountSignatureKey=e.accountSignatureKey)),e.accountSignature!=null&&(typeof e.accountSignature=="string"?l.base64.decode(e.accountSignature,a.accountSignature=l.newBuffer(l.base64.length(e.accountSignature)),0):e.accountSignature.length>=0&&(a.accountSignature=e.accountSignature)),e.deviceSignature!=null&&(typeof e.deviceSignature=="string"?l.base64.decode(e.deviceSignature,a.deviceSignature=l.newBuffer(l.base64.length(e.deviceSignature)),0):e.deviceSignature.length>=0&&(a.deviceSignature=e.deviceSignature)),a},t.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?l.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.accountSignatureKey!=null&&e.hasOwnProperty("accountSignatureKey")&&(A.accountSignatureKey=a.bytes===String?l.base64.encode(e.accountSignatureKey,0,e.accountSignatureKey.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignatureKey):e.accountSignatureKey,a.oneofs&&(A._accountSignatureKey="accountSignatureKey")),e.accountSignature!=null&&e.hasOwnProperty("accountSignature")&&(A.accountSignature=a.bytes===String?l.base64.encode(e.accountSignature,0,e.accountSignature.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignature):e.accountSignature,a.oneofs&&(A._accountSignature="accountSignature")),e.deviceSignature!=null&&e.hasOwnProperty("deviceSignature")&&(A.deviceSignature=a.bytes===String?l.base64.encode(e.deviceSignature,0,e.deviceSignature.length):a.bytes===Array?Array.prototype.slice.call(e.deviceSignature):e.deviceSignature,a.oneofs&&(A._deviceSignature="deviceSignature")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVSignedDeviceIdentity"},t})(),n.ADVSignedDeviceIdentityHMAC=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.details=e.bytes();break}case 2:{s.hmac=e.bytes();break}case 3:{s.accountType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ADVSignedDeviceIdentityHMAC)return e;var a=new p.proto.ADVSignedDeviceIdentityHMAC;switch(e.details!=null&&(typeof e.details=="string"?l.base64.decode(e.details,a.details=l.newBuffer(l.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.hmac!=null&&(typeof e.hmac=="string"?l.base64.decode(e.hmac,a.hmac=l.newBuffer(l.base64.length(e.hmac)),0):e.hmac.length>=0&&(a.hmac=e.hmac)),e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"E2EE":case 0:a.accountType=0;break;case"HOSTED":case 1:a.accountType=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?l.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.hmac!=null&&e.hasOwnProperty("hmac")&&(A.hmac=a.bytes===String?l.base64.encode(e.hmac,0,e.hmac.length):a.bytes===Array?Array.prototype.slice.call(e.hmac):e.hmac,a.oneofs&&(A._hmac="hmac")),e.accountType!=null&&e.hasOwnProperty("accountType")&&(A.accountType=a.enums===String?p.proto.ADVEncryptionType[e.accountType]===void 0?e.accountType:p.proto.ADVEncryptionType[e.accountType]:e.accountType,a.oneofs&&(A._accountType="accountType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVSignedDeviceIdentityHMAC"},t})(),n.ADVSignedKeyIndexList=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.details=e.bytes();break}case 2:{s.accountSignature=e.bytes();break}case 3:{s.accountSignatureKey=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ADVSignedKeyIndexList)return e;var a=new p.proto.ADVSignedKeyIndexList;return e.details!=null&&(typeof e.details=="string"?l.base64.decode(e.details,a.details=l.newBuffer(l.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.accountSignature!=null&&(typeof e.accountSignature=="string"?l.base64.decode(e.accountSignature,a.accountSignature=l.newBuffer(l.base64.length(e.accountSignature)),0):e.accountSignature.length>=0&&(a.accountSignature=e.accountSignature)),e.accountSignatureKey!=null&&(typeof e.accountSignatureKey=="string"?l.base64.decode(e.accountSignatureKey,a.accountSignatureKey=l.newBuffer(l.base64.length(e.accountSignatureKey)),0):e.accountSignatureKey.length>=0&&(a.accountSignatureKey=e.accountSignatureKey)),a},t.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?l.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.accountSignature!=null&&e.hasOwnProperty("accountSignature")&&(A.accountSignature=a.bytes===String?l.base64.encode(e.accountSignature,0,e.accountSignature.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignature):e.accountSignature,a.oneofs&&(A._accountSignature="accountSignature")),e.accountSignatureKey!=null&&e.hasOwnProperty("accountSignatureKey")&&(A.accountSignatureKey=a.bytes===String?l.base64.encode(e.accountSignatureKey,0,e.accountSignatureKey.length):a.bytes===Array?Array.prototype.slice.call(e.accountSignatureKey):e.accountSignatureKey,a.oneofs&&(A._accountSignatureKey="accountSignatureKey")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ADVSignedKeyIndexList"},t})(),n.AIHomeState=(function(){function t(i){if(this.capabilityOptions=[],this.conversationOptions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lastFetchTime=e.int64();break}case 2:{s.capabilityOptions&&s.capabilityOptions.length||(s.capabilityOptions=[]),s.capabilityOptions.push(p.proto.AIHomeState.AIHomeOption.decode(e,e.uint32()));break}case 3:{s.conversationOptions&&s.conversationOptions.length||(s.conversationOptions=[]),s.conversationOptions.push(p.proto.AIHomeState.AIHomeOption.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIHomeState)return e;var a=new p.proto.AIHomeState;if(e.lastFetchTime!=null&&(l.Long?(a.lastFetchTime=l.Long.fromValue(e.lastFetchTime)).unsigned=!1:typeof e.lastFetchTime=="string"?a.lastFetchTime=parseInt(e.lastFetchTime,10):typeof e.lastFetchTime=="number"?a.lastFetchTime=e.lastFetchTime:typeof e.lastFetchTime=="object"&&(a.lastFetchTime=new l.LongBits(e.lastFetchTime.low>>>0,e.lastFetchTime.high>>>0).toNumber())),e.capabilityOptions){if(!Array.isArray(e.capabilityOptions))throw TypeError(".proto.AIHomeState.capabilityOptions: array expected");a.capabilityOptions=[];for(var A=0;A>>3){case 1:{c.type=A.int32();break}case 2:{c.title=A.string();break}case 3:{c.promptText=A.string();break}case 4:{c.sessionId=A.string();break}case 5:{c.imageWdsIdentifier=A.string();break}case 6:{c.imageTintColor=A.string();break}case 7:{c.imageBackgroundColor=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIHomeState.AIHomeOption)return A;var r=new p.proto.AIHomeState.AIHomeOption;switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"PROMPT":case 0:r.type=0;break;case"CREATE_IMAGE":case 1:r.type=1;break;case"ANIMATE_PHOTO":case 2:r.type=2;break;case"ANALYZE_FILE":case 3:r.type=3;break}return A.title!=null&&(r.title=String(A.title)),A.promptText!=null&&(r.promptText=String(A.promptText)),A.sessionId!=null&&(r.sessionId=String(A.sessionId)),A.imageWdsIdentifier!=null&&(r.imageWdsIdentifier=String(A.imageWdsIdentifier)),A.imageTintColor!=null&&(r.imageTintColor=String(A.imageTintColor)),A.imageBackgroundColor!=null&&(r.imageBackgroundColor=String(A.imageBackgroundColor)),r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.AIHomeState.AIHomeOption.AIHomeActionType[A.type]===void 0?A.type:p.proto.AIHomeState.AIHomeOption.AIHomeActionType[A.type]:A.type,r.oneofs&&(s._type="type")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.promptText!=null&&A.hasOwnProperty("promptText")&&(s.promptText=A.promptText,r.oneofs&&(s._promptText="promptText")),A.sessionId!=null&&A.hasOwnProperty("sessionId")&&(s.sessionId=A.sessionId,r.oneofs&&(s._sessionId="sessionId")),A.imageWdsIdentifier!=null&&A.hasOwnProperty("imageWdsIdentifier")&&(s.imageWdsIdentifier=A.imageWdsIdentifier,r.oneofs&&(s._imageWdsIdentifier="imageWdsIdentifier")),A.imageTintColor!=null&&A.hasOwnProperty("imageTintColor")&&(s.imageTintColor=A.imageTintColor,r.oneofs&&(s._imageTintColor="imageTintColor")),A.imageBackgroundColor!=null&&A.hasOwnProperty("imageBackgroundColor")&&(s.imageBackgroundColor=A.imageBackgroundColor,r.oneofs&&(s._imageBackgroundColor="imageBackgroundColor")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIHomeState.AIHomeOption"},i.AIHomeActionType=(function(){let a={},A=Object.create(a);return A[a[0]="PROMPT"]=0,A[a[1]="CREATE_IMAGE"]=1,A[a[2]="ANIMATE_PHOTO"]=2,A[a[3]="ANALYZE_FILE"]=3,A})(),i})(),t})(),n.AIQueryFanout=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.message=p.proto.Message.decode(e,e.uint32());break}case 3:{s.timestamp=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIQueryFanout)return e;var a=new p.proto.AIQueryFanout;if(e.messageKey!=null){if(typeof e.messageKey!="object")throw TypeError(".proto.AIQueryFanout.messageKey: object expected");a.messageKey=p.proto.MessageKey.fromObject(e.messageKey)}if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.AIQueryFanout.message: object expected");a.message=p.proto.Message.fromObject(e.message)}return e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.messageKey!=null&&e.hasOwnProperty("messageKey")&&(A.messageKey=p.proto.MessageKey.toObject(e.messageKey,a),a.oneofs&&(A._messageKey="messageKey")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=p.proto.Message.toObject(e.message,a),a.oneofs&&(A._message="message")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp):a.longs===Number?ge(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIQueryFanout"},t})(),n.AIRegenerateMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.responseTimestampMs=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRegenerateMetadata)return e;var a=new p.proto.AIRegenerateMetadata;if(e.messageKey!=null){if(typeof e.messageKey!="object")throw TypeError(".proto.AIRegenerateMetadata.messageKey: object expected");a.messageKey=p.proto.MessageKey.fromObject(e.messageKey)}return e.responseTimestampMs!=null&&(l.Long?(a.responseTimestampMs=l.Long.fromValue(e.responseTimestampMs)).unsigned=!1:typeof e.responseTimestampMs=="string"?a.responseTimestampMs=parseInt(e.responseTimestampMs,10):typeof e.responseTimestampMs=="number"?a.responseTimestampMs=e.responseTimestampMs:typeof e.responseTimestampMs=="object"&&(a.responseTimestampMs=new l.LongBits(e.responseTimestampMs.low>>>0,e.responseTimestampMs.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.messageKey!=null&&e.hasOwnProperty("messageKey")&&(A.messageKey=p.proto.MessageKey.toObject(e.messageKey,a),a.oneofs&&(A._messageKey="messageKey")),e.responseTimestampMs!=null&&e.hasOwnProperty("responseTimestampMs")&&(typeof e.responseTimestampMs=="number"?A.responseTimestampMs=a.longs===String?String(e.responseTimestampMs):e.responseTimestampMs:A.responseTimestampMs=a.longs===String?se(e.responseTimestampMs):a.longs===Number?ge(e.responseTimestampMs):e.responseTimestampMs,a.oneofs&&(A._responseTimestampMs="responseTimestampMs")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRegenerateMetadata"},t})(),n.AIRichResponseCodeMetadata=(function(){function t(i){if(this.codeBlocks=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.codeLanguage=e.string();break}case 2:{s.codeBlocks&&s.codeBlocks.length||(s.codeBlocks=[]),s.codeBlocks.push(p.proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseCodeMetadata)return e;var a=new p.proto.AIRichResponseCodeMetadata;if(e.codeLanguage!=null&&(a.codeLanguage=String(e.codeLanguage)),e.codeBlocks){if(!Array.isArray(e.codeBlocks))throw TypeError(".proto.AIRichResponseCodeMetadata.codeBlocks: array expected");a.codeBlocks=[];for(var A=0;A>>3){case 1:{c.highlightType=A.int32();break}case 2:{c.codeContent=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock)return A;var r=new p.proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock;switch(A.highlightType){default:if(typeof A.highlightType=="number"){r.highlightType=A.highlightType;break}break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_DEFAULT":case 0:r.highlightType=0;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_KEYWORD":case 1:r.highlightType=1;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_METHOD":case 2:r.highlightType=2;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_STRING":case 3:r.highlightType=3;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_NUMBER":case 4:r.highlightType=4;break;case"AI_RICH_RESPONSE_CODE_HIGHLIGHT_COMMENT":case 5:r.highlightType=5;break}return A.codeContent!=null&&(r.codeContent=String(A.codeContent)),r},i.toObject=function(A,r){r||(r={});var s={};return A.highlightType!=null&&A.hasOwnProperty("highlightType")&&(s.highlightType=r.enums===String?p.proto.AIRichResponseCodeMetadata.AIRichResponseCodeHighlightType[A.highlightType]===void 0?A.highlightType:p.proto.AIRichResponseCodeMetadata.AIRichResponseCodeHighlightType[A.highlightType]:A.highlightType,r.oneofs&&(s._highlightType="highlightType")),A.codeContent!=null&&A.hasOwnProperty("codeContent")&&(s.codeContent=A.codeContent,r.oneofs&&(s._codeContent="codeContent")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseCodeMetadata.AIRichResponseCodeBlock"},i})(),t.AIRichResponseCodeHighlightType=(function(){let i={},e=Object.create(i);return e[i[0]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_DEFAULT"]=0,e[i[1]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_KEYWORD"]=1,e[i[2]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_METHOD"]=2,e[i[3]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_STRING"]=3,e[i[4]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_NUMBER"]=4,e[i[5]="AI_RICH_RESPONSE_CODE_HIGHLIGHT_COMMENT"]=5,e})(),t})(),n.AIRichResponseContentItemsMetadata=(function(){function t(i){if(this.itemsMetadata=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.itemsMetadata&&s.itemsMetadata.length||(s.itemsMetadata=[]),s.itemsMetadata.push(p.proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata.decode(e,e.uint32()));break}case 2:{s.contentType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseContentItemsMetadata)return e;var a=new p.proto.AIRichResponseContentItemsMetadata;if(e.itemsMetadata){if(!Array.isArray(e.itemsMetadata))throw TypeError(".proto.AIRichResponseContentItemsMetadata.itemsMetadata: array expected");a.itemsMetadata=[];for(var A=0;A>>3){case 1:{c.reelItem=p.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata)return A;var r=new p.proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata;if(A.reelItem!=null){if(typeof A.reelItem!="object")throw TypeError(".proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata.reelItem: object expected");r.reelItem=p.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem.fromObject(A.reelItem)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.reelItem!=null&&A.hasOwnProperty("reelItem")&&(s.reelItem=p.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem.toObject(A.reelItem,r),r.oneofs&&(s.aIRichResponseContentItem="reelItem")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseContentItemsMetadata.AIRichResponseContentItemMetadata"},i})(),t.AIRichResponseReelItem=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.title=A.string();break}case 2:{c.profileIconUrl=A.string();break}case 3:{c.thumbnailUrl=A.string();break}case 4:{c.videoUrl=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem)return A;var r=new p.proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem;return A.title!=null&&(r.title=String(A.title)),A.profileIconUrl!=null&&(r.profileIconUrl=String(A.profileIconUrl)),A.thumbnailUrl!=null&&(r.thumbnailUrl=String(A.thumbnailUrl)),A.videoUrl!=null&&(r.videoUrl=String(A.videoUrl)),r},i.toObject=function(A,r){r||(r={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.profileIconUrl!=null&&A.hasOwnProperty("profileIconUrl")&&(s.profileIconUrl=A.profileIconUrl,r.oneofs&&(s._profileIconUrl="profileIconUrl")),A.thumbnailUrl!=null&&A.hasOwnProperty("thumbnailUrl")&&(s.thumbnailUrl=A.thumbnailUrl,r.oneofs&&(s._thumbnailUrl="thumbnailUrl")),A.videoUrl!=null&&A.hasOwnProperty("videoUrl")&&(s.videoUrl=A.videoUrl,r.oneofs&&(s._videoUrl="videoUrl")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseContentItemsMetadata.AIRichResponseReelItem"},i})(),t.ContentType=(function(){let i={},e=Object.create(i);return e[i[0]="DEFAULT"]=0,e[i[1]="CAROUSEL"]=1,e})(),t})(),n.AIRichResponseDynamicMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}case 2:{s.version=e.uint64();break}case 3:{s.url=e.string();break}case 4:{s.loopCount=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseDynamicMetadata)return e;var a=new p.proto.AIRichResponseDynamicMetadata;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_UNKNOWN":case 0:a.type=0;break;case"AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE":case 1:a.type=1;break;case"AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF":case 2:a.type=2;break}return e.version!=null&&(l.Long?(a.version=l.Long.fromValue(e.version)).unsigned=!0:typeof e.version=="string"?a.version=parseInt(e.version,10):typeof e.version=="number"?a.version=e.version:typeof e.version=="object"&&(a.version=new l.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber(!0))),e.url!=null&&(a.url=String(e.url)),e.loopCount!=null&&(a.loopCount=e.loopCount>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType[e.type]===void 0?e.type:p.proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType[e.type]:e.type,a.oneofs&&(A._type="type")),e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?A.version=a.longs===String?String(e.version):e.version:A.version=a.longs===String?se(e.version,!0):a.longs===Number?ge(e.version,!0):e.version,a.oneofs&&(A._version="version")),e.url!=null&&e.hasOwnProperty("url")&&(A.url=e.url,a.oneofs&&(A._url="url")),e.loopCount!=null&&e.hasOwnProperty("loopCount")&&(A.loopCount=e.loopCount,a.oneofs&&(A._loopCount="loopCount")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseDynamicMetadata"},t.AIRichResponseDynamicMetadataType=(function(){let i={},e=Object.create(i);return e[i[0]="AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_UNKNOWN"]=0,e[i[1]="AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE"]=1,e[i[2]="AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF"]=2,e})(),t})(),n.AIRichResponseGridImageMetadata=(function(){function t(i){if(this.imageUrls=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.gridImageUrl=p.proto.AIRichResponseImageURL.decode(e,e.uint32());break}case 2:{s.imageUrls&&s.imageUrls.length||(s.imageUrls=[]),s.imageUrls.push(p.proto.AIRichResponseImageURL.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseGridImageMetadata)return e;var a=new p.proto.AIRichResponseGridImageMetadata;if(e.gridImageUrl!=null){if(typeof e.gridImageUrl!="object")throw TypeError(".proto.AIRichResponseGridImageMetadata.gridImageUrl: object expected");a.gridImageUrl=p.proto.AIRichResponseImageURL.fromObject(e.gridImageUrl)}if(e.imageUrls){if(!Array.isArray(e.imageUrls))throw TypeError(".proto.AIRichResponseGridImageMetadata.imageUrls: array expected");a.imageUrls=[];for(var A=0;A>>3){case 1:{s.imagePreviewUrl=e.string();break}case 2:{s.imageHighResUrl=e.string();break}case 3:{s.sourceUrl=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseImageURL)return e;var a=new p.proto.AIRichResponseImageURL;return e.imagePreviewUrl!=null&&(a.imagePreviewUrl=String(e.imagePreviewUrl)),e.imageHighResUrl!=null&&(a.imageHighResUrl=String(e.imageHighResUrl)),e.sourceUrl!=null&&(a.sourceUrl=String(e.sourceUrl)),a},t.toObject=function(e,a){a||(a={});var A={};return e.imagePreviewUrl!=null&&e.hasOwnProperty("imagePreviewUrl")&&(A.imagePreviewUrl=e.imagePreviewUrl,a.oneofs&&(A._imagePreviewUrl="imagePreviewUrl")),e.imageHighResUrl!=null&&e.hasOwnProperty("imageHighResUrl")&&(A.imageHighResUrl=e.imageHighResUrl,a.oneofs&&(A._imageHighResUrl="imageHighResUrl")),e.sourceUrl!=null&&e.hasOwnProperty("sourceUrl")&&(A.sourceUrl=e.sourceUrl,a.oneofs&&(A._sourceUrl="sourceUrl")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseImageURL"},t})(),n.AIRichResponseInlineImageMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.imageUrl=p.proto.AIRichResponseImageURL.decode(e,e.uint32());break}case 2:{s.imageText=e.string();break}case 3:{s.alignment=e.int32();break}case 4:{s.tapLinkUrl=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseInlineImageMetadata)return e;var a=new p.proto.AIRichResponseInlineImageMetadata;if(e.imageUrl!=null){if(typeof e.imageUrl!="object")throw TypeError(".proto.AIRichResponseInlineImageMetadata.imageUrl: object expected");a.imageUrl=p.proto.AIRichResponseImageURL.fromObject(e.imageUrl)}switch(e.imageText!=null&&(a.imageText=String(e.imageText)),e.alignment){default:if(typeof e.alignment=="number"){a.alignment=e.alignment;break}break;case"AI_RICH_RESPONSE_IMAGE_LAYOUT_LEADING_ALIGNED":case 0:a.alignment=0;break;case"AI_RICH_RESPONSE_IMAGE_LAYOUT_TRAILING_ALIGNED":case 1:a.alignment=1;break;case"AI_RICH_RESPONSE_IMAGE_LAYOUT_CENTER_ALIGNED":case 2:a.alignment=2;break}return e.tapLinkUrl!=null&&(a.tapLinkUrl=String(e.tapLinkUrl)),a},t.toObject=function(e,a){a||(a={});var A={};return e.imageUrl!=null&&e.hasOwnProperty("imageUrl")&&(A.imageUrl=p.proto.AIRichResponseImageURL.toObject(e.imageUrl,a),a.oneofs&&(A._imageUrl="imageUrl")),e.imageText!=null&&e.hasOwnProperty("imageText")&&(A.imageText=e.imageText,a.oneofs&&(A._imageText="imageText")),e.alignment!=null&&e.hasOwnProperty("alignment")&&(A.alignment=a.enums===String?p.proto.AIRichResponseInlineImageMetadata.AIRichResponseImageAlignment[e.alignment]===void 0?e.alignment:p.proto.AIRichResponseInlineImageMetadata.AIRichResponseImageAlignment[e.alignment]:e.alignment,a.oneofs&&(A._alignment="alignment")),e.tapLinkUrl!=null&&e.hasOwnProperty("tapLinkUrl")&&(A.tapLinkUrl=e.tapLinkUrl,a.oneofs&&(A._tapLinkUrl="tapLinkUrl")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseInlineImageMetadata"},t.AIRichResponseImageAlignment=(function(){let i={},e=Object.create(i);return e[i[0]="AI_RICH_RESPONSE_IMAGE_LAYOUT_LEADING_ALIGNED"]=0,e[i[1]="AI_RICH_RESPONSE_IMAGE_LAYOUT_TRAILING_ALIGNED"]=1,e[i[2]="AI_RICH_RESPONSE_IMAGE_LAYOUT_CENTER_ALIGNED"]=2,e})(),t})(),n.AIRichResponseLatexMetadata=(function(){function t(i){if(this.expressions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.text=e.string();break}case 2:{s.expressions&&s.expressions.length||(s.expressions=[]),s.expressions.push(p.proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseLatexMetadata)return e;var a=new p.proto.AIRichResponseLatexMetadata;if(e.text!=null&&(a.text=String(e.text)),e.expressions){if(!Array.isArray(e.expressions))throw TypeError(".proto.AIRichResponseLatexMetadata.expressions: array expected");a.expressions=[];for(var A=0;A>>3){case 1:{c.latexExpression=A.string();break}case 2:{c.url=A.string();break}case 3:{c.width=A.double();break}case 4:{c.height=A.double();break}case 5:{c.fontHeight=A.double();break}case 6:{c.imageTopPadding=A.double();break}case 7:{c.imageLeadingPadding=A.double();break}case 8:{c.imageBottomPadding=A.double();break}case 9:{c.imageTrailingPadding=A.double();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression)return A;var r=new p.proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression;return A.latexExpression!=null&&(r.latexExpression=String(A.latexExpression)),A.url!=null&&(r.url=String(A.url)),A.width!=null&&(r.width=Number(A.width)),A.height!=null&&(r.height=Number(A.height)),A.fontHeight!=null&&(r.fontHeight=Number(A.fontHeight)),A.imageTopPadding!=null&&(r.imageTopPadding=Number(A.imageTopPadding)),A.imageLeadingPadding!=null&&(r.imageLeadingPadding=Number(A.imageLeadingPadding)),A.imageBottomPadding!=null&&(r.imageBottomPadding=Number(A.imageBottomPadding)),A.imageTrailingPadding!=null&&(r.imageTrailingPadding=Number(A.imageTrailingPadding)),r},i.toObject=function(A,r){r||(r={});var s={};return A.latexExpression!=null&&A.hasOwnProperty("latexExpression")&&(s.latexExpression=A.latexExpression,r.oneofs&&(s._latexExpression="latexExpression")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=r.json&&!isFinite(A.width)?String(A.width):A.width,r.oneofs&&(s._width="width")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=r.json&&!isFinite(A.height)?String(A.height):A.height,r.oneofs&&(s._height="height")),A.fontHeight!=null&&A.hasOwnProperty("fontHeight")&&(s.fontHeight=r.json&&!isFinite(A.fontHeight)?String(A.fontHeight):A.fontHeight,r.oneofs&&(s._fontHeight="fontHeight")),A.imageTopPadding!=null&&A.hasOwnProperty("imageTopPadding")&&(s.imageTopPadding=r.json&&!isFinite(A.imageTopPadding)?String(A.imageTopPadding):A.imageTopPadding,r.oneofs&&(s._imageTopPadding="imageTopPadding")),A.imageLeadingPadding!=null&&A.hasOwnProperty("imageLeadingPadding")&&(s.imageLeadingPadding=r.json&&!isFinite(A.imageLeadingPadding)?String(A.imageLeadingPadding):A.imageLeadingPadding,r.oneofs&&(s._imageLeadingPadding="imageLeadingPadding")),A.imageBottomPadding!=null&&A.hasOwnProperty("imageBottomPadding")&&(s.imageBottomPadding=r.json&&!isFinite(A.imageBottomPadding)?String(A.imageBottomPadding):A.imageBottomPadding,r.oneofs&&(s._imageBottomPadding="imageBottomPadding")),A.imageTrailingPadding!=null&&A.hasOwnProperty("imageTrailingPadding")&&(s.imageTrailingPadding=r.json&&!isFinite(A.imageTrailingPadding)?String(A.imageTrailingPadding):A.imageTrailingPadding,r.oneofs&&(s._imageTrailingPadding="imageTrailingPadding")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseLatexMetadata.AIRichResponseLatexExpression"},i})(),t})(),n.AIRichResponseMapMetadata=(function(){function t(i){if(this.annotations=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.centerLatitude=e.double();break}case 2:{s.centerLongitude=e.double();break}case 3:{s.latitudeDelta=e.double();break}case 4:{s.longitudeDelta=e.double();break}case 5:{s.annotations&&s.annotations.length||(s.annotations=[]),s.annotations.push(p.proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation.decode(e,e.uint32()));break}case 6:{s.showInfoList=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseMapMetadata)return e;var a=new p.proto.AIRichResponseMapMetadata;if(e.centerLatitude!=null&&(a.centerLatitude=Number(e.centerLatitude)),e.centerLongitude!=null&&(a.centerLongitude=Number(e.centerLongitude)),e.latitudeDelta!=null&&(a.latitudeDelta=Number(e.latitudeDelta)),e.longitudeDelta!=null&&(a.longitudeDelta=Number(e.longitudeDelta)),e.annotations){if(!Array.isArray(e.annotations))throw TypeError(".proto.AIRichResponseMapMetadata.annotations: array expected");a.annotations=[];for(var A=0;A>>3){case 1:{c.annotationNumber=A.uint32();break}case 2:{c.latitude=A.double();break}case 3:{c.longitude=A.double();break}case 4:{c.title=A.string();break}case 5:{c.body=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation)return A;var r=new p.proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation;return A.annotationNumber!=null&&(r.annotationNumber=A.annotationNumber>>>0),A.latitude!=null&&(r.latitude=Number(A.latitude)),A.longitude!=null&&(r.longitude=Number(A.longitude)),A.title!=null&&(r.title=String(A.title)),A.body!=null&&(r.body=String(A.body)),r},i.toObject=function(A,r){r||(r={});var s={};return A.annotationNumber!=null&&A.hasOwnProperty("annotationNumber")&&(s.annotationNumber=A.annotationNumber,r.oneofs&&(s._annotationNumber="annotationNumber")),A.latitude!=null&&A.hasOwnProperty("latitude")&&(s.latitude=r.json&&!isFinite(A.latitude)?String(A.latitude):A.latitude,r.oneofs&&(s._latitude="latitude")),A.longitude!=null&&A.hasOwnProperty("longitude")&&(s.longitude=r.json&&!isFinite(A.longitude)?String(A.longitude):A.longitude,r.oneofs&&(s._longitude="longitude")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=A.body,r.oneofs&&(s._body="body")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIRichResponseMapMetadata.AIRichResponseMapAnnotation"},i})(),t})(),n.AIRichResponseMessage=(function(){function t(i){if(this.submessages=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageType=e.int32();break}case 2:{s.submessages&&s.submessages.length||(s.submessages=[]),s.submessages.push(p.proto.AIRichResponseSubMessage.decode(e,e.uint32()));break}case 3:{s.unifiedResponse=p.proto.AIRichResponseUnifiedResponse.decode(e,e.uint32());break}case 4:{s.contextInfo=p.proto.ContextInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseMessage)return e;var a=new p.proto.AIRichResponseMessage;switch(e.messageType){default:if(typeof e.messageType=="number"){a.messageType=e.messageType;break}break;case"AI_RICH_RESPONSE_TYPE_UNKNOWN":case 0:a.messageType=0;break;case"AI_RICH_RESPONSE_TYPE_STANDARD":case 1:a.messageType=1;break}if(e.submessages){if(!Array.isArray(e.submessages))throw TypeError(".proto.AIRichResponseMessage.submessages: array expected");a.submessages=[];for(var A=0;A>>3){case 1:{s.messageType=e.int32();break}case 2:{s.gridImageMetadata=p.proto.AIRichResponseGridImageMetadata.decode(e,e.uint32());break}case 3:{s.messageText=e.string();break}case 4:{s.imageMetadata=p.proto.AIRichResponseInlineImageMetadata.decode(e,e.uint32());break}case 5:{s.codeMetadata=p.proto.AIRichResponseCodeMetadata.decode(e,e.uint32());break}case 6:{s.tableMetadata=p.proto.AIRichResponseTableMetadata.decode(e,e.uint32());break}case 7:{s.dynamicMetadata=p.proto.AIRichResponseDynamicMetadata.decode(e,e.uint32());break}case 8:{s.latexMetadata=p.proto.AIRichResponseLatexMetadata.decode(e,e.uint32());break}case 9:{s.mapMetadata=p.proto.AIRichResponseMapMetadata.decode(e,e.uint32());break}case 10:{s.contentItemsMetadata=p.proto.AIRichResponseContentItemsMetadata.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseSubMessage)return e;var a=new p.proto.AIRichResponseSubMessage;switch(e.messageType){default:if(typeof e.messageType=="number"){a.messageType=e.messageType;break}break;case"AI_RICH_RESPONSE_UNKNOWN":case 0:a.messageType=0;break;case"AI_RICH_RESPONSE_GRID_IMAGE":case 1:a.messageType=1;break;case"AI_RICH_RESPONSE_TEXT":case 2:a.messageType=2;break;case"AI_RICH_RESPONSE_INLINE_IMAGE":case 3:a.messageType=3;break;case"AI_RICH_RESPONSE_TABLE":case 4:a.messageType=4;break;case"AI_RICH_RESPONSE_CODE":case 5:a.messageType=5;break;case"AI_RICH_RESPONSE_DYNAMIC":case 6:a.messageType=6;break;case"AI_RICH_RESPONSE_MAP":case 7:a.messageType=7;break;case"AI_RICH_RESPONSE_LATEX":case 8:a.messageType=8;break;case"AI_RICH_RESPONSE_CONTENT_ITEMS":case 9:a.messageType=9;break}if(e.gridImageMetadata!=null){if(typeof e.gridImageMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.gridImageMetadata: object expected");a.gridImageMetadata=p.proto.AIRichResponseGridImageMetadata.fromObject(e.gridImageMetadata)}if(e.messageText!=null&&(a.messageText=String(e.messageText)),e.imageMetadata!=null){if(typeof e.imageMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.imageMetadata: object expected");a.imageMetadata=p.proto.AIRichResponseInlineImageMetadata.fromObject(e.imageMetadata)}if(e.codeMetadata!=null){if(typeof e.codeMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.codeMetadata: object expected");a.codeMetadata=p.proto.AIRichResponseCodeMetadata.fromObject(e.codeMetadata)}if(e.tableMetadata!=null){if(typeof e.tableMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.tableMetadata: object expected");a.tableMetadata=p.proto.AIRichResponseTableMetadata.fromObject(e.tableMetadata)}if(e.dynamicMetadata!=null){if(typeof e.dynamicMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.dynamicMetadata: object expected");a.dynamicMetadata=p.proto.AIRichResponseDynamicMetadata.fromObject(e.dynamicMetadata)}if(e.latexMetadata!=null){if(typeof e.latexMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.latexMetadata: object expected");a.latexMetadata=p.proto.AIRichResponseLatexMetadata.fromObject(e.latexMetadata)}if(e.mapMetadata!=null){if(typeof e.mapMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.mapMetadata: object expected");a.mapMetadata=p.proto.AIRichResponseMapMetadata.fromObject(e.mapMetadata)}if(e.contentItemsMetadata!=null){if(typeof e.contentItemsMetadata!="object")throw TypeError(".proto.AIRichResponseSubMessage.contentItemsMetadata: object expected");a.contentItemsMetadata=p.proto.AIRichResponseContentItemsMetadata.fromObject(e.contentItemsMetadata)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.messageType!=null&&e.hasOwnProperty("messageType")&&(A.messageType=a.enums===String?p.proto.AIRichResponseSubMessageType[e.messageType]===void 0?e.messageType:p.proto.AIRichResponseSubMessageType[e.messageType]:e.messageType,a.oneofs&&(A._messageType="messageType")),e.gridImageMetadata!=null&&e.hasOwnProperty("gridImageMetadata")&&(A.gridImageMetadata=p.proto.AIRichResponseGridImageMetadata.toObject(e.gridImageMetadata,a),a.oneofs&&(A._gridImageMetadata="gridImageMetadata")),e.messageText!=null&&e.hasOwnProperty("messageText")&&(A.messageText=e.messageText,a.oneofs&&(A._messageText="messageText")),e.imageMetadata!=null&&e.hasOwnProperty("imageMetadata")&&(A.imageMetadata=p.proto.AIRichResponseInlineImageMetadata.toObject(e.imageMetadata,a),a.oneofs&&(A._imageMetadata="imageMetadata")),e.codeMetadata!=null&&e.hasOwnProperty("codeMetadata")&&(A.codeMetadata=p.proto.AIRichResponseCodeMetadata.toObject(e.codeMetadata,a),a.oneofs&&(A._codeMetadata="codeMetadata")),e.tableMetadata!=null&&e.hasOwnProperty("tableMetadata")&&(A.tableMetadata=p.proto.AIRichResponseTableMetadata.toObject(e.tableMetadata,a),a.oneofs&&(A._tableMetadata="tableMetadata")),e.dynamicMetadata!=null&&e.hasOwnProperty("dynamicMetadata")&&(A.dynamicMetadata=p.proto.AIRichResponseDynamicMetadata.toObject(e.dynamicMetadata,a),a.oneofs&&(A._dynamicMetadata="dynamicMetadata")),e.latexMetadata!=null&&e.hasOwnProperty("latexMetadata")&&(A.latexMetadata=p.proto.AIRichResponseLatexMetadata.toObject(e.latexMetadata,a),a.oneofs&&(A._latexMetadata="latexMetadata")),e.mapMetadata!=null&&e.hasOwnProperty("mapMetadata")&&(A.mapMetadata=p.proto.AIRichResponseMapMetadata.toObject(e.mapMetadata,a),a.oneofs&&(A._mapMetadata="mapMetadata")),e.contentItemsMetadata!=null&&e.hasOwnProperty("contentItemsMetadata")&&(A.contentItemsMetadata=p.proto.AIRichResponseContentItemsMetadata.toObject(e.contentItemsMetadata,a),a.oneofs&&(A._contentItemsMetadata="contentItemsMetadata")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseSubMessage"},t})(),n.AIRichResponseSubMessageType=(function(){let t={},o=Object.create(t);return o[t[0]="AI_RICH_RESPONSE_UNKNOWN"]=0,o[t[1]="AI_RICH_RESPONSE_GRID_IMAGE"]=1,o[t[2]="AI_RICH_RESPONSE_TEXT"]=2,o[t[3]="AI_RICH_RESPONSE_INLINE_IMAGE"]=3,o[t[4]="AI_RICH_RESPONSE_TABLE"]=4,o[t[5]="AI_RICH_RESPONSE_CODE"]=5,o[t[6]="AI_RICH_RESPONSE_DYNAMIC"]=6,o[t[7]="AI_RICH_RESPONSE_MAP"]=7,o[t[8]="AI_RICH_RESPONSE_LATEX"]=8,o[t[9]="AI_RICH_RESPONSE_CONTENT_ITEMS"]=9,o})(),n.AIRichResponseTableMetadata=(function(){function t(i){if(this.rows=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.rows&&s.rows.length||(s.rows=[]),s.rows.push(p.proto.AIRichResponseTableMetadata.AIRichResponseTableRow.decode(e,e.uint32()));break}case 2:{s.title=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseTableMetadata)return e;var a=new p.proto.AIRichResponseTableMetadata;if(e.rows){if(!Array.isArray(e.rows))throw TypeError(".proto.AIRichResponseTableMetadata.rows: array expected");a.rows=[];for(var A=0;A>>3){case 1:{c.items&&c.items.length||(c.items=[]),c.items.push(A.string());break}case 2:{c.isHeading=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIRichResponseTableMetadata.AIRichResponseTableRow)return A;var r=new p.proto.AIRichResponseTableMetadata.AIRichResponseTableRow;if(A.items){if(!Array.isArray(A.items))throw TypeError(".proto.AIRichResponseTableMetadata.AIRichResponseTableRow.items: array expected");r.items=[];for(var s=0;s>>3){case 1:{s.data=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIRichResponseUnifiedResponse)return e;var a=new p.proto.AIRichResponseUnifiedResponse;return e.data!=null&&(typeof e.data=="string"?l.base64.decode(e.data,a.data=l.newBuffer(l.base64.length(e.data)),0):e.data.length>=0&&(a.data=e.data)),a},t.toObject=function(e,a){a||(a={});var A={};return e.data!=null&&e.hasOwnProperty("data")&&(A.data=a.bytes===String?l.base64.encode(e.data,0,e.data.length):a.bytes===Array?Array.prototype.slice.call(e.data):e.data,a.oneofs&&(A._data="data")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIRichResponseUnifiedResponse"},t})(),n.AIThreadInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.serverInfo=p.proto.AIThreadInfo.AIThreadServerInfo.decode(e,e.uint32());break}case 2:{s.clientInfo=p.proto.AIThreadInfo.AIThreadClientInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AIThreadInfo)return e;var a=new p.proto.AIThreadInfo;if(e.serverInfo!=null){if(typeof e.serverInfo!="object")throw TypeError(".proto.AIThreadInfo.serverInfo: object expected");a.serverInfo=p.proto.AIThreadInfo.AIThreadServerInfo.fromObject(e.serverInfo)}if(e.clientInfo!=null){if(typeof e.clientInfo!="object")throw TypeError(".proto.AIThreadInfo.clientInfo: object expected");a.clientInfo=p.proto.AIThreadInfo.AIThreadClientInfo.fromObject(e.clientInfo)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.serverInfo!=null&&e.hasOwnProperty("serverInfo")&&(A.serverInfo=p.proto.AIThreadInfo.AIThreadServerInfo.toObject(e.serverInfo,a),a.oneofs&&(A._serverInfo="serverInfo")),e.clientInfo!=null&&e.hasOwnProperty("clientInfo")&&(A.clientInfo=p.proto.AIThreadInfo.AIThreadClientInfo.toObject(e.clientInfo,a),a.oneofs&&(A._clientInfo="clientInfo")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AIThreadInfo"},t.AIThreadClientInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.type=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIThreadInfo.AIThreadClientInfo)return A;var r=new p.proto.AIThreadInfo.AIThreadClientInfo;switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNKNOWN":case 0:r.type=0;break;case"DEFAULT":case 1:r.type=1;break;case"INCOGNITO":case 2:r.type=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.AIThreadInfo.AIThreadClientInfo.AIThreadType[A.type]===void 0?A.type:p.proto.AIThreadInfo.AIThreadClientInfo.AIThreadType[A.type]:A.type,r.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIThreadInfo.AIThreadClientInfo"},i.AIThreadType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="DEFAULT"]=1,A[a[2]="INCOGNITO"]=2,A})(),i})(),t.AIThreadServerInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.title=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.AIThreadInfo.AIThreadServerInfo)return A;var r=new p.proto.AIThreadInfo.AIThreadServerInfo;return A.title!=null&&(r.title=String(A.title)),r},i.toObject=function(A,r){r||(r={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.AIThreadInfo.AIThreadServerInfo"},i})(),t})(),n.Account=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lid=e.string();break}case 2:{s.username=e.string();break}case 3:{s.countryCode=e.string();break}case 4:{s.isUsernameDeleted=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Account)return e;var a=new p.proto.Account;return e.lid!=null&&(a.lid=String(e.lid)),e.username!=null&&(a.username=String(e.username)),e.countryCode!=null&&(a.countryCode=String(e.countryCode)),e.isUsernameDeleted!=null&&(a.isUsernameDeleted=!!e.isUsernameDeleted),a},t.toObject=function(e,a){a||(a={});var A={};return e.lid!=null&&e.hasOwnProperty("lid")&&(A.lid=e.lid,a.oneofs&&(A._lid="lid")),e.username!=null&&e.hasOwnProperty("username")&&(A.username=e.username,a.oneofs&&(A._username="username")),e.countryCode!=null&&e.hasOwnProperty("countryCode")&&(A.countryCode=e.countryCode,a.oneofs&&(A._countryCode="countryCode")),e.isUsernameDeleted!=null&&e.hasOwnProperty("isUsernameDeleted")&&(A.isUsernameDeleted=e.isUsernameDeleted,a.oneofs&&(A._isUsernameDeleted="isUsernameDeleted")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Account"},t})(),n.ActionLink=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.url=e.string();break}case 2:{s.buttonTitle=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ActionLink)return e;var a=new p.proto.ActionLink;return e.url!=null&&(a.url=String(e.url)),e.buttonTitle!=null&&(a.buttonTitle=String(e.buttonTitle)),a},t.toObject=function(e,a){a||(a={});var A={};return e.url!=null&&e.hasOwnProperty("url")&&(A.url=e.url,a.oneofs&&(A._url="url")),e.buttonTitle!=null&&e.hasOwnProperty("buttonTitle")&&(A.buttonTitle=e.buttonTitle,a.oneofs&&(A._buttonTitle="buttonTitle")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ActionLink"},t})(),n.AutoDownloadSettings=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.downloadImages=e.bool();break}case 2:{s.downloadAudio=e.bool();break}case 3:{s.downloadVideo=e.bool();break}case 4:{s.downloadDocuments=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AutoDownloadSettings)return e;var a=new p.proto.AutoDownloadSettings;return e.downloadImages!=null&&(a.downloadImages=!!e.downloadImages),e.downloadAudio!=null&&(a.downloadAudio=!!e.downloadAudio),e.downloadVideo!=null&&(a.downloadVideo=!!e.downloadVideo),e.downloadDocuments!=null&&(a.downloadDocuments=!!e.downloadDocuments),a},t.toObject=function(e,a){a||(a={});var A={};return e.downloadImages!=null&&e.hasOwnProperty("downloadImages")&&(A.downloadImages=e.downloadImages,a.oneofs&&(A._downloadImages="downloadImages")),e.downloadAudio!=null&&e.hasOwnProperty("downloadAudio")&&(A.downloadAudio=e.downloadAudio,a.oneofs&&(A._downloadAudio="downloadAudio")),e.downloadVideo!=null&&e.hasOwnProperty("downloadVideo")&&(A.downloadVideo=e.downloadVideo,a.oneofs&&(A._downloadVideo="downloadVideo")),e.downloadDocuments!=null&&e.hasOwnProperty("downloadDocuments")&&(A.downloadDocuments=e.downloadDocuments,a.oneofs&&(A._downloadDocuments="downloadDocuments")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AutoDownloadSettings"},t})(),n.AvatarUserSettings=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.fbid=e.string();break}case 2:{s.password=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.AvatarUserSettings)return e;var a=new p.proto.AvatarUserSettings;return e.fbid!=null&&(a.fbid=String(e.fbid)),e.password!=null&&(a.password=String(e.password)),a},t.toObject=function(e,a){a||(a={});var A={};return e.fbid!=null&&e.hasOwnProperty("fbid")&&(A.fbid=e.fbid,a.oneofs&&(A._fbid="fbid")),e.password!=null&&e.hasOwnProperty("password")&&(A.password=e.password,a.oneofs&&(A._password="password")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.AvatarUserSettings"},t})(),n.BizAccountLinkInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.whatsappBizAcctFbid=e.uint64();break}case 2:{s.whatsappAcctNumber=e.string();break}case 3:{s.issueTime=e.uint64();break}case 4:{s.hostStorage=e.int32();break}case 5:{s.accountType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BizAccountLinkInfo)return e;var a=new p.proto.BizAccountLinkInfo;switch(e.whatsappBizAcctFbid!=null&&(l.Long?(a.whatsappBizAcctFbid=l.Long.fromValue(e.whatsappBizAcctFbid)).unsigned=!0:typeof e.whatsappBizAcctFbid=="string"?a.whatsappBizAcctFbid=parseInt(e.whatsappBizAcctFbid,10):typeof e.whatsappBizAcctFbid=="number"?a.whatsappBizAcctFbid=e.whatsappBizAcctFbid:typeof e.whatsappBizAcctFbid=="object"&&(a.whatsappBizAcctFbid=new l.LongBits(e.whatsappBizAcctFbid.low>>>0,e.whatsappBizAcctFbid.high>>>0).toNumber(!0))),e.whatsappAcctNumber!=null&&(a.whatsappAcctNumber=String(e.whatsappAcctNumber)),e.issueTime!=null&&(l.Long?(a.issueTime=l.Long.fromValue(e.issueTime)).unsigned=!0:typeof e.issueTime=="string"?a.issueTime=parseInt(e.issueTime,10):typeof e.issueTime=="number"?a.issueTime=e.issueTime:typeof e.issueTime=="object"&&(a.issueTime=new l.LongBits(e.issueTime.low>>>0,e.issueTime.high>>>0).toNumber(!0))),e.hostStorage){default:if(typeof e.hostStorage=="number"){a.hostStorage=e.hostStorage;break}break;case"ON_PREMISE":case 0:a.hostStorage=0;break;case"FACEBOOK":case 1:a.hostStorage=1;break}switch(e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"ENTERPRISE":case 0:a.accountType=0;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.whatsappBizAcctFbid!=null&&e.hasOwnProperty("whatsappBizAcctFbid")&&(typeof e.whatsappBizAcctFbid=="number"?A.whatsappBizAcctFbid=a.longs===String?String(e.whatsappBizAcctFbid):e.whatsappBizAcctFbid:A.whatsappBizAcctFbid=a.longs===String?se(e.whatsappBizAcctFbid,!0):a.longs===Number?ge(e.whatsappBizAcctFbid,!0):e.whatsappBizAcctFbid,a.oneofs&&(A._whatsappBizAcctFbid="whatsappBizAcctFbid")),e.whatsappAcctNumber!=null&&e.hasOwnProperty("whatsappAcctNumber")&&(A.whatsappAcctNumber=e.whatsappAcctNumber,a.oneofs&&(A._whatsappAcctNumber="whatsappAcctNumber")),e.issueTime!=null&&e.hasOwnProperty("issueTime")&&(typeof e.issueTime=="number"?A.issueTime=a.longs===String?String(e.issueTime):e.issueTime:A.issueTime=a.longs===String?se(e.issueTime,!0):a.longs===Number?ge(e.issueTime,!0):e.issueTime,a.oneofs&&(A._issueTime="issueTime")),e.hostStorage!=null&&e.hasOwnProperty("hostStorage")&&(A.hostStorage=a.enums===String?p.proto.BizAccountLinkInfo.HostStorageType[e.hostStorage]===void 0?e.hostStorage:p.proto.BizAccountLinkInfo.HostStorageType[e.hostStorage]:e.hostStorage,a.oneofs&&(A._hostStorage="hostStorage")),e.accountType!=null&&e.hasOwnProperty("accountType")&&(A.accountType=a.enums===String?p.proto.BizAccountLinkInfo.AccountType[e.accountType]===void 0?e.accountType:p.proto.BizAccountLinkInfo.AccountType[e.accountType]:e.accountType,a.oneofs&&(A._accountType="accountType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BizAccountLinkInfo"},t.AccountType=(function(){let i={},e=Object.create(i);return e[i[0]="ENTERPRISE"]=0,e})(),t.HostStorageType=(function(){let i={},e=Object.create(i);return e[i[0]="ON_PREMISE"]=0,e[i[1]="FACEBOOK"]=1,e})(),t})(),n.BizAccountPayload=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.vnameCert=p.proto.VerifiedNameCertificate.decode(e,e.uint32());break}case 2:{s.bizAcctLinkInfo=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BizAccountPayload)return e;var a=new p.proto.BizAccountPayload;if(e.vnameCert!=null){if(typeof e.vnameCert!="object")throw TypeError(".proto.BizAccountPayload.vnameCert: object expected");a.vnameCert=p.proto.VerifiedNameCertificate.fromObject(e.vnameCert)}return e.bizAcctLinkInfo!=null&&(typeof e.bizAcctLinkInfo=="string"?l.base64.decode(e.bizAcctLinkInfo,a.bizAcctLinkInfo=l.newBuffer(l.base64.length(e.bizAcctLinkInfo)),0):e.bizAcctLinkInfo.length>=0&&(a.bizAcctLinkInfo=e.bizAcctLinkInfo)),a},t.toObject=function(e,a){a||(a={});var A={};return e.vnameCert!=null&&e.hasOwnProperty("vnameCert")&&(A.vnameCert=p.proto.VerifiedNameCertificate.toObject(e.vnameCert,a),a.oneofs&&(A._vnameCert="vnameCert")),e.bizAcctLinkInfo!=null&&e.hasOwnProperty("bizAcctLinkInfo")&&(A.bizAcctLinkInfo=a.bytes===String?l.base64.encode(e.bizAcctLinkInfo,0,e.bizAcctLinkInfo.length):a.bytes===Array?Array.prototype.slice.call(e.bizAcctLinkInfo):e.bizAcctLinkInfo,a.oneofs&&(A._bizAcctLinkInfo="bizAcctLinkInfo")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BizAccountPayload"},t})(),n.BizIdentityInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.vlevel=e.int32();break}case 2:{s.vnameCert=p.proto.VerifiedNameCertificate.decode(e,e.uint32());break}case 3:{s.signed=e.bool();break}case 4:{s.revoked=e.bool();break}case 5:{s.hostStorage=e.int32();break}case 6:{s.actualActors=e.int32();break}case 7:{s.privacyModeTs=e.uint64();break}case 8:{s.featureControls=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BizIdentityInfo)return e;var a=new p.proto.BizIdentityInfo;switch(e.vlevel){default:if(typeof e.vlevel=="number"){a.vlevel=e.vlevel;break}break;case"UNKNOWN":case 0:a.vlevel=0;break;case"LOW":case 1:a.vlevel=1;break;case"HIGH":case 2:a.vlevel=2;break}if(e.vnameCert!=null){if(typeof e.vnameCert!="object")throw TypeError(".proto.BizIdentityInfo.vnameCert: object expected");a.vnameCert=p.proto.VerifiedNameCertificate.fromObject(e.vnameCert)}switch(e.signed!=null&&(a.signed=!!e.signed),e.revoked!=null&&(a.revoked=!!e.revoked),e.hostStorage){default:if(typeof e.hostStorage=="number"){a.hostStorage=e.hostStorage;break}break;case"ON_PREMISE":case 0:a.hostStorage=0;break;case"FACEBOOK":case 1:a.hostStorage=1;break}switch(e.actualActors){default:if(typeof e.actualActors=="number"){a.actualActors=e.actualActors;break}break;case"SELF":case 0:a.actualActors=0;break;case"BSP":case 1:a.actualActors=1;break}return e.privacyModeTs!=null&&(l.Long?(a.privacyModeTs=l.Long.fromValue(e.privacyModeTs)).unsigned=!0:typeof e.privacyModeTs=="string"?a.privacyModeTs=parseInt(e.privacyModeTs,10):typeof e.privacyModeTs=="number"?a.privacyModeTs=e.privacyModeTs:typeof e.privacyModeTs=="object"&&(a.privacyModeTs=new l.LongBits(e.privacyModeTs.low>>>0,e.privacyModeTs.high>>>0).toNumber(!0))),e.featureControls!=null&&(l.Long?(a.featureControls=l.Long.fromValue(e.featureControls)).unsigned=!0:typeof e.featureControls=="string"?a.featureControls=parseInt(e.featureControls,10):typeof e.featureControls=="number"?a.featureControls=e.featureControls:typeof e.featureControls=="object"&&(a.featureControls=new l.LongBits(e.featureControls.low>>>0,e.featureControls.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};return e.vlevel!=null&&e.hasOwnProperty("vlevel")&&(A.vlevel=a.enums===String?p.proto.BizIdentityInfo.VerifiedLevelValue[e.vlevel]===void 0?e.vlevel:p.proto.BizIdentityInfo.VerifiedLevelValue[e.vlevel]:e.vlevel,a.oneofs&&(A._vlevel="vlevel")),e.vnameCert!=null&&e.hasOwnProperty("vnameCert")&&(A.vnameCert=p.proto.VerifiedNameCertificate.toObject(e.vnameCert,a),a.oneofs&&(A._vnameCert="vnameCert")),e.signed!=null&&e.hasOwnProperty("signed")&&(A.signed=e.signed,a.oneofs&&(A._signed="signed")),e.revoked!=null&&e.hasOwnProperty("revoked")&&(A.revoked=e.revoked,a.oneofs&&(A._revoked="revoked")),e.hostStorage!=null&&e.hasOwnProperty("hostStorage")&&(A.hostStorage=a.enums===String?p.proto.BizIdentityInfo.HostStorageType[e.hostStorage]===void 0?e.hostStorage:p.proto.BizIdentityInfo.HostStorageType[e.hostStorage]:e.hostStorage,a.oneofs&&(A._hostStorage="hostStorage")),e.actualActors!=null&&e.hasOwnProperty("actualActors")&&(A.actualActors=a.enums===String?p.proto.BizIdentityInfo.ActualActorsType[e.actualActors]===void 0?e.actualActors:p.proto.BizIdentityInfo.ActualActorsType[e.actualActors]:e.actualActors,a.oneofs&&(A._actualActors="actualActors")),e.privacyModeTs!=null&&e.hasOwnProperty("privacyModeTs")&&(typeof e.privacyModeTs=="number"?A.privacyModeTs=a.longs===String?String(e.privacyModeTs):e.privacyModeTs:A.privacyModeTs=a.longs===String?se(e.privacyModeTs,!0):a.longs===Number?ge(e.privacyModeTs,!0):e.privacyModeTs,a.oneofs&&(A._privacyModeTs="privacyModeTs")),e.featureControls!=null&&e.hasOwnProperty("featureControls")&&(typeof e.featureControls=="number"?A.featureControls=a.longs===String?String(e.featureControls):e.featureControls:A.featureControls=a.longs===String?se(e.featureControls,!0):a.longs===Number?ge(e.featureControls,!0):e.featureControls,a.oneofs&&(A._featureControls="featureControls")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BizIdentityInfo"},t.ActualActorsType=(function(){let i={},e=Object.create(i);return e[i[0]="SELF"]=0,e[i[1]="BSP"]=1,e})(),t.HostStorageType=(function(){let i={},e=Object.create(i);return e[i[0]="ON_PREMISE"]=0,e[i[1]="FACEBOOK"]=1,e})(),t.VerifiedLevelValue=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="LOW"]=1,e[i[2]="HIGH"]=2,e})(),t})(),n.BotAgeCollectionMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.ageCollectionEligible=e.bool();break}case 2:{s.shouldTriggerAgeCollectionOnClient=e.bool();break}case 3:{s.ageCollectionType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotAgeCollectionMetadata)return e;var a=new p.proto.BotAgeCollectionMetadata;switch(e.ageCollectionEligible!=null&&(a.ageCollectionEligible=!!e.ageCollectionEligible),e.shouldTriggerAgeCollectionOnClient!=null&&(a.shouldTriggerAgeCollectionOnClient=!!e.shouldTriggerAgeCollectionOnClient),e.ageCollectionType){default:if(typeof e.ageCollectionType=="number"){a.ageCollectionType=e.ageCollectionType;break}break;case"O18_BINARY":case 0:a.ageCollectionType=0;break;case"WAFFLE":case 1:a.ageCollectionType=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.ageCollectionEligible!=null&&e.hasOwnProperty("ageCollectionEligible")&&(A.ageCollectionEligible=e.ageCollectionEligible,a.oneofs&&(A._ageCollectionEligible="ageCollectionEligible")),e.shouldTriggerAgeCollectionOnClient!=null&&e.hasOwnProperty("shouldTriggerAgeCollectionOnClient")&&(A.shouldTriggerAgeCollectionOnClient=e.shouldTriggerAgeCollectionOnClient,a.oneofs&&(A._shouldTriggerAgeCollectionOnClient="shouldTriggerAgeCollectionOnClient")),e.ageCollectionType!=null&&e.hasOwnProperty("ageCollectionType")&&(A.ageCollectionType=a.enums===String?p.proto.BotAgeCollectionMetadata.AgeCollectionType[e.ageCollectionType]===void 0?e.ageCollectionType:p.proto.BotAgeCollectionMetadata.AgeCollectionType[e.ageCollectionType]:e.ageCollectionType,a.oneofs&&(A._ageCollectionType="ageCollectionType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotAgeCollectionMetadata"},t.AgeCollectionType=(function(){let i={},e=Object.create(i);return e[i[0]="O18_BINARY"]=0,e[i[1]="WAFFLE"]=1,e})(),t})(),n.BotAvatarMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.sentiment=e.uint32();break}case 2:{s.behaviorGraph=e.string();break}case 3:{s.action=e.uint32();break}case 4:{s.intensity=e.uint32();break}case 5:{s.wordCount=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotAvatarMetadata)return e;var a=new p.proto.BotAvatarMetadata;return e.sentiment!=null&&(a.sentiment=e.sentiment>>>0),e.behaviorGraph!=null&&(a.behaviorGraph=String(e.behaviorGraph)),e.action!=null&&(a.action=e.action>>>0),e.intensity!=null&&(a.intensity=e.intensity>>>0),e.wordCount!=null&&(a.wordCount=e.wordCount>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.sentiment!=null&&e.hasOwnProperty("sentiment")&&(A.sentiment=e.sentiment,a.oneofs&&(A._sentiment="sentiment")),e.behaviorGraph!=null&&e.hasOwnProperty("behaviorGraph")&&(A.behaviorGraph=e.behaviorGraph,a.oneofs&&(A._behaviorGraph="behaviorGraph")),e.action!=null&&e.hasOwnProperty("action")&&(A.action=e.action,a.oneofs&&(A._action="action")),e.intensity!=null&&e.hasOwnProperty("intensity")&&(A.intensity=e.intensity,a.oneofs&&(A._intensity="intensity")),e.wordCount!=null&&e.hasOwnProperty("wordCount")&&(A.wordCount=e.wordCount,a.oneofs&&(A._wordCount="wordCount")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotAvatarMetadata"},t})(),n.BotCapabilityMetadata=(function(){function t(o){if(this.capabilities=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{if(r.capabilities&&r.capabilities.length||(r.capabilities=[]),(s&7)===2)for(var g=i.uint32()+i.pos;i.pos>>3){case 1:{s.messageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.kind=e.int32();break}case 3:{s.text=e.string();break}case 4:{s.kindNegative=e.uint64();break}case 5:{s.kindPositive=e.uint64();break}case 6:{s.kindReport=e.int32();break}case 7:{s.sideBySideSurveyMetadata=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotFeedbackMessage)return e;var a=new p.proto.BotFeedbackMessage;if(e.messageKey!=null){if(typeof e.messageKey!="object")throw TypeError(".proto.BotFeedbackMessage.messageKey: object expected");a.messageKey=p.proto.MessageKey.fromObject(e.messageKey)}switch(e.kind){default:if(typeof e.kind=="number"){a.kind=e.kind;break}break;case"BOT_FEEDBACK_POSITIVE":case 0:a.kind=0;break;case"BOT_FEEDBACK_NEGATIVE_GENERIC":case 1:a.kind=1;break;case"BOT_FEEDBACK_NEGATIVE_HELPFUL":case 2:a.kind=2;break;case"BOT_FEEDBACK_NEGATIVE_INTERESTING":case 3:a.kind=3;break;case"BOT_FEEDBACK_NEGATIVE_ACCURATE":case 4:a.kind=4;break;case"BOT_FEEDBACK_NEGATIVE_SAFE":case 5:a.kind=5;break;case"BOT_FEEDBACK_NEGATIVE_OTHER":case 6:a.kind=6;break;case"BOT_FEEDBACK_NEGATIVE_REFUSED":case 7:a.kind=7;break;case"BOT_FEEDBACK_NEGATIVE_NOT_VISUALLY_APPEALING":case 8:a.kind=8;break;case"BOT_FEEDBACK_NEGATIVE_NOT_RELEVANT_TO_TEXT":case 9:a.kind=9;break;case"BOT_FEEDBACK_NEGATIVE_PERSONALIZED":case 10:a.kind=10;break;case"BOT_FEEDBACK_NEGATIVE_CLARITY":case 11:a.kind=11;break;case"BOT_FEEDBACK_NEGATIVE_DOESNT_LOOK_LIKE_THE_PERSON":case 12:a.kind=12;break;case"BOT_FEEDBACK_NEGATIVE_HALLUCINATION_INTERNAL_ONLY":case 13:a.kind=13;break;case"BOT_FEEDBACK_NEGATIVE":case 14:a.kind=14;break}switch(e.text!=null&&(a.text=String(e.text)),e.kindNegative!=null&&(l.Long?(a.kindNegative=l.Long.fromValue(e.kindNegative)).unsigned=!0:typeof e.kindNegative=="string"?a.kindNegative=parseInt(e.kindNegative,10):typeof e.kindNegative=="number"?a.kindNegative=e.kindNegative:typeof e.kindNegative=="object"&&(a.kindNegative=new l.LongBits(e.kindNegative.low>>>0,e.kindNegative.high>>>0).toNumber(!0))),e.kindPositive!=null&&(l.Long?(a.kindPositive=l.Long.fromValue(e.kindPositive)).unsigned=!0:typeof e.kindPositive=="string"?a.kindPositive=parseInt(e.kindPositive,10):typeof e.kindPositive=="number"?a.kindPositive=e.kindPositive:typeof e.kindPositive=="object"&&(a.kindPositive=new l.LongBits(e.kindPositive.low>>>0,e.kindPositive.high>>>0).toNumber(!0))),e.kindReport){default:if(typeof e.kindReport=="number"){a.kindReport=e.kindReport;break}break;case"NONE":case 0:a.kindReport=0;break;case"GENERIC":case 1:a.kindReport=1;break}if(e.sideBySideSurveyMetadata!=null){if(typeof e.sideBySideSurveyMetadata!="object")throw TypeError(".proto.BotFeedbackMessage.sideBySideSurveyMetadata: object expected");a.sideBySideSurveyMetadata=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.fromObject(e.sideBySideSurveyMetadata)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.messageKey!=null&&e.hasOwnProperty("messageKey")&&(A.messageKey=p.proto.MessageKey.toObject(e.messageKey,a),a.oneofs&&(A._messageKey="messageKey")),e.kind!=null&&e.hasOwnProperty("kind")&&(A.kind=a.enums===String?p.proto.BotFeedbackMessage.BotFeedbackKind[e.kind]===void 0?e.kind:p.proto.BotFeedbackMessage.BotFeedbackKind[e.kind]:e.kind,a.oneofs&&(A._kind="kind")),e.text!=null&&e.hasOwnProperty("text")&&(A.text=e.text,a.oneofs&&(A._text="text")),e.kindNegative!=null&&e.hasOwnProperty("kindNegative")&&(typeof e.kindNegative=="number"?A.kindNegative=a.longs===String?String(e.kindNegative):e.kindNegative:A.kindNegative=a.longs===String?se(e.kindNegative,!0):a.longs===Number?ge(e.kindNegative,!0):e.kindNegative,a.oneofs&&(A._kindNegative="kindNegative")),e.kindPositive!=null&&e.hasOwnProperty("kindPositive")&&(typeof e.kindPositive=="number"?A.kindPositive=a.longs===String?String(e.kindPositive):e.kindPositive:A.kindPositive=a.longs===String?se(e.kindPositive,!0):a.longs===Number?ge(e.kindPositive,!0):e.kindPositive,a.oneofs&&(A._kindPositive="kindPositive")),e.kindReport!=null&&e.hasOwnProperty("kindReport")&&(A.kindReport=a.enums===String?p.proto.BotFeedbackMessage.ReportKind[e.kindReport]===void 0?e.kindReport:p.proto.BotFeedbackMessage.ReportKind[e.kindReport]:e.kindReport,a.oneofs&&(A._kindReport="kindReport")),e.sideBySideSurveyMetadata!=null&&e.hasOwnProperty("sideBySideSurveyMetadata")&&(A.sideBySideSurveyMetadata=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.toObject(e.sideBySideSurveyMetadata,a),a.oneofs&&(A._sideBySideSurveyMetadata="sideBySideSurveyMetadata")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotFeedbackMessage"},t.BotFeedbackKind=(function(){let i={},e=Object.create(i);return e[i[0]="BOT_FEEDBACK_POSITIVE"]=0,e[i[1]="BOT_FEEDBACK_NEGATIVE_GENERIC"]=1,e[i[2]="BOT_FEEDBACK_NEGATIVE_HELPFUL"]=2,e[i[3]="BOT_FEEDBACK_NEGATIVE_INTERESTING"]=3,e[i[4]="BOT_FEEDBACK_NEGATIVE_ACCURATE"]=4,e[i[5]="BOT_FEEDBACK_NEGATIVE_SAFE"]=5,e[i[6]="BOT_FEEDBACK_NEGATIVE_OTHER"]=6,e[i[7]="BOT_FEEDBACK_NEGATIVE_REFUSED"]=7,e[i[8]="BOT_FEEDBACK_NEGATIVE_NOT_VISUALLY_APPEALING"]=8,e[i[9]="BOT_FEEDBACK_NEGATIVE_NOT_RELEVANT_TO_TEXT"]=9,e[i[10]="BOT_FEEDBACK_NEGATIVE_PERSONALIZED"]=10,e[i[11]="BOT_FEEDBACK_NEGATIVE_CLARITY"]=11,e[i[12]="BOT_FEEDBACK_NEGATIVE_DOESNT_LOOK_LIKE_THE_PERSON"]=12,e[i[13]="BOT_FEEDBACK_NEGATIVE_HALLUCINATION_INTERNAL_ONLY"]=13,e[i[14]="BOT_FEEDBACK_NEGATIVE"]=14,e})(),t.BotFeedbackKindMultipleNegative=(function(){let i={},e=Object.create(i);return e[i[1]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_GENERIC"]=1,e[i[2]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_HELPFUL"]=2,e[i[4]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_INTERESTING"]=4,e[i[8]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_ACCURATE"]=8,e[i[16]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_SAFE"]=16,e[i[32]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_OTHER"]=32,e[i[64]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_REFUSED"]=64,e[i[128]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_NOT_VISUALLY_APPEALING"]=128,e[i[256]="BOT_FEEDBACK_MULTIPLE_NEGATIVE_NOT_RELEVANT_TO_TEXT"]=256,e})(),t.BotFeedbackKindMultiplePositive=(function(){let i={},e=Object.create(i);return e[i[1]="BOT_FEEDBACK_MULTIPLE_POSITIVE_GENERIC"]=1,e})(),t.ReportKind=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="GENERIC"]=1,e})(),t.SideBySideSurveyMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.selectedRequestId=A.string();break}case 2:{c.surveyId=A.uint32();break}case 3:{c.simonSessionFbid=A.string();break}case 4:{c.responseOtid=A.string();break}case 5:{c.responseTimestampMsString=A.string();break}case 6:{c.isSelectedResponsePrimary=A.bool();break}case 7:{c.messageIdToEdit=A.string();break}case 8:{c.analyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData.decode(A,A.uint32());break}case 9:{c.metaAiAnalyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata)return A;var r=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata;if(A.selectedRequestId!=null&&(r.selectedRequestId=String(A.selectedRequestId)),A.surveyId!=null&&(r.surveyId=A.surveyId>>>0),A.simonSessionFbid!=null&&(r.simonSessionFbid=String(A.simonSessionFbid)),A.responseOtid!=null&&(r.responseOtid=String(A.responseOtid)),A.responseTimestampMsString!=null&&(r.responseTimestampMsString=String(A.responseTimestampMsString)),A.isSelectedResponsePrimary!=null&&(r.isSelectedResponsePrimary=!!A.isSelectedResponsePrimary),A.messageIdToEdit!=null&&(r.messageIdToEdit=String(A.messageIdToEdit)),A.analyticsData!=null){if(typeof A.analyticsData!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.analyticsData: object expected");r.analyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData.fromObject(A.analyticsData)}if(A.metaAiAnalyticsData!=null){if(typeof A.metaAiAnalyticsData!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.metaAiAnalyticsData: object expected");r.metaAiAnalyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.fromObject(A.metaAiAnalyticsData)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.selectedRequestId!=null&&A.hasOwnProperty("selectedRequestId")&&(s.selectedRequestId=A.selectedRequestId,r.oneofs&&(s._selectedRequestId="selectedRequestId")),A.surveyId!=null&&A.hasOwnProperty("surveyId")&&(s.surveyId=A.surveyId,r.oneofs&&(s._surveyId="surveyId")),A.simonSessionFbid!=null&&A.hasOwnProperty("simonSessionFbid")&&(s.simonSessionFbid=A.simonSessionFbid,r.oneofs&&(s._simonSessionFbid="simonSessionFbid")),A.responseOtid!=null&&A.hasOwnProperty("responseOtid")&&(s.responseOtid=A.responseOtid,r.oneofs&&(s._responseOtid="responseOtid")),A.responseTimestampMsString!=null&&A.hasOwnProperty("responseTimestampMsString")&&(s.responseTimestampMsString=A.responseTimestampMsString,r.oneofs&&(s._responseTimestampMsString="responseTimestampMsString")),A.isSelectedResponsePrimary!=null&&A.hasOwnProperty("isSelectedResponsePrimary")&&(s.isSelectedResponsePrimary=A.isSelectedResponsePrimary,r.oneofs&&(s._isSelectedResponsePrimary="isSelectedResponsePrimary")),A.messageIdToEdit!=null&&A.hasOwnProperty("messageIdToEdit")&&(s.messageIdToEdit=A.messageIdToEdit,r.oneofs&&(s._messageIdToEdit="messageIdToEdit")),A.analyticsData!=null&&A.hasOwnProperty("analyticsData")&&(s.analyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData.toObject(A.analyticsData,r),r.oneofs&&(s._analyticsData="analyticsData")),A.metaAiAnalyticsData!=null&&A.hasOwnProperty("metaAiAnalyticsData")&&(s.metaAiAnalyticsData=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.toObject(A.metaAiAnalyticsData,r),r.oneofs&&(s._metaAiAnalyticsData="metaAiAnalyticsData")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata"},i.SideBySideSurveyAnalyticsData=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.tessaEvent=s.string();break}case 2:{d.tessaSessionFbid=s.string();break}case 3:{d.simonSessionFbid=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData)return s;var g=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData;return s.tessaEvent!=null&&(g.tessaEvent=String(s.tessaEvent)),s.tessaSessionFbid!=null&&(g.tessaSessionFbid=String(s.tessaSessionFbid)),s.simonSessionFbid!=null&&(g.simonSessionFbid=String(s.simonSessionFbid)),g},a.toObject=function(s,g){g||(g={});var c={};return s.tessaEvent!=null&&s.hasOwnProperty("tessaEvent")&&(c.tessaEvent=s.tessaEvent,g.oneofs&&(c._tessaEvent="tessaEvent")),s.tessaSessionFbid!=null&&s.hasOwnProperty("tessaSessionFbid")&&(c.tessaSessionFbid=s.tessaSessionFbid,g.oneofs&&(c._tessaSessionFbid="tessaSessionFbid")),s.simonSessionFbid!=null&&s.hasOwnProperty("simonSessionFbid")&&(c.simonSessionFbid=s.simonSessionFbid,g.oneofs&&(c._simonSessionFbid="simonSessionFbid")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SideBySideSurveyAnalyticsData"},a})(),i.SidebySideSurveyMetaAiAnalyticsData=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.surveyId=s.uint32();break}case 2:{d.primaryResponseId=s.string();break}case 3:{d.testArmName=s.string();break}case 4:{d.timestampMsString=s.string();break}case 5:{d.ctaImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData.decode(s,s.uint32());break}case 6:{d.ctaClickEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData.decode(s,s.uint32());break}case 7:{d.cardImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData.decode(s,s.uint32());break}case 8:{d.responseEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData.decode(s,s.uint32());break}case 9:{d.abandonEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData)return s;var g=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData;if(s.surveyId!=null&&(g.surveyId=s.surveyId>>>0),s.primaryResponseId!=null&&(g.primaryResponseId=String(s.primaryResponseId)),s.testArmName!=null&&(g.testArmName=String(s.testArmName)),s.timestampMsString!=null&&(g.timestampMsString=String(s.timestampMsString)),s.ctaImpressionEvent!=null){if(typeof s.ctaImpressionEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.ctaImpressionEvent: object expected");g.ctaImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData.fromObject(s.ctaImpressionEvent)}if(s.ctaClickEvent!=null){if(typeof s.ctaClickEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.ctaClickEvent: object expected");g.ctaClickEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData.fromObject(s.ctaClickEvent)}if(s.cardImpressionEvent!=null){if(typeof s.cardImpressionEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.cardImpressionEvent: object expected");g.cardImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData.fromObject(s.cardImpressionEvent)}if(s.responseEvent!=null){if(typeof s.responseEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.responseEvent: object expected");g.responseEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData.fromObject(s.responseEvent)}if(s.abandonEvent!=null){if(typeof s.abandonEvent!="object")throw TypeError(".proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.abandonEvent: object expected");g.abandonEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData.fromObject(s.abandonEvent)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.surveyId!=null&&s.hasOwnProperty("surveyId")&&(c.surveyId=s.surveyId,g.oneofs&&(c._surveyId="surveyId")),s.primaryResponseId!=null&&s.hasOwnProperty("primaryResponseId")&&(c.primaryResponseId=s.primaryResponseId,g.oneofs&&(c._primaryResponseId="primaryResponseId")),s.testArmName!=null&&s.hasOwnProperty("testArmName")&&(c.testArmName=s.testArmName,g.oneofs&&(c._testArmName="testArmName")),s.timestampMsString!=null&&s.hasOwnProperty("timestampMsString")&&(c.timestampMsString=s.timestampMsString,g.oneofs&&(c._timestampMsString="timestampMsString")),s.ctaImpressionEvent!=null&&s.hasOwnProperty("ctaImpressionEvent")&&(c.ctaImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData.toObject(s.ctaImpressionEvent,g),g.oneofs&&(c._ctaImpressionEvent="ctaImpressionEvent")),s.ctaClickEvent!=null&&s.hasOwnProperty("ctaClickEvent")&&(c.ctaClickEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData.toObject(s.ctaClickEvent,g),g.oneofs&&(c._ctaClickEvent="ctaClickEvent")),s.cardImpressionEvent!=null&&s.hasOwnProperty("cardImpressionEvent")&&(c.cardImpressionEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData.toObject(s.cardImpressionEvent,g),g.oneofs&&(c._cardImpressionEvent="cardImpressionEvent")),s.responseEvent!=null&&s.hasOwnProperty("responseEvent")&&(c.responseEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData.toObject(s.responseEvent,g),g.oneofs&&(c._responseEvent="responseEvent")),s.abandonEvent!=null&&s.hasOwnProperty("abandonEvent")&&(c.abandonEvent=p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData.toObject(s.abandonEvent,g),g.oneofs&&(c._abandonEvent="abandonEvent")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData"},a.SideBySideSurveyAbandonEventData=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.abandonDwellTimeMsString=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData)return c;var I=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData;return c.abandonDwellTimeMsString!=null&&(I.abandonDwellTimeMsString=String(c.abandonDwellTimeMsString)),I},r.toObject=function(c,I){I||(I={});var d={};return c.abandonDwellTimeMsString!=null&&c.hasOwnProperty("abandonDwellTimeMsString")&&(d.abandonDwellTimeMsString=c.abandonDwellTimeMsString,I.oneofs&&(d._abandonDwellTimeMsString="abandonDwellTimeMsString")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyAbandonEventData"},r})(),a.SideBySideSurveyCTAClickEventData=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.isSurveyExpired=c.bool();break}case 2:{f.clickDwellTimeMsString=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData)return c;var I=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData;return c.isSurveyExpired!=null&&(I.isSurveyExpired=!!c.isSurveyExpired),c.clickDwellTimeMsString!=null&&(I.clickDwellTimeMsString=String(c.clickDwellTimeMsString)),I},r.toObject=function(c,I){I||(I={});var d={};return c.isSurveyExpired!=null&&c.hasOwnProperty("isSurveyExpired")&&(d.isSurveyExpired=c.isSurveyExpired,I.oneofs&&(d._isSurveyExpired="isSurveyExpired")),c.clickDwellTimeMsString!=null&&c.hasOwnProperty("clickDwellTimeMsString")&&(d.clickDwellTimeMsString=c.clickDwellTimeMsString,I.oneofs&&(d._clickDwellTimeMsString="clickDwellTimeMsString")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAClickEventData"},r})(),a.SideBySideSurveyCTAImpressionEventData=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.isSurveyExpired=c.bool();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData)return c;var I=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData;return c.isSurveyExpired!=null&&(I.isSurveyExpired=!!c.isSurveyExpired),I},r.toObject=function(c,I){I||(I={});var d={};return c.isSurveyExpired!=null&&c.hasOwnProperty("isSurveyExpired")&&(d.isSurveyExpired=c.isSurveyExpired,I.oneofs&&(d._isSurveyExpired="isSurveyExpired")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCTAImpressionEventData"},r})(),a.SideBySideSurveyCardImpressionEventData=(function(){function r(s){if(s)for(var g=Object.keys(s),c=0;c>>3){default:g.skipType(f&7);break}}return B},r.fromObject=function(g){return g instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData?g:new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData},r.toObject=function(){return{}},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(g){return g===void 0&&(g="type.googleapis.com"),g+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyCardImpressionEventData"},r})(),a.SideBySideSurveyResponseEventData=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.responseDwellTimeMsString=c.string();break}case 2:{f.selectedResponseId=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData)return c;var I=new p.proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData;return c.responseDwellTimeMsString!=null&&(I.responseDwellTimeMsString=String(c.responseDwellTimeMsString)),c.selectedResponseId!=null&&(I.selectedResponseId=String(c.selectedResponseId)),I},r.toObject=function(c,I){I||(I={});var d={};return c.responseDwellTimeMsString!=null&&c.hasOwnProperty("responseDwellTimeMsString")&&(d.responseDwellTimeMsString=c.responseDwellTimeMsString,I.oneofs&&(d._responseDwellTimeMsString="responseDwellTimeMsString")),c.selectedResponseId!=null&&c.hasOwnProperty("selectedResponseId")&&(d.selectedResponseId=c.selectedResponseId,I.oneofs&&(d._selectedResponseId="selectedResponseId")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.BotFeedbackMessage.SideBySideSurveyMetadata.SidebySideSurveyMetaAiAnalyticsData.SideBySideSurveyResponseEventData"},r})(),a})(),i})(),t})(),n.BotImagineMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.imagineType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotImagineMetadata)return e;var a=new p.proto.BotImagineMetadata;switch(e.imagineType){default:if(typeof e.imagineType=="number"){a.imagineType=e.imagineType;break}break;case"UNKNOWN":case 0:a.imagineType=0;break;case"IMAGINE":case 1:a.imagineType=1;break;case"MEMU":case 2:a.imagineType=2;break;case"FLASH":case 3:a.imagineType=3;break;case"EDIT":case 4:a.imagineType=4;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.imagineType!=null&&e.hasOwnProperty("imagineType")&&(A.imagineType=a.enums===String?p.proto.BotImagineMetadata.ImagineType[e.imagineType]===void 0?e.imagineType:p.proto.BotImagineMetadata.ImagineType[e.imagineType]:e.imagineType,a.oneofs&&(A._imagineType="imagineType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotImagineMetadata"},t.ImagineType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="IMAGINE"]=1,e[i[2]="MEMU"]=2,e[i[3]="FLASH"]=3,e[i[4]="EDIT"]=4,e})(),t})(),n.BotLinkedAccount=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotLinkedAccount)return e;var a=new p.proto.BotLinkedAccount;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"BOT_LINKED_ACCOUNT_TYPE_1P":case 0:a.type=0;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.BotLinkedAccount.BotLinkedAccountType[e.type]===void 0?e.type:p.proto.BotLinkedAccount.BotLinkedAccountType[e.type]:e.type,a.oneofs&&(A._type="type")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotLinkedAccount"},t.BotLinkedAccountType=(function(){let i={},e=Object.create(i);return e[i[0]="BOT_LINKED_ACCOUNT_TYPE_1P"]=0,e})(),t})(),n.BotLinkedAccountsMetadata=(function(){function t(i){if(this.accounts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.accounts&&s.accounts.length||(s.accounts=[]),s.accounts.push(p.proto.BotLinkedAccount.decode(e,e.uint32()));break}case 2:{s.acAuthTokens=e.bytes();break}case 3:{s.acErrorCode=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotLinkedAccountsMetadata)return e;var a=new p.proto.BotLinkedAccountsMetadata;if(e.accounts){if(!Array.isArray(e.accounts))throw TypeError(".proto.BotLinkedAccountsMetadata.accounts: array expected");a.accounts=[];for(var A=0;A=0&&(a.acAuthTokens=e.acAuthTokens)),e.acErrorCode!=null&&(a.acErrorCode=e.acErrorCode|0),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.accounts=[]),e.accounts&&e.accounts.length){A.accounts=[];for(var r=0;r>>3){case 1:{s.fileSha256=e.string();break}case 2:{s.mediaKey=e.string();break}case 3:{s.fileEncSha256=e.string();break}case 4:{s.directPath=e.string();break}case 5:{s.mediaKeyTimestamp=e.int64();break}case 6:{s.mimetype=e.string();break}case 7:{s.orientationType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMediaMetadata)return e;var a=new p.proto.BotMediaMetadata;switch(e.fileSha256!=null&&(a.fileSha256=String(e.fileSha256)),e.mediaKey!=null&&(a.mediaKey=String(e.mediaKey)),e.fileEncSha256!=null&&(a.fileEncSha256=String(e.fileEncSha256)),e.directPath!=null&&(a.directPath=String(e.directPath)),e.mediaKeyTimestamp!=null&&(l.Long?(a.mediaKeyTimestamp=l.Long.fromValue(e.mediaKeyTimestamp)).unsigned=!1:typeof e.mediaKeyTimestamp=="string"?a.mediaKeyTimestamp=parseInt(e.mediaKeyTimestamp,10):typeof e.mediaKeyTimestamp=="number"?a.mediaKeyTimestamp=e.mediaKeyTimestamp:typeof e.mediaKeyTimestamp=="object"&&(a.mediaKeyTimestamp=new l.LongBits(e.mediaKeyTimestamp.low>>>0,e.mediaKeyTimestamp.high>>>0).toNumber())),e.mimetype!=null&&(a.mimetype=String(e.mimetype)),e.orientationType){default:if(typeof e.orientationType=="number"){a.orientationType=e.orientationType;break}break;case"CENTER":case 1:a.orientationType=1;break;case"LEFT":case 2:a.orientationType=2;break;case"RIGHT":case 3:a.orientationType=3;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.fileSha256!=null&&e.hasOwnProperty("fileSha256")&&(A.fileSha256=e.fileSha256,a.oneofs&&(A._fileSha256="fileSha256")),e.mediaKey!=null&&e.hasOwnProperty("mediaKey")&&(A.mediaKey=e.mediaKey,a.oneofs&&(A._mediaKey="mediaKey")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.mediaKeyTimestamp!=null&&e.hasOwnProperty("mediaKeyTimestamp")&&(typeof e.mediaKeyTimestamp=="number"?A.mediaKeyTimestamp=a.longs===String?String(e.mediaKeyTimestamp):e.mediaKeyTimestamp:A.mediaKeyTimestamp=a.longs===String?se(e.mediaKeyTimestamp):a.longs===Number?ge(e.mediaKeyTimestamp):e.mediaKeyTimestamp,a.oneofs&&(A._mediaKeyTimestamp="mediaKeyTimestamp")),e.mimetype!=null&&e.hasOwnProperty("mimetype")&&(A.mimetype=e.mimetype,a.oneofs&&(A._mimetype="mimetype")),e.orientationType!=null&&e.hasOwnProperty("orientationType")&&(A.orientationType=a.enums===String?p.proto.BotMediaMetadata.OrientationType[e.orientationType]===void 0?e.orientationType:p.proto.BotMediaMetadata.OrientationType[e.orientationType]:e.orientationType,a.oneofs&&(A._orientationType="orientationType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMediaMetadata"},t.OrientationType=(function(){let i={},e=Object.create(i);return e[i[1]="CENTER"]=1,e[i[2]="LEFT"]=2,e[i[3]="RIGHT"]=3,e})(),t})(),n.BotMemoryFact=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.fact=e.string();break}case 2:{s.factId=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMemoryFact)return e;var a=new p.proto.BotMemoryFact;return e.fact!=null&&(a.fact=String(e.fact)),e.factId!=null&&(a.factId=String(e.factId)),a},t.toObject=function(e,a){a||(a={});var A={};return e.fact!=null&&e.hasOwnProperty("fact")&&(A.fact=e.fact,a.oneofs&&(A._fact="fact")),e.factId!=null&&e.hasOwnProperty("factId")&&(A.factId=e.factId,a.oneofs&&(A._factId="factId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMemoryFact"},t})(),n.BotMemoryMetadata=(function(){function t(i){if(this.addedFacts=[],this.removedFacts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.addedFacts&&s.addedFacts.length||(s.addedFacts=[]),s.addedFacts.push(p.proto.BotMemoryFact.decode(e,e.uint32()));break}case 2:{s.removedFacts&&s.removedFacts.length||(s.removedFacts=[]),s.removedFacts.push(p.proto.BotMemoryFact.decode(e,e.uint32()));break}case 3:{s.disclaimer=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMemoryMetadata)return e;var a=new p.proto.BotMemoryMetadata;if(e.addedFacts){if(!Array.isArray(e.addedFacts))throw TypeError(".proto.BotMemoryMetadata.addedFacts: array expected");a.addedFacts=[];for(var A=0;A>>3){case 1:{r.faceImages&&r.faceImages.length||(r.faceImages=[]),r.faceImages.push(p.proto.BotMediaMetadata.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotMemuMetadata)return i;var e=new p.proto.BotMemuMetadata;if(i.faceImages){if(!Array.isArray(i.faceImages))throw TypeError(".proto.BotMemuMetadata.faceImages: array expected");e.faceImages=[];for(var a=0;a>>3){case 1:{s.type=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMessageOrigin)return e;var a=new p.proto.BotMessageOrigin;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"BOT_MESSAGE_ORIGIN_TYPE_AI_INITIATED":case 0:a.type=0;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.BotMessageOrigin.BotMessageOriginType[e.type]===void 0?e.type:p.proto.BotMessageOrigin.BotMessageOriginType[e.type]:e.type,a.oneofs&&(A._type="type")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMessageOrigin"},t.BotMessageOriginType=(function(){let i={},e=Object.create(i);return e[i[0]="BOT_MESSAGE_ORIGIN_TYPE_AI_INITIATED"]=0,e})(),t})(),n.BotMessageOriginMetadata=(function(){function t(o){if(this.origins=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.origins&&r.origins.length||(r.origins=[]),r.origins.push(p.proto.BotMessageOrigin.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotMessageOriginMetadata)return i;var e=new p.proto.BotMessageOriginMetadata;if(i.origins){if(!Array.isArray(i.origins))throw TypeError(".proto.BotMessageOriginMetadata.origins: array expected");e.origins=[];for(var a=0;a>>3){case 1:{s.botEntryPointOrigin=e.int32();break}case 2:{s.forwardScore=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMessageSharingInfo)return e;var a=new p.proto.BotMessageSharingInfo;switch(e.botEntryPointOrigin){default:if(typeof e.botEntryPointOrigin=="number"){a.botEntryPointOrigin=e.botEntryPointOrigin;break}break;case"UNDEFINED_ENTRY_POINT":case 0:a.botEntryPointOrigin=0;break;case"FAVICON":case 1:a.botEntryPointOrigin=1;break;case"CHATLIST":case 2:a.botEntryPointOrigin=2;break;case"AISEARCH_NULL_STATE_PAPER_PLANE":case 3:a.botEntryPointOrigin=3;break;case"AISEARCH_NULL_STATE_SUGGESTION":case 4:a.botEntryPointOrigin=4;break;case"AISEARCH_TYPE_AHEAD_SUGGESTION":case 5:a.botEntryPointOrigin=5;break;case"AISEARCH_TYPE_AHEAD_PAPER_PLANE":case 6:a.botEntryPointOrigin=6;break;case"AISEARCH_TYPE_AHEAD_RESULT_CHATLIST":case 7:a.botEntryPointOrigin=7;break;case"AISEARCH_TYPE_AHEAD_RESULT_MESSAGES":case 8:a.botEntryPointOrigin=8;break;case"AIVOICE_SEARCH_BAR":case 9:a.botEntryPointOrigin=9;break;case"AIVOICE_FAVICON":case 10:a.botEntryPointOrigin=10;break;case"AISTUDIO":case 11:a.botEntryPointOrigin=11;break;case"DEEPLINK":case 12:a.botEntryPointOrigin=12;break;case"NOTIFICATION":case 13:a.botEntryPointOrigin=13;break;case"PROFILE_MESSAGE_BUTTON":case 14:a.botEntryPointOrigin=14;break;case"FORWARD":case 15:a.botEntryPointOrigin=15;break;case"APP_SHORTCUT":case 16:a.botEntryPointOrigin=16;break;case"FF_FAMILY":case 17:a.botEntryPointOrigin=17;break;case"AI_TAB":case 18:a.botEntryPointOrigin=18;break;case"AI_HOME":case 19:a.botEntryPointOrigin=19;break;case"AI_DEEPLINK_IMMERSIVE":case 20:a.botEntryPointOrigin=20;break;case"AI_DEEPLINK":case 21:a.botEntryPointOrigin=21;break;case"META_AI_CHAT_SHORTCUT_AI_STUDIO":case 22:a.botEntryPointOrigin=22;break;case"UGC_CHAT_SHORTCUT_AI_STUDIO":case 23:a.botEntryPointOrigin=23;break;case"NEW_CHAT_AI_STUDIO":case 24:a.botEntryPointOrigin=24;break;case"AIVOICE_FAVICON_CALL_HISTORY":case 25:a.botEntryPointOrigin=25;break;case"ASK_META_AI_CONTEXT_MENU":case 26:a.botEntryPointOrigin=26;break;case"ASK_META_AI_CONTEXT_MENU_1ON1":case 27:a.botEntryPointOrigin=27;break;case"ASK_META_AI_CONTEXT_MENU_GROUP":case 28:a.botEntryPointOrigin=28;break;case"INVOKE_META_AI_1ON1":case 29:a.botEntryPointOrigin=29;break;case"INVOKE_META_AI_GROUP":case 30:a.botEntryPointOrigin=30;break;case"META_AI_FORWARD":case 31:a.botEntryPointOrigin=31;break;case"NEW_CHAT_AI_CONTACT":case 32:a.botEntryPointOrigin=32;break;case"MESSAGE_QUICK_ACTION_1_ON_1_CHAT":case 33:a.botEntryPointOrigin=33;break;case"MESSAGE_QUICK_ACTION_GROUP_CHAT":case 34:a.botEntryPointOrigin=34;break;case"ATTACHMENT_TRAY_1_ON_1_CHAT":case 35:a.botEntryPointOrigin=35;break;case"ATTACHMENT_TRAY_GROUP_CHAT":case 36:a.botEntryPointOrigin=36;break;case"ASK_META_AI_MEDIA_VIEWER_1ON1":case 37:a.botEntryPointOrigin=37;break;case"ASK_META_AI_MEDIA_VIEWER_GROUP":case 38:a.botEntryPointOrigin=38;break}return e.forwardScore!=null&&(a.forwardScore=e.forwardScore>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.botEntryPointOrigin!=null&&e.hasOwnProperty("botEntryPointOrigin")&&(A.botEntryPointOrigin=a.enums===String?p.proto.BotMetricsEntryPoint[e.botEntryPointOrigin]===void 0?e.botEntryPointOrigin:p.proto.BotMetricsEntryPoint[e.botEntryPointOrigin]:e.botEntryPointOrigin,a.oneofs&&(A._botEntryPointOrigin="botEntryPointOrigin")),e.forwardScore!=null&&e.hasOwnProperty("forwardScore")&&(A.forwardScore=e.forwardScore,a.oneofs&&(A._forwardScore="forwardScore")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMessageSharingInfo"},t})(),n.BotMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.avatarMetadata=p.proto.BotAvatarMetadata.decode(e,e.uint32());break}case 2:{s.personaId=e.string();break}case 3:{s.pluginMetadata=p.proto.BotPluginMetadata.decode(e,e.uint32());break}case 4:{s.suggestedPromptMetadata=p.proto.BotSuggestedPromptMetadata.decode(e,e.uint32());break}case 5:{s.invokerJid=e.string();break}case 6:{s.sessionMetadata=p.proto.BotSessionMetadata.decode(e,e.uint32());break}case 7:{s.memuMetadata=p.proto.BotMemuMetadata.decode(e,e.uint32());break}case 8:{s.timezone=e.string();break}case 9:{s.reminderMetadata=p.proto.BotReminderMetadata.decode(e,e.uint32());break}case 10:{s.modelMetadata=p.proto.BotModelMetadata.decode(e,e.uint32());break}case 11:{s.messageDisclaimerText=e.string();break}case 12:{s.progressIndicatorMetadata=p.proto.BotProgressIndicatorMetadata.decode(e,e.uint32());break}case 13:{s.capabilityMetadata=p.proto.BotCapabilityMetadata.decode(e,e.uint32());break}case 14:{s.imagineMetadata=p.proto.BotImagineMetadata.decode(e,e.uint32());break}case 15:{s.memoryMetadata=p.proto.BotMemoryMetadata.decode(e,e.uint32());break}case 16:{s.renderingMetadata=p.proto.BotRenderingMetadata.decode(e,e.uint32());break}case 17:{s.botMetricsMetadata=p.proto.BotMetricsMetadata.decode(e,e.uint32());break}case 18:{s.botLinkedAccountsMetadata=p.proto.BotLinkedAccountsMetadata.decode(e,e.uint32());break}case 19:{s.richResponseSourcesMetadata=p.proto.BotSourcesMetadata.decode(e,e.uint32());break}case 20:{s.aiConversationContext=e.bytes();break}case 21:{s.botPromotionMessageMetadata=p.proto.BotPromotionMessageMetadata.decode(e,e.uint32());break}case 22:{s.botModeSelectionMetadata=p.proto.BotModeSelectionMetadata.decode(e,e.uint32());break}case 23:{s.botQuotaMetadata=p.proto.BotQuotaMetadata.decode(e,e.uint32());break}case 24:{s.botAgeCollectionMetadata=p.proto.BotAgeCollectionMetadata.decode(e,e.uint32());break}case 25:{s.conversationStarterPromptId=e.string();break}case 26:{s.botResponseId=e.string();break}case 27:{s.verificationMetadata=p.proto.BotSignatureVerificationMetadata.decode(e,e.uint32());break}case 28:{s.unifiedResponseMutation=p.proto.BotUnifiedResponseMutation.decode(e,e.uint32());break}case 29:{s.botMessageOriginMetadata=p.proto.BotMessageOriginMetadata.decode(e,e.uint32());break}case 30:{s.inThreadSurveyMetadata=p.proto.InThreadSurveyMetadata.decode(e,e.uint32());break}case 31:{s.botThreadInfo=p.proto.AIThreadInfo.decode(e,e.uint32());break}case 32:{s.regenerateMetadata=p.proto.AIRegenerateMetadata.decode(e,e.uint32());break}case 33:{s.sessionTransparencyMetadata=p.proto.SessionTransparencyMetadata.decode(e,e.uint32());break}case 999:{s.internalMetadata=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMetadata)return e;var a=new p.proto.BotMetadata;if(e.avatarMetadata!=null){if(typeof e.avatarMetadata!="object")throw TypeError(".proto.BotMetadata.avatarMetadata: object expected");a.avatarMetadata=p.proto.BotAvatarMetadata.fromObject(e.avatarMetadata)}if(e.personaId!=null&&(a.personaId=String(e.personaId)),e.pluginMetadata!=null){if(typeof e.pluginMetadata!="object")throw TypeError(".proto.BotMetadata.pluginMetadata: object expected");a.pluginMetadata=p.proto.BotPluginMetadata.fromObject(e.pluginMetadata)}if(e.suggestedPromptMetadata!=null){if(typeof e.suggestedPromptMetadata!="object")throw TypeError(".proto.BotMetadata.suggestedPromptMetadata: object expected");a.suggestedPromptMetadata=p.proto.BotSuggestedPromptMetadata.fromObject(e.suggestedPromptMetadata)}if(e.invokerJid!=null&&(a.invokerJid=String(e.invokerJid)),e.sessionMetadata!=null){if(typeof e.sessionMetadata!="object")throw TypeError(".proto.BotMetadata.sessionMetadata: object expected");a.sessionMetadata=p.proto.BotSessionMetadata.fromObject(e.sessionMetadata)}if(e.memuMetadata!=null){if(typeof e.memuMetadata!="object")throw TypeError(".proto.BotMetadata.memuMetadata: object expected");a.memuMetadata=p.proto.BotMemuMetadata.fromObject(e.memuMetadata)}if(e.timezone!=null&&(a.timezone=String(e.timezone)),e.reminderMetadata!=null){if(typeof e.reminderMetadata!="object")throw TypeError(".proto.BotMetadata.reminderMetadata: object expected");a.reminderMetadata=p.proto.BotReminderMetadata.fromObject(e.reminderMetadata)}if(e.modelMetadata!=null){if(typeof e.modelMetadata!="object")throw TypeError(".proto.BotMetadata.modelMetadata: object expected");a.modelMetadata=p.proto.BotModelMetadata.fromObject(e.modelMetadata)}if(e.messageDisclaimerText!=null&&(a.messageDisclaimerText=String(e.messageDisclaimerText)),e.progressIndicatorMetadata!=null){if(typeof e.progressIndicatorMetadata!="object")throw TypeError(".proto.BotMetadata.progressIndicatorMetadata: object expected");a.progressIndicatorMetadata=p.proto.BotProgressIndicatorMetadata.fromObject(e.progressIndicatorMetadata)}if(e.capabilityMetadata!=null){if(typeof e.capabilityMetadata!="object")throw TypeError(".proto.BotMetadata.capabilityMetadata: object expected");a.capabilityMetadata=p.proto.BotCapabilityMetadata.fromObject(e.capabilityMetadata)}if(e.imagineMetadata!=null){if(typeof e.imagineMetadata!="object")throw TypeError(".proto.BotMetadata.imagineMetadata: object expected");a.imagineMetadata=p.proto.BotImagineMetadata.fromObject(e.imagineMetadata)}if(e.memoryMetadata!=null){if(typeof e.memoryMetadata!="object")throw TypeError(".proto.BotMetadata.memoryMetadata: object expected");a.memoryMetadata=p.proto.BotMemoryMetadata.fromObject(e.memoryMetadata)}if(e.renderingMetadata!=null){if(typeof e.renderingMetadata!="object")throw TypeError(".proto.BotMetadata.renderingMetadata: object expected");a.renderingMetadata=p.proto.BotRenderingMetadata.fromObject(e.renderingMetadata)}if(e.botMetricsMetadata!=null){if(typeof e.botMetricsMetadata!="object")throw TypeError(".proto.BotMetadata.botMetricsMetadata: object expected");a.botMetricsMetadata=p.proto.BotMetricsMetadata.fromObject(e.botMetricsMetadata)}if(e.botLinkedAccountsMetadata!=null){if(typeof e.botLinkedAccountsMetadata!="object")throw TypeError(".proto.BotMetadata.botLinkedAccountsMetadata: object expected");a.botLinkedAccountsMetadata=p.proto.BotLinkedAccountsMetadata.fromObject(e.botLinkedAccountsMetadata)}if(e.richResponseSourcesMetadata!=null){if(typeof e.richResponseSourcesMetadata!="object")throw TypeError(".proto.BotMetadata.richResponseSourcesMetadata: object expected");a.richResponseSourcesMetadata=p.proto.BotSourcesMetadata.fromObject(e.richResponseSourcesMetadata)}if(e.aiConversationContext!=null&&(typeof e.aiConversationContext=="string"?l.base64.decode(e.aiConversationContext,a.aiConversationContext=l.newBuffer(l.base64.length(e.aiConversationContext)),0):e.aiConversationContext.length>=0&&(a.aiConversationContext=e.aiConversationContext)),e.botPromotionMessageMetadata!=null){if(typeof e.botPromotionMessageMetadata!="object")throw TypeError(".proto.BotMetadata.botPromotionMessageMetadata: object expected");a.botPromotionMessageMetadata=p.proto.BotPromotionMessageMetadata.fromObject(e.botPromotionMessageMetadata)}if(e.botModeSelectionMetadata!=null){if(typeof e.botModeSelectionMetadata!="object")throw TypeError(".proto.BotMetadata.botModeSelectionMetadata: object expected");a.botModeSelectionMetadata=p.proto.BotModeSelectionMetadata.fromObject(e.botModeSelectionMetadata)}if(e.botQuotaMetadata!=null){if(typeof e.botQuotaMetadata!="object")throw TypeError(".proto.BotMetadata.botQuotaMetadata: object expected");a.botQuotaMetadata=p.proto.BotQuotaMetadata.fromObject(e.botQuotaMetadata)}if(e.botAgeCollectionMetadata!=null){if(typeof e.botAgeCollectionMetadata!="object")throw TypeError(".proto.BotMetadata.botAgeCollectionMetadata: object expected");a.botAgeCollectionMetadata=p.proto.BotAgeCollectionMetadata.fromObject(e.botAgeCollectionMetadata)}if(e.conversationStarterPromptId!=null&&(a.conversationStarterPromptId=String(e.conversationStarterPromptId)),e.botResponseId!=null&&(a.botResponseId=String(e.botResponseId)),e.verificationMetadata!=null){if(typeof e.verificationMetadata!="object")throw TypeError(".proto.BotMetadata.verificationMetadata: object expected");a.verificationMetadata=p.proto.BotSignatureVerificationMetadata.fromObject(e.verificationMetadata)}if(e.unifiedResponseMutation!=null){if(typeof e.unifiedResponseMutation!="object")throw TypeError(".proto.BotMetadata.unifiedResponseMutation: object expected");a.unifiedResponseMutation=p.proto.BotUnifiedResponseMutation.fromObject(e.unifiedResponseMutation)}if(e.botMessageOriginMetadata!=null){if(typeof e.botMessageOriginMetadata!="object")throw TypeError(".proto.BotMetadata.botMessageOriginMetadata: object expected");a.botMessageOriginMetadata=p.proto.BotMessageOriginMetadata.fromObject(e.botMessageOriginMetadata)}if(e.inThreadSurveyMetadata!=null){if(typeof e.inThreadSurveyMetadata!="object")throw TypeError(".proto.BotMetadata.inThreadSurveyMetadata: object expected");a.inThreadSurveyMetadata=p.proto.InThreadSurveyMetadata.fromObject(e.inThreadSurveyMetadata)}if(e.botThreadInfo!=null){if(typeof e.botThreadInfo!="object")throw TypeError(".proto.BotMetadata.botThreadInfo: object expected");a.botThreadInfo=p.proto.AIThreadInfo.fromObject(e.botThreadInfo)}if(e.regenerateMetadata!=null){if(typeof e.regenerateMetadata!="object")throw TypeError(".proto.BotMetadata.regenerateMetadata: object expected");a.regenerateMetadata=p.proto.AIRegenerateMetadata.fromObject(e.regenerateMetadata)}if(e.sessionTransparencyMetadata!=null){if(typeof e.sessionTransparencyMetadata!="object")throw TypeError(".proto.BotMetadata.sessionTransparencyMetadata: object expected");a.sessionTransparencyMetadata=p.proto.SessionTransparencyMetadata.fromObject(e.sessionTransparencyMetadata)}return e.internalMetadata!=null&&(typeof e.internalMetadata=="string"?l.base64.decode(e.internalMetadata,a.internalMetadata=l.newBuffer(l.base64.length(e.internalMetadata)),0):e.internalMetadata.length>=0&&(a.internalMetadata=e.internalMetadata)),a},t.toObject=function(e,a){a||(a={});var A={};return e.avatarMetadata!=null&&e.hasOwnProperty("avatarMetadata")&&(A.avatarMetadata=p.proto.BotAvatarMetadata.toObject(e.avatarMetadata,a),a.oneofs&&(A._avatarMetadata="avatarMetadata")),e.personaId!=null&&e.hasOwnProperty("personaId")&&(A.personaId=e.personaId,a.oneofs&&(A._personaId="personaId")),e.pluginMetadata!=null&&e.hasOwnProperty("pluginMetadata")&&(A.pluginMetadata=p.proto.BotPluginMetadata.toObject(e.pluginMetadata,a),a.oneofs&&(A._pluginMetadata="pluginMetadata")),e.suggestedPromptMetadata!=null&&e.hasOwnProperty("suggestedPromptMetadata")&&(A.suggestedPromptMetadata=p.proto.BotSuggestedPromptMetadata.toObject(e.suggestedPromptMetadata,a),a.oneofs&&(A._suggestedPromptMetadata="suggestedPromptMetadata")),e.invokerJid!=null&&e.hasOwnProperty("invokerJid")&&(A.invokerJid=e.invokerJid,a.oneofs&&(A._invokerJid="invokerJid")),e.sessionMetadata!=null&&e.hasOwnProperty("sessionMetadata")&&(A.sessionMetadata=p.proto.BotSessionMetadata.toObject(e.sessionMetadata,a),a.oneofs&&(A._sessionMetadata="sessionMetadata")),e.memuMetadata!=null&&e.hasOwnProperty("memuMetadata")&&(A.memuMetadata=p.proto.BotMemuMetadata.toObject(e.memuMetadata,a),a.oneofs&&(A._memuMetadata="memuMetadata")),e.timezone!=null&&e.hasOwnProperty("timezone")&&(A.timezone=e.timezone,a.oneofs&&(A._timezone="timezone")),e.reminderMetadata!=null&&e.hasOwnProperty("reminderMetadata")&&(A.reminderMetadata=p.proto.BotReminderMetadata.toObject(e.reminderMetadata,a),a.oneofs&&(A._reminderMetadata="reminderMetadata")),e.modelMetadata!=null&&e.hasOwnProperty("modelMetadata")&&(A.modelMetadata=p.proto.BotModelMetadata.toObject(e.modelMetadata,a),a.oneofs&&(A._modelMetadata="modelMetadata")),e.messageDisclaimerText!=null&&e.hasOwnProperty("messageDisclaimerText")&&(A.messageDisclaimerText=e.messageDisclaimerText,a.oneofs&&(A._messageDisclaimerText="messageDisclaimerText")),e.progressIndicatorMetadata!=null&&e.hasOwnProperty("progressIndicatorMetadata")&&(A.progressIndicatorMetadata=p.proto.BotProgressIndicatorMetadata.toObject(e.progressIndicatorMetadata,a),a.oneofs&&(A._progressIndicatorMetadata="progressIndicatorMetadata")),e.capabilityMetadata!=null&&e.hasOwnProperty("capabilityMetadata")&&(A.capabilityMetadata=p.proto.BotCapabilityMetadata.toObject(e.capabilityMetadata,a),a.oneofs&&(A._capabilityMetadata="capabilityMetadata")),e.imagineMetadata!=null&&e.hasOwnProperty("imagineMetadata")&&(A.imagineMetadata=p.proto.BotImagineMetadata.toObject(e.imagineMetadata,a),a.oneofs&&(A._imagineMetadata="imagineMetadata")),e.memoryMetadata!=null&&e.hasOwnProperty("memoryMetadata")&&(A.memoryMetadata=p.proto.BotMemoryMetadata.toObject(e.memoryMetadata,a),a.oneofs&&(A._memoryMetadata="memoryMetadata")),e.renderingMetadata!=null&&e.hasOwnProperty("renderingMetadata")&&(A.renderingMetadata=p.proto.BotRenderingMetadata.toObject(e.renderingMetadata,a),a.oneofs&&(A._renderingMetadata="renderingMetadata")),e.botMetricsMetadata!=null&&e.hasOwnProperty("botMetricsMetadata")&&(A.botMetricsMetadata=p.proto.BotMetricsMetadata.toObject(e.botMetricsMetadata,a),a.oneofs&&(A._botMetricsMetadata="botMetricsMetadata")),e.botLinkedAccountsMetadata!=null&&e.hasOwnProperty("botLinkedAccountsMetadata")&&(A.botLinkedAccountsMetadata=p.proto.BotLinkedAccountsMetadata.toObject(e.botLinkedAccountsMetadata,a),a.oneofs&&(A._botLinkedAccountsMetadata="botLinkedAccountsMetadata")),e.richResponseSourcesMetadata!=null&&e.hasOwnProperty("richResponseSourcesMetadata")&&(A.richResponseSourcesMetadata=p.proto.BotSourcesMetadata.toObject(e.richResponseSourcesMetadata,a),a.oneofs&&(A._richResponseSourcesMetadata="richResponseSourcesMetadata")),e.aiConversationContext!=null&&e.hasOwnProperty("aiConversationContext")&&(A.aiConversationContext=a.bytes===String?l.base64.encode(e.aiConversationContext,0,e.aiConversationContext.length):a.bytes===Array?Array.prototype.slice.call(e.aiConversationContext):e.aiConversationContext,a.oneofs&&(A._aiConversationContext="aiConversationContext")),e.botPromotionMessageMetadata!=null&&e.hasOwnProperty("botPromotionMessageMetadata")&&(A.botPromotionMessageMetadata=p.proto.BotPromotionMessageMetadata.toObject(e.botPromotionMessageMetadata,a),a.oneofs&&(A._botPromotionMessageMetadata="botPromotionMessageMetadata")),e.botModeSelectionMetadata!=null&&e.hasOwnProperty("botModeSelectionMetadata")&&(A.botModeSelectionMetadata=p.proto.BotModeSelectionMetadata.toObject(e.botModeSelectionMetadata,a),a.oneofs&&(A._botModeSelectionMetadata="botModeSelectionMetadata")),e.botQuotaMetadata!=null&&e.hasOwnProperty("botQuotaMetadata")&&(A.botQuotaMetadata=p.proto.BotQuotaMetadata.toObject(e.botQuotaMetadata,a),a.oneofs&&(A._botQuotaMetadata="botQuotaMetadata")),e.botAgeCollectionMetadata!=null&&e.hasOwnProperty("botAgeCollectionMetadata")&&(A.botAgeCollectionMetadata=p.proto.BotAgeCollectionMetadata.toObject(e.botAgeCollectionMetadata,a),a.oneofs&&(A._botAgeCollectionMetadata="botAgeCollectionMetadata")),e.conversationStarterPromptId!=null&&e.hasOwnProperty("conversationStarterPromptId")&&(A.conversationStarterPromptId=e.conversationStarterPromptId,a.oneofs&&(A._conversationStarterPromptId="conversationStarterPromptId")),e.botResponseId!=null&&e.hasOwnProperty("botResponseId")&&(A.botResponseId=e.botResponseId,a.oneofs&&(A._botResponseId="botResponseId")),e.verificationMetadata!=null&&e.hasOwnProperty("verificationMetadata")&&(A.verificationMetadata=p.proto.BotSignatureVerificationMetadata.toObject(e.verificationMetadata,a),a.oneofs&&(A._verificationMetadata="verificationMetadata")),e.unifiedResponseMutation!=null&&e.hasOwnProperty("unifiedResponseMutation")&&(A.unifiedResponseMutation=p.proto.BotUnifiedResponseMutation.toObject(e.unifiedResponseMutation,a),a.oneofs&&(A._unifiedResponseMutation="unifiedResponseMutation")),e.botMessageOriginMetadata!=null&&e.hasOwnProperty("botMessageOriginMetadata")&&(A.botMessageOriginMetadata=p.proto.BotMessageOriginMetadata.toObject(e.botMessageOriginMetadata,a),a.oneofs&&(A._botMessageOriginMetadata="botMessageOriginMetadata")),e.inThreadSurveyMetadata!=null&&e.hasOwnProperty("inThreadSurveyMetadata")&&(A.inThreadSurveyMetadata=p.proto.InThreadSurveyMetadata.toObject(e.inThreadSurveyMetadata,a),a.oneofs&&(A._inThreadSurveyMetadata="inThreadSurveyMetadata")),e.botThreadInfo!=null&&e.hasOwnProperty("botThreadInfo")&&(A.botThreadInfo=p.proto.AIThreadInfo.toObject(e.botThreadInfo,a),a.oneofs&&(A._botThreadInfo="botThreadInfo")),e.regenerateMetadata!=null&&e.hasOwnProperty("regenerateMetadata")&&(A.regenerateMetadata=p.proto.AIRegenerateMetadata.toObject(e.regenerateMetadata,a),a.oneofs&&(A._regenerateMetadata="regenerateMetadata")),e.sessionTransparencyMetadata!=null&&e.hasOwnProperty("sessionTransparencyMetadata")&&(A.sessionTransparencyMetadata=p.proto.SessionTransparencyMetadata.toObject(e.sessionTransparencyMetadata,a),a.oneofs&&(A._sessionTransparencyMetadata="sessionTransparencyMetadata")),e.internalMetadata!=null&&e.hasOwnProperty("internalMetadata")&&(A.internalMetadata=a.bytes===String?l.base64.encode(e.internalMetadata,0,e.internalMetadata.length):a.bytes===Array?Array.prototype.slice.call(e.internalMetadata):e.internalMetadata,a.oneofs&&(A._internalMetadata="internalMetadata")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMetadata"},t})(),n.BotMetricsEntryPoint=(function(){let t={},o=Object.create(t);return o[t[0]="UNDEFINED_ENTRY_POINT"]=0,o[t[1]="FAVICON"]=1,o[t[2]="CHATLIST"]=2,o[t[3]="AISEARCH_NULL_STATE_PAPER_PLANE"]=3,o[t[4]="AISEARCH_NULL_STATE_SUGGESTION"]=4,o[t[5]="AISEARCH_TYPE_AHEAD_SUGGESTION"]=5,o[t[6]="AISEARCH_TYPE_AHEAD_PAPER_PLANE"]=6,o[t[7]="AISEARCH_TYPE_AHEAD_RESULT_CHATLIST"]=7,o[t[8]="AISEARCH_TYPE_AHEAD_RESULT_MESSAGES"]=8,o[t[9]="AIVOICE_SEARCH_BAR"]=9,o[t[10]="AIVOICE_FAVICON"]=10,o[t[11]="AISTUDIO"]=11,o[t[12]="DEEPLINK"]=12,o[t[13]="NOTIFICATION"]=13,o[t[14]="PROFILE_MESSAGE_BUTTON"]=14,o[t[15]="FORWARD"]=15,o[t[16]="APP_SHORTCUT"]=16,o[t[17]="FF_FAMILY"]=17,o[t[18]="AI_TAB"]=18,o[t[19]="AI_HOME"]=19,o[t[20]="AI_DEEPLINK_IMMERSIVE"]=20,o[t[21]="AI_DEEPLINK"]=21,o[t[22]="META_AI_CHAT_SHORTCUT_AI_STUDIO"]=22,o[t[23]="UGC_CHAT_SHORTCUT_AI_STUDIO"]=23,o[t[24]="NEW_CHAT_AI_STUDIO"]=24,o[t[25]="AIVOICE_FAVICON_CALL_HISTORY"]=25,o[t[26]="ASK_META_AI_CONTEXT_MENU"]=26,o[t[27]="ASK_META_AI_CONTEXT_MENU_1ON1"]=27,o[t[28]="ASK_META_AI_CONTEXT_MENU_GROUP"]=28,o[t[29]="INVOKE_META_AI_1ON1"]=29,o[t[30]="INVOKE_META_AI_GROUP"]=30,o[t[31]="META_AI_FORWARD"]=31,o[t[32]="NEW_CHAT_AI_CONTACT"]=32,o[t[33]="MESSAGE_QUICK_ACTION_1_ON_1_CHAT"]=33,o[t[34]="MESSAGE_QUICK_ACTION_GROUP_CHAT"]=34,o[t[35]="ATTACHMENT_TRAY_1_ON_1_CHAT"]=35,o[t[36]="ATTACHMENT_TRAY_GROUP_CHAT"]=36,o[t[37]="ASK_META_AI_MEDIA_VIEWER_1ON1"]=37,o[t[38]="ASK_META_AI_MEDIA_VIEWER_GROUP"]=38,o})(),n.BotMetricsMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.destinationId=e.string();break}case 2:{s.destinationEntryPoint=e.int32();break}case 3:{s.threadOrigin=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotMetricsMetadata)return e;var a=new p.proto.BotMetricsMetadata;switch(e.destinationId!=null&&(a.destinationId=String(e.destinationId)),e.destinationEntryPoint){default:if(typeof e.destinationEntryPoint=="number"){a.destinationEntryPoint=e.destinationEntryPoint;break}break;case"UNDEFINED_ENTRY_POINT":case 0:a.destinationEntryPoint=0;break;case"FAVICON":case 1:a.destinationEntryPoint=1;break;case"CHATLIST":case 2:a.destinationEntryPoint=2;break;case"AISEARCH_NULL_STATE_PAPER_PLANE":case 3:a.destinationEntryPoint=3;break;case"AISEARCH_NULL_STATE_SUGGESTION":case 4:a.destinationEntryPoint=4;break;case"AISEARCH_TYPE_AHEAD_SUGGESTION":case 5:a.destinationEntryPoint=5;break;case"AISEARCH_TYPE_AHEAD_PAPER_PLANE":case 6:a.destinationEntryPoint=6;break;case"AISEARCH_TYPE_AHEAD_RESULT_CHATLIST":case 7:a.destinationEntryPoint=7;break;case"AISEARCH_TYPE_AHEAD_RESULT_MESSAGES":case 8:a.destinationEntryPoint=8;break;case"AIVOICE_SEARCH_BAR":case 9:a.destinationEntryPoint=9;break;case"AIVOICE_FAVICON":case 10:a.destinationEntryPoint=10;break;case"AISTUDIO":case 11:a.destinationEntryPoint=11;break;case"DEEPLINK":case 12:a.destinationEntryPoint=12;break;case"NOTIFICATION":case 13:a.destinationEntryPoint=13;break;case"PROFILE_MESSAGE_BUTTON":case 14:a.destinationEntryPoint=14;break;case"FORWARD":case 15:a.destinationEntryPoint=15;break;case"APP_SHORTCUT":case 16:a.destinationEntryPoint=16;break;case"FF_FAMILY":case 17:a.destinationEntryPoint=17;break;case"AI_TAB":case 18:a.destinationEntryPoint=18;break;case"AI_HOME":case 19:a.destinationEntryPoint=19;break;case"AI_DEEPLINK_IMMERSIVE":case 20:a.destinationEntryPoint=20;break;case"AI_DEEPLINK":case 21:a.destinationEntryPoint=21;break;case"META_AI_CHAT_SHORTCUT_AI_STUDIO":case 22:a.destinationEntryPoint=22;break;case"UGC_CHAT_SHORTCUT_AI_STUDIO":case 23:a.destinationEntryPoint=23;break;case"NEW_CHAT_AI_STUDIO":case 24:a.destinationEntryPoint=24;break;case"AIVOICE_FAVICON_CALL_HISTORY":case 25:a.destinationEntryPoint=25;break;case"ASK_META_AI_CONTEXT_MENU":case 26:a.destinationEntryPoint=26;break;case"ASK_META_AI_CONTEXT_MENU_1ON1":case 27:a.destinationEntryPoint=27;break;case"ASK_META_AI_CONTEXT_MENU_GROUP":case 28:a.destinationEntryPoint=28;break;case"INVOKE_META_AI_1ON1":case 29:a.destinationEntryPoint=29;break;case"INVOKE_META_AI_GROUP":case 30:a.destinationEntryPoint=30;break;case"META_AI_FORWARD":case 31:a.destinationEntryPoint=31;break;case"NEW_CHAT_AI_CONTACT":case 32:a.destinationEntryPoint=32;break;case"MESSAGE_QUICK_ACTION_1_ON_1_CHAT":case 33:a.destinationEntryPoint=33;break;case"MESSAGE_QUICK_ACTION_GROUP_CHAT":case 34:a.destinationEntryPoint=34;break;case"ATTACHMENT_TRAY_1_ON_1_CHAT":case 35:a.destinationEntryPoint=35;break;case"ATTACHMENT_TRAY_GROUP_CHAT":case 36:a.destinationEntryPoint=36;break;case"ASK_META_AI_MEDIA_VIEWER_1ON1":case 37:a.destinationEntryPoint=37;break;case"ASK_META_AI_MEDIA_VIEWER_GROUP":case 38:a.destinationEntryPoint=38;break}switch(e.threadOrigin){default:if(typeof e.threadOrigin=="number"){a.threadOrigin=e.threadOrigin;break}break;case"AI_TAB_THREAD":case 1:a.threadOrigin=1;break;case"AI_HOME_THREAD":case 2:a.threadOrigin=2;break;case"AI_DEEPLINK_IMMERSIVE_THREAD":case 3:a.threadOrigin=3;break;case"AI_DEEPLINK_THREAD":case 4:a.threadOrigin=4;break;case"ASK_META_AI_CONTEXT_MENU_THREAD":case 5:a.threadOrigin=5;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.destinationId!=null&&e.hasOwnProperty("destinationId")&&(A.destinationId=e.destinationId,a.oneofs&&(A._destinationId="destinationId")),e.destinationEntryPoint!=null&&e.hasOwnProperty("destinationEntryPoint")&&(A.destinationEntryPoint=a.enums===String?p.proto.BotMetricsEntryPoint[e.destinationEntryPoint]===void 0?e.destinationEntryPoint:p.proto.BotMetricsEntryPoint[e.destinationEntryPoint]:e.destinationEntryPoint,a.oneofs&&(A._destinationEntryPoint="destinationEntryPoint")),e.threadOrigin!=null&&e.hasOwnProperty("threadOrigin")&&(A.threadOrigin=a.enums===String?p.proto.BotMetricsThreadEntryPoint[e.threadOrigin]===void 0?e.threadOrigin:p.proto.BotMetricsThreadEntryPoint[e.threadOrigin]:e.threadOrigin,a.oneofs&&(A._threadOrigin="threadOrigin")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotMetricsMetadata"},t})(),n.BotMetricsThreadEntryPoint=(function(){let t={},o=Object.create(t);return o[t[1]="AI_TAB_THREAD"]=1,o[t[2]="AI_HOME_THREAD"]=2,o[t[3]="AI_DEEPLINK_IMMERSIVE_THREAD"]=3,o[t[4]="AI_DEEPLINK_THREAD"]=4,o[t[5]="ASK_META_AI_CONTEXT_MENU_THREAD"]=5,o})(),n.BotModeSelectionMetadata=(function(){function t(o){if(this.mode=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{if(r.mode&&r.mode.length||(r.mode=[]),(s&7)===2)for(var g=i.uint32()+i.pos;i.pos>>3){case 1:{s.modelType=e.int32();break}case 2:{s.premiumModelStatus=e.int32();break}case 3:{s.modelNameOverride=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotModelMetadata)return e;var a=new p.proto.BotModelMetadata;switch(e.modelType){default:if(typeof e.modelType=="number"){a.modelType=e.modelType;break}break;case"UNKNOWN_TYPE":case 0:a.modelType=0;break;case"LLAMA_PROD":case 1:a.modelType=1;break;case"LLAMA_PROD_PREMIUM":case 2:a.modelType=2;break}switch(e.premiumModelStatus){default:if(typeof e.premiumModelStatus=="number"){a.premiumModelStatus=e.premiumModelStatus;break}break;case"UNKNOWN_STATUS":case 0:a.premiumModelStatus=0;break;case"AVAILABLE":case 1:a.premiumModelStatus=1;break;case"QUOTA_EXCEED_LIMIT":case 2:a.premiumModelStatus=2;break}return e.modelNameOverride!=null&&(a.modelNameOverride=String(e.modelNameOverride)),a},t.toObject=function(e,a){a||(a={});var A={};return e.modelType!=null&&e.hasOwnProperty("modelType")&&(A.modelType=a.enums===String?p.proto.BotModelMetadata.ModelType[e.modelType]===void 0?e.modelType:p.proto.BotModelMetadata.ModelType[e.modelType]:e.modelType,a.oneofs&&(A._modelType="modelType")),e.premiumModelStatus!=null&&e.hasOwnProperty("premiumModelStatus")&&(A.premiumModelStatus=a.enums===String?p.proto.BotModelMetadata.PremiumModelStatus[e.premiumModelStatus]===void 0?e.premiumModelStatus:p.proto.BotModelMetadata.PremiumModelStatus[e.premiumModelStatus]:e.premiumModelStatus,a.oneofs&&(A._premiumModelStatus="premiumModelStatus")),e.modelNameOverride!=null&&e.hasOwnProperty("modelNameOverride")&&(A.modelNameOverride=e.modelNameOverride,a.oneofs&&(A._modelNameOverride="modelNameOverride")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotModelMetadata"},t.ModelType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_TYPE"]=0,e[i[1]="LLAMA_PROD"]=1,e[i[2]="LLAMA_PROD_PREMIUM"]=2,e})(),t.PremiumModelStatus=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_STATUS"]=0,e[i[1]="AVAILABLE"]=1,e[i[2]="QUOTA_EXCEED_LIMIT"]=2,e})(),t})(),n.BotPluginMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.provider=e.int32();break}case 2:{s.pluginType=e.int32();break}case 3:{s.thumbnailCdnUrl=e.string();break}case 4:{s.profilePhotoCdnUrl=e.string();break}case 5:{s.searchProviderUrl=e.string();break}case 6:{s.referenceIndex=e.uint32();break}case 7:{s.expectedLinksCount=e.uint32();break}case 9:{s.searchQuery=e.string();break}case 10:{s.parentPluginMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 11:{s.deprecatedField=e.int32();break}case 12:{s.parentPluginType=e.int32();break}case 13:{s.faviconCdnUrl=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotPluginMetadata)return e;var a=new p.proto.BotPluginMetadata;switch(e.provider){default:if(typeof e.provider=="number"){a.provider=e.provider;break}break;case"UNKNOWN":case 0:a.provider=0;break;case"BING":case 1:a.provider=1;break;case"GOOGLE":case 2:a.provider=2;break;case"SUPPORT":case 3:a.provider=3;break}switch(e.pluginType){default:if(typeof e.pluginType=="number"){a.pluginType=e.pluginType;break}break;case"UNKNOWN_PLUGIN":case 0:a.pluginType=0;break;case"REELS":case 1:a.pluginType=1;break;case"SEARCH":case 2:a.pluginType=2;break}if(e.thumbnailCdnUrl!=null&&(a.thumbnailCdnUrl=String(e.thumbnailCdnUrl)),e.profilePhotoCdnUrl!=null&&(a.profilePhotoCdnUrl=String(e.profilePhotoCdnUrl)),e.searchProviderUrl!=null&&(a.searchProviderUrl=String(e.searchProviderUrl)),e.referenceIndex!=null&&(a.referenceIndex=e.referenceIndex>>>0),e.expectedLinksCount!=null&&(a.expectedLinksCount=e.expectedLinksCount>>>0),e.searchQuery!=null&&(a.searchQuery=String(e.searchQuery)),e.parentPluginMessageKey!=null){if(typeof e.parentPluginMessageKey!="object")throw TypeError(".proto.BotPluginMetadata.parentPluginMessageKey: object expected");a.parentPluginMessageKey=p.proto.MessageKey.fromObject(e.parentPluginMessageKey)}switch(e.deprecatedField){default:if(typeof e.deprecatedField=="number"){a.deprecatedField=e.deprecatedField;break}break;case"UNKNOWN_PLUGIN":case 0:a.deprecatedField=0;break;case"REELS":case 1:a.deprecatedField=1;break;case"SEARCH":case 2:a.deprecatedField=2;break}switch(e.parentPluginType){default:if(typeof e.parentPluginType=="number"){a.parentPluginType=e.parentPluginType;break}break;case"UNKNOWN_PLUGIN":case 0:a.parentPluginType=0;break;case"REELS":case 1:a.parentPluginType=1;break;case"SEARCH":case 2:a.parentPluginType=2;break}return e.faviconCdnUrl!=null&&(a.faviconCdnUrl=String(e.faviconCdnUrl)),a},t.toObject=function(e,a){a||(a={});var A={};return e.provider!=null&&e.hasOwnProperty("provider")&&(A.provider=a.enums===String?p.proto.BotPluginMetadata.SearchProvider[e.provider]===void 0?e.provider:p.proto.BotPluginMetadata.SearchProvider[e.provider]:e.provider,a.oneofs&&(A._provider="provider")),e.pluginType!=null&&e.hasOwnProperty("pluginType")&&(A.pluginType=a.enums===String?p.proto.BotPluginMetadata.PluginType[e.pluginType]===void 0?e.pluginType:p.proto.BotPluginMetadata.PluginType[e.pluginType]:e.pluginType,a.oneofs&&(A._pluginType="pluginType")),e.thumbnailCdnUrl!=null&&e.hasOwnProperty("thumbnailCdnUrl")&&(A.thumbnailCdnUrl=e.thumbnailCdnUrl,a.oneofs&&(A._thumbnailCdnUrl="thumbnailCdnUrl")),e.profilePhotoCdnUrl!=null&&e.hasOwnProperty("profilePhotoCdnUrl")&&(A.profilePhotoCdnUrl=e.profilePhotoCdnUrl,a.oneofs&&(A._profilePhotoCdnUrl="profilePhotoCdnUrl")),e.searchProviderUrl!=null&&e.hasOwnProperty("searchProviderUrl")&&(A.searchProviderUrl=e.searchProviderUrl,a.oneofs&&(A._searchProviderUrl="searchProviderUrl")),e.referenceIndex!=null&&e.hasOwnProperty("referenceIndex")&&(A.referenceIndex=e.referenceIndex,a.oneofs&&(A._referenceIndex="referenceIndex")),e.expectedLinksCount!=null&&e.hasOwnProperty("expectedLinksCount")&&(A.expectedLinksCount=e.expectedLinksCount,a.oneofs&&(A._expectedLinksCount="expectedLinksCount")),e.searchQuery!=null&&e.hasOwnProperty("searchQuery")&&(A.searchQuery=e.searchQuery,a.oneofs&&(A._searchQuery="searchQuery")),e.parentPluginMessageKey!=null&&e.hasOwnProperty("parentPluginMessageKey")&&(A.parentPluginMessageKey=p.proto.MessageKey.toObject(e.parentPluginMessageKey,a),a.oneofs&&(A._parentPluginMessageKey="parentPluginMessageKey")),e.deprecatedField!=null&&e.hasOwnProperty("deprecatedField")&&(A.deprecatedField=a.enums===String?p.proto.BotPluginMetadata.PluginType[e.deprecatedField]===void 0?e.deprecatedField:p.proto.BotPluginMetadata.PluginType[e.deprecatedField]:e.deprecatedField,a.oneofs&&(A._deprecatedField="deprecatedField")),e.parentPluginType!=null&&e.hasOwnProperty("parentPluginType")&&(A.parentPluginType=a.enums===String?p.proto.BotPluginMetadata.PluginType[e.parentPluginType]===void 0?e.parentPluginType:p.proto.BotPluginMetadata.PluginType[e.parentPluginType]:e.parentPluginType,a.oneofs&&(A._parentPluginType="parentPluginType")),e.faviconCdnUrl!=null&&e.hasOwnProperty("faviconCdnUrl")&&(A.faviconCdnUrl=e.faviconCdnUrl,a.oneofs&&(A._faviconCdnUrl="faviconCdnUrl")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotPluginMetadata"},t.PluginType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_PLUGIN"]=0,e[i[1]="REELS"]=1,e[i[2]="SEARCH"]=2,e})(),t.SearchProvider=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="BING"]=1,e[i[2]="GOOGLE"]=2,e[i[3]="SUPPORT"]=3,e})(),t})(),n.BotProgressIndicatorMetadata=(function(){function t(i){if(this.stepsMetadata=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.progressDescription=e.string();break}case 2:{s.stepsMetadata&&s.stepsMetadata.length||(s.stepsMetadata=[]),s.stepsMetadata.push(p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotProgressIndicatorMetadata)return e;var a=new p.proto.BotProgressIndicatorMetadata;if(e.progressDescription!=null&&(a.progressDescription=String(e.progressDescription)),e.stepsMetadata){if(!Array.isArray(e.stepsMetadata))throw TypeError(".proto.BotProgressIndicatorMetadata.stepsMetadata: array expected");a.stepsMetadata=[];for(var A=0;A>>3){case 1:{c.statusTitle=A.string();break}case 2:{c.statusBody=A.string();break}case 3:{c.sourcesMetadata&&c.sourcesMetadata.length||(c.sourcesMetadata=[]),c.sourcesMetadata.push(p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata.decode(A,A.uint32()));break}case 4:{c.status=A.int32();break}case 5:{c.isReasoning=A.bool();break}case 6:{c.isEnhancedSearch=A.bool();break}case 7:{c.sections&&c.sections.length||(c.sections=[]),c.sections.push(p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata)return A;var r=new p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata;if(A.statusTitle!=null&&(r.statusTitle=String(A.statusTitle)),A.statusBody!=null&&(r.statusBody=String(A.statusBody)),A.sourcesMetadata){if(!Array.isArray(A.sourcesMetadata))throw TypeError(".proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.sourcesMetadata: array expected");r.sourcesMetadata=[];for(var s=0;s>>3){case 1:{d.title=s.string();break}case 2:{d.provider=s.int32();break}case 3:{d.sourceUrl=s.string();break}case 4:{d.favIconUrl=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata)return s;var g=new p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata;switch(s.title!=null&&(g.title=String(s.title)),s.provider){default:if(typeof s.provider=="number"){g.provider=s.provider;break}break;case"UNKNOWN_PROVIDER":case 0:g.provider=0;break;case"OTHER":case 1:g.provider=1;break;case"GOOGLE":case 2:g.provider=2;break;case"BING":case 3:g.provider=3;break}return s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),s.favIconUrl!=null&&(g.favIconUrl=String(s.favIconUrl)),g},a.toObject=function(s,g){g||(g={});var c={};return s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.provider!=null&&s.hasOwnProperty("provider")&&(c.provider=g.enums===String?p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotSearchSourceProvider[s.provider]===void 0?s.provider:p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotSearchSourceProvider[s.provider]:s.provider,g.oneofs&&(c._provider="provider")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),s.favIconUrl!=null&&s.hasOwnProperty("favIconUrl")&&(c.favIconUrl=s.favIconUrl,g.oneofs&&(c._favIconUrl="favIconUrl")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata"},a})(),i.BotPlanningSearchSourcesMetadata=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.sourceTitle=s.string();break}case 2:{d.provider=s.int32();break}case 3:{d.sourceUrl=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata)return s;var g=new p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata;switch(s.sourceTitle!=null&&(g.sourceTitle=String(s.sourceTitle)),s.provider){default:if(typeof s.provider=="number"){g.provider=s.provider;break}break;case"UNKNOWN":case 0:g.provider=0;break;case"OTHER":case 1:g.provider=1;break;case"GOOGLE":case 2:g.provider=2;break;case"BING":case 3:g.provider=3;break}return s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),g},a.toObject=function(s,g){g||(g={});var c={};return s.sourceTitle!=null&&s.hasOwnProperty("sourceTitle")&&(c.sourceTitle=s.sourceTitle,g.oneofs&&(c._sourceTitle="sourceTitle")),s.provider!=null&&s.hasOwnProperty("provider")&&(c.provider=g.enums===String?p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata.BotPlanningSearchSourceProvider[s.provider]===void 0?s.provider:p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata.BotPlanningSearchSourceProvider[s.provider]:s.provider,g.oneofs&&(c._provider="provider")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourcesMetadata"},a.BotPlanningSearchSourceProvider=(function(){let r={},s=Object.create(r);return s[r[0]="UNKNOWN"]=0,s[r[1]="OTHER"]=1,s[r[2]="GOOGLE"]=2,s[r[3]="BING"]=3,s})(),a})(),i.BotPlanningStepSectionMetadata=(function(){function a(r){if(this.sourcesMetadata=[],r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.sectionTitle=s.string();break}case 2:{d.sectionBody=s.string();break}case 3:{d.sourcesMetadata&&d.sourcesMetadata.length||(d.sourcesMetadata=[]),d.sourcesMetadata.push(p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningSearchSourceMetadata.decode(s,s.uint32()));break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata)return s;var g=new p.proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata;if(s.sectionTitle!=null&&(g.sectionTitle=String(s.sectionTitle)),s.sectionBody!=null&&(g.sectionBody=String(s.sectionBody)),s.sourcesMetadata){if(!Array.isArray(s.sourcesMetadata))throw TypeError(".proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.BotPlanningStepSectionMetadata.sourcesMetadata: array expected");g.sourcesMetadata=[];for(var c=0;c>>3){case 1:{s.promotionType=e.int32();break}case 2:{s.buttonTitle=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotPromotionMessageMetadata)return e;var a=new p.proto.BotPromotionMessageMetadata;switch(e.promotionType){default:if(typeof e.promotionType=="number"){a.promotionType=e.promotionType;break}break;case"UNKNOWN_TYPE":case 0:a.promotionType=0;break;case"C50":case 1:a.promotionType=1;break;case"SURVEY_PLATFORM":case 2:a.promotionType=2;break}return e.buttonTitle!=null&&(a.buttonTitle=String(e.buttonTitle)),a},t.toObject=function(e,a){a||(a={});var A={};return e.promotionType!=null&&e.hasOwnProperty("promotionType")&&(A.promotionType=a.enums===String?p.proto.BotPromotionMessageMetadata.BotPromotionType[e.promotionType]===void 0?e.promotionType:p.proto.BotPromotionMessageMetadata.BotPromotionType[e.promotionType]:e.promotionType,a.oneofs&&(A._promotionType="promotionType")),e.buttonTitle!=null&&e.hasOwnProperty("buttonTitle")&&(A.buttonTitle=e.buttonTitle,a.oneofs&&(A._buttonTitle="buttonTitle")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotPromotionMessageMetadata"},t.BotPromotionType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_TYPE"]=0,e[i[1]="C50"]=1,e[i[2]="SURVEY_PLATFORM"]=2,e})(),t})(),n.BotPromptSuggestion=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.prompt=e.string();break}case 2:{s.promptId=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotPromptSuggestion)return e;var a=new p.proto.BotPromptSuggestion;return e.prompt!=null&&(a.prompt=String(e.prompt)),e.promptId!=null&&(a.promptId=String(e.promptId)),a},t.toObject=function(e,a){a||(a={});var A={};return e.prompt!=null&&e.hasOwnProperty("prompt")&&(A.prompt=e.prompt,a.oneofs&&(A._prompt="prompt")),e.promptId!=null&&e.hasOwnProperty("promptId")&&(A.promptId=e.promptId,a.oneofs&&(A._promptId="promptId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotPromptSuggestion"},t})(),n.BotPromptSuggestions=(function(){function t(o){if(this.suggestions=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.suggestions&&r.suggestions.length||(r.suggestions=[]),r.suggestions.push(p.proto.BotPromptSuggestion.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotPromptSuggestions)return i;var e=new p.proto.BotPromptSuggestions;if(i.suggestions){if(!Array.isArray(i.suggestions))throw TypeError(".proto.BotPromptSuggestions.suggestions: array expected");e.suggestions=[];for(var a=0;a>>3){case 1:{r.botFeatureQuotaMetadata&&r.botFeatureQuotaMetadata.length||(r.botFeatureQuotaMetadata=[]),r.botFeatureQuotaMetadata.push(p.proto.BotQuotaMetadata.BotFeatureQuotaMetadata.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotQuotaMetadata)return i;var e=new p.proto.BotQuotaMetadata;if(i.botFeatureQuotaMetadata){if(!Array.isArray(i.botFeatureQuotaMetadata))throw TypeError(".proto.BotQuotaMetadata.botFeatureQuotaMetadata: array expected");e.botFeatureQuotaMetadata=[];for(var a=0;a>>3){case 1:{g.featureType=a.int32();break}case 2:{g.remainingQuota=a.uint32();break}case 3:{g.expirationTimestamp=a.uint64();break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof p.proto.BotQuotaMetadata.BotFeatureQuotaMetadata)return a;var A=new p.proto.BotQuotaMetadata.BotFeatureQuotaMetadata;switch(a.featureType){default:if(typeof a.featureType=="number"){A.featureType=a.featureType;break}break;case"UNKNOWN_FEATURE":case 0:A.featureType=0;break;case"REASONING_FEATURE":case 1:A.featureType=1;break}return a.remainingQuota!=null&&(A.remainingQuota=a.remainingQuota>>>0),a.expirationTimestamp!=null&&(l.Long?(A.expirationTimestamp=l.Long.fromValue(a.expirationTimestamp)).unsigned=!0:typeof a.expirationTimestamp=="string"?A.expirationTimestamp=parseInt(a.expirationTimestamp,10):typeof a.expirationTimestamp=="number"?A.expirationTimestamp=a.expirationTimestamp:typeof a.expirationTimestamp=="object"&&(A.expirationTimestamp=new l.LongBits(a.expirationTimestamp.low>>>0,a.expirationTimestamp.high>>>0).toNumber(!0))),A},o.toObject=function(a,A){A||(A={});var r={};return a.featureType!=null&&a.hasOwnProperty("featureType")&&(r.featureType=A.enums===String?p.proto.BotQuotaMetadata.BotFeatureQuotaMetadata.BotFeatureType[a.featureType]===void 0?a.featureType:p.proto.BotQuotaMetadata.BotFeatureQuotaMetadata.BotFeatureType[a.featureType]:a.featureType,A.oneofs&&(r._featureType="featureType")),a.remainingQuota!=null&&a.hasOwnProperty("remainingQuota")&&(r.remainingQuota=a.remainingQuota,A.oneofs&&(r._remainingQuota="remainingQuota")),a.expirationTimestamp!=null&&a.hasOwnProperty("expirationTimestamp")&&(typeof a.expirationTimestamp=="number"?r.expirationTimestamp=A.longs===String?String(a.expirationTimestamp):a.expirationTimestamp:r.expirationTimestamp=A.longs===String?se(a.expirationTimestamp,!0):A.longs===Number?ge(a.expirationTimestamp,!0):a.expirationTimestamp,A.oneofs&&(r._expirationTimestamp="expirationTimestamp")),r},o.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.BotQuotaMetadata.BotFeatureQuotaMetadata"},o.BotFeatureType=(function(){let e={},a=Object.create(e);return a[e[0]="UNKNOWN_FEATURE"]=0,a[e[1]="REASONING_FEATURE"]=1,a})(),o})(),t})(),n.BotReminderMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.requestMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.action=e.int32();break}case 3:{s.name=e.string();break}case 4:{s.nextTriggerTimestamp=e.uint64();break}case 5:{s.frequency=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotReminderMetadata)return e;var a=new p.proto.BotReminderMetadata;if(e.requestMessageKey!=null){if(typeof e.requestMessageKey!="object")throw TypeError(".proto.BotReminderMetadata.requestMessageKey: object expected");a.requestMessageKey=p.proto.MessageKey.fromObject(e.requestMessageKey)}switch(e.action){default:if(typeof e.action=="number"){a.action=e.action;break}break;case"NOTIFY":case 1:a.action=1;break;case"CREATE":case 2:a.action=2;break;case"DELETE":case 3:a.action=3;break;case"UPDATE":case 4:a.action=4;break}switch(e.name!=null&&(a.name=String(e.name)),e.nextTriggerTimestamp!=null&&(l.Long?(a.nextTriggerTimestamp=l.Long.fromValue(e.nextTriggerTimestamp)).unsigned=!0:typeof e.nextTriggerTimestamp=="string"?a.nextTriggerTimestamp=parseInt(e.nextTriggerTimestamp,10):typeof e.nextTriggerTimestamp=="number"?a.nextTriggerTimestamp=e.nextTriggerTimestamp:typeof e.nextTriggerTimestamp=="object"&&(a.nextTriggerTimestamp=new l.LongBits(e.nextTriggerTimestamp.low>>>0,e.nextTriggerTimestamp.high>>>0).toNumber(!0))),e.frequency){default:if(typeof e.frequency=="number"){a.frequency=e.frequency;break}break;case"ONCE":case 1:a.frequency=1;break;case"DAILY":case 2:a.frequency=2;break;case"WEEKLY":case 3:a.frequency=3;break;case"BIWEEKLY":case 4:a.frequency=4;break;case"MONTHLY":case 5:a.frequency=5;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.requestMessageKey!=null&&e.hasOwnProperty("requestMessageKey")&&(A.requestMessageKey=p.proto.MessageKey.toObject(e.requestMessageKey,a),a.oneofs&&(A._requestMessageKey="requestMessageKey")),e.action!=null&&e.hasOwnProperty("action")&&(A.action=a.enums===String?p.proto.BotReminderMetadata.ReminderAction[e.action]===void 0?e.action:p.proto.BotReminderMetadata.ReminderAction[e.action]:e.action,a.oneofs&&(A._action="action")),e.name!=null&&e.hasOwnProperty("name")&&(A.name=e.name,a.oneofs&&(A._name="name")),e.nextTriggerTimestamp!=null&&e.hasOwnProperty("nextTriggerTimestamp")&&(typeof e.nextTriggerTimestamp=="number"?A.nextTriggerTimestamp=a.longs===String?String(e.nextTriggerTimestamp):e.nextTriggerTimestamp:A.nextTriggerTimestamp=a.longs===String?se(e.nextTriggerTimestamp,!0):a.longs===Number?ge(e.nextTriggerTimestamp,!0):e.nextTriggerTimestamp,a.oneofs&&(A._nextTriggerTimestamp="nextTriggerTimestamp")),e.frequency!=null&&e.hasOwnProperty("frequency")&&(A.frequency=a.enums===String?p.proto.BotReminderMetadata.ReminderFrequency[e.frequency]===void 0?e.frequency:p.proto.BotReminderMetadata.ReminderFrequency[e.frequency]:e.frequency,a.oneofs&&(A._frequency="frequency")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotReminderMetadata"},t.ReminderAction=(function(){let i={},e=Object.create(i);return e[i[1]="NOTIFY"]=1,e[i[2]="CREATE"]=2,e[i[3]="DELETE"]=3,e[i[4]="UPDATE"]=4,e})(),t.ReminderFrequency=(function(){let i={},e=Object.create(i);return e[i[1]="ONCE"]=1,e[i[2]="DAILY"]=2,e[i[3]="WEEKLY"]=3,e[i[4]="BIWEEKLY"]=4,e[i[5]="MONTHLY"]=5,e})(),t})(),n.BotRenderingMetadata=(function(){function t(o){if(this.keywords=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.keywords&&r.keywords.length||(r.keywords=[]),r.keywords.push(p.proto.BotRenderingMetadata.Keyword.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotRenderingMetadata)return i;var e=new p.proto.BotRenderingMetadata;if(i.keywords){if(!Array.isArray(i.keywords))throw TypeError(".proto.BotRenderingMetadata.keywords: array expected");e.keywords=[];for(var a=0;a>>3){case 1:{g.value=a.string();break}case 2:{g.associatedPrompts&&g.associatedPrompts.length||(g.associatedPrompts=[]),g.associatedPrompts.push(a.string());break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof p.proto.BotRenderingMetadata.Keyword)return a;var A=new p.proto.BotRenderingMetadata.Keyword;if(a.value!=null&&(A.value=String(a.value)),a.associatedPrompts){if(!Array.isArray(a.associatedPrompts))throw TypeError(".proto.BotRenderingMetadata.Keyword.associatedPrompts: array expected");A.associatedPrompts=[];for(var r=0;r>>3){case 1:{s.sessionId=e.string();break}case 2:{s.sessionSource=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotSessionMetadata)return e;var a=new p.proto.BotSessionMetadata;switch(e.sessionId!=null&&(a.sessionId=String(e.sessionId)),e.sessionSource){default:if(typeof e.sessionSource=="number"){a.sessionSource=e.sessionSource;break}break;case"NONE":case 0:a.sessionSource=0;break;case"NULL_STATE":case 1:a.sessionSource=1;break;case"TYPEAHEAD":case 2:a.sessionSource=2;break;case"USER_INPUT":case 3:a.sessionSource=3;break;case"EMU_FLASH":case 4:a.sessionSource=4;break;case"EMU_FLASH_FOLLOWUP":case 5:a.sessionSource=5;break;case"VOICE":case 6:a.sessionSource=6;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.sessionId!=null&&e.hasOwnProperty("sessionId")&&(A.sessionId=e.sessionId,a.oneofs&&(A._sessionId="sessionId")),e.sessionSource!=null&&e.hasOwnProperty("sessionSource")&&(A.sessionSource=a.enums===String?p.proto.BotSessionSource[e.sessionSource]===void 0?e.sessionSource:p.proto.BotSessionSource[e.sessionSource]:e.sessionSource,a.oneofs&&(A._sessionSource="sessionSource")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.BotSessionMetadata"},t})(),n.BotSessionSource=(function(){let t={},o=Object.create(t);return o[t[0]="NONE"]=0,o[t[1]="NULL_STATE"]=1,o[t[2]="TYPEAHEAD"]=2,o[t[3]="USER_INPUT"]=3,o[t[4]="EMU_FLASH"]=4,o[t[5]="EMU_FLASH_FOLLOWUP"]=5,o[t[6]="VOICE"]=6,o})(),n.BotSignatureVerificationMetadata=(function(){function t(o){if(this.proofs=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.proofs&&r.proofs.length||(r.proofs=[]),r.proofs.push(p.proto.BotSignatureVerificationUseCaseProof.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotSignatureVerificationMetadata)return i;var e=new p.proto.BotSignatureVerificationMetadata;if(i.proofs){if(!Array.isArray(i.proofs))throw TypeError(".proto.BotSignatureVerificationMetadata.proofs: array expected");e.proofs=[];for(var a=0;a>>3){case 1:{s.version=e.int32();break}case 2:{s.useCase=e.int32();break}case 3:{s.signature=e.bytes();break}case 4:{s.certificateChain&&s.certificateChain.length||(s.certificateChain=[]),s.certificateChain.push(e.bytes());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotSignatureVerificationUseCaseProof)return e;var a=new p.proto.BotSignatureVerificationUseCaseProof;switch(e.version!=null&&(a.version=e.version|0),e.useCase){default:if(typeof e.useCase=="number"){a.useCase=e.useCase;break}break;case"UNSPECIFIED":case 0:a.useCase=0;break;case"WA_BOT_MSG":case 1:a.useCase=1;break}if(e.signature!=null&&(typeof e.signature=="string"?l.base64.decode(e.signature,a.signature=l.newBuffer(l.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),e.certificateChain){if(!Array.isArray(e.certificateChain))throw TypeError(".proto.BotSignatureVerificationUseCaseProof.certificateChain: array expected");a.certificateChain=[];for(var A=0;A=0&&(a.certificateChain[A]=e.certificateChain[A])}return a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.certificateChain=[]),e.version!=null&&e.hasOwnProperty("version")&&(A.version=e.version,a.oneofs&&(A._version="version")),e.useCase!=null&&e.hasOwnProperty("useCase")&&(A.useCase=a.enums===String?p.proto.BotSignatureVerificationUseCaseProof.BotSignatureUseCase[e.useCase]===void 0?e.useCase:p.proto.BotSignatureVerificationUseCaseProof.BotSignatureUseCase[e.useCase]:e.useCase,a.oneofs&&(A._useCase="useCase")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?l.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),e.certificateChain&&e.certificateChain.length){A.certificateChain=[];for(var r=0;r>>3){case 1:{r.sources&&r.sources.length||(r.sources=[]),r.sources.push(p.proto.BotSourcesMetadata.BotSourceItem.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.BotSourcesMetadata)return i;var e=new p.proto.BotSourcesMetadata;if(i.sources){if(!Array.isArray(i.sources))throw TypeError(".proto.BotSourcesMetadata.sources: array expected");e.sources=[];for(var a=0;a>>3){case 1:{g.provider=a.int32();break}case 2:{g.thumbnailCdnUrl=a.string();break}case 3:{g.sourceProviderUrl=a.string();break}case 4:{g.sourceQuery=a.string();break}case 5:{g.faviconCdnUrl=a.string();break}case 6:{g.citationNumber=a.uint32();break}case 7:{g.sourceTitle=a.string();break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof p.proto.BotSourcesMetadata.BotSourceItem)return a;var A=new p.proto.BotSourcesMetadata.BotSourceItem;switch(a.provider){default:if(typeof a.provider=="number"){A.provider=a.provider;break}break;case"UNKNOWN":case 0:A.provider=0;break;case"BING":case 1:A.provider=1;break;case"GOOGLE":case 2:A.provider=2;break;case"SUPPORT":case 3:A.provider=3;break;case"OTHER":case 4:A.provider=4;break}return a.thumbnailCdnUrl!=null&&(A.thumbnailCdnUrl=String(a.thumbnailCdnUrl)),a.sourceProviderUrl!=null&&(A.sourceProviderUrl=String(a.sourceProviderUrl)),a.sourceQuery!=null&&(A.sourceQuery=String(a.sourceQuery)),a.faviconCdnUrl!=null&&(A.faviconCdnUrl=String(a.faviconCdnUrl)),a.citationNumber!=null&&(A.citationNumber=a.citationNumber>>>0),a.sourceTitle!=null&&(A.sourceTitle=String(a.sourceTitle)),A},o.toObject=function(a,A){A||(A={});var r={};return a.provider!=null&&a.hasOwnProperty("provider")&&(r.provider=A.enums===String?p.proto.BotSourcesMetadata.BotSourceItem.SourceProvider[a.provider]===void 0?a.provider:p.proto.BotSourcesMetadata.BotSourceItem.SourceProvider[a.provider]:a.provider,A.oneofs&&(r._provider="provider")),a.thumbnailCdnUrl!=null&&a.hasOwnProperty("thumbnailCdnUrl")&&(r.thumbnailCdnUrl=a.thumbnailCdnUrl,A.oneofs&&(r._thumbnailCdnUrl="thumbnailCdnUrl")),a.sourceProviderUrl!=null&&a.hasOwnProperty("sourceProviderUrl")&&(r.sourceProviderUrl=a.sourceProviderUrl,A.oneofs&&(r._sourceProviderUrl="sourceProviderUrl")),a.sourceQuery!=null&&a.hasOwnProperty("sourceQuery")&&(r.sourceQuery=a.sourceQuery,A.oneofs&&(r._sourceQuery="sourceQuery")),a.faviconCdnUrl!=null&&a.hasOwnProperty("faviconCdnUrl")&&(r.faviconCdnUrl=a.faviconCdnUrl,A.oneofs&&(r._faviconCdnUrl="faviconCdnUrl")),a.citationNumber!=null&&a.hasOwnProperty("citationNumber")&&(r.citationNumber=a.citationNumber,A.oneofs&&(r._citationNumber="citationNumber")),a.sourceTitle!=null&&a.hasOwnProperty("sourceTitle")&&(r.sourceTitle=a.sourceTitle,A.oneofs&&(r._sourceTitle="sourceTitle")),r},o.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.BotSourcesMetadata.BotSourceItem"},o.SourceProvider=(function(){let e={},a=Object.create(e);return a[e[0]="UNKNOWN"]=0,a[e[1]="BING"]=1,a[e[2]="GOOGLE"]=2,a[e[3]="SUPPORT"]=3,a[e[4]="OTHER"]=4,a})(),o})(),t})(),n.BotSuggestedPromptMetadata=(function(){function t(i){if(this.suggestedPrompts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.suggestedPrompts&&s.suggestedPrompts.length||(s.suggestedPrompts=[]),s.suggestedPrompts.push(e.string());break}case 2:{s.selectedPromptIndex=e.uint32();break}case 3:{s.promptSuggestions=p.proto.BotPromptSuggestions.decode(e,e.uint32());break}case 4:{s.selectedPromptId=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotSuggestedPromptMetadata)return e;var a=new p.proto.BotSuggestedPromptMetadata;if(e.suggestedPrompts){if(!Array.isArray(e.suggestedPrompts))throw TypeError(".proto.BotSuggestedPromptMetadata.suggestedPrompts: array expected");a.suggestedPrompts=[];for(var A=0;A>>0),e.promptSuggestions!=null){if(typeof e.promptSuggestions!="object")throw TypeError(".proto.BotSuggestedPromptMetadata.promptSuggestions: object expected");a.promptSuggestions=p.proto.BotPromptSuggestions.fromObject(e.promptSuggestions)}return e.selectedPromptId!=null&&(a.selectedPromptId=String(e.selectedPromptId)),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.suggestedPrompts=[]),e.suggestedPrompts&&e.suggestedPrompts.length){A.suggestedPrompts=[];for(var r=0;r>>3){case 1:{s.sbsMetadata=p.proto.BotUnifiedResponseMutation.SideBySideMetadata.decode(e,e.uint32());break}case 2:{s.mediaDetailsMetadataList&&s.mediaDetailsMetadataList.length||(s.mediaDetailsMetadataList=[]),s.mediaDetailsMetadataList.push(p.proto.BotUnifiedResponseMutation.MediaDetailsMetadata.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.BotUnifiedResponseMutation)return e;var a=new p.proto.BotUnifiedResponseMutation;if(e.sbsMetadata!=null){if(typeof e.sbsMetadata!="object")throw TypeError(".proto.BotUnifiedResponseMutation.sbsMetadata: object expected");a.sbsMetadata=p.proto.BotUnifiedResponseMutation.SideBySideMetadata.fromObject(e.sbsMetadata)}if(e.mediaDetailsMetadataList){if(!Array.isArray(e.mediaDetailsMetadataList))throw TypeError(".proto.BotUnifiedResponseMutation.mediaDetailsMetadataList: array expected");a.mediaDetailsMetadataList=[];for(var A=0;A>>3){case 1:{c.id=A.string();break}case 2:{c.highResMedia=p.proto.BotMediaMetadata.decode(A,A.uint32());break}case 3:{c.previewMedia=p.proto.BotMediaMetadata.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.BotUnifiedResponseMutation.MediaDetailsMetadata)return A;var r=new p.proto.BotUnifiedResponseMutation.MediaDetailsMetadata;if(A.id!=null&&(r.id=String(A.id)),A.highResMedia!=null){if(typeof A.highResMedia!="object")throw TypeError(".proto.BotUnifiedResponseMutation.MediaDetailsMetadata.highResMedia: object expected");r.highResMedia=p.proto.BotMediaMetadata.fromObject(A.highResMedia)}if(A.previewMedia!=null){if(typeof A.previewMedia!="object")throw TypeError(".proto.BotUnifiedResponseMutation.MediaDetailsMetadata.previewMedia: object expected");r.previewMedia=p.proto.BotMediaMetadata.fromObject(A.previewMedia)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,r.oneofs&&(s._id="id")),A.highResMedia!=null&&A.hasOwnProperty("highResMedia")&&(s.highResMedia=p.proto.BotMediaMetadata.toObject(A.highResMedia,r),r.oneofs&&(s._highResMedia="highResMedia")),A.previewMedia!=null&&A.hasOwnProperty("previewMedia")&&(s.previewMedia=p.proto.BotMediaMetadata.toObject(A.previewMedia,r),r.oneofs&&(s._previewMedia="previewMedia")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.BotUnifiedResponseMutation.MediaDetailsMetadata"},i})(),t.SideBySideMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.primaryResponseId=A.string();break}case 2:{c.surveyCtaHasRendered=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.BotUnifiedResponseMutation.SideBySideMetadata)return A;var r=new p.proto.BotUnifiedResponseMutation.SideBySideMetadata;return A.primaryResponseId!=null&&(r.primaryResponseId=String(A.primaryResponseId)),A.surveyCtaHasRendered!=null&&(r.surveyCtaHasRendered=!!A.surveyCtaHasRendered),r},i.toObject=function(A,r){r||(r={});var s={};return A.primaryResponseId!=null&&A.hasOwnProperty("primaryResponseId")&&(s.primaryResponseId=A.primaryResponseId,r.oneofs&&(s._primaryResponseId="primaryResponseId")),A.surveyCtaHasRendered!=null&&A.hasOwnProperty("surveyCtaHasRendered")&&(s.surveyCtaHasRendered=A.surveyCtaHasRendered,r.oneofs&&(s._surveyCtaHasRendered="surveyCtaHasRendered")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.BotUnifiedResponseMutation.SideBySideMetadata"},i})(),t})(),n.CallLogRecord=(function(){function t(i){if(this.participants=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.callResult=e.int32();break}case 2:{s.isDndMode=e.bool();break}case 3:{s.silenceReason=e.int32();break}case 4:{s.duration=e.int64();break}case 5:{s.startTime=e.int64();break}case 6:{s.isIncoming=e.bool();break}case 7:{s.isVideo=e.bool();break}case 8:{s.isCallLink=e.bool();break}case 9:{s.callLinkToken=e.string();break}case 10:{s.scheduledCallId=e.string();break}case 11:{s.callId=e.string();break}case 12:{s.callCreatorJid=e.string();break}case 13:{s.groupJid=e.string();break}case 14:{s.participants&&s.participants.length||(s.participants=[]),s.participants.push(p.proto.CallLogRecord.ParticipantInfo.decode(e,e.uint32()));break}case 15:{s.callType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.CallLogRecord)return e;var a=new p.proto.CallLogRecord;switch(e.callResult){default:if(typeof e.callResult=="number"){a.callResult=e.callResult;break}break;case"CONNECTED":case 0:a.callResult=0;break;case"REJECTED":case 1:a.callResult=1;break;case"CANCELLED":case 2:a.callResult=2;break;case"ACCEPTEDELSEWHERE":case 3:a.callResult=3;break;case"MISSED":case 4:a.callResult=4;break;case"INVALID":case 5:a.callResult=5;break;case"UNAVAILABLE":case 6:a.callResult=6;break;case"UPCOMING":case 7:a.callResult=7;break;case"FAILED":case 8:a.callResult=8;break;case"ABANDONED":case 9:a.callResult=9;break;case"ONGOING":case 10:a.callResult=10;break}switch(e.isDndMode!=null&&(a.isDndMode=!!e.isDndMode),e.silenceReason){default:if(typeof e.silenceReason=="number"){a.silenceReason=e.silenceReason;break}break;case"NONE":case 0:a.silenceReason=0;break;case"SCHEDULED":case 1:a.silenceReason=1;break;case"PRIVACY":case 2:a.silenceReason=2;break;case"LIGHTWEIGHT":case 3:a.silenceReason=3;break}if(e.duration!=null&&(l.Long?(a.duration=l.Long.fromValue(e.duration)).unsigned=!1:typeof e.duration=="string"?a.duration=parseInt(e.duration,10):typeof e.duration=="number"?a.duration=e.duration:typeof e.duration=="object"&&(a.duration=new l.LongBits(e.duration.low>>>0,e.duration.high>>>0).toNumber())),e.startTime!=null&&(l.Long?(a.startTime=l.Long.fromValue(e.startTime)).unsigned=!1:typeof e.startTime=="string"?a.startTime=parseInt(e.startTime,10):typeof e.startTime=="number"?a.startTime=e.startTime:typeof e.startTime=="object"&&(a.startTime=new l.LongBits(e.startTime.low>>>0,e.startTime.high>>>0).toNumber())),e.isIncoming!=null&&(a.isIncoming=!!e.isIncoming),e.isVideo!=null&&(a.isVideo=!!e.isVideo),e.isCallLink!=null&&(a.isCallLink=!!e.isCallLink),e.callLinkToken!=null&&(a.callLinkToken=String(e.callLinkToken)),e.scheduledCallId!=null&&(a.scheduledCallId=String(e.scheduledCallId)),e.callId!=null&&(a.callId=String(e.callId)),e.callCreatorJid!=null&&(a.callCreatorJid=String(e.callCreatorJid)),e.groupJid!=null&&(a.groupJid=String(e.groupJid)),e.participants){if(!Array.isArray(e.participants))throw TypeError(".proto.CallLogRecord.participants: array expected");a.participants=[];for(var A=0;A>>3){case 1:{c.userJid=A.string();break}case 2:{c.callResult=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.CallLogRecord.ParticipantInfo)return A;var r=new p.proto.CallLogRecord.ParticipantInfo;switch(A.userJid!=null&&(r.userJid=String(A.userJid)),A.callResult){default:if(typeof A.callResult=="number"){r.callResult=A.callResult;break}break;case"CONNECTED":case 0:r.callResult=0;break;case"REJECTED":case 1:r.callResult=1;break;case"CANCELLED":case 2:r.callResult=2;break;case"ACCEPTEDELSEWHERE":case 3:r.callResult=3;break;case"MISSED":case 4:r.callResult=4;break;case"INVALID":case 5:r.callResult=5;break;case"UNAVAILABLE":case 6:r.callResult=6;break;case"UPCOMING":case 7:r.callResult=7;break;case"FAILED":case 8:r.callResult=8;break;case"ABANDONED":case 9:r.callResult=9;break;case"ONGOING":case 10:r.callResult=10;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.userJid!=null&&A.hasOwnProperty("userJid")&&(s.userJid=A.userJid,r.oneofs&&(s._userJid="userJid")),A.callResult!=null&&A.hasOwnProperty("callResult")&&(s.callResult=r.enums===String?p.proto.CallLogRecord.CallResult[A.callResult]===void 0?A.callResult:p.proto.CallLogRecord.CallResult[A.callResult]:A.callResult,r.oneofs&&(s._callResult="callResult")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.CallLogRecord.ParticipantInfo"},i})(),t.SilenceReason=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="SCHEDULED"]=1,e[i[2]="PRIVACY"]=2,e[i[3]="LIGHTWEIGHT"]=3,e})(),t})(),n.CertChain=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.leaf=p.proto.CertChain.NoiseCertificate.decode(e,e.uint32());break}case 2:{s.intermediate=p.proto.CertChain.NoiseCertificate.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.CertChain)return e;var a=new p.proto.CertChain;if(e.leaf!=null){if(typeof e.leaf!="object")throw TypeError(".proto.CertChain.leaf: object expected");a.leaf=p.proto.CertChain.NoiseCertificate.fromObject(e.leaf)}if(e.intermediate!=null){if(typeof e.intermediate!="object")throw TypeError(".proto.CertChain.intermediate: object expected");a.intermediate=p.proto.CertChain.NoiseCertificate.fromObject(e.intermediate)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.leaf!=null&&e.hasOwnProperty("leaf")&&(A.leaf=p.proto.CertChain.NoiseCertificate.toObject(e.leaf,a),a.oneofs&&(A._leaf="leaf")),e.intermediate!=null&&e.hasOwnProperty("intermediate")&&(A.intermediate=p.proto.CertChain.NoiseCertificate.toObject(e.intermediate,a),a.oneofs&&(A._intermediate="intermediate")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CertChain"},t.NoiseCertificate=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.details=A.bytes();break}case 2:{c.signature=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.CertChain.NoiseCertificate)return A;var r=new p.proto.CertChain.NoiseCertificate;return A.details!=null&&(typeof A.details=="string"?l.base64.decode(A.details,r.details=l.newBuffer(l.base64.length(A.details)),0):A.details.length>=0&&(r.details=A.details)),A.signature!=null&&(typeof A.signature=="string"?l.base64.decode(A.signature,r.signature=l.newBuffer(l.base64.length(A.signature)),0):A.signature.length>=0&&(r.signature=A.signature)),r},i.toObject=function(A,r){r||(r={});var s={};return A.details!=null&&A.hasOwnProperty("details")&&(s.details=r.bytes===String?l.base64.encode(A.details,0,A.details.length):r.bytes===Array?Array.prototype.slice.call(A.details):A.details,r.oneofs&&(s._details="details")),A.signature!=null&&A.hasOwnProperty("signature")&&(s.signature=r.bytes===String?l.base64.encode(A.signature,0,A.signature.length):r.bytes===Array?Array.prototype.slice.call(A.signature):A.signature,r.oneofs&&(s._signature="signature")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.CertChain.NoiseCertificate"},i.Details=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.serial=s.uint32();break}case 2:{d.issuerSerial=s.uint32();break}case 3:{d.key=s.bytes();break}case 4:{d.notBefore=s.uint64();break}case 5:{d.notAfter=s.uint64();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.CertChain.NoiseCertificate.Details)return s;var g=new p.proto.CertChain.NoiseCertificate.Details;return s.serial!=null&&(g.serial=s.serial>>>0),s.issuerSerial!=null&&(g.issuerSerial=s.issuerSerial>>>0),s.key!=null&&(typeof s.key=="string"?l.base64.decode(s.key,g.key=l.newBuffer(l.base64.length(s.key)),0):s.key.length>=0&&(g.key=s.key)),s.notBefore!=null&&(l.Long?(g.notBefore=l.Long.fromValue(s.notBefore)).unsigned=!0:typeof s.notBefore=="string"?g.notBefore=parseInt(s.notBefore,10):typeof s.notBefore=="number"?g.notBefore=s.notBefore:typeof s.notBefore=="object"&&(g.notBefore=new l.LongBits(s.notBefore.low>>>0,s.notBefore.high>>>0).toNumber(!0))),s.notAfter!=null&&(l.Long?(g.notAfter=l.Long.fromValue(s.notAfter)).unsigned=!0:typeof s.notAfter=="string"?g.notAfter=parseInt(s.notAfter,10):typeof s.notAfter=="number"?g.notAfter=s.notAfter:typeof s.notAfter=="object"&&(g.notAfter=new l.LongBits(s.notAfter.low>>>0,s.notAfter.high>>>0).toNumber(!0))),g},a.toObject=function(s,g){g||(g={});var c={};return s.serial!=null&&s.hasOwnProperty("serial")&&(c.serial=s.serial,g.oneofs&&(c._serial="serial")),s.issuerSerial!=null&&s.hasOwnProperty("issuerSerial")&&(c.issuerSerial=s.issuerSerial,g.oneofs&&(c._issuerSerial="issuerSerial")),s.key!=null&&s.hasOwnProperty("key")&&(c.key=g.bytes===String?l.base64.encode(s.key,0,s.key.length):g.bytes===Array?Array.prototype.slice.call(s.key):s.key,g.oneofs&&(c._key="key")),s.notBefore!=null&&s.hasOwnProperty("notBefore")&&(typeof s.notBefore=="number"?c.notBefore=g.longs===String?String(s.notBefore):s.notBefore:c.notBefore=g.longs===String?se(s.notBefore,!0):g.longs===Number?ge(s.notBefore,!0):s.notBefore,g.oneofs&&(c._notBefore="notBefore")),s.notAfter!=null&&s.hasOwnProperty("notAfter")&&(typeof s.notAfter=="number"?c.notAfter=g.longs===String?String(s.notAfter):s.notAfter:c.notAfter=g.longs===String?se(s.notAfter,!0):g.longs===Number?ge(s.notAfter,!0):s.notAfter,g.oneofs&&(c._notAfter="notAfter")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.CertChain.NoiseCertificate.Details"},a})(),i})(),t})(),n.ChatLockSettings=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.hideLockedChats=e.bool();break}case 2:{s.secretCode=p.proto.UserPassword.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ChatLockSettings)return e;var a=new p.proto.ChatLockSettings;if(e.hideLockedChats!=null&&(a.hideLockedChats=!!e.hideLockedChats),e.secretCode!=null){if(typeof e.secretCode!="object")throw TypeError(".proto.ChatLockSettings.secretCode: object expected");a.secretCode=p.proto.UserPassword.fromObject(e.secretCode)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.hideLockedChats!=null&&e.hasOwnProperty("hideLockedChats")&&(A.hideLockedChats=e.hideLockedChats,a.oneofs&&(A._hideLockedChats="hideLockedChats")),e.secretCode!=null&&e.hasOwnProperty("secretCode")&&(A.secretCode=p.proto.UserPassword.toObject(e.secretCode,a),a.oneofs&&(A._secretCode="secretCode")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ChatLockSettings"},t})(),n.ChatRowOpaqueData=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.draftMessage=p.proto.ChatRowOpaqueData.DraftMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ChatRowOpaqueData)return e;var a=new p.proto.ChatRowOpaqueData;if(e.draftMessage!=null){if(typeof e.draftMessage!="object")throw TypeError(".proto.ChatRowOpaqueData.draftMessage: object expected");a.draftMessage=p.proto.ChatRowOpaqueData.DraftMessage.fromObject(e.draftMessage)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.draftMessage!=null&&e.hasOwnProperty("draftMessage")&&(A.draftMessage=p.proto.ChatRowOpaqueData.DraftMessage.toObject(e.draftMessage,a),a.oneofs&&(A._draftMessage="draftMessage")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ChatRowOpaqueData"},t.DraftMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.text=A.string();break}case 2:{c.omittedUrl=A.string();break}case 3:{c.ctwaContextLinkData=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData.decode(A,A.uint32());break}case 4:{c.ctwaContext=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.decode(A,A.uint32());break}case 5:{c.timestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ChatRowOpaqueData.DraftMessage)return A;var r=new p.proto.ChatRowOpaqueData.DraftMessage;if(A.text!=null&&(r.text=String(A.text)),A.omittedUrl!=null&&(r.omittedUrl=String(A.omittedUrl)),A.ctwaContextLinkData!=null){if(typeof A.ctwaContextLinkData!="object")throw TypeError(".proto.ChatRowOpaqueData.DraftMessage.ctwaContextLinkData: object expected");r.ctwaContextLinkData=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData.fromObject(A.ctwaContextLinkData)}if(A.ctwaContext!=null){if(typeof A.ctwaContext!="object")throw TypeError(".proto.ChatRowOpaqueData.DraftMessage.ctwaContext: object expected");r.ctwaContext=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.fromObject(A.ctwaContext)}return A.timestamp!=null&&(l.Long?(r.timestamp=l.Long.fromValue(A.timestamp)).unsigned=!1:typeof A.timestamp=="string"?r.timestamp=parseInt(A.timestamp,10):typeof A.timestamp=="number"?r.timestamp=A.timestamp:typeof A.timestamp=="object"&&(r.timestamp=new l.LongBits(A.timestamp.low>>>0,A.timestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),A.omittedUrl!=null&&A.hasOwnProperty("omittedUrl")&&(s.omittedUrl=A.omittedUrl,r.oneofs&&(s._omittedUrl="omittedUrl")),A.ctwaContextLinkData!=null&&A.hasOwnProperty("ctwaContextLinkData")&&(s.ctwaContextLinkData=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData.toObject(A.ctwaContextLinkData,r),r.oneofs&&(s._ctwaContextLinkData="ctwaContextLinkData")),A.ctwaContext!=null&&A.hasOwnProperty("ctwaContext")&&(s.ctwaContext=p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.toObject(A.ctwaContext,r),r.oneofs&&(s._ctwaContext="ctwaContext")),A.timestamp!=null&&A.hasOwnProperty("timestamp")&&(typeof A.timestamp=="number"?s.timestamp=r.longs===String?String(A.timestamp):A.timestamp:s.timestamp=r.longs===String?se(A.timestamp):r.longs===Number?ge(A.timestamp):A.timestamp,r.oneofs&&(s._timestamp="timestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ChatRowOpaqueData.DraftMessage"},i.CtwaContextData=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.conversionSource=s.string();break}case 2:{d.conversionData=s.bytes();break}case 3:{d.sourceUrl=s.string();break}case 4:{d.sourceId=s.string();break}case 5:{d.sourceType=s.string();break}case 6:{d.title=s.string();break}case 7:{d.description=s.string();break}case 8:{d.thumbnail=s.string();break}case 9:{d.thumbnailUrl=s.string();break}case 10:{d.mediaType=s.int32();break}case 11:{d.mediaUrl=s.string();break}case 12:{d.isSuspiciousLink=s.bool();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData)return s;var g=new p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData;switch(s.conversionSource!=null&&(g.conversionSource=String(s.conversionSource)),s.conversionData!=null&&(typeof s.conversionData=="string"?l.base64.decode(s.conversionData,g.conversionData=l.newBuffer(l.base64.length(s.conversionData)),0):s.conversionData.length>=0&&(g.conversionData=s.conversionData)),s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),s.sourceId!=null&&(g.sourceId=String(s.sourceId)),s.sourceType!=null&&(g.sourceType=String(s.sourceType)),s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),s.thumbnail!=null&&(g.thumbnail=String(s.thumbnail)),s.thumbnailUrl!=null&&(g.thumbnailUrl=String(s.thumbnailUrl)),s.mediaType){default:if(typeof s.mediaType=="number"){g.mediaType=s.mediaType;break}break;case"NONE":case 0:g.mediaType=0;break;case"IMAGE":case 1:g.mediaType=1;break;case"VIDEO":case 2:g.mediaType=2;break}return s.mediaUrl!=null&&(g.mediaUrl=String(s.mediaUrl)),s.isSuspiciousLink!=null&&(g.isSuspiciousLink=!!s.isSuspiciousLink),g},a.toObject=function(s,g){g||(g={});var c={};return s.conversionSource!=null&&s.hasOwnProperty("conversionSource")&&(c.conversionSource=s.conversionSource,g.oneofs&&(c._conversionSource="conversionSource")),s.conversionData!=null&&s.hasOwnProperty("conversionData")&&(c.conversionData=g.bytes===String?l.base64.encode(s.conversionData,0,s.conversionData.length):g.bytes===Array?Array.prototype.slice.call(s.conversionData):s.conversionData,g.oneofs&&(c._conversionData="conversionData")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),s.sourceId!=null&&s.hasOwnProperty("sourceId")&&(c.sourceId=s.sourceId,g.oneofs&&(c._sourceId="sourceId")),s.sourceType!=null&&s.hasOwnProperty("sourceType")&&(c.sourceType=s.sourceType,g.oneofs&&(c._sourceType="sourceType")),s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),s.thumbnail!=null&&s.hasOwnProperty("thumbnail")&&(c.thumbnail=s.thumbnail,g.oneofs&&(c._thumbnail="thumbnail")),s.thumbnailUrl!=null&&s.hasOwnProperty("thumbnailUrl")&&(c.thumbnailUrl=s.thumbnailUrl,g.oneofs&&(c._thumbnailUrl="thumbnailUrl")),s.mediaType!=null&&s.hasOwnProperty("mediaType")&&(c.mediaType=g.enums===String?p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.ContextInfoExternalAdReplyInfoMediaType[s.mediaType]===void 0?s.mediaType:p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextData.ContextInfoExternalAdReplyInfoMediaType[s.mediaType]:s.mediaType,g.oneofs&&(c._mediaType="mediaType")),s.mediaUrl!=null&&s.hasOwnProperty("mediaUrl")&&(c.mediaUrl=s.mediaUrl,g.oneofs&&(c._mediaUrl="mediaUrl")),s.isSuspiciousLink!=null&&s.hasOwnProperty("isSuspiciousLink")&&(c.isSuspiciousLink=s.isSuspiciousLink,g.oneofs&&(c._isSuspiciousLink="isSuspiciousLink")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ChatRowOpaqueData.DraftMessage.CtwaContextData"},a.ContextInfoExternalAdReplyInfoMediaType=(function(){let r={},s=Object.create(r);return s[r[0]="NONE"]=0,s[r[1]="IMAGE"]=1,s[r[2]="VIDEO"]=2,s})(),a})(),i.CtwaContextLinkData=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.context=s.string();break}case 2:{d.sourceUrl=s.string();break}case 3:{d.icebreaker=s.string();break}case 4:{d.phone=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData)return s;var g=new p.proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData;return s.context!=null&&(g.context=String(s.context)),s.sourceUrl!=null&&(g.sourceUrl=String(s.sourceUrl)),s.icebreaker!=null&&(g.icebreaker=String(s.icebreaker)),s.phone!=null&&(g.phone=String(s.phone)),g},a.toObject=function(s,g){g||(g={});var c={};return s.context!=null&&s.hasOwnProperty("context")&&(c.context=s.context,g.oneofs&&(c._context="context")),s.sourceUrl!=null&&s.hasOwnProperty("sourceUrl")&&(c.sourceUrl=s.sourceUrl,g.oneofs&&(c._sourceUrl="sourceUrl")),s.icebreaker!=null&&s.hasOwnProperty("icebreaker")&&(c.icebreaker=s.icebreaker,g.oneofs&&(c._icebreaker="icebreaker")),s.phone!=null&&s.hasOwnProperty("phone")&&(c.phone=s.phone,g.oneofs&&(c._phone="phone")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ChatRowOpaqueData.DraftMessage.CtwaContextLinkData"},a})(),i})(),t})(),n.Citation=(function(){function t(o){if(o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.title=i.string();break}case 2:{r.subtitle=i.string();break}case 3:{r.cmsId=i.string();break}case 4:{r.imageUrl=i.string();break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.Citation)return i;var e=new p.proto.Citation;return i.title!=null&&(e.title=String(i.title)),i.subtitle!=null&&(e.subtitle=String(i.subtitle)),i.cmsId!=null&&(e.cmsId=String(i.cmsId)),i.imageUrl!=null&&(e.imageUrl=String(i.imageUrl)),e},t.toObject=function(i,e){e||(e={});var a={};return e.defaults&&(a.title="",a.subtitle="",a.cmsId="",a.imageUrl=""),i.title!=null&&i.hasOwnProperty("title")&&(a.title=i.title),i.subtitle!=null&&i.hasOwnProperty("subtitle")&&(a.subtitle=i.subtitle),i.cmsId!=null&&i.hasOwnProperty("cmsId")&&(a.cmsId=i.cmsId),i.imageUrl!=null&&i.hasOwnProperty("imageUrl")&&(a.imageUrl=i.imageUrl),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(i){return i===void 0&&(i="type.googleapis.com"),i+"/proto.Citation"},t})(),n.ClientPairingProps=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.isChatDbLidMigrated=e.bool();break}case 2:{s.isSyncdPureLidSession=e.bool();break}case 3:{s.isSyncdSnapshotRecoveryEnabled=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ClientPairingProps)return e;var a=new p.proto.ClientPairingProps;return e.isChatDbLidMigrated!=null&&(a.isChatDbLidMigrated=!!e.isChatDbLidMigrated),e.isSyncdPureLidSession!=null&&(a.isSyncdPureLidSession=!!e.isSyncdPureLidSession),e.isSyncdSnapshotRecoveryEnabled!=null&&(a.isSyncdSnapshotRecoveryEnabled=!!e.isSyncdSnapshotRecoveryEnabled),a},t.toObject=function(e,a){a||(a={});var A={};return e.isChatDbLidMigrated!=null&&e.hasOwnProperty("isChatDbLidMigrated")&&(A.isChatDbLidMigrated=e.isChatDbLidMigrated,a.oneofs&&(A._isChatDbLidMigrated="isChatDbLidMigrated")),e.isSyncdPureLidSession!=null&&e.hasOwnProperty("isSyncdPureLidSession")&&(A.isSyncdPureLidSession=e.isSyncdPureLidSession,a.oneofs&&(A._isSyncdPureLidSession="isSyncdPureLidSession")),e.isSyncdSnapshotRecoveryEnabled!=null&&e.hasOwnProperty("isSyncdSnapshotRecoveryEnabled")&&(A.isSyncdSnapshotRecoveryEnabled=e.isSyncdSnapshotRecoveryEnabled,a.oneofs&&(A._isSyncdSnapshotRecoveryEnabled="isSyncdSnapshotRecoveryEnabled")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ClientPairingProps"},t})(),n.ClientPayload=(function(){function t(i){if(this.shards=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.username=e.uint64();break}case 3:{s.passive=e.bool();break}case 5:{s.userAgent=p.proto.ClientPayload.UserAgent.decode(e,e.uint32());break}case 6:{s.webInfo=p.proto.ClientPayload.WebInfo.decode(e,e.uint32());break}case 7:{s.pushName=e.string();break}case 9:{s.sessionId=e.sfixed32();break}case 10:{s.shortConnect=e.bool();break}case 12:{s.connectType=e.int32();break}case 13:{s.connectReason=e.int32();break}case 14:{if(s.shards&&s.shards.length||(s.shards=[]),(g&7)===2)for(var c=e.uint32()+e.pos;e.pos>>0,e.username.high>>>0).toNumber(!0))),e.passive!=null&&(a.passive=!!e.passive),e.userAgent!=null){if(typeof e.userAgent!="object")throw TypeError(".proto.ClientPayload.userAgent: object expected");a.userAgent=p.proto.ClientPayload.UserAgent.fromObject(e.userAgent)}if(e.webInfo!=null){if(typeof e.webInfo!="object")throw TypeError(".proto.ClientPayload.webInfo: object expected");a.webInfo=p.proto.ClientPayload.WebInfo.fromObject(e.webInfo)}switch(e.pushName!=null&&(a.pushName=String(e.pushName)),e.sessionId!=null&&(a.sessionId=e.sessionId|0),e.shortConnect!=null&&(a.shortConnect=!!e.shortConnect),e.connectType){default:if(typeof e.connectType=="number"){a.connectType=e.connectType;break}break;case"CELLULAR_UNKNOWN":case 0:a.connectType=0;break;case"WIFI_UNKNOWN":case 1:a.connectType=1;break;case"CELLULAR_EDGE":case 100:a.connectType=100;break;case"CELLULAR_IDEN":case 101:a.connectType=101;break;case"CELLULAR_UMTS":case 102:a.connectType=102;break;case"CELLULAR_EVDO":case 103:a.connectType=103;break;case"CELLULAR_GPRS":case 104:a.connectType=104;break;case"CELLULAR_HSDPA":case 105:a.connectType=105;break;case"CELLULAR_HSUPA":case 106:a.connectType=106;break;case"CELLULAR_HSPA":case 107:a.connectType=107;break;case"CELLULAR_CDMA":case 108:a.connectType=108;break;case"CELLULAR_1XRTT":case 109:a.connectType=109;break;case"CELLULAR_EHRPD":case 110:a.connectType=110;break;case"CELLULAR_LTE":case 111:a.connectType=111;break;case"CELLULAR_HSPAP":case 112:a.connectType=112;break}switch(e.connectReason){default:if(typeof e.connectReason=="number"){a.connectReason=e.connectReason;break}break;case"PUSH":case 0:a.connectReason=0;break;case"USER_ACTIVATED":case 1:a.connectReason=1;break;case"SCHEDULED":case 2:a.connectReason=2;break;case"ERROR_RECONNECT":case 3:a.connectReason=3;break;case"NETWORK_SWITCH":case 4:a.connectReason=4;break;case"PING_RECONNECT":case 5:a.connectReason=5;break;case"UNKNOWN":case 6:a.connectReason=6;break}if(e.shards){if(!Array.isArray(e.shards))throw TypeError(".proto.ClientPayload.shards: array expected");a.shards=[];for(var A=0;A>>0),e.device!=null&&(a.device=e.device>>>0),e.devicePairingData!=null){if(typeof e.devicePairingData!="object")throw TypeError(".proto.ClientPayload.devicePairingData: object expected");a.devicePairingData=p.proto.ClientPayload.DevicePairingRegistrationData.fromObject(e.devicePairingData)}switch(e.product){default:if(typeof e.product=="number"){a.product=e.product;break}break;case"WHATSAPP":case 0:a.product=0;break;case"MESSENGER":case 1:a.product=1;break;case"INTEROP":case 2:a.product=2;break;case"INTEROP_MSGR":case 3:a.product=3;break;case"WHATSAPP_LID":case 4:a.product=4;break}switch(e.fbCat!=null&&(typeof e.fbCat=="string"?l.base64.decode(e.fbCat,a.fbCat=l.newBuffer(l.base64.length(e.fbCat)),0):e.fbCat.length>=0&&(a.fbCat=e.fbCat)),e.fbUserAgent!=null&&(typeof e.fbUserAgent=="string"?l.base64.decode(e.fbUserAgent,a.fbUserAgent=l.newBuffer(l.base64.length(e.fbUserAgent)),0):e.fbUserAgent.length>=0&&(a.fbUserAgent=e.fbUserAgent)),e.oc!=null&&(a.oc=!!e.oc),e.lc!=null&&(a.lc=e.lc|0),e.iosAppExtension){default:if(typeof e.iosAppExtension=="number"){a.iosAppExtension=e.iosAppExtension;break}break;case"SHARE_EXTENSION":case 0:a.iosAppExtension=0;break;case"SERVICE_EXTENSION":case 1:a.iosAppExtension=1;break;case"INTENTS_EXTENSION":case 2:a.iosAppExtension=2;break}if(e.fbAppId!=null&&(l.Long?(a.fbAppId=l.Long.fromValue(e.fbAppId)).unsigned=!0:typeof e.fbAppId=="string"?a.fbAppId=parseInt(e.fbAppId,10):typeof e.fbAppId=="number"?a.fbAppId=e.fbAppId:typeof e.fbAppId=="object"&&(a.fbAppId=new l.LongBits(e.fbAppId.low>>>0,e.fbAppId.high>>>0).toNumber(!0))),e.fbDeviceId!=null&&(typeof e.fbDeviceId=="string"?l.base64.decode(e.fbDeviceId,a.fbDeviceId=l.newBuffer(l.base64.length(e.fbDeviceId)),0):e.fbDeviceId.length>=0&&(a.fbDeviceId=e.fbDeviceId)),e.pull!=null&&(a.pull=!!e.pull),e.paddingBytes!=null&&(typeof e.paddingBytes=="string"?l.base64.decode(e.paddingBytes,a.paddingBytes=l.newBuffer(l.base64.length(e.paddingBytes)),0):e.paddingBytes.length>=0&&(a.paddingBytes=e.paddingBytes)),e.yearClass!=null&&(a.yearClass=e.yearClass|0),e.memClass!=null&&(a.memClass=e.memClass|0),e.interopData!=null){if(typeof e.interopData!="object")throw TypeError(".proto.ClientPayload.interopData: object expected");a.interopData=p.proto.ClientPayload.InteropData.fromObject(e.interopData)}switch(e.trafficAnonymization){default:if(typeof e.trafficAnonymization=="number"){a.trafficAnonymization=e.trafficAnonymization;break}break;case"OFF":case 0:a.trafficAnonymization=0;break;case"STANDARD":case 1:a.trafficAnonymization=1;break}switch(e.lidDbMigrated!=null&&(a.lidDbMigrated=!!e.lidDbMigrated),e.accountType){default:if(typeof e.accountType=="number"){a.accountType=e.accountType;break}break;case"DEFAULT":case 0:a.accountType=0;break;case"GUEST":case 1:a.accountType=1;break}return e.connectionSequenceInfo!=null&&(a.connectionSequenceInfo=e.connectionSequenceInfo|0),e.paaLink!=null&&(a.paaLink=!!e.paaLink),e.preacksCount!=null&&(a.preacksCount=e.preacksCount|0),e.processingQueueSize!=null&&(a.processingQueueSize=e.processingQueueSize|0),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.shards=[]),e.username!=null&&e.hasOwnProperty("username")&&(typeof e.username=="number"?A.username=a.longs===String?String(e.username):e.username:A.username=a.longs===String?se(e.username,!0):a.longs===Number?ge(e.username,!0):e.username,a.oneofs&&(A._username="username")),e.passive!=null&&e.hasOwnProperty("passive")&&(A.passive=e.passive,a.oneofs&&(A._passive="passive")),e.userAgent!=null&&e.hasOwnProperty("userAgent")&&(A.userAgent=p.proto.ClientPayload.UserAgent.toObject(e.userAgent,a),a.oneofs&&(A._userAgent="userAgent")),e.webInfo!=null&&e.hasOwnProperty("webInfo")&&(A.webInfo=p.proto.ClientPayload.WebInfo.toObject(e.webInfo,a),a.oneofs&&(A._webInfo="webInfo")),e.pushName!=null&&e.hasOwnProperty("pushName")&&(A.pushName=e.pushName,a.oneofs&&(A._pushName="pushName")),e.sessionId!=null&&e.hasOwnProperty("sessionId")&&(A.sessionId=e.sessionId,a.oneofs&&(A._sessionId="sessionId")),e.shortConnect!=null&&e.hasOwnProperty("shortConnect")&&(A.shortConnect=e.shortConnect,a.oneofs&&(A._shortConnect="shortConnect")),e.connectType!=null&&e.hasOwnProperty("connectType")&&(A.connectType=a.enums===String?p.proto.ClientPayload.ConnectType[e.connectType]===void 0?e.connectType:p.proto.ClientPayload.ConnectType[e.connectType]:e.connectType,a.oneofs&&(A._connectType="connectType")),e.connectReason!=null&&e.hasOwnProperty("connectReason")&&(A.connectReason=a.enums===String?p.proto.ClientPayload.ConnectReason[e.connectReason]===void 0?e.connectReason:p.proto.ClientPayload.ConnectReason[e.connectReason]:e.connectReason,a.oneofs&&(A._connectReason="connectReason")),e.shards&&e.shards.length){A.shards=[];for(var r=0;r>>3){case 15:{c.dnsMethod=A.int32();break}case 16:{c.appCached=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ClientPayload.DNSSource)return A;var r=new p.proto.ClientPayload.DNSSource;switch(A.dnsMethod){default:if(typeof A.dnsMethod=="number"){r.dnsMethod=A.dnsMethod;break}break;case"SYSTEM":case 0:r.dnsMethod=0;break;case"GOOGLE":case 1:r.dnsMethod=1;break;case"HARDCODED":case 2:r.dnsMethod=2;break;case"OVERRIDE":case 3:r.dnsMethod=3;break;case"FALLBACK":case 4:r.dnsMethod=4;break;case"MNS":case 5:r.dnsMethod=5;break}return A.appCached!=null&&(r.appCached=!!A.appCached),r},i.toObject=function(A,r){r||(r={});var s={};return A.dnsMethod!=null&&A.hasOwnProperty("dnsMethod")&&(s.dnsMethod=r.enums===String?p.proto.ClientPayload.DNSSource.DNSResolutionMethod[A.dnsMethod]===void 0?A.dnsMethod:p.proto.ClientPayload.DNSSource.DNSResolutionMethod[A.dnsMethod]:A.dnsMethod,r.oneofs&&(s._dnsMethod="dnsMethod")),A.appCached!=null&&A.hasOwnProperty("appCached")&&(s.appCached=A.appCached,r.oneofs&&(s._appCached="appCached")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.DNSSource"},i.DNSResolutionMethod=(function(){let a={},A=Object.create(a);return A[a[0]="SYSTEM"]=0,A[a[1]="GOOGLE"]=1,A[a[2]="HARDCODED"]=2,A[a[3]="OVERRIDE"]=3,A[a[4]="FALLBACK"]=4,A[a[5]="MNS"]=5,A})(),i})(),t.DevicePairingRegistrationData=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.eRegid=A.bytes();break}case 2:{c.eKeytype=A.bytes();break}case 3:{c.eIdent=A.bytes();break}case 4:{c.eSkeyId=A.bytes();break}case 5:{c.eSkeyVal=A.bytes();break}case 6:{c.eSkeySig=A.bytes();break}case 7:{c.buildHash=A.bytes();break}case 8:{c.deviceProps=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ClientPayload.DevicePairingRegistrationData)return A;var r=new p.proto.ClientPayload.DevicePairingRegistrationData;return A.eRegid!=null&&(typeof A.eRegid=="string"?l.base64.decode(A.eRegid,r.eRegid=l.newBuffer(l.base64.length(A.eRegid)),0):A.eRegid.length>=0&&(r.eRegid=A.eRegid)),A.eKeytype!=null&&(typeof A.eKeytype=="string"?l.base64.decode(A.eKeytype,r.eKeytype=l.newBuffer(l.base64.length(A.eKeytype)),0):A.eKeytype.length>=0&&(r.eKeytype=A.eKeytype)),A.eIdent!=null&&(typeof A.eIdent=="string"?l.base64.decode(A.eIdent,r.eIdent=l.newBuffer(l.base64.length(A.eIdent)),0):A.eIdent.length>=0&&(r.eIdent=A.eIdent)),A.eSkeyId!=null&&(typeof A.eSkeyId=="string"?l.base64.decode(A.eSkeyId,r.eSkeyId=l.newBuffer(l.base64.length(A.eSkeyId)),0):A.eSkeyId.length>=0&&(r.eSkeyId=A.eSkeyId)),A.eSkeyVal!=null&&(typeof A.eSkeyVal=="string"?l.base64.decode(A.eSkeyVal,r.eSkeyVal=l.newBuffer(l.base64.length(A.eSkeyVal)),0):A.eSkeyVal.length>=0&&(r.eSkeyVal=A.eSkeyVal)),A.eSkeySig!=null&&(typeof A.eSkeySig=="string"?l.base64.decode(A.eSkeySig,r.eSkeySig=l.newBuffer(l.base64.length(A.eSkeySig)),0):A.eSkeySig.length>=0&&(r.eSkeySig=A.eSkeySig)),A.buildHash!=null&&(typeof A.buildHash=="string"?l.base64.decode(A.buildHash,r.buildHash=l.newBuffer(l.base64.length(A.buildHash)),0):A.buildHash.length>=0&&(r.buildHash=A.buildHash)),A.deviceProps!=null&&(typeof A.deviceProps=="string"?l.base64.decode(A.deviceProps,r.deviceProps=l.newBuffer(l.base64.length(A.deviceProps)),0):A.deviceProps.length>=0&&(r.deviceProps=A.deviceProps)),r},i.toObject=function(A,r){r||(r={});var s={};return A.eRegid!=null&&A.hasOwnProperty("eRegid")&&(s.eRegid=r.bytes===String?l.base64.encode(A.eRegid,0,A.eRegid.length):r.bytes===Array?Array.prototype.slice.call(A.eRegid):A.eRegid,r.oneofs&&(s._eRegid="eRegid")),A.eKeytype!=null&&A.hasOwnProperty("eKeytype")&&(s.eKeytype=r.bytes===String?l.base64.encode(A.eKeytype,0,A.eKeytype.length):r.bytes===Array?Array.prototype.slice.call(A.eKeytype):A.eKeytype,r.oneofs&&(s._eKeytype="eKeytype")),A.eIdent!=null&&A.hasOwnProperty("eIdent")&&(s.eIdent=r.bytes===String?l.base64.encode(A.eIdent,0,A.eIdent.length):r.bytes===Array?Array.prototype.slice.call(A.eIdent):A.eIdent,r.oneofs&&(s._eIdent="eIdent")),A.eSkeyId!=null&&A.hasOwnProperty("eSkeyId")&&(s.eSkeyId=r.bytes===String?l.base64.encode(A.eSkeyId,0,A.eSkeyId.length):r.bytes===Array?Array.prototype.slice.call(A.eSkeyId):A.eSkeyId,r.oneofs&&(s._eSkeyId="eSkeyId")),A.eSkeyVal!=null&&A.hasOwnProperty("eSkeyVal")&&(s.eSkeyVal=r.bytes===String?l.base64.encode(A.eSkeyVal,0,A.eSkeyVal.length):r.bytes===Array?Array.prototype.slice.call(A.eSkeyVal):A.eSkeyVal,r.oneofs&&(s._eSkeyVal="eSkeyVal")),A.eSkeySig!=null&&A.hasOwnProperty("eSkeySig")&&(s.eSkeySig=r.bytes===String?l.base64.encode(A.eSkeySig,0,A.eSkeySig.length):r.bytes===Array?Array.prototype.slice.call(A.eSkeySig):A.eSkeySig,r.oneofs&&(s._eSkeySig="eSkeySig")),A.buildHash!=null&&A.hasOwnProperty("buildHash")&&(s.buildHash=r.bytes===String?l.base64.encode(A.buildHash,0,A.buildHash.length):r.bytes===Array?Array.prototype.slice.call(A.buildHash):A.buildHash,r.oneofs&&(s._buildHash="buildHash")),A.deviceProps!=null&&A.hasOwnProperty("deviceProps")&&(s.deviceProps=r.bytes===String?l.base64.encode(A.deviceProps,0,A.deviceProps.length):r.bytes===Array?Array.prototype.slice.call(A.deviceProps):A.deviceProps,r.oneofs&&(s._deviceProps="deviceProps")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.DevicePairingRegistrationData"},i})(),t.IOSAppExtension=(function(){let i={},e=Object.create(i);return e[i[0]="SHARE_EXTENSION"]=0,e[i[1]="SERVICE_EXTENSION"]=1,e[i[2]="INTENTS_EXTENSION"]=2,e})(),t.InteropData=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.accountId=A.uint64();break}case 2:{c.token=A.bytes();break}case 3:{c.enableReadReceipts=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ClientPayload.InteropData)return A;var r=new p.proto.ClientPayload.InteropData;return A.accountId!=null&&(l.Long?(r.accountId=l.Long.fromValue(A.accountId)).unsigned=!0:typeof A.accountId=="string"?r.accountId=parseInt(A.accountId,10):typeof A.accountId=="number"?r.accountId=A.accountId:typeof A.accountId=="object"&&(r.accountId=new l.LongBits(A.accountId.low>>>0,A.accountId.high>>>0).toNumber(!0))),A.token!=null&&(typeof A.token=="string"?l.base64.decode(A.token,r.token=l.newBuffer(l.base64.length(A.token)),0):A.token.length>=0&&(r.token=A.token)),A.enableReadReceipts!=null&&(r.enableReadReceipts=!!A.enableReadReceipts),r},i.toObject=function(A,r){r||(r={});var s={};return A.accountId!=null&&A.hasOwnProperty("accountId")&&(typeof A.accountId=="number"?s.accountId=r.longs===String?String(A.accountId):A.accountId:s.accountId=r.longs===String?se(A.accountId,!0):r.longs===Number?ge(A.accountId,!0):A.accountId,r.oneofs&&(s._accountId="accountId")),A.token!=null&&A.hasOwnProperty("token")&&(s.token=r.bytes===String?l.base64.encode(A.token,0,A.token.length):r.bytes===Array?Array.prototype.slice.call(A.token):A.token,r.oneofs&&(s._token="token")),A.enableReadReceipts!=null&&A.hasOwnProperty("enableReadReceipts")&&(s.enableReadReceipts=A.enableReadReceipts,r.oneofs&&(s._enableReadReceipts="enableReadReceipts")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.InteropData"},i})(),t.Product=(function(){let i={},e=Object.create(i);return e[i[0]="WHATSAPP"]=0,e[i[1]="MESSENGER"]=1,e[i[2]="INTEROP"]=2,e[i[3]="INTEROP_MSGR"]=3,e[i[4]="WHATSAPP_LID"]=4,e})(),t.TrafficAnonymization=(function(){let i={},e=Object.create(i);return e[i[0]="OFF"]=0,e[i[1]="STANDARD"]=1,e})(),t.UserAgent=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.platform=A.int32();break}case 2:{c.appVersion=p.proto.ClientPayload.UserAgent.AppVersion.decode(A,A.uint32());break}case 3:{c.mcc=A.string();break}case 4:{c.mnc=A.string();break}case 5:{c.osVersion=A.string();break}case 6:{c.manufacturer=A.string();break}case 7:{c.device=A.string();break}case 8:{c.osBuildNumber=A.string();break}case 9:{c.phoneId=A.string();break}case 10:{c.releaseChannel=A.int32();break}case 11:{c.localeLanguageIso6391=A.string();break}case 12:{c.localeCountryIso31661Alpha2=A.string();break}case 13:{c.deviceBoard=A.string();break}case 14:{c.deviceExpId=A.string();break}case 15:{c.deviceType=A.int32();break}case 16:{c.deviceModelType=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ClientPayload.UserAgent)return A;var r=new p.proto.ClientPayload.UserAgent;switch(A.platform){default:if(typeof A.platform=="number"){r.platform=A.platform;break}break;case"ANDROID":case 0:r.platform=0;break;case"IOS":case 1:r.platform=1;break;case"WINDOWS_PHONE":case 2:r.platform=2;break;case"BLACKBERRY":case 3:r.platform=3;break;case"BLACKBERRYX":case 4:r.platform=4;break;case"S40":case 5:r.platform=5;break;case"S60":case 6:r.platform=6;break;case"PYTHON_CLIENT":case 7:r.platform=7;break;case"TIZEN":case 8:r.platform=8;break;case"ENTERPRISE":case 9:r.platform=9;break;case"SMB_ANDROID":case 10:r.platform=10;break;case"KAIOS":case 11:r.platform=11;break;case"SMB_IOS":case 12:r.platform=12;break;case"WINDOWS":case 13:r.platform=13;break;case"WEB":case 14:r.platform=14;break;case"PORTAL":case 15:r.platform=15;break;case"GREEN_ANDROID":case 16:r.platform=16;break;case"GREEN_IPHONE":case 17:r.platform=17;break;case"BLUE_ANDROID":case 18:r.platform=18;break;case"BLUE_IPHONE":case 19:r.platform=19;break;case"FBLITE_ANDROID":case 20:r.platform=20;break;case"MLITE_ANDROID":case 21:r.platform=21;break;case"IGLITE_ANDROID":case 22:r.platform=22;break;case"PAGE":case 23:r.platform=23;break;case"MACOS":case 24:r.platform=24;break;case"OCULUS_MSG":case 25:r.platform=25;break;case"OCULUS_CALL":case 26:r.platform=26;break;case"MILAN":case 27:r.platform=27;break;case"CAPI":case 28:r.platform=28;break;case"WEAROS":case 29:r.platform=29;break;case"ARDEVICE":case 30:r.platform=30;break;case"VRDEVICE":case 31:r.platform=31;break;case"BLUE_WEB":case 32:r.platform=32;break;case"IPAD":case 33:r.platform=33;break;case"TEST":case 34:r.platform=34;break;case"SMART_GLASSES":case 35:r.platform=35;break;case"BLUE_VR":case 36:r.platform=36;break;case"AR_WRIST":case 37:r.platform=37;break}if(A.appVersion!=null){if(typeof A.appVersion!="object")throw TypeError(".proto.ClientPayload.UserAgent.appVersion: object expected");r.appVersion=p.proto.ClientPayload.UserAgent.AppVersion.fromObject(A.appVersion)}switch(A.mcc!=null&&(r.mcc=String(A.mcc)),A.mnc!=null&&(r.mnc=String(A.mnc)),A.osVersion!=null&&(r.osVersion=String(A.osVersion)),A.manufacturer!=null&&(r.manufacturer=String(A.manufacturer)),A.device!=null&&(r.device=String(A.device)),A.osBuildNumber!=null&&(r.osBuildNumber=String(A.osBuildNumber)),A.phoneId!=null&&(r.phoneId=String(A.phoneId)),A.releaseChannel){default:if(typeof A.releaseChannel=="number"){r.releaseChannel=A.releaseChannel;break}break;case"RELEASE":case 0:r.releaseChannel=0;break;case"BETA":case 1:r.releaseChannel=1;break;case"ALPHA":case 2:r.releaseChannel=2;break;case"DEBUG":case 3:r.releaseChannel=3;break}switch(A.localeLanguageIso6391!=null&&(r.localeLanguageIso6391=String(A.localeLanguageIso6391)),A.localeCountryIso31661Alpha2!=null&&(r.localeCountryIso31661Alpha2=String(A.localeCountryIso31661Alpha2)),A.deviceBoard!=null&&(r.deviceBoard=String(A.deviceBoard)),A.deviceExpId!=null&&(r.deviceExpId=String(A.deviceExpId)),A.deviceType){default:if(typeof A.deviceType=="number"){r.deviceType=A.deviceType;break}break;case"PHONE":case 0:r.deviceType=0;break;case"TABLET":case 1:r.deviceType=1;break;case"DESKTOP":case 2:r.deviceType=2;break;case"WEARABLE":case 3:r.deviceType=3;break;case"VR":case 4:r.deviceType=4;break}return A.deviceModelType!=null&&(r.deviceModelType=String(A.deviceModelType)),r},i.toObject=function(A,r){r||(r={});var s={};return A.platform!=null&&A.hasOwnProperty("platform")&&(s.platform=r.enums===String?p.proto.ClientPayload.UserAgent.Platform[A.platform]===void 0?A.platform:p.proto.ClientPayload.UserAgent.Platform[A.platform]:A.platform,r.oneofs&&(s._platform="platform")),A.appVersion!=null&&A.hasOwnProperty("appVersion")&&(s.appVersion=p.proto.ClientPayload.UserAgent.AppVersion.toObject(A.appVersion,r),r.oneofs&&(s._appVersion="appVersion")),A.mcc!=null&&A.hasOwnProperty("mcc")&&(s.mcc=A.mcc,r.oneofs&&(s._mcc="mcc")),A.mnc!=null&&A.hasOwnProperty("mnc")&&(s.mnc=A.mnc,r.oneofs&&(s._mnc="mnc")),A.osVersion!=null&&A.hasOwnProperty("osVersion")&&(s.osVersion=A.osVersion,r.oneofs&&(s._osVersion="osVersion")),A.manufacturer!=null&&A.hasOwnProperty("manufacturer")&&(s.manufacturer=A.manufacturer,r.oneofs&&(s._manufacturer="manufacturer")),A.device!=null&&A.hasOwnProperty("device")&&(s.device=A.device,r.oneofs&&(s._device="device")),A.osBuildNumber!=null&&A.hasOwnProperty("osBuildNumber")&&(s.osBuildNumber=A.osBuildNumber,r.oneofs&&(s._osBuildNumber="osBuildNumber")),A.phoneId!=null&&A.hasOwnProperty("phoneId")&&(s.phoneId=A.phoneId,r.oneofs&&(s._phoneId="phoneId")),A.releaseChannel!=null&&A.hasOwnProperty("releaseChannel")&&(s.releaseChannel=r.enums===String?p.proto.ClientPayload.UserAgent.ReleaseChannel[A.releaseChannel]===void 0?A.releaseChannel:p.proto.ClientPayload.UserAgent.ReleaseChannel[A.releaseChannel]:A.releaseChannel,r.oneofs&&(s._releaseChannel="releaseChannel")),A.localeLanguageIso6391!=null&&A.hasOwnProperty("localeLanguageIso6391")&&(s.localeLanguageIso6391=A.localeLanguageIso6391,r.oneofs&&(s._localeLanguageIso6391="localeLanguageIso6391")),A.localeCountryIso31661Alpha2!=null&&A.hasOwnProperty("localeCountryIso31661Alpha2")&&(s.localeCountryIso31661Alpha2=A.localeCountryIso31661Alpha2,r.oneofs&&(s._localeCountryIso31661Alpha2="localeCountryIso31661Alpha2")),A.deviceBoard!=null&&A.hasOwnProperty("deviceBoard")&&(s.deviceBoard=A.deviceBoard,r.oneofs&&(s._deviceBoard="deviceBoard")),A.deviceExpId!=null&&A.hasOwnProperty("deviceExpId")&&(s.deviceExpId=A.deviceExpId,r.oneofs&&(s._deviceExpId="deviceExpId")),A.deviceType!=null&&A.hasOwnProperty("deviceType")&&(s.deviceType=r.enums===String?p.proto.ClientPayload.UserAgent.DeviceType[A.deviceType]===void 0?A.deviceType:p.proto.ClientPayload.UserAgent.DeviceType[A.deviceType]:A.deviceType,r.oneofs&&(s._deviceType="deviceType")),A.deviceModelType!=null&&A.hasOwnProperty("deviceModelType")&&(s.deviceModelType=A.deviceModelType,r.oneofs&&(s._deviceModelType="deviceModelType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.UserAgent"},i.AppVersion=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.primary=s.uint32();break}case 2:{d.secondary=s.uint32();break}case 3:{d.tertiary=s.uint32();break}case 4:{d.quaternary=s.uint32();break}case 5:{d.quinary=s.uint32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.ClientPayload.UserAgent.AppVersion)return s;var g=new p.proto.ClientPayload.UserAgent.AppVersion;return s.primary!=null&&(g.primary=s.primary>>>0),s.secondary!=null&&(g.secondary=s.secondary>>>0),s.tertiary!=null&&(g.tertiary=s.tertiary>>>0),s.quaternary!=null&&(g.quaternary=s.quaternary>>>0),s.quinary!=null&&(g.quinary=s.quinary>>>0),g},a.toObject=function(s,g){g||(g={});var c={};return s.primary!=null&&s.hasOwnProperty("primary")&&(c.primary=s.primary,g.oneofs&&(c._primary="primary")),s.secondary!=null&&s.hasOwnProperty("secondary")&&(c.secondary=s.secondary,g.oneofs&&(c._secondary="secondary")),s.tertiary!=null&&s.hasOwnProperty("tertiary")&&(c.tertiary=s.tertiary,g.oneofs&&(c._tertiary="tertiary")),s.quaternary!=null&&s.hasOwnProperty("quaternary")&&(c.quaternary=s.quaternary,g.oneofs&&(c._quaternary="quaternary")),s.quinary!=null&&s.hasOwnProperty("quinary")&&(c.quinary=s.quinary,g.oneofs&&(c._quinary="quinary")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ClientPayload.UserAgent.AppVersion"},a})(),i.DeviceType=(function(){let a={},A=Object.create(a);return A[a[0]="PHONE"]=0,A[a[1]="TABLET"]=1,A[a[2]="DESKTOP"]=2,A[a[3]="WEARABLE"]=3,A[a[4]="VR"]=4,A})(),i.Platform=(function(){let a={},A=Object.create(a);return A[a[0]="ANDROID"]=0,A[a[1]="IOS"]=1,A[a[2]="WINDOWS_PHONE"]=2,A[a[3]="BLACKBERRY"]=3,A[a[4]="BLACKBERRYX"]=4,A[a[5]="S40"]=5,A[a[6]="S60"]=6,A[a[7]="PYTHON_CLIENT"]=7,A[a[8]="TIZEN"]=8,A[a[9]="ENTERPRISE"]=9,A[a[10]="SMB_ANDROID"]=10,A[a[11]="KAIOS"]=11,A[a[12]="SMB_IOS"]=12,A[a[13]="WINDOWS"]=13,A[a[14]="WEB"]=14,A[a[15]="PORTAL"]=15,A[a[16]="GREEN_ANDROID"]=16,A[a[17]="GREEN_IPHONE"]=17,A[a[18]="BLUE_ANDROID"]=18,A[a[19]="BLUE_IPHONE"]=19,A[a[20]="FBLITE_ANDROID"]=20,A[a[21]="MLITE_ANDROID"]=21,A[a[22]="IGLITE_ANDROID"]=22,A[a[23]="PAGE"]=23,A[a[24]="MACOS"]=24,A[a[25]="OCULUS_MSG"]=25,A[a[26]="OCULUS_CALL"]=26,A[a[27]="MILAN"]=27,A[a[28]="CAPI"]=28,A[a[29]="WEAROS"]=29,A[a[30]="ARDEVICE"]=30,A[a[31]="VRDEVICE"]=31,A[a[32]="BLUE_WEB"]=32,A[a[33]="IPAD"]=33,A[a[34]="TEST"]=34,A[a[35]="SMART_GLASSES"]=35,A[a[36]="BLUE_VR"]=36,A[a[37]="AR_WRIST"]=37,A})(),i.ReleaseChannel=(function(){let a={},A=Object.create(a);return A[a[0]="RELEASE"]=0,A[a[1]="BETA"]=1,A[a[2]="ALPHA"]=2,A[a[3]="DEBUG"]=3,A})(),i})(),t.WebInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.refToken=A.string();break}case 2:{c.version=A.string();break}case 3:{c.webdPayload=p.proto.ClientPayload.WebInfo.WebdPayload.decode(A,A.uint32());break}case 4:{c.webSubPlatform=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ClientPayload.WebInfo)return A;var r=new p.proto.ClientPayload.WebInfo;if(A.refToken!=null&&(r.refToken=String(A.refToken)),A.version!=null&&(r.version=String(A.version)),A.webdPayload!=null){if(typeof A.webdPayload!="object")throw TypeError(".proto.ClientPayload.WebInfo.webdPayload: object expected");r.webdPayload=p.proto.ClientPayload.WebInfo.WebdPayload.fromObject(A.webdPayload)}switch(A.webSubPlatform){default:if(typeof A.webSubPlatform=="number"){r.webSubPlatform=A.webSubPlatform;break}break;case"WEB_BROWSER":case 0:r.webSubPlatform=0;break;case"APP_STORE":case 1:r.webSubPlatform=1;break;case"WIN_STORE":case 2:r.webSubPlatform=2;break;case"DARWIN":case 3:r.webSubPlatform=3;break;case"WIN32":case 4:r.webSubPlatform=4;break;case"WIN_HYBRID":case 5:r.webSubPlatform=5;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.refToken!=null&&A.hasOwnProperty("refToken")&&(s.refToken=A.refToken,r.oneofs&&(s._refToken="refToken")),A.version!=null&&A.hasOwnProperty("version")&&(s.version=A.version,r.oneofs&&(s._version="version")),A.webdPayload!=null&&A.hasOwnProperty("webdPayload")&&(s.webdPayload=p.proto.ClientPayload.WebInfo.WebdPayload.toObject(A.webdPayload,r),r.oneofs&&(s._webdPayload="webdPayload")),A.webSubPlatform!=null&&A.hasOwnProperty("webSubPlatform")&&(s.webSubPlatform=r.enums===String?p.proto.ClientPayload.WebInfo.WebSubPlatform[A.webSubPlatform]===void 0?A.webSubPlatform:p.proto.ClientPayload.WebInfo.WebSubPlatform[A.webSubPlatform]:A.webSubPlatform,r.oneofs&&(s._webSubPlatform="webSubPlatform")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ClientPayload.WebInfo"},i.WebSubPlatform=(function(){let a={},A=Object.create(a);return A[a[0]="WEB_BROWSER"]=0,A[a[1]="APP_STORE"]=1,A[a[2]="WIN_STORE"]=2,A[a[3]="DARWIN"]=3,A[a[4]="WIN32"]=4,A[a[5]="WIN_HYBRID"]=5,A})(),i.WebdPayload=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.usesParticipantInKey=s.bool();break}case 2:{d.supportsStarredMessages=s.bool();break}case 3:{d.supportsDocumentMessages=s.bool();break}case 4:{d.supportsUrlMessages=s.bool();break}case 5:{d.supportsMediaRetry=s.bool();break}case 6:{d.supportsE2EImage=s.bool();break}case 7:{d.supportsE2EVideo=s.bool();break}case 8:{d.supportsE2EAudio=s.bool();break}case 9:{d.supportsE2EDocument=s.bool();break}case 10:{d.documentTypes=s.string();break}case 11:{d.features=s.bytes();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.ClientPayload.WebInfo.WebdPayload)return s;var g=new p.proto.ClientPayload.WebInfo.WebdPayload;return s.usesParticipantInKey!=null&&(g.usesParticipantInKey=!!s.usesParticipantInKey),s.supportsStarredMessages!=null&&(g.supportsStarredMessages=!!s.supportsStarredMessages),s.supportsDocumentMessages!=null&&(g.supportsDocumentMessages=!!s.supportsDocumentMessages),s.supportsUrlMessages!=null&&(g.supportsUrlMessages=!!s.supportsUrlMessages),s.supportsMediaRetry!=null&&(g.supportsMediaRetry=!!s.supportsMediaRetry),s.supportsE2EImage!=null&&(g.supportsE2EImage=!!s.supportsE2EImage),s.supportsE2EVideo!=null&&(g.supportsE2EVideo=!!s.supportsE2EVideo),s.supportsE2EAudio!=null&&(g.supportsE2EAudio=!!s.supportsE2EAudio),s.supportsE2EDocument!=null&&(g.supportsE2EDocument=!!s.supportsE2EDocument),s.documentTypes!=null&&(g.documentTypes=String(s.documentTypes)),s.features!=null&&(typeof s.features=="string"?l.base64.decode(s.features,g.features=l.newBuffer(l.base64.length(s.features)),0):s.features.length>=0&&(g.features=s.features)),g},a.toObject=function(s,g){g||(g={});var c={};return s.usesParticipantInKey!=null&&s.hasOwnProperty("usesParticipantInKey")&&(c.usesParticipantInKey=s.usesParticipantInKey,g.oneofs&&(c._usesParticipantInKey="usesParticipantInKey")),s.supportsStarredMessages!=null&&s.hasOwnProperty("supportsStarredMessages")&&(c.supportsStarredMessages=s.supportsStarredMessages,g.oneofs&&(c._supportsStarredMessages="supportsStarredMessages")),s.supportsDocumentMessages!=null&&s.hasOwnProperty("supportsDocumentMessages")&&(c.supportsDocumentMessages=s.supportsDocumentMessages,g.oneofs&&(c._supportsDocumentMessages="supportsDocumentMessages")),s.supportsUrlMessages!=null&&s.hasOwnProperty("supportsUrlMessages")&&(c.supportsUrlMessages=s.supportsUrlMessages,g.oneofs&&(c._supportsUrlMessages="supportsUrlMessages")),s.supportsMediaRetry!=null&&s.hasOwnProperty("supportsMediaRetry")&&(c.supportsMediaRetry=s.supportsMediaRetry,g.oneofs&&(c._supportsMediaRetry="supportsMediaRetry")),s.supportsE2EImage!=null&&s.hasOwnProperty("supportsE2EImage")&&(c.supportsE2EImage=s.supportsE2EImage,g.oneofs&&(c._supportsE2EImage="supportsE2EImage")),s.supportsE2EVideo!=null&&s.hasOwnProperty("supportsE2EVideo")&&(c.supportsE2EVideo=s.supportsE2EVideo,g.oneofs&&(c._supportsE2EVideo="supportsE2EVideo")),s.supportsE2EAudio!=null&&s.hasOwnProperty("supportsE2EAudio")&&(c.supportsE2EAudio=s.supportsE2EAudio,g.oneofs&&(c._supportsE2EAudio="supportsE2EAudio")),s.supportsE2EDocument!=null&&s.hasOwnProperty("supportsE2EDocument")&&(c.supportsE2EDocument=s.supportsE2EDocument,g.oneofs&&(c._supportsE2EDocument="supportsE2EDocument")),s.documentTypes!=null&&s.hasOwnProperty("documentTypes")&&(c.documentTypes=s.documentTypes,g.oneofs&&(c._documentTypes="documentTypes")),s.features!=null&&s.hasOwnProperty("features")&&(c.features=g.bytes===String?l.base64.encode(s.features,0,s.features.length):g.bytes===Array?Array.prototype.slice.call(s.features):s.features,g.oneofs&&(c._features="features")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ClientPayload.WebInfo.WebdPayload"},a})(),i})(),t})(),n.CollectionName=(function(){let t={},o=Object.create(t);return o[t[0]="COLLECTION_NAME_UNKNOWN"]=0,o[t[1]="REGULAR"]=1,o[t[2]="REGULAR_LOW"]=2,o[t[3]="REGULAR_HIGH"]=3,o[t[4]="CRITICAL_BLOCK"]=4,o[t[5]="CRITICAL_UNBLOCK_LOW"]=5,o})(),n.CommentMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.commentParentKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.replyCount=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.CommentMetadata)return e;var a=new p.proto.CommentMetadata;if(e.commentParentKey!=null){if(typeof e.commentParentKey!="object")throw TypeError(".proto.CommentMetadata.commentParentKey: object expected");a.commentParentKey=p.proto.MessageKey.fromObject(e.commentParentKey)}return e.replyCount!=null&&(a.replyCount=e.replyCount>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.commentParentKey!=null&&e.hasOwnProperty("commentParentKey")&&(A.commentParentKey=p.proto.MessageKey.toObject(e.commentParentKey,a),a.oneofs&&(A._commentParentKey="commentParentKey")),e.replyCount!=null&&e.hasOwnProperty("replyCount")&&(A.replyCount=e.replyCount,a.oneofs&&(A._replyCount="replyCount")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CommentMetadata"},t})(),n.CompanionCommitment=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.hash=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.CompanionCommitment)return e;var a=new p.proto.CompanionCommitment;return e.hash!=null&&(typeof e.hash=="string"?l.base64.decode(e.hash,a.hash=l.newBuffer(l.base64.length(e.hash)),0):e.hash.length>=0&&(a.hash=e.hash)),a},t.toObject=function(e,a){a||(a={});var A={};return e.hash!=null&&e.hasOwnProperty("hash")&&(A.hash=a.bytes===String?l.base64.encode(e.hash,0,e.hash.length):a.bytes===Array?Array.prototype.slice.call(e.hash):e.hash,a.oneofs&&(A._hash="hash")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CompanionCommitment"},t})(),n.CompanionEphemeralIdentity=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.deviceType=e.int32();break}case 3:{s.ref=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.CompanionEphemeralIdentity)return e;var a=new p.proto.CompanionEphemeralIdentity;switch(e.publicKey!=null&&(typeof e.publicKey=="string"?l.base64.decode(e.publicKey,a.publicKey=l.newBuffer(l.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.deviceType){default:if(typeof e.deviceType=="number"){a.deviceType=e.deviceType;break}break;case"UNKNOWN":case 0:a.deviceType=0;break;case"CHROME":case 1:a.deviceType=1;break;case"FIREFOX":case 2:a.deviceType=2;break;case"IE":case 3:a.deviceType=3;break;case"OPERA":case 4:a.deviceType=4;break;case"SAFARI":case 5:a.deviceType=5;break;case"EDGE":case 6:a.deviceType=6;break;case"DESKTOP":case 7:a.deviceType=7;break;case"IPAD":case 8:a.deviceType=8;break;case"ANDROID_TABLET":case 9:a.deviceType=9;break;case"OHANA":case 10:a.deviceType=10;break;case"ALOHA":case 11:a.deviceType=11;break;case"CATALINA":case 12:a.deviceType=12;break;case"TCL_TV":case 13:a.deviceType=13;break;case"IOS_PHONE":case 14:a.deviceType=14;break;case"IOS_CATALYST":case 15:a.deviceType=15;break;case"ANDROID_PHONE":case 16:a.deviceType=16;break;case"ANDROID_AMBIGUOUS":case 17:a.deviceType=17;break;case"WEAR_OS":case 18:a.deviceType=18;break;case"AR_WRIST":case 19:a.deviceType=19;break;case"AR_DEVICE":case 20:a.deviceType=20;break;case"UWP":case 21:a.deviceType=21;break;case"VR":case 22:a.deviceType=22;break;case"CLOUD_API":case 23:a.deviceType=23;break;case"SMARTGLASSES":case 24:a.deviceType=24;break}return e.ref!=null&&(a.ref=String(e.ref)),a},t.toObject=function(e,a){a||(a={});var A={};return e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?l.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.deviceType!=null&&e.hasOwnProperty("deviceType")&&(A.deviceType=a.enums===String?p.proto.DeviceProps.PlatformType[e.deviceType]===void 0?e.deviceType:p.proto.DeviceProps.PlatformType[e.deviceType]:e.deviceType,a.oneofs&&(A._deviceType="deviceType")),e.ref!=null&&e.hasOwnProperty("ref")&&(A.ref=e.ref,a.oneofs&&(A._ref="ref")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.CompanionEphemeralIdentity"},t})(),n.Config=(function(){function t(i){if(this.field={},i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.field===l.emptyObject&&(s.field={});var d=e.uint32()+e.pos;for(g=0,c=null;e.pos>>3){case 1:g=e.uint32();break;case 2:c=p.proto.Field.decode(e,e.uint32());break;default:e.skipType(B&7);break}}s.field[g]=c;break}case 2:{s.version=e.uint32();break}default:e.skipType(I&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Config)return e;var a=new p.proto.Config;if(e.field){if(typeof e.field!="object")throw TypeError(".proto.Config.field: object expected");a.field={};for(var A=Object.keys(e.field),r=0;r>>0),a},t.toObject=function(e,a){a||(a={});var A={};(a.objects||a.defaults)&&(A.field={});var r;if(e.field&&(r=Object.keys(e.field)).length){A.field={};for(var s=0;s>>3){case 1:{s.stanzaId=e.string();break}case 2:{s.participant=e.string();break}case 3:{s.quotedMessage=p.proto.Message.decode(e,e.uint32());break}case 4:{s.remoteJid=e.string();break}case 15:{s.mentionedJid&&s.mentionedJid.length||(s.mentionedJid=[]),s.mentionedJid.push(e.string());break}case 18:{s.conversionSource=e.string();break}case 19:{s.conversionData=e.bytes();break}case 20:{s.conversionDelaySeconds=e.uint32();break}case 21:{s.forwardingScore=e.uint32();break}case 22:{s.isForwarded=e.bool();break}case 23:{s.quotedAd=p.proto.ContextInfo.AdReplyInfo.decode(e,e.uint32());break}case 24:{s.placeholderKey=p.proto.MessageKey.decode(e,e.uint32());break}case 25:{s.expiration=e.uint32();break}case 26:{s.ephemeralSettingTimestamp=e.int64();break}case 27:{s.ephemeralSharedSecret=e.bytes();break}case 28:{s.externalAdReply=p.proto.ContextInfo.ExternalAdReplyInfo.decode(e,e.uint32());break}case 29:{s.entryPointConversionSource=e.string();break}case 30:{s.entryPointConversionApp=e.string();break}case 31:{s.entryPointConversionDelaySeconds=e.uint32();break}case 32:{s.disappearingMode=p.proto.DisappearingMode.decode(e,e.uint32());break}case 33:{s.actionLink=p.proto.ActionLink.decode(e,e.uint32());break}case 34:{s.groupSubject=e.string();break}case 35:{s.parentGroupJid=e.string();break}case 37:{s.trustBannerType=e.string();break}case 38:{s.trustBannerAction=e.uint32();break}case 39:{s.isSampled=e.bool();break}case 40:{s.groupMentions&&s.groupMentions.length||(s.groupMentions=[]),s.groupMentions.push(p.proto.GroupMention.decode(e,e.uint32()));break}case 41:{s.utm=p.proto.ContextInfo.UTMInfo.decode(e,e.uint32());break}case 43:{s.forwardedNewsletterMessageInfo=p.proto.ContextInfo.ForwardedNewsletterMessageInfo.decode(e,e.uint32());break}case 44:{s.businessMessageForwardInfo=p.proto.ContextInfo.BusinessMessageForwardInfo.decode(e,e.uint32());break}case 45:{s.smbClientCampaignId=e.string();break}case 46:{s.smbServerCampaignId=e.string();break}case 47:{s.dataSharingContext=p.proto.ContextInfo.DataSharingContext.decode(e,e.uint32());break}case 48:{s.alwaysShowAdAttribution=e.bool();break}case 49:{s.featureEligibilities=p.proto.ContextInfo.FeatureEligibilities.decode(e,e.uint32());break}case 50:{s.entryPointConversionExternalSource=e.string();break}case 51:{s.entryPointConversionExternalMedium=e.string();break}case 54:{s.ctwaSignals=e.string();break}case 55:{s.ctwaPayload=e.bytes();break}case 56:{s.forwardedAiBotMessageInfo=p.proto.ForwardedAIBotMessageInfo.decode(e,e.uint32());break}case 57:{s.statusAttributionType=e.int32();break}case 58:{s.urlTrackingMap=p.proto.UrlTrackingMap.decode(e,e.uint32());break}case 59:{s.pairedMediaType=e.int32();break}case 60:{s.rankingVersion=e.uint32();break}case 62:{s.memberLabel=p.proto.MemberLabel.decode(e,e.uint32());break}case 63:{s.isQuestion=e.bool();break}case 64:{s.statusSourceType=e.int32();break}case 65:{s.statusAttributions&&s.statusAttributions.length||(s.statusAttributions=[]),s.statusAttributions.push(p.proto.StatusAttribution.decode(e,e.uint32()));break}case 66:{s.isGroupStatus=e.bool();break}case 67:{s.forwardOrigin=e.int32();break}case 68:{s.questionReplyQuotedMessage=p.proto.ContextInfo.QuestionReplyQuotedMessage.decode(e,e.uint32());break}case 69:{s.statusAudienceMetadata=p.proto.ContextInfo.StatusAudienceMetadata.decode(e,e.uint32());break}case 70:{s.nonJidMentions=e.uint32();break}case 71:{s.quotedType=e.int32();break}case 72:{s.botMessageSharingInfo=p.proto.BotMessageSharingInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ContextInfo)return e;var a=new p.proto.ContextInfo;if(e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),e.participant!=null&&(a.participant=String(e.participant)),e.quotedMessage!=null){if(typeof e.quotedMessage!="object")throw TypeError(".proto.ContextInfo.quotedMessage: object expected");a.quotedMessage=p.proto.Message.fromObject(e.quotedMessage)}if(e.remoteJid!=null&&(a.remoteJid=String(e.remoteJid)),e.mentionedJid){if(!Array.isArray(e.mentionedJid))throw TypeError(".proto.ContextInfo.mentionedJid: array expected");a.mentionedJid=[];for(var A=0;A=0&&(a.conversionData=e.conversionData)),e.conversionDelaySeconds!=null&&(a.conversionDelaySeconds=e.conversionDelaySeconds>>>0),e.forwardingScore!=null&&(a.forwardingScore=e.forwardingScore>>>0),e.isForwarded!=null&&(a.isForwarded=!!e.isForwarded),e.quotedAd!=null){if(typeof e.quotedAd!="object")throw TypeError(".proto.ContextInfo.quotedAd: object expected");a.quotedAd=p.proto.ContextInfo.AdReplyInfo.fromObject(e.quotedAd)}if(e.placeholderKey!=null){if(typeof e.placeholderKey!="object")throw TypeError(".proto.ContextInfo.placeholderKey: object expected");a.placeholderKey=p.proto.MessageKey.fromObject(e.placeholderKey)}if(e.expiration!=null&&(a.expiration=e.expiration>>>0),e.ephemeralSettingTimestamp!=null&&(l.Long?(a.ephemeralSettingTimestamp=l.Long.fromValue(e.ephemeralSettingTimestamp)).unsigned=!1:typeof e.ephemeralSettingTimestamp=="string"?a.ephemeralSettingTimestamp=parseInt(e.ephemeralSettingTimestamp,10):typeof e.ephemeralSettingTimestamp=="number"?a.ephemeralSettingTimestamp=e.ephemeralSettingTimestamp:typeof e.ephemeralSettingTimestamp=="object"&&(a.ephemeralSettingTimestamp=new l.LongBits(e.ephemeralSettingTimestamp.low>>>0,e.ephemeralSettingTimestamp.high>>>0).toNumber())),e.ephemeralSharedSecret!=null&&(typeof e.ephemeralSharedSecret=="string"?l.base64.decode(e.ephemeralSharedSecret,a.ephemeralSharedSecret=l.newBuffer(l.base64.length(e.ephemeralSharedSecret)),0):e.ephemeralSharedSecret.length>=0&&(a.ephemeralSharedSecret=e.ephemeralSharedSecret)),e.externalAdReply!=null){if(typeof e.externalAdReply!="object")throw TypeError(".proto.ContextInfo.externalAdReply: object expected");a.externalAdReply=p.proto.ContextInfo.ExternalAdReplyInfo.fromObject(e.externalAdReply)}if(e.entryPointConversionSource!=null&&(a.entryPointConversionSource=String(e.entryPointConversionSource)),e.entryPointConversionApp!=null&&(a.entryPointConversionApp=String(e.entryPointConversionApp)),e.entryPointConversionDelaySeconds!=null&&(a.entryPointConversionDelaySeconds=e.entryPointConversionDelaySeconds>>>0),e.disappearingMode!=null){if(typeof e.disappearingMode!="object")throw TypeError(".proto.ContextInfo.disappearingMode: object expected");a.disappearingMode=p.proto.DisappearingMode.fromObject(e.disappearingMode)}if(e.actionLink!=null){if(typeof e.actionLink!="object")throw TypeError(".proto.ContextInfo.actionLink: object expected");a.actionLink=p.proto.ActionLink.fromObject(e.actionLink)}if(e.groupSubject!=null&&(a.groupSubject=String(e.groupSubject)),e.parentGroupJid!=null&&(a.parentGroupJid=String(e.parentGroupJid)),e.trustBannerType!=null&&(a.trustBannerType=String(e.trustBannerType)),e.trustBannerAction!=null&&(a.trustBannerAction=e.trustBannerAction>>>0),e.isSampled!=null&&(a.isSampled=!!e.isSampled),e.groupMentions){if(!Array.isArray(e.groupMentions))throw TypeError(".proto.ContextInfo.groupMentions: array expected");a.groupMentions=[];for(var A=0;A=0&&(a.ctwaPayload=e.ctwaPayload)),e.forwardedAiBotMessageInfo!=null){if(typeof e.forwardedAiBotMessageInfo!="object")throw TypeError(".proto.ContextInfo.forwardedAiBotMessageInfo: object expected");a.forwardedAiBotMessageInfo=p.proto.ForwardedAIBotMessageInfo.fromObject(e.forwardedAiBotMessageInfo)}switch(e.statusAttributionType){default:if(typeof e.statusAttributionType=="number"){a.statusAttributionType=e.statusAttributionType;break}break;case"NONE":case 0:a.statusAttributionType=0;break;case"RESHARED_FROM_MENTION":case 1:a.statusAttributionType=1;break;case"RESHARED_FROM_POST":case 2:a.statusAttributionType=2;break;case"RESHARED_FROM_POST_MANY_TIMES":case 3:a.statusAttributionType=3;break;case"FORWARDED_FROM_STATUS":case 4:a.statusAttributionType=4;break}if(e.urlTrackingMap!=null){if(typeof e.urlTrackingMap!="object")throw TypeError(".proto.ContextInfo.urlTrackingMap: object expected");a.urlTrackingMap=p.proto.UrlTrackingMap.fromObject(e.urlTrackingMap)}switch(e.pairedMediaType){default:if(typeof e.pairedMediaType=="number"){a.pairedMediaType=e.pairedMediaType;break}break;case"NOT_PAIRED_MEDIA":case 0:a.pairedMediaType=0;break;case"SD_VIDEO_PARENT":case 1:a.pairedMediaType=1;break;case"HD_VIDEO_CHILD":case 2:a.pairedMediaType=2;break;case"SD_IMAGE_PARENT":case 3:a.pairedMediaType=3;break;case"HD_IMAGE_CHILD":case 4:a.pairedMediaType=4;break;case"MOTION_PHOTO_PARENT":case 5:a.pairedMediaType=5;break;case"MOTION_PHOTO_CHILD":case 6:a.pairedMediaType=6;break;case"HEVC_VIDEO_PARENT":case 7:a.pairedMediaType=7;break;case"HEVC_VIDEO_CHILD":case 8:a.pairedMediaType=8;break}if(e.rankingVersion!=null&&(a.rankingVersion=e.rankingVersion>>>0),e.memberLabel!=null){if(typeof e.memberLabel!="object")throw TypeError(".proto.ContextInfo.memberLabel: object expected");a.memberLabel=p.proto.MemberLabel.fromObject(e.memberLabel)}switch(e.isQuestion!=null&&(a.isQuestion=!!e.isQuestion),e.statusSourceType){default:if(typeof e.statusSourceType=="number"){a.statusSourceType=e.statusSourceType;break}break;case"IMAGE":case 0:a.statusSourceType=0;break;case"VIDEO":case 1:a.statusSourceType=1;break;case"GIF":case 2:a.statusSourceType=2;break;case"AUDIO":case 3:a.statusSourceType=3;break;case"TEXT":case 4:a.statusSourceType=4;break;case"MUSIC_STANDALONE":case 5:a.statusSourceType=5;break}if(e.statusAttributions){if(!Array.isArray(e.statusAttributions))throw TypeError(".proto.ContextInfo.statusAttributions: array expected");a.statusAttributions=[];for(var A=0;A>>0),e.quotedType){default:if(typeof e.quotedType=="number"){a.quotedType=e.quotedType;break}break;case"EXPLICIT":case 0:a.quotedType=0;break;case"AUTO":case 1:a.quotedType=1;break}if(e.botMessageSharingInfo!=null){if(typeof e.botMessageSharingInfo!="object")throw TypeError(".proto.ContextInfo.botMessageSharingInfo: object expected");a.botMessageSharingInfo=p.proto.BotMessageSharingInfo.fromObject(e.botMessageSharingInfo)}return a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.mentionedJid=[],A.groupMentions=[],A.statusAttributions=[]),e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),e.participant!=null&&e.hasOwnProperty("participant")&&(A.participant=e.participant,a.oneofs&&(A._participant="participant")),e.quotedMessage!=null&&e.hasOwnProperty("quotedMessage")&&(A.quotedMessage=p.proto.Message.toObject(e.quotedMessage,a),a.oneofs&&(A._quotedMessage="quotedMessage")),e.remoteJid!=null&&e.hasOwnProperty("remoteJid")&&(A.remoteJid=e.remoteJid,a.oneofs&&(A._remoteJid="remoteJid")),e.mentionedJid&&e.mentionedJid.length){A.mentionedJid=[];for(var r=0;r>>3){case 1:{c.advertiserName=A.string();break}case 2:{c.mediaType=A.int32();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.caption=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.AdReplyInfo)return A;var r=new p.proto.ContextInfo.AdReplyInfo;switch(A.advertiserName!=null&&(r.advertiserName=String(A.advertiserName)),A.mediaType){default:if(typeof A.mediaType=="number"){r.mediaType=A.mediaType;break}break;case"NONE":case 0:r.mediaType=0;break;case"IMAGE":case 1:r.mediaType=1;break;case"VIDEO":case 2:r.mediaType=2;break}return A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(r.caption=String(A.caption)),r},i.toObject=function(A,r){r||(r={});var s={};return A.advertiserName!=null&&A.hasOwnProperty("advertiserName")&&(s.advertiserName=A.advertiserName,r.oneofs&&(s._advertiserName="advertiserName")),A.mediaType!=null&&A.hasOwnProperty("mediaType")&&(s.mediaType=r.enums===String?p.proto.ContextInfo.AdReplyInfo.MediaType[A.mediaType]===void 0?A.mediaType:p.proto.ContextInfo.AdReplyInfo.MediaType[A.mediaType]:A.mediaType,r.oneofs&&(s._mediaType="mediaType")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.AdReplyInfo"},i.MediaType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="IMAGE"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),t.BusinessMessageForwardInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.businessOwnerJid=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.BusinessMessageForwardInfo)return A;var r=new p.proto.ContextInfo.BusinessMessageForwardInfo;return A.businessOwnerJid!=null&&(r.businessOwnerJid=String(A.businessOwnerJid)),r},i.toObject=function(A,r){r||(r={});var s={};return A.businessOwnerJid!=null&&A.hasOwnProperty("businessOwnerJid")&&(s.businessOwnerJid=A.businessOwnerJid,r.oneofs&&(s._businessOwnerJid="businessOwnerJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.BusinessMessageForwardInfo"},i})(),t.DataSharingContext=(function(){function i(a){if(this.parameters=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.showMmDisclosure=A.bool();break}case 2:{c.encryptedSignalTokenConsented=A.string();break}case 3:{c.parameters&&c.parameters.length||(c.parameters=[]),c.parameters.push(p.proto.ContextInfo.DataSharingContext.Parameters.decode(A,A.uint32()));break}case 4:{c.dataSharingFlags=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.DataSharingContext)return A;var r=new p.proto.ContextInfo.DataSharingContext;if(A.showMmDisclosure!=null&&(r.showMmDisclosure=!!A.showMmDisclosure),A.encryptedSignalTokenConsented!=null&&(r.encryptedSignalTokenConsented=String(A.encryptedSignalTokenConsented)),A.parameters){if(!Array.isArray(A.parameters))throw TypeError(".proto.ContextInfo.DataSharingContext.parameters: array expected");r.parameters=[];for(var s=0;s>>3){case 1:{d.key=s.string();break}case 2:{d.stringData=s.string();break}case 3:{d.intData=s.int64();break}case 4:{d.floatData=s.float();break}case 5:{d.contents=p.proto.ContextInfo.DataSharingContext.Parameters.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.ContextInfo.DataSharingContext.Parameters)return s;var g=new p.proto.ContextInfo.DataSharingContext.Parameters;if(s.key!=null&&(g.key=String(s.key)),s.stringData!=null&&(g.stringData=String(s.stringData)),s.intData!=null&&(l.Long?(g.intData=l.Long.fromValue(s.intData)).unsigned=!1:typeof s.intData=="string"?g.intData=parseInt(s.intData,10):typeof s.intData=="number"?g.intData=s.intData:typeof s.intData=="object"&&(g.intData=new l.LongBits(s.intData.low>>>0,s.intData.high>>>0).toNumber())),s.floatData!=null&&(g.floatData=Number(s.floatData)),s.contents!=null){if(typeof s.contents!="object")throw TypeError(".proto.ContextInfo.DataSharingContext.Parameters.contents: object expected");g.contents=p.proto.ContextInfo.DataSharingContext.Parameters.fromObject(s.contents)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.key!=null&&s.hasOwnProperty("key")&&(c.key=s.key,g.oneofs&&(c._key="key")),s.stringData!=null&&s.hasOwnProperty("stringData")&&(c.stringData=s.stringData,g.oneofs&&(c._stringData="stringData")),s.intData!=null&&s.hasOwnProperty("intData")&&(typeof s.intData=="number"?c.intData=g.longs===String?String(s.intData):s.intData:c.intData=g.longs===String?se(s.intData):g.longs===Number?ge(s.intData):s.intData,g.oneofs&&(c._intData="intData")),s.floatData!=null&&s.hasOwnProperty("floatData")&&(c.floatData=g.json&&!isFinite(s.floatData)?String(s.floatData):s.floatData,g.oneofs&&(c._floatData="floatData")),s.contents!=null&&s.hasOwnProperty("contents")&&(c.contents=p.proto.ContextInfo.DataSharingContext.Parameters.toObject(s.contents,g),g.oneofs&&(c._contents="contents")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.ContextInfo.DataSharingContext.Parameters"},a})(),i})(),t.ExternalAdReplyInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.title=A.string();break}case 2:{c.body=A.string();break}case 3:{c.mediaType=A.int32();break}case 4:{c.thumbnailUrl=A.string();break}case 5:{c.mediaUrl=A.string();break}case 6:{c.thumbnail=A.bytes();break}case 7:{c.sourceType=A.string();break}case 8:{c.sourceId=A.string();break}case 9:{c.sourceUrl=A.string();break}case 10:{c.containsAutoReply=A.bool();break}case 11:{c.renderLargerThumbnail=A.bool();break}case 12:{c.showAdAttribution=A.bool();break}case 13:{c.ctwaClid=A.string();break}case 14:{c.ref=A.string();break}case 15:{c.clickToWhatsappCall=A.bool();break}case 16:{c.adContextPreviewDismissed=A.bool();break}case 17:{c.sourceApp=A.string();break}case 18:{c.automatedGreetingMessageShown=A.bool();break}case 19:{c.greetingMessageBody=A.string();break}case 20:{c.ctaPayload=A.string();break}case 21:{c.disableNudge=A.bool();break}case 22:{c.originalImageUrl=A.string();break}case 23:{c.automatedGreetingMessageCtaType=A.string();break}case 24:{c.wtwaAdFormat=A.bool();break}case 25:{c.adType=A.int32();break}case 26:{c.wtwaWebsiteUrl=A.string();break}case 27:{c.adPreviewUrl=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.ExternalAdReplyInfo)return A;var r=new p.proto.ContextInfo.ExternalAdReplyInfo;switch(A.title!=null&&(r.title=String(A.title)),A.body!=null&&(r.body=String(A.body)),A.mediaType){default:if(typeof A.mediaType=="number"){r.mediaType=A.mediaType;break}break;case"NONE":case 0:r.mediaType=0;break;case"IMAGE":case 1:r.mediaType=1;break;case"VIDEO":case 2:r.mediaType=2;break}switch(A.thumbnailUrl!=null&&(r.thumbnailUrl=String(A.thumbnailUrl)),A.mediaUrl!=null&&(r.mediaUrl=String(A.mediaUrl)),A.thumbnail!=null&&(typeof A.thumbnail=="string"?l.base64.decode(A.thumbnail,r.thumbnail=l.newBuffer(l.base64.length(A.thumbnail)),0):A.thumbnail.length>=0&&(r.thumbnail=A.thumbnail)),A.sourceType!=null&&(r.sourceType=String(A.sourceType)),A.sourceId!=null&&(r.sourceId=String(A.sourceId)),A.sourceUrl!=null&&(r.sourceUrl=String(A.sourceUrl)),A.containsAutoReply!=null&&(r.containsAutoReply=!!A.containsAutoReply),A.renderLargerThumbnail!=null&&(r.renderLargerThumbnail=!!A.renderLargerThumbnail),A.showAdAttribution!=null&&(r.showAdAttribution=!!A.showAdAttribution),A.ctwaClid!=null&&(r.ctwaClid=String(A.ctwaClid)),A.ref!=null&&(r.ref=String(A.ref)),A.clickToWhatsappCall!=null&&(r.clickToWhatsappCall=!!A.clickToWhatsappCall),A.adContextPreviewDismissed!=null&&(r.adContextPreviewDismissed=!!A.adContextPreviewDismissed),A.sourceApp!=null&&(r.sourceApp=String(A.sourceApp)),A.automatedGreetingMessageShown!=null&&(r.automatedGreetingMessageShown=!!A.automatedGreetingMessageShown),A.greetingMessageBody!=null&&(r.greetingMessageBody=String(A.greetingMessageBody)),A.ctaPayload!=null&&(r.ctaPayload=String(A.ctaPayload)),A.disableNudge!=null&&(r.disableNudge=!!A.disableNudge),A.originalImageUrl!=null&&(r.originalImageUrl=String(A.originalImageUrl)),A.automatedGreetingMessageCtaType!=null&&(r.automatedGreetingMessageCtaType=String(A.automatedGreetingMessageCtaType)),A.wtwaAdFormat!=null&&(r.wtwaAdFormat=!!A.wtwaAdFormat),A.adType){default:if(typeof A.adType=="number"){r.adType=A.adType;break}break;case"CTWA":case 0:r.adType=0;break;case"CAWC":case 1:r.adType=1;break}return A.wtwaWebsiteUrl!=null&&(r.wtwaWebsiteUrl=String(A.wtwaWebsiteUrl)),A.adPreviewUrl!=null&&(r.adPreviewUrl=String(A.adPreviewUrl)),r},i.toObject=function(A,r){r||(r={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=A.body,r.oneofs&&(s._body="body")),A.mediaType!=null&&A.hasOwnProperty("mediaType")&&(s.mediaType=r.enums===String?p.proto.ContextInfo.ExternalAdReplyInfo.MediaType[A.mediaType]===void 0?A.mediaType:p.proto.ContextInfo.ExternalAdReplyInfo.MediaType[A.mediaType]:A.mediaType,r.oneofs&&(s._mediaType="mediaType")),A.thumbnailUrl!=null&&A.hasOwnProperty("thumbnailUrl")&&(s.thumbnailUrl=A.thumbnailUrl,r.oneofs&&(s._thumbnailUrl="thumbnailUrl")),A.mediaUrl!=null&&A.hasOwnProperty("mediaUrl")&&(s.mediaUrl=A.mediaUrl,r.oneofs&&(s._mediaUrl="mediaUrl")),A.thumbnail!=null&&A.hasOwnProperty("thumbnail")&&(s.thumbnail=r.bytes===String?l.base64.encode(A.thumbnail,0,A.thumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnail):A.thumbnail,r.oneofs&&(s._thumbnail="thumbnail")),A.sourceType!=null&&A.hasOwnProperty("sourceType")&&(s.sourceType=A.sourceType,r.oneofs&&(s._sourceType="sourceType")),A.sourceId!=null&&A.hasOwnProperty("sourceId")&&(s.sourceId=A.sourceId,r.oneofs&&(s._sourceId="sourceId")),A.sourceUrl!=null&&A.hasOwnProperty("sourceUrl")&&(s.sourceUrl=A.sourceUrl,r.oneofs&&(s._sourceUrl="sourceUrl")),A.containsAutoReply!=null&&A.hasOwnProperty("containsAutoReply")&&(s.containsAutoReply=A.containsAutoReply,r.oneofs&&(s._containsAutoReply="containsAutoReply")),A.renderLargerThumbnail!=null&&A.hasOwnProperty("renderLargerThumbnail")&&(s.renderLargerThumbnail=A.renderLargerThumbnail,r.oneofs&&(s._renderLargerThumbnail="renderLargerThumbnail")),A.showAdAttribution!=null&&A.hasOwnProperty("showAdAttribution")&&(s.showAdAttribution=A.showAdAttribution,r.oneofs&&(s._showAdAttribution="showAdAttribution")),A.ctwaClid!=null&&A.hasOwnProperty("ctwaClid")&&(s.ctwaClid=A.ctwaClid,r.oneofs&&(s._ctwaClid="ctwaClid")),A.ref!=null&&A.hasOwnProperty("ref")&&(s.ref=A.ref,r.oneofs&&(s._ref="ref")),A.clickToWhatsappCall!=null&&A.hasOwnProperty("clickToWhatsappCall")&&(s.clickToWhatsappCall=A.clickToWhatsappCall,r.oneofs&&(s._clickToWhatsappCall="clickToWhatsappCall")),A.adContextPreviewDismissed!=null&&A.hasOwnProperty("adContextPreviewDismissed")&&(s.adContextPreviewDismissed=A.adContextPreviewDismissed,r.oneofs&&(s._adContextPreviewDismissed="adContextPreviewDismissed")),A.sourceApp!=null&&A.hasOwnProperty("sourceApp")&&(s.sourceApp=A.sourceApp,r.oneofs&&(s._sourceApp="sourceApp")),A.automatedGreetingMessageShown!=null&&A.hasOwnProperty("automatedGreetingMessageShown")&&(s.automatedGreetingMessageShown=A.automatedGreetingMessageShown,r.oneofs&&(s._automatedGreetingMessageShown="automatedGreetingMessageShown")),A.greetingMessageBody!=null&&A.hasOwnProperty("greetingMessageBody")&&(s.greetingMessageBody=A.greetingMessageBody,r.oneofs&&(s._greetingMessageBody="greetingMessageBody")),A.ctaPayload!=null&&A.hasOwnProperty("ctaPayload")&&(s.ctaPayload=A.ctaPayload,r.oneofs&&(s._ctaPayload="ctaPayload")),A.disableNudge!=null&&A.hasOwnProperty("disableNudge")&&(s.disableNudge=A.disableNudge,r.oneofs&&(s._disableNudge="disableNudge")),A.originalImageUrl!=null&&A.hasOwnProperty("originalImageUrl")&&(s.originalImageUrl=A.originalImageUrl,r.oneofs&&(s._originalImageUrl="originalImageUrl")),A.automatedGreetingMessageCtaType!=null&&A.hasOwnProperty("automatedGreetingMessageCtaType")&&(s.automatedGreetingMessageCtaType=A.automatedGreetingMessageCtaType,r.oneofs&&(s._automatedGreetingMessageCtaType="automatedGreetingMessageCtaType")),A.wtwaAdFormat!=null&&A.hasOwnProperty("wtwaAdFormat")&&(s.wtwaAdFormat=A.wtwaAdFormat,r.oneofs&&(s._wtwaAdFormat="wtwaAdFormat")),A.adType!=null&&A.hasOwnProperty("adType")&&(s.adType=r.enums===String?p.proto.ContextInfo.ExternalAdReplyInfo.AdType[A.adType]===void 0?A.adType:p.proto.ContextInfo.ExternalAdReplyInfo.AdType[A.adType]:A.adType,r.oneofs&&(s._adType="adType")),A.wtwaWebsiteUrl!=null&&A.hasOwnProperty("wtwaWebsiteUrl")&&(s.wtwaWebsiteUrl=A.wtwaWebsiteUrl,r.oneofs&&(s._wtwaWebsiteUrl="wtwaWebsiteUrl")),A.adPreviewUrl!=null&&A.hasOwnProperty("adPreviewUrl")&&(s.adPreviewUrl=A.adPreviewUrl,r.oneofs&&(s._adPreviewUrl="adPreviewUrl")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.ExternalAdReplyInfo"},i.AdType=(function(){let a={},A=Object.create(a);return A[a[0]="CTWA"]=0,A[a[1]="CAWC"]=1,A})(),i.MediaType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="IMAGE"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),t.FeatureEligibilities=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.cannotBeReactedTo=A.bool();break}case 2:{c.cannotBeRanked=A.bool();break}case 3:{c.canRequestFeedback=A.bool();break}case 4:{c.canBeReshared=A.bool();break}case 5:{c.canReceiveMultiReact=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.FeatureEligibilities)return A;var r=new p.proto.ContextInfo.FeatureEligibilities;return A.cannotBeReactedTo!=null&&(r.cannotBeReactedTo=!!A.cannotBeReactedTo),A.cannotBeRanked!=null&&(r.cannotBeRanked=!!A.cannotBeRanked),A.canRequestFeedback!=null&&(r.canRequestFeedback=!!A.canRequestFeedback),A.canBeReshared!=null&&(r.canBeReshared=!!A.canBeReshared),A.canReceiveMultiReact!=null&&(r.canReceiveMultiReact=!!A.canReceiveMultiReact),r},i.toObject=function(A,r){r||(r={});var s={};return A.cannotBeReactedTo!=null&&A.hasOwnProperty("cannotBeReactedTo")&&(s.cannotBeReactedTo=A.cannotBeReactedTo,r.oneofs&&(s._cannotBeReactedTo="cannotBeReactedTo")),A.cannotBeRanked!=null&&A.hasOwnProperty("cannotBeRanked")&&(s.cannotBeRanked=A.cannotBeRanked,r.oneofs&&(s._cannotBeRanked="cannotBeRanked")),A.canRequestFeedback!=null&&A.hasOwnProperty("canRequestFeedback")&&(s.canRequestFeedback=A.canRequestFeedback,r.oneofs&&(s._canRequestFeedback="canRequestFeedback")),A.canBeReshared!=null&&A.hasOwnProperty("canBeReshared")&&(s.canBeReshared=A.canBeReshared,r.oneofs&&(s._canBeReshared="canBeReshared")),A.canReceiveMultiReact!=null&&A.hasOwnProperty("canReceiveMultiReact")&&(s.canReceiveMultiReact=A.canReceiveMultiReact,r.oneofs&&(s._canReceiveMultiReact="canReceiveMultiReact")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.FeatureEligibilities"},i})(),t.ForwardOrigin=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHAT"]=1,e[i[2]="STATUS"]=2,e[i[3]="CHANNELS"]=3,e[i[4]="META_AI"]=4,e[i[5]="UGC"]=5,e})(),t.ForwardedNewsletterMessageInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.newsletterJid=A.string();break}case 2:{c.serverMessageId=A.int32();break}case 3:{c.newsletterName=A.string();break}case 4:{c.contentType=A.int32();break}case 5:{c.accessibilityText=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.ForwardedNewsletterMessageInfo)return A;var r=new p.proto.ContextInfo.ForwardedNewsletterMessageInfo;switch(A.newsletterJid!=null&&(r.newsletterJid=String(A.newsletterJid)),A.serverMessageId!=null&&(r.serverMessageId=A.serverMessageId|0),A.newsletterName!=null&&(r.newsletterName=String(A.newsletterName)),A.contentType){default:if(typeof A.contentType=="number"){r.contentType=A.contentType;break}break;case"UPDATE":case 1:r.contentType=1;break;case"UPDATE_CARD":case 2:r.contentType=2;break;case"LINK_CARD":case 3:r.contentType=3;break}return A.accessibilityText!=null&&(r.accessibilityText=String(A.accessibilityText)),r},i.toObject=function(A,r){r||(r={});var s={};return A.newsletterJid!=null&&A.hasOwnProperty("newsletterJid")&&(s.newsletterJid=A.newsletterJid,r.oneofs&&(s._newsletterJid="newsletterJid")),A.serverMessageId!=null&&A.hasOwnProperty("serverMessageId")&&(s.serverMessageId=A.serverMessageId,r.oneofs&&(s._serverMessageId="serverMessageId")),A.newsletterName!=null&&A.hasOwnProperty("newsletterName")&&(s.newsletterName=A.newsletterName,r.oneofs&&(s._newsletterName="newsletterName")),A.contentType!=null&&A.hasOwnProperty("contentType")&&(s.contentType=r.enums===String?p.proto.ContextInfo.ForwardedNewsletterMessageInfo.ContentType[A.contentType]===void 0?A.contentType:p.proto.ContextInfo.ForwardedNewsletterMessageInfo.ContentType[A.contentType]:A.contentType,r.oneofs&&(s._contentType="contentType")),A.accessibilityText!=null&&A.hasOwnProperty("accessibilityText")&&(s.accessibilityText=A.accessibilityText,r.oneofs&&(s._accessibilityText="accessibilityText")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.ForwardedNewsletterMessageInfo"},i.ContentType=(function(){let a={},A=Object.create(a);return A[a[1]="UPDATE"]=1,A[a[2]="UPDATE_CARD"]=2,A[a[3]="LINK_CARD"]=3,A})(),i})(),t.PairedMediaType=(function(){let i={},e=Object.create(i);return e[i[0]="NOT_PAIRED_MEDIA"]=0,e[i[1]="SD_VIDEO_PARENT"]=1,e[i[2]="HD_VIDEO_CHILD"]=2,e[i[3]="SD_IMAGE_PARENT"]=3,e[i[4]="HD_IMAGE_CHILD"]=4,e[i[5]="MOTION_PHOTO_PARENT"]=5,e[i[6]="MOTION_PHOTO_CHILD"]=6,e[i[7]="HEVC_VIDEO_PARENT"]=7,e[i[8]="HEVC_VIDEO_CHILD"]=8,e})(),t.QuestionReplyQuotedMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.serverQuestionId=A.int32();break}case 2:{c.quotedQuestion=p.proto.Message.decode(A,A.uint32());break}case 3:{c.quotedResponse=p.proto.Message.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.QuestionReplyQuotedMessage)return A;var r=new p.proto.ContextInfo.QuestionReplyQuotedMessage;if(A.serverQuestionId!=null&&(r.serverQuestionId=A.serverQuestionId|0),A.quotedQuestion!=null){if(typeof A.quotedQuestion!="object")throw TypeError(".proto.ContextInfo.QuestionReplyQuotedMessage.quotedQuestion: object expected");r.quotedQuestion=p.proto.Message.fromObject(A.quotedQuestion)}if(A.quotedResponse!=null){if(typeof A.quotedResponse!="object")throw TypeError(".proto.ContextInfo.QuestionReplyQuotedMessage.quotedResponse: object expected");r.quotedResponse=p.proto.Message.fromObject(A.quotedResponse)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.serverQuestionId!=null&&A.hasOwnProperty("serverQuestionId")&&(s.serverQuestionId=A.serverQuestionId,r.oneofs&&(s._serverQuestionId="serverQuestionId")),A.quotedQuestion!=null&&A.hasOwnProperty("quotedQuestion")&&(s.quotedQuestion=p.proto.Message.toObject(A.quotedQuestion,r),r.oneofs&&(s._quotedQuestion="quotedQuestion")),A.quotedResponse!=null&&A.hasOwnProperty("quotedResponse")&&(s.quotedResponse=p.proto.Message.toObject(A.quotedResponse,r),r.oneofs&&(s._quotedResponse="quotedResponse")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.QuestionReplyQuotedMessage"},i})(),t.QuotedType=(function(){let i={},e=Object.create(i);return e[i[0]="EXPLICIT"]=0,e[i[1]="AUTO"]=1,e})(),t.StatusAttributionType=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="RESHARED_FROM_MENTION"]=1,e[i[2]="RESHARED_FROM_POST"]=2,e[i[3]="RESHARED_FROM_POST_MANY_TIMES"]=3,e[i[4]="FORWARDED_FROM_STATUS"]=4,e})(),t.StatusAudienceMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.audienceType=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.StatusAudienceMetadata)return A;var r=new p.proto.ContextInfo.StatusAudienceMetadata;switch(A.audienceType){default:if(typeof A.audienceType=="number"){r.audienceType=A.audienceType;break}break;case"UNKNOWN":case 0:r.audienceType=0;break;case"CLOSE_FRIENDS":case 1:r.audienceType=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.audienceType!=null&&A.hasOwnProperty("audienceType")&&(s.audienceType=r.enums===String?p.proto.ContextInfo.StatusAudienceMetadata.AudienceType[A.audienceType]===void 0?A.audienceType:p.proto.ContextInfo.StatusAudienceMetadata.AudienceType[A.audienceType]:A.audienceType,r.oneofs&&(s._audienceType="audienceType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.StatusAudienceMetadata"},i.AudienceType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="CLOSE_FRIENDS"]=1,A})(),i})(),t.StatusSourceType=(function(){let i={},e=Object.create(i);return e[i[0]="IMAGE"]=0,e[i[1]="VIDEO"]=1,e[i[2]="GIF"]=2,e[i[3]="AUDIO"]=3,e[i[4]="TEXT"]=4,e[i[5]="MUSIC_STANDALONE"]=5,e})(),t.UTMInfo=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.utmSource=A.string();break}case 2:{c.utmCampaign=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.ContextInfo.UTMInfo)return A;var r=new p.proto.ContextInfo.UTMInfo;return A.utmSource!=null&&(r.utmSource=String(A.utmSource)),A.utmCampaign!=null&&(r.utmCampaign=String(A.utmCampaign)),r},i.toObject=function(A,r){r||(r={});var s={};return A.utmSource!=null&&A.hasOwnProperty("utmSource")&&(s.utmSource=A.utmSource,r.oneofs&&(s._utmSource="utmSource")),A.utmCampaign!=null&&A.hasOwnProperty("utmCampaign")&&(s.utmCampaign=A.utmCampaign,r.oneofs&&(s._utmCampaign="utmCampaign")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.ContextInfo.UTMInfo"},i})(),t})(),n.Conversation=(function(){function t(i){if(this.messages=[],this.participant=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.string();break}case 2:{s.messages&&s.messages.length||(s.messages=[]),s.messages.push(p.proto.HistorySyncMsg.decode(e,e.uint32()));break}case 3:{s.newJid=e.string();break}case 4:{s.oldJid=e.string();break}case 5:{s.lastMsgTimestamp=e.uint64();break}case 6:{s.unreadCount=e.uint32();break}case 7:{s.readOnly=e.bool();break}case 8:{s.endOfHistoryTransfer=e.bool();break}case 9:{s.ephemeralExpiration=e.uint32();break}case 10:{s.ephemeralSettingTimestamp=e.int64();break}case 11:{s.endOfHistoryTransferType=e.int32();break}case 12:{s.conversationTimestamp=e.uint64();break}case 13:{s.name=e.string();break}case 14:{s.pHash=e.string();break}case 15:{s.notSpam=e.bool();break}case 16:{s.archived=e.bool();break}case 17:{s.disappearingMode=p.proto.DisappearingMode.decode(e,e.uint32());break}case 18:{s.unreadMentionCount=e.uint32();break}case 19:{s.markedAsUnread=e.bool();break}case 20:{s.participant&&s.participant.length||(s.participant=[]),s.participant.push(p.proto.GroupParticipant.decode(e,e.uint32()));break}case 21:{s.tcToken=e.bytes();break}case 22:{s.tcTokenTimestamp=e.uint64();break}case 23:{s.contactPrimaryIdentityKey=e.bytes();break}case 24:{s.pinned=e.uint32();break}case 25:{s.muteEndTime=e.uint64();break}case 26:{s.wallpaper=p.proto.WallpaperSettings.decode(e,e.uint32());break}case 27:{s.mediaVisibility=e.int32();break}case 28:{s.tcTokenSenderTimestamp=e.uint64();break}case 29:{s.suspended=e.bool();break}case 30:{s.terminated=e.bool();break}case 31:{s.createdAt=e.uint64();break}case 32:{s.createdBy=e.string();break}case 33:{s.description=e.string();break}case 34:{s.support=e.bool();break}case 35:{s.isParentGroup=e.bool();break}case 37:{s.parentGroupId=e.string();break}case 36:{s.isDefaultSubgroup=e.bool();break}case 38:{s.displayName=e.string();break}case 39:{s.pnJid=e.string();break}case 40:{s.shareOwnPn=e.bool();break}case 41:{s.pnhDuplicateLidThread=e.bool();break}case 42:{s.lidJid=e.string();break}case 43:{s.username=e.string();break}case 44:{s.lidOriginType=e.string();break}case 45:{s.commentsCount=e.uint32();break}case 46:{s.locked=e.bool();break}case 47:{s.systemMessageToInsert=e.int32();break}case 48:{s.capiCreatedGroup=e.bool();break}case 49:{s.accountLid=e.string();break}case 50:{s.limitSharing=e.bool();break}case 51:{s.limitSharingSettingTimestamp=e.int64();break}case 52:{s.limitSharingTrigger=e.int32();break}case 53:{s.limitSharingInitiatedByMe=e.bool();break}case 54:{s.maibaAiThreadEnabled=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Conversation)return e;var a=new p.proto.Conversation;if(e.id!=null&&(a.id=String(e.id)),e.messages){if(!Array.isArray(e.messages))throw TypeError(".proto.Conversation.messages: array expected");a.messages=[];for(var A=0;A>>0,e.lastMsgTimestamp.high>>>0).toNumber(!0))),e.unreadCount!=null&&(a.unreadCount=e.unreadCount>>>0),e.readOnly!=null&&(a.readOnly=!!e.readOnly),e.endOfHistoryTransfer!=null&&(a.endOfHistoryTransfer=!!e.endOfHistoryTransfer),e.ephemeralExpiration!=null&&(a.ephemeralExpiration=e.ephemeralExpiration>>>0),e.ephemeralSettingTimestamp!=null&&(l.Long?(a.ephemeralSettingTimestamp=l.Long.fromValue(e.ephemeralSettingTimestamp)).unsigned=!1:typeof e.ephemeralSettingTimestamp=="string"?a.ephemeralSettingTimestamp=parseInt(e.ephemeralSettingTimestamp,10):typeof e.ephemeralSettingTimestamp=="number"?a.ephemeralSettingTimestamp=e.ephemeralSettingTimestamp:typeof e.ephemeralSettingTimestamp=="object"&&(a.ephemeralSettingTimestamp=new l.LongBits(e.ephemeralSettingTimestamp.low>>>0,e.ephemeralSettingTimestamp.high>>>0).toNumber())),e.endOfHistoryTransferType){default:if(typeof e.endOfHistoryTransferType=="number"){a.endOfHistoryTransferType=e.endOfHistoryTransferType;break}break;case"COMPLETE_BUT_MORE_MESSAGES_REMAIN_ON_PRIMARY":case 0:a.endOfHistoryTransferType=0;break;case"COMPLETE_AND_NO_MORE_MESSAGE_REMAIN_ON_PRIMARY":case 1:a.endOfHistoryTransferType=1;break;case"COMPLETE_ON_DEMAND_SYNC_BUT_MORE_MSG_REMAIN_ON_PRIMARY":case 2:a.endOfHistoryTransferType=2;break}if(e.conversationTimestamp!=null&&(l.Long?(a.conversationTimestamp=l.Long.fromValue(e.conversationTimestamp)).unsigned=!0:typeof e.conversationTimestamp=="string"?a.conversationTimestamp=parseInt(e.conversationTimestamp,10):typeof e.conversationTimestamp=="number"?a.conversationTimestamp=e.conversationTimestamp:typeof e.conversationTimestamp=="object"&&(a.conversationTimestamp=new l.LongBits(e.conversationTimestamp.low>>>0,e.conversationTimestamp.high>>>0).toNumber(!0))),e.name!=null&&(a.name=String(e.name)),e.pHash!=null&&(a.pHash=String(e.pHash)),e.notSpam!=null&&(a.notSpam=!!e.notSpam),e.archived!=null&&(a.archived=!!e.archived),e.disappearingMode!=null){if(typeof e.disappearingMode!="object")throw TypeError(".proto.Conversation.disappearingMode: object expected");a.disappearingMode=p.proto.DisappearingMode.fromObject(e.disappearingMode)}if(e.unreadMentionCount!=null&&(a.unreadMentionCount=e.unreadMentionCount>>>0),e.markedAsUnread!=null&&(a.markedAsUnread=!!e.markedAsUnread),e.participant){if(!Array.isArray(e.participant))throw TypeError(".proto.Conversation.participant: array expected");a.participant=[];for(var A=0;A=0&&(a.tcToken=e.tcToken)),e.tcTokenTimestamp!=null&&(l.Long?(a.tcTokenTimestamp=l.Long.fromValue(e.tcTokenTimestamp)).unsigned=!0:typeof e.tcTokenTimestamp=="string"?a.tcTokenTimestamp=parseInt(e.tcTokenTimestamp,10):typeof e.tcTokenTimestamp=="number"?a.tcTokenTimestamp=e.tcTokenTimestamp:typeof e.tcTokenTimestamp=="object"&&(a.tcTokenTimestamp=new l.LongBits(e.tcTokenTimestamp.low>>>0,e.tcTokenTimestamp.high>>>0).toNumber(!0))),e.contactPrimaryIdentityKey!=null&&(typeof e.contactPrimaryIdentityKey=="string"?l.base64.decode(e.contactPrimaryIdentityKey,a.contactPrimaryIdentityKey=l.newBuffer(l.base64.length(e.contactPrimaryIdentityKey)),0):e.contactPrimaryIdentityKey.length>=0&&(a.contactPrimaryIdentityKey=e.contactPrimaryIdentityKey)),e.pinned!=null&&(a.pinned=e.pinned>>>0),e.muteEndTime!=null&&(l.Long?(a.muteEndTime=l.Long.fromValue(e.muteEndTime)).unsigned=!0:typeof e.muteEndTime=="string"?a.muteEndTime=parseInt(e.muteEndTime,10):typeof e.muteEndTime=="number"?a.muteEndTime=e.muteEndTime:typeof e.muteEndTime=="object"&&(a.muteEndTime=new l.LongBits(e.muteEndTime.low>>>0,e.muteEndTime.high>>>0).toNumber(!0))),e.wallpaper!=null){if(typeof e.wallpaper!="object")throw TypeError(".proto.Conversation.wallpaper: object expected");a.wallpaper=p.proto.WallpaperSettings.fromObject(e.wallpaper)}switch(e.mediaVisibility){default:if(typeof e.mediaVisibility=="number"){a.mediaVisibility=e.mediaVisibility;break}break;case"DEFAULT":case 0:a.mediaVisibility=0;break;case"OFF":case 1:a.mediaVisibility=1;break;case"ON":case 2:a.mediaVisibility=2;break}switch(e.tcTokenSenderTimestamp!=null&&(l.Long?(a.tcTokenSenderTimestamp=l.Long.fromValue(e.tcTokenSenderTimestamp)).unsigned=!0:typeof e.tcTokenSenderTimestamp=="string"?a.tcTokenSenderTimestamp=parseInt(e.tcTokenSenderTimestamp,10):typeof e.tcTokenSenderTimestamp=="number"?a.tcTokenSenderTimestamp=e.tcTokenSenderTimestamp:typeof e.tcTokenSenderTimestamp=="object"&&(a.tcTokenSenderTimestamp=new l.LongBits(e.tcTokenSenderTimestamp.low>>>0,e.tcTokenSenderTimestamp.high>>>0).toNumber(!0))),e.suspended!=null&&(a.suspended=!!e.suspended),e.terminated!=null&&(a.terminated=!!e.terminated),e.createdAt!=null&&(l.Long?(a.createdAt=l.Long.fromValue(e.createdAt)).unsigned=!0:typeof e.createdAt=="string"?a.createdAt=parseInt(e.createdAt,10):typeof e.createdAt=="number"?a.createdAt=e.createdAt:typeof e.createdAt=="object"&&(a.createdAt=new l.LongBits(e.createdAt.low>>>0,e.createdAt.high>>>0).toNumber(!0))),e.createdBy!=null&&(a.createdBy=String(e.createdBy)),e.description!=null&&(a.description=String(e.description)),e.support!=null&&(a.support=!!e.support),e.isParentGroup!=null&&(a.isParentGroup=!!e.isParentGroup),e.parentGroupId!=null&&(a.parentGroupId=String(e.parentGroupId)),e.isDefaultSubgroup!=null&&(a.isDefaultSubgroup=!!e.isDefaultSubgroup),e.displayName!=null&&(a.displayName=String(e.displayName)),e.pnJid!=null&&(a.pnJid=String(e.pnJid)),e.shareOwnPn!=null&&(a.shareOwnPn=!!e.shareOwnPn),e.pnhDuplicateLidThread!=null&&(a.pnhDuplicateLidThread=!!e.pnhDuplicateLidThread),e.lidJid!=null&&(a.lidJid=String(e.lidJid)),e.username!=null&&(a.username=String(e.username)),e.lidOriginType!=null&&(a.lidOriginType=String(e.lidOriginType)),e.commentsCount!=null&&(a.commentsCount=e.commentsCount>>>0),e.locked!=null&&(a.locked=!!e.locked),e.systemMessageToInsert){default:if(typeof e.systemMessageToInsert=="number"){a.systemMessageToInsert=e.systemMessageToInsert;break}break;case"E2EE_MSG":case 1:a.systemMessageToInsert=1;break;case"NE2EE_SELF":case 2:a.systemMessageToInsert=2;break;case"NE2EE_OTHER":case 3:a.systemMessageToInsert=3;break}switch(e.capiCreatedGroup!=null&&(a.capiCreatedGroup=!!e.capiCreatedGroup),e.accountLid!=null&&(a.accountLid=String(e.accountLid)),e.limitSharing!=null&&(a.limitSharing=!!e.limitSharing),e.limitSharingSettingTimestamp!=null&&(l.Long?(a.limitSharingSettingTimestamp=l.Long.fromValue(e.limitSharingSettingTimestamp)).unsigned=!1:typeof e.limitSharingSettingTimestamp=="string"?a.limitSharingSettingTimestamp=parseInt(e.limitSharingSettingTimestamp,10):typeof e.limitSharingSettingTimestamp=="number"?a.limitSharingSettingTimestamp=e.limitSharingSettingTimestamp:typeof e.limitSharingSettingTimestamp=="object"&&(a.limitSharingSettingTimestamp=new l.LongBits(e.limitSharingSettingTimestamp.low>>>0,e.limitSharingSettingTimestamp.high>>>0).toNumber())),e.limitSharingTrigger){default:if(typeof e.limitSharingTrigger=="number"){a.limitSharingTrigger=e.limitSharingTrigger;break}break;case"UNKNOWN":case 0:a.limitSharingTrigger=0;break;case"CHAT_SETTING":case 1:a.limitSharingTrigger=1;break;case"BIZ_SUPPORTS_FB_HOSTING":case 2:a.limitSharingTrigger=2;break;case"UNKNOWN_GROUP":case 3:a.limitSharingTrigger=3;break}return e.limitSharingInitiatedByMe!=null&&(a.limitSharingInitiatedByMe=!!e.limitSharingInitiatedByMe),e.maibaAiThreadEnabled!=null&&(a.maibaAiThreadEnabled=!!e.maibaAiThreadEnabled),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.messages=[],A.participant=[]),a.defaults&&(A.id=""),e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id),e.messages&&e.messages.length){A.messages=[];for(var r=0;r>>3){case 1:{s.chatLockSupportLevel=e.int32();break}case 2:{s.lidMigration=p.proto.DeviceCapabilities.LIDMigration.decode(e,e.uint32());break}case 3:{s.businessBroadcast=p.proto.DeviceCapabilities.BusinessBroadcast.decode(e,e.uint32());break}case 4:{s.userHasAvatar=p.proto.DeviceCapabilities.UserHasAvatar.decode(e,e.uint32());break}case 5:{s.memberNameTagPrimarySupport=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.DeviceCapabilities)return e;var a=new p.proto.DeviceCapabilities;switch(e.chatLockSupportLevel){default:if(typeof e.chatLockSupportLevel=="number"){a.chatLockSupportLevel=e.chatLockSupportLevel;break}break;case"NONE":case 0:a.chatLockSupportLevel=0;break;case"MINIMAL":case 1:a.chatLockSupportLevel=1;break;case"FULL":case 2:a.chatLockSupportLevel=2;break}if(e.lidMigration!=null){if(typeof e.lidMigration!="object")throw TypeError(".proto.DeviceCapabilities.lidMigration: object expected");a.lidMigration=p.proto.DeviceCapabilities.LIDMigration.fromObject(e.lidMigration)}if(e.businessBroadcast!=null){if(typeof e.businessBroadcast!="object")throw TypeError(".proto.DeviceCapabilities.businessBroadcast: object expected");a.businessBroadcast=p.proto.DeviceCapabilities.BusinessBroadcast.fromObject(e.businessBroadcast)}if(e.userHasAvatar!=null){if(typeof e.userHasAvatar!="object")throw TypeError(".proto.DeviceCapabilities.userHasAvatar: object expected");a.userHasAvatar=p.proto.DeviceCapabilities.UserHasAvatar.fromObject(e.userHasAvatar)}switch(e.memberNameTagPrimarySupport){default:if(typeof e.memberNameTagPrimarySupport=="number"){a.memberNameTagPrimarySupport=e.memberNameTagPrimarySupport;break}break;case"DISABLED":case 0:a.memberNameTagPrimarySupport=0;break;case"RECEIVER_ENABLED":case 1:a.memberNameTagPrimarySupport=1;break;case"SENDER_ENABLED":case 2:a.memberNameTagPrimarySupport=2;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.chatLockSupportLevel!=null&&e.hasOwnProperty("chatLockSupportLevel")&&(A.chatLockSupportLevel=a.enums===String?p.proto.DeviceCapabilities.ChatLockSupportLevel[e.chatLockSupportLevel]===void 0?e.chatLockSupportLevel:p.proto.DeviceCapabilities.ChatLockSupportLevel[e.chatLockSupportLevel]:e.chatLockSupportLevel,a.oneofs&&(A._chatLockSupportLevel="chatLockSupportLevel")),e.lidMigration!=null&&e.hasOwnProperty("lidMigration")&&(A.lidMigration=p.proto.DeviceCapabilities.LIDMigration.toObject(e.lidMigration,a),a.oneofs&&(A._lidMigration="lidMigration")),e.businessBroadcast!=null&&e.hasOwnProperty("businessBroadcast")&&(A.businessBroadcast=p.proto.DeviceCapabilities.BusinessBroadcast.toObject(e.businessBroadcast,a),a.oneofs&&(A._businessBroadcast="businessBroadcast")),e.userHasAvatar!=null&&e.hasOwnProperty("userHasAvatar")&&(A.userHasAvatar=p.proto.DeviceCapabilities.UserHasAvatar.toObject(e.userHasAvatar,a),a.oneofs&&(A._userHasAvatar="userHasAvatar")),e.memberNameTagPrimarySupport!=null&&e.hasOwnProperty("memberNameTagPrimarySupport")&&(A.memberNameTagPrimarySupport=a.enums===String?p.proto.DeviceCapabilities.MemberNameTagPrimarySupport[e.memberNameTagPrimarySupport]===void 0?e.memberNameTagPrimarySupport:p.proto.DeviceCapabilities.MemberNameTagPrimarySupport[e.memberNameTagPrimarySupport]:e.memberNameTagPrimarySupport,a.oneofs&&(A._memberNameTagPrimarySupport="memberNameTagPrimarySupport")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DeviceCapabilities"},t.BusinessBroadcast=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.importListEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.DeviceCapabilities.BusinessBroadcast)return A;var r=new p.proto.DeviceCapabilities.BusinessBroadcast;return A.importListEnabled!=null&&(r.importListEnabled=!!A.importListEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.importListEnabled!=null&&A.hasOwnProperty("importListEnabled")&&(s.importListEnabled=A.importListEnabled,r.oneofs&&(s._importListEnabled="importListEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceCapabilities.BusinessBroadcast"},i})(),t.ChatLockSupportLevel=(function(){let i={},e=Object.create(i);return e[i[0]="NONE"]=0,e[i[1]="MINIMAL"]=1,e[i[2]="FULL"]=2,e})(),t.LIDMigration=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.chatDbMigrationTimestamp=A.uint64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.DeviceCapabilities.LIDMigration)return A;var r=new p.proto.DeviceCapabilities.LIDMigration;return A.chatDbMigrationTimestamp!=null&&(l.Long?(r.chatDbMigrationTimestamp=l.Long.fromValue(A.chatDbMigrationTimestamp)).unsigned=!0:typeof A.chatDbMigrationTimestamp=="string"?r.chatDbMigrationTimestamp=parseInt(A.chatDbMigrationTimestamp,10):typeof A.chatDbMigrationTimestamp=="number"?r.chatDbMigrationTimestamp=A.chatDbMigrationTimestamp:typeof A.chatDbMigrationTimestamp=="object"&&(r.chatDbMigrationTimestamp=new l.LongBits(A.chatDbMigrationTimestamp.low>>>0,A.chatDbMigrationTimestamp.high>>>0).toNumber(!0))),r},i.toObject=function(A,r){r||(r={});var s={};return A.chatDbMigrationTimestamp!=null&&A.hasOwnProperty("chatDbMigrationTimestamp")&&(typeof A.chatDbMigrationTimestamp=="number"?s.chatDbMigrationTimestamp=r.longs===String?String(A.chatDbMigrationTimestamp):A.chatDbMigrationTimestamp:s.chatDbMigrationTimestamp=r.longs===String?se(A.chatDbMigrationTimestamp,!0):r.longs===Number?ge(A.chatDbMigrationTimestamp,!0):A.chatDbMigrationTimestamp,r.oneofs&&(s._chatDbMigrationTimestamp="chatDbMigrationTimestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceCapabilities.LIDMigration"},i})(),t.MemberNameTagPrimarySupport=(function(){let i={},e=Object.create(i);return e[i[0]="DISABLED"]=0,e[i[1]="RECEIVER_ENABLED"]=1,e[i[2]="SENDER_ENABLED"]=2,e})(),t.UserHasAvatar=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.userHasAvatar=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.DeviceCapabilities.UserHasAvatar)return A;var r=new p.proto.DeviceCapabilities.UserHasAvatar;return A.userHasAvatar!=null&&(r.userHasAvatar=!!A.userHasAvatar),r},i.toObject=function(A,r){r||(r={});var s={};return A.userHasAvatar!=null&&A.hasOwnProperty("userHasAvatar")&&(s.userHasAvatar=A.userHasAvatar,r.oneofs&&(s._userHasAvatar="userHasAvatar")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceCapabilities.UserHasAvatar"},i})(),t})(),n.DeviceConsistencyCodeMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.generation=e.uint32();break}case 2:{s.signature=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.DeviceConsistencyCodeMessage)return e;var a=new p.proto.DeviceConsistencyCodeMessage;return e.generation!=null&&(a.generation=e.generation>>>0),e.signature!=null&&(typeof e.signature=="string"?l.base64.decode(e.signature,a.signature=l.newBuffer(l.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),a},t.toObject=function(e,a){a||(a={});var A={};return e.generation!=null&&e.hasOwnProperty("generation")&&(A.generation=e.generation,a.oneofs&&(A._generation="generation")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?l.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DeviceConsistencyCodeMessage"},t})(),n.DeviceListMetadata=(function(){function t(i){if(this.senderKeyIndexes=[],this.recipientKeyIndexes=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.senderKeyHash=e.bytes();break}case 2:{s.senderTimestamp=e.uint64();break}case 3:{if(s.senderKeyIndexes&&s.senderKeyIndexes.length||(s.senderKeyIndexes=[]),(g&7)===2)for(var c=e.uint32()+e.pos;e.pos=0&&(a.senderKeyHash=e.senderKeyHash)),e.senderTimestamp!=null&&(l.Long?(a.senderTimestamp=l.Long.fromValue(e.senderTimestamp)).unsigned=!0:typeof e.senderTimestamp=="string"?a.senderTimestamp=parseInt(e.senderTimestamp,10):typeof e.senderTimestamp=="number"?a.senderTimestamp=e.senderTimestamp:typeof e.senderTimestamp=="object"&&(a.senderTimestamp=new l.LongBits(e.senderTimestamp.low>>>0,e.senderTimestamp.high>>>0).toNumber(!0))),e.senderKeyIndexes){if(!Array.isArray(e.senderKeyIndexes))throw TypeError(".proto.DeviceListMetadata.senderKeyIndexes: array expected");a.senderKeyIndexes=[];for(var A=0;A>>0}switch(e.senderAccountType){default:if(typeof e.senderAccountType=="number"){a.senderAccountType=e.senderAccountType;break}break;case"E2EE":case 0:a.senderAccountType=0;break;case"HOSTED":case 1:a.senderAccountType=1;break}switch(e.receiverAccountType){default:if(typeof e.receiverAccountType=="number"){a.receiverAccountType=e.receiverAccountType;break}break;case"E2EE":case 0:a.receiverAccountType=0;break;case"HOSTED":case 1:a.receiverAccountType=1;break}if(e.recipientKeyHash!=null&&(typeof e.recipientKeyHash=="string"?l.base64.decode(e.recipientKeyHash,a.recipientKeyHash=l.newBuffer(l.base64.length(e.recipientKeyHash)),0):e.recipientKeyHash.length>=0&&(a.recipientKeyHash=e.recipientKeyHash)),e.recipientTimestamp!=null&&(l.Long?(a.recipientTimestamp=l.Long.fromValue(e.recipientTimestamp)).unsigned=!0:typeof e.recipientTimestamp=="string"?a.recipientTimestamp=parseInt(e.recipientTimestamp,10):typeof e.recipientTimestamp=="number"?a.recipientTimestamp=e.recipientTimestamp:typeof e.recipientTimestamp=="object"&&(a.recipientTimestamp=new l.LongBits(e.recipientTimestamp.low>>>0,e.recipientTimestamp.high>>>0).toNumber(!0))),e.recipientKeyIndexes){if(!Array.isArray(e.recipientKeyIndexes))throw TypeError(".proto.DeviceListMetadata.recipientKeyIndexes: array expected");a.recipientKeyIndexes=[];for(var A=0;A>>0}return a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.senderKeyIndexes=[],A.recipientKeyIndexes=[]),e.senderKeyHash!=null&&e.hasOwnProperty("senderKeyHash")&&(A.senderKeyHash=a.bytes===String?l.base64.encode(e.senderKeyHash,0,e.senderKeyHash.length):a.bytes===Array?Array.prototype.slice.call(e.senderKeyHash):e.senderKeyHash,a.oneofs&&(A._senderKeyHash="senderKeyHash")),e.senderTimestamp!=null&&e.hasOwnProperty("senderTimestamp")&&(typeof e.senderTimestamp=="number"?A.senderTimestamp=a.longs===String?String(e.senderTimestamp):e.senderTimestamp:A.senderTimestamp=a.longs===String?se(e.senderTimestamp,!0):a.longs===Number?ge(e.senderTimestamp,!0):e.senderTimestamp,a.oneofs&&(A._senderTimestamp="senderTimestamp")),e.senderKeyIndexes&&e.senderKeyIndexes.length){A.senderKeyIndexes=[];for(var r=0;r>>3){case 1:{s.os=e.string();break}case 2:{s.version=p.proto.DeviceProps.AppVersion.decode(e,e.uint32());break}case 3:{s.platformType=e.int32();break}case 4:{s.requireFullSync=e.bool();break}case 5:{s.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.DeviceProps)return e;var a=new p.proto.DeviceProps;if(e.os!=null&&(a.os=String(e.os)),e.version!=null){if(typeof e.version!="object")throw TypeError(".proto.DeviceProps.version: object expected");a.version=p.proto.DeviceProps.AppVersion.fromObject(e.version)}switch(e.platformType){default:if(typeof e.platformType=="number"){a.platformType=e.platformType;break}break;case"UNKNOWN":case 0:a.platformType=0;break;case"CHROME":case 1:a.platformType=1;break;case"FIREFOX":case 2:a.platformType=2;break;case"IE":case 3:a.platformType=3;break;case"OPERA":case 4:a.platformType=4;break;case"SAFARI":case 5:a.platformType=5;break;case"EDGE":case 6:a.platformType=6;break;case"DESKTOP":case 7:a.platformType=7;break;case"IPAD":case 8:a.platformType=8;break;case"ANDROID_TABLET":case 9:a.platformType=9;break;case"OHANA":case 10:a.platformType=10;break;case"ALOHA":case 11:a.platformType=11;break;case"CATALINA":case 12:a.platformType=12;break;case"TCL_TV":case 13:a.platformType=13;break;case"IOS_PHONE":case 14:a.platformType=14;break;case"IOS_CATALYST":case 15:a.platformType=15;break;case"ANDROID_PHONE":case 16:a.platformType=16;break;case"ANDROID_AMBIGUOUS":case 17:a.platformType=17;break;case"WEAR_OS":case 18:a.platformType=18;break;case"AR_WRIST":case 19:a.platformType=19;break;case"AR_DEVICE":case 20:a.platformType=20;break;case"UWP":case 21:a.platformType=21;break;case"VR":case 22:a.platformType=22;break;case"CLOUD_API":case 23:a.platformType=23;break;case"SMARTGLASSES":case 24:a.platformType=24;break}if(e.requireFullSync!=null&&(a.requireFullSync=!!e.requireFullSync),e.historySyncConfig!=null){if(typeof e.historySyncConfig!="object")throw TypeError(".proto.DeviceProps.historySyncConfig: object expected");a.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.fromObject(e.historySyncConfig)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.os!=null&&e.hasOwnProperty("os")&&(A.os=e.os,a.oneofs&&(A._os="os")),e.version!=null&&e.hasOwnProperty("version")&&(A.version=p.proto.DeviceProps.AppVersion.toObject(e.version,a),a.oneofs&&(A._version="version")),e.platformType!=null&&e.hasOwnProperty("platformType")&&(A.platformType=a.enums===String?p.proto.DeviceProps.PlatformType[e.platformType]===void 0?e.platformType:p.proto.DeviceProps.PlatformType[e.platformType]:e.platformType,a.oneofs&&(A._platformType="platformType")),e.requireFullSync!=null&&e.hasOwnProperty("requireFullSync")&&(A.requireFullSync=e.requireFullSync,a.oneofs&&(A._requireFullSync="requireFullSync")),e.historySyncConfig!=null&&e.hasOwnProperty("historySyncConfig")&&(A.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.toObject(e.historySyncConfig,a),a.oneofs&&(A._historySyncConfig="historySyncConfig")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DeviceProps"},t.AppVersion=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.primary=A.uint32();break}case 2:{c.secondary=A.uint32();break}case 3:{c.tertiary=A.uint32();break}case 4:{c.quaternary=A.uint32();break}case 5:{c.quinary=A.uint32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.DeviceProps.AppVersion)return A;var r=new p.proto.DeviceProps.AppVersion;return A.primary!=null&&(r.primary=A.primary>>>0),A.secondary!=null&&(r.secondary=A.secondary>>>0),A.tertiary!=null&&(r.tertiary=A.tertiary>>>0),A.quaternary!=null&&(r.quaternary=A.quaternary>>>0),A.quinary!=null&&(r.quinary=A.quinary>>>0),r},i.toObject=function(A,r){r||(r={});var s={};return A.primary!=null&&A.hasOwnProperty("primary")&&(s.primary=A.primary,r.oneofs&&(s._primary="primary")),A.secondary!=null&&A.hasOwnProperty("secondary")&&(s.secondary=A.secondary,r.oneofs&&(s._secondary="secondary")),A.tertiary!=null&&A.hasOwnProperty("tertiary")&&(s.tertiary=A.tertiary,r.oneofs&&(s._tertiary="tertiary")),A.quaternary!=null&&A.hasOwnProperty("quaternary")&&(s.quaternary=A.quaternary,r.oneofs&&(s._quaternary="quaternary")),A.quinary!=null&&A.hasOwnProperty("quinary")&&(s.quinary=A.quinary,r.oneofs&&(s._quinary="quinary")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceProps.AppVersion"},i})(),t.HistorySyncConfig=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.fullSyncDaysLimit=A.uint32();break}case 2:{c.fullSyncSizeMbLimit=A.uint32();break}case 3:{c.storageQuotaMb=A.uint32();break}case 4:{c.inlineInitialPayloadInE2EeMsg=A.bool();break}case 5:{c.recentSyncDaysLimit=A.uint32();break}case 6:{c.supportCallLogHistory=A.bool();break}case 7:{c.supportBotUserAgentChatHistory=A.bool();break}case 8:{c.supportCagReactionsAndPolls=A.bool();break}case 9:{c.supportBizHostedMsg=A.bool();break}case 10:{c.supportRecentSyncChunkMessageCountTuning=A.bool();break}case 11:{c.supportHostedGroupMsg=A.bool();break}case 12:{c.supportFbidBotChatHistory=A.bool();break}case 13:{c.supportAddOnHistorySyncMigration=A.bool();break}case 14:{c.supportMessageAssociation=A.bool();break}case 15:{c.supportGroupHistory=A.bool();break}case 16:{c.onDemandReady=A.bool();break}case 17:{c.supportGuestChat=A.bool();break}case 18:{c.completeOnDemandReady=A.bool();break}case 19:{c.thumbnailSyncDaysLimit=A.uint32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.DeviceProps.HistorySyncConfig)return A;var r=new p.proto.DeviceProps.HistorySyncConfig;return A.fullSyncDaysLimit!=null&&(r.fullSyncDaysLimit=A.fullSyncDaysLimit>>>0),A.fullSyncSizeMbLimit!=null&&(r.fullSyncSizeMbLimit=A.fullSyncSizeMbLimit>>>0),A.storageQuotaMb!=null&&(r.storageQuotaMb=A.storageQuotaMb>>>0),A.inlineInitialPayloadInE2EeMsg!=null&&(r.inlineInitialPayloadInE2EeMsg=!!A.inlineInitialPayloadInE2EeMsg),A.recentSyncDaysLimit!=null&&(r.recentSyncDaysLimit=A.recentSyncDaysLimit>>>0),A.supportCallLogHistory!=null&&(r.supportCallLogHistory=!!A.supportCallLogHistory),A.supportBotUserAgentChatHistory!=null&&(r.supportBotUserAgentChatHistory=!!A.supportBotUserAgentChatHistory),A.supportCagReactionsAndPolls!=null&&(r.supportCagReactionsAndPolls=!!A.supportCagReactionsAndPolls),A.supportBizHostedMsg!=null&&(r.supportBizHostedMsg=!!A.supportBizHostedMsg),A.supportRecentSyncChunkMessageCountTuning!=null&&(r.supportRecentSyncChunkMessageCountTuning=!!A.supportRecentSyncChunkMessageCountTuning),A.supportHostedGroupMsg!=null&&(r.supportHostedGroupMsg=!!A.supportHostedGroupMsg),A.supportFbidBotChatHistory!=null&&(r.supportFbidBotChatHistory=!!A.supportFbidBotChatHistory),A.supportAddOnHistorySyncMigration!=null&&(r.supportAddOnHistorySyncMigration=!!A.supportAddOnHistorySyncMigration),A.supportMessageAssociation!=null&&(r.supportMessageAssociation=!!A.supportMessageAssociation),A.supportGroupHistory!=null&&(r.supportGroupHistory=!!A.supportGroupHistory),A.onDemandReady!=null&&(r.onDemandReady=!!A.onDemandReady),A.supportGuestChat!=null&&(r.supportGuestChat=!!A.supportGuestChat),A.completeOnDemandReady!=null&&(r.completeOnDemandReady=!!A.completeOnDemandReady),A.thumbnailSyncDaysLimit!=null&&(r.thumbnailSyncDaysLimit=A.thumbnailSyncDaysLimit>>>0),r},i.toObject=function(A,r){r||(r={});var s={};return A.fullSyncDaysLimit!=null&&A.hasOwnProperty("fullSyncDaysLimit")&&(s.fullSyncDaysLimit=A.fullSyncDaysLimit,r.oneofs&&(s._fullSyncDaysLimit="fullSyncDaysLimit")),A.fullSyncSizeMbLimit!=null&&A.hasOwnProperty("fullSyncSizeMbLimit")&&(s.fullSyncSizeMbLimit=A.fullSyncSizeMbLimit,r.oneofs&&(s._fullSyncSizeMbLimit="fullSyncSizeMbLimit")),A.storageQuotaMb!=null&&A.hasOwnProperty("storageQuotaMb")&&(s.storageQuotaMb=A.storageQuotaMb,r.oneofs&&(s._storageQuotaMb="storageQuotaMb")),A.inlineInitialPayloadInE2EeMsg!=null&&A.hasOwnProperty("inlineInitialPayloadInE2EeMsg")&&(s.inlineInitialPayloadInE2EeMsg=A.inlineInitialPayloadInE2EeMsg,r.oneofs&&(s._inlineInitialPayloadInE2EeMsg="inlineInitialPayloadInE2EeMsg")),A.recentSyncDaysLimit!=null&&A.hasOwnProperty("recentSyncDaysLimit")&&(s.recentSyncDaysLimit=A.recentSyncDaysLimit,r.oneofs&&(s._recentSyncDaysLimit="recentSyncDaysLimit")),A.supportCallLogHistory!=null&&A.hasOwnProperty("supportCallLogHistory")&&(s.supportCallLogHistory=A.supportCallLogHistory,r.oneofs&&(s._supportCallLogHistory="supportCallLogHistory")),A.supportBotUserAgentChatHistory!=null&&A.hasOwnProperty("supportBotUserAgentChatHistory")&&(s.supportBotUserAgentChatHistory=A.supportBotUserAgentChatHistory,r.oneofs&&(s._supportBotUserAgentChatHistory="supportBotUserAgentChatHistory")),A.supportCagReactionsAndPolls!=null&&A.hasOwnProperty("supportCagReactionsAndPolls")&&(s.supportCagReactionsAndPolls=A.supportCagReactionsAndPolls,r.oneofs&&(s._supportCagReactionsAndPolls="supportCagReactionsAndPolls")),A.supportBizHostedMsg!=null&&A.hasOwnProperty("supportBizHostedMsg")&&(s.supportBizHostedMsg=A.supportBizHostedMsg,r.oneofs&&(s._supportBizHostedMsg="supportBizHostedMsg")),A.supportRecentSyncChunkMessageCountTuning!=null&&A.hasOwnProperty("supportRecentSyncChunkMessageCountTuning")&&(s.supportRecentSyncChunkMessageCountTuning=A.supportRecentSyncChunkMessageCountTuning,r.oneofs&&(s._supportRecentSyncChunkMessageCountTuning="supportRecentSyncChunkMessageCountTuning")),A.supportHostedGroupMsg!=null&&A.hasOwnProperty("supportHostedGroupMsg")&&(s.supportHostedGroupMsg=A.supportHostedGroupMsg,r.oneofs&&(s._supportHostedGroupMsg="supportHostedGroupMsg")),A.supportFbidBotChatHistory!=null&&A.hasOwnProperty("supportFbidBotChatHistory")&&(s.supportFbidBotChatHistory=A.supportFbidBotChatHistory,r.oneofs&&(s._supportFbidBotChatHistory="supportFbidBotChatHistory")),A.supportAddOnHistorySyncMigration!=null&&A.hasOwnProperty("supportAddOnHistorySyncMigration")&&(s.supportAddOnHistorySyncMigration=A.supportAddOnHistorySyncMigration,r.oneofs&&(s._supportAddOnHistorySyncMigration="supportAddOnHistorySyncMigration")),A.supportMessageAssociation!=null&&A.hasOwnProperty("supportMessageAssociation")&&(s.supportMessageAssociation=A.supportMessageAssociation,r.oneofs&&(s._supportMessageAssociation="supportMessageAssociation")),A.supportGroupHistory!=null&&A.hasOwnProperty("supportGroupHistory")&&(s.supportGroupHistory=A.supportGroupHistory,r.oneofs&&(s._supportGroupHistory="supportGroupHistory")),A.onDemandReady!=null&&A.hasOwnProperty("onDemandReady")&&(s.onDemandReady=A.onDemandReady,r.oneofs&&(s._onDemandReady="onDemandReady")),A.supportGuestChat!=null&&A.hasOwnProperty("supportGuestChat")&&(s.supportGuestChat=A.supportGuestChat,r.oneofs&&(s._supportGuestChat="supportGuestChat")),A.completeOnDemandReady!=null&&A.hasOwnProperty("completeOnDemandReady")&&(s.completeOnDemandReady=A.completeOnDemandReady,r.oneofs&&(s._completeOnDemandReady="completeOnDemandReady")),A.thumbnailSyncDaysLimit!=null&&A.hasOwnProperty("thumbnailSyncDaysLimit")&&(s.thumbnailSyncDaysLimit=A.thumbnailSyncDaysLimit,r.oneofs&&(s._thumbnailSyncDaysLimit="thumbnailSyncDaysLimit")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.DeviceProps.HistorySyncConfig"},i})(),t.PlatformType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHROME"]=1,e[i[2]="FIREFOX"]=2,e[i[3]="IE"]=3,e[i[4]="OPERA"]=4,e[i[5]="SAFARI"]=5,e[i[6]="EDGE"]=6,e[i[7]="DESKTOP"]=7,e[i[8]="IPAD"]=8,e[i[9]="ANDROID_TABLET"]=9,e[i[10]="OHANA"]=10,e[i[11]="ALOHA"]=11,e[i[12]="CATALINA"]=12,e[i[13]="TCL_TV"]=13,e[i[14]="IOS_PHONE"]=14,e[i[15]="IOS_CATALYST"]=15,e[i[16]="ANDROID_PHONE"]=16,e[i[17]="ANDROID_AMBIGUOUS"]=17,e[i[18]="WEAR_OS"]=18,e[i[19]="AR_WRIST"]=19,e[i[20]="AR_DEVICE"]=20,e[i[21]="UWP"]=21,e[i[22]="VR"]=22,e[i[23]="CLOUD_API"]=23,e[i[24]="SMARTGLASSES"]=24,e})(),t})(),n.DisappearingMode=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.initiator=e.int32();break}case 2:{s.trigger=e.int32();break}case 3:{s.initiatorDeviceJid=e.string();break}case 4:{s.initiatedByMe=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.DisappearingMode)return e;var a=new p.proto.DisappearingMode;switch(e.initiator){default:if(typeof e.initiator=="number"){a.initiator=e.initiator;break}break;case"CHANGED_IN_CHAT":case 0:a.initiator=0;break;case"INITIATED_BY_ME":case 1:a.initiator=1;break;case"INITIATED_BY_OTHER":case 2:a.initiator=2;break;case"BIZ_UPGRADE_FB_HOSTING":case 3:a.initiator=3;break}switch(e.trigger){default:if(typeof e.trigger=="number"){a.trigger=e.trigger;break}break;case"UNKNOWN":case 0:a.trigger=0;break;case"CHAT_SETTING":case 1:a.trigger=1;break;case"ACCOUNT_SETTING":case 2:a.trigger=2;break;case"BULK_CHANGE":case 3:a.trigger=3;break;case"BIZ_SUPPORTS_FB_HOSTING":case 4:a.trigger=4;break;case"UNKNOWN_GROUPS":case 5:a.trigger=5;break}return e.initiatorDeviceJid!=null&&(a.initiatorDeviceJid=String(e.initiatorDeviceJid)),e.initiatedByMe!=null&&(a.initiatedByMe=!!e.initiatedByMe),a},t.toObject=function(e,a){a||(a={});var A={};return e.initiator!=null&&e.hasOwnProperty("initiator")&&(A.initiator=a.enums===String?p.proto.DisappearingMode.Initiator[e.initiator]===void 0?e.initiator:p.proto.DisappearingMode.Initiator[e.initiator]:e.initiator,a.oneofs&&(A._initiator="initiator")),e.trigger!=null&&e.hasOwnProperty("trigger")&&(A.trigger=a.enums===String?p.proto.DisappearingMode.Trigger[e.trigger]===void 0?e.trigger:p.proto.DisappearingMode.Trigger[e.trigger]:e.trigger,a.oneofs&&(A._trigger="trigger")),e.initiatorDeviceJid!=null&&e.hasOwnProperty("initiatorDeviceJid")&&(A.initiatorDeviceJid=e.initiatorDeviceJid,a.oneofs&&(A._initiatorDeviceJid="initiatorDeviceJid")),e.initiatedByMe!=null&&e.hasOwnProperty("initiatedByMe")&&(A.initiatedByMe=e.initiatedByMe,a.oneofs&&(A._initiatedByMe="initiatedByMe")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.DisappearingMode"},t.Initiator=(function(){let i={},e=Object.create(i);return e[i[0]="CHANGED_IN_CHAT"]=0,e[i[1]="INITIATED_BY_ME"]=1,e[i[2]="INITIATED_BY_OTHER"]=2,e[i[3]="BIZ_UPGRADE_FB_HOSTING"]=3,e})(),t.Trigger=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHAT_SETTING"]=1,e[i[2]="ACCOUNT_SETTING"]=2,e[i[3]="BULK_CHANGE"]=3,e[i[4]="BIZ_SUPPORTS_FB_HOSTING"]=4,e[i[5]="UNKNOWN_GROUPS"]=5,e})(),t})(),n.EmbeddedContent=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.embeddedMessage=p.proto.EmbeddedMessage.decode(e,e.uint32());break}case 2:{s.embeddedMusic=p.proto.EmbeddedMusic.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EmbeddedContent)return e;var a=new p.proto.EmbeddedContent;if(e.embeddedMessage!=null){if(typeof e.embeddedMessage!="object")throw TypeError(".proto.EmbeddedContent.embeddedMessage: object expected");a.embeddedMessage=p.proto.EmbeddedMessage.fromObject(e.embeddedMessage)}if(e.embeddedMusic!=null){if(typeof e.embeddedMusic!="object")throw TypeError(".proto.EmbeddedContent.embeddedMusic: object expected");a.embeddedMusic=p.proto.EmbeddedMusic.fromObject(e.embeddedMusic)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.embeddedMessage!=null&&e.hasOwnProperty("embeddedMessage")&&(A.embeddedMessage=p.proto.EmbeddedMessage.toObject(e.embeddedMessage,a),a.oneofs&&(A.content="embeddedMessage")),e.embeddedMusic!=null&&e.hasOwnProperty("embeddedMusic")&&(A.embeddedMusic=p.proto.EmbeddedMusic.toObject(e.embeddedMusic,a),a.oneofs&&(A.content="embeddedMusic")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EmbeddedContent"},t})(),n.EmbeddedMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.stanzaId=e.string();break}case 2:{s.message=p.proto.Message.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EmbeddedMessage)return e;var a=new p.proto.EmbeddedMessage;if(e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.EmbeddedMessage.message: object expected");a.message=p.proto.Message.fromObject(e.message)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=p.proto.Message.toObject(e.message,a),a.oneofs&&(A._message="message")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EmbeddedMessage"},t})(),n.EmbeddedMusic=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.musicContentMediaId=e.string();break}case 2:{s.songId=e.string();break}case 3:{s.author=e.string();break}case 4:{s.title=e.string();break}case 5:{s.artworkDirectPath=e.string();break}case 6:{s.artworkSha256=e.bytes();break}case 7:{s.artworkEncSha256=e.bytes();break}case 8:{s.artistAttribution=e.string();break}case 9:{s.countryBlocklist=e.bytes();break}case 10:{s.isExplicit=e.bool();break}case 11:{s.artworkMediaKey=e.bytes();break}case 12:{s.musicSongStartTimeInMs=e.int64();break}case 13:{s.derivedContentStartTimeInMs=e.int64();break}case 14:{s.overlapDurationInMs=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EmbeddedMusic)return e;var a=new p.proto.EmbeddedMusic;return e.musicContentMediaId!=null&&(a.musicContentMediaId=String(e.musicContentMediaId)),e.songId!=null&&(a.songId=String(e.songId)),e.author!=null&&(a.author=String(e.author)),e.title!=null&&(a.title=String(e.title)),e.artworkDirectPath!=null&&(a.artworkDirectPath=String(e.artworkDirectPath)),e.artworkSha256!=null&&(typeof e.artworkSha256=="string"?l.base64.decode(e.artworkSha256,a.artworkSha256=l.newBuffer(l.base64.length(e.artworkSha256)),0):e.artworkSha256.length>=0&&(a.artworkSha256=e.artworkSha256)),e.artworkEncSha256!=null&&(typeof e.artworkEncSha256=="string"?l.base64.decode(e.artworkEncSha256,a.artworkEncSha256=l.newBuffer(l.base64.length(e.artworkEncSha256)),0):e.artworkEncSha256.length>=0&&(a.artworkEncSha256=e.artworkEncSha256)),e.artistAttribution!=null&&(a.artistAttribution=String(e.artistAttribution)),e.countryBlocklist!=null&&(typeof e.countryBlocklist=="string"?l.base64.decode(e.countryBlocklist,a.countryBlocklist=l.newBuffer(l.base64.length(e.countryBlocklist)),0):e.countryBlocklist.length>=0&&(a.countryBlocklist=e.countryBlocklist)),e.isExplicit!=null&&(a.isExplicit=!!e.isExplicit),e.artworkMediaKey!=null&&(typeof e.artworkMediaKey=="string"?l.base64.decode(e.artworkMediaKey,a.artworkMediaKey=l.newBuffer(l.base64.length(e.artworkMediaKey)),0):e.artworkMediaKey.length>=0&&(a.artworkMediaKey=e.artworkMediaKey)),e.musicSongStartTimeInMs!=null&&(l.Long?(a.musicSongStartTimeInMs=l.Long.fromValue(e.musicSongStartTimeInMs)).unsigned=!1:typeof e.musicSongStartTimeInMs=="string"?a.musicSongStartTimeInMs=parseInt(e.musicSongStartTimeInMs,10):typeof e.musicSongStartTimeInMs=="number"?a.musicSongStartTimeInMs=e.musicSongStartTimeInMs:typeof e.musicSongStartTimeInMs=="object"&&(a.musicSongStartTimeInMs=new l.LongBits(e.musicSongStartTimeInMs.low>>>0,e.musicSongStartTimeInMs.high>>>0).toNumber())),e.derivedContentStartTimeInMs!=null&&(l.Long?(a.derivedContentStartTimeInMs=l.Long.fromValue(e.derivedContentStartTimeInMs)).unsigned=!1:typeof e.derivedContentStartTimeInMs=="string"?a.derivedContentStartTimeInMs=parseInt(e.derivedContentStartTimeInMs,10):typeof e.derivedContentStartTimeInMs=="number"?a.derivedContentStartTimeInMs=e.derivedContentStartTimeInMs:typeof e.derivedContentStartTimeInMs=="object"&&(a.derivedContentStartTimeInMs=new l.LongBits(e.derivedContentStartTimeInMs.low>>>0,e.derivedContentStartTimeInMs.high>>>0).toNumber())),e.overlapDurationInMs!=null&&(l.Long?(a.overlapDurationInMs=l.Long.fromValue(e.overlapDurationInMs)).unsigned=!1:typeof e.overlapDurationInMs=="string"?a.overlapDurationInMs=parseInt(e.overlapDurationInMs,10):typeof e.overlapDurationInMs=="number"?a.overlapDurationInMs=e.overlapDurationInMs:typeof e.overlapDurationInMs=="object"&&(a.overlapDurationInMs=new l.LongBits(e.overlapDurationInMs.low>>>0,e.overlapDurationInMs.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.musicContentMediaId!=null&&e.hasOwnProperty("musicContentMediaId")&&(A.musicContentMediaId=e.musicContentMediaId,a.oneofs&&(A._musicContentMediaId="musicContentMediaId")),e.songId!=null&&e.hasOwnProperty("songId")&&(A.songId=e.songId,a.oneofs&&(A._songId="songId")),e.author!=null&&e.hasOwnProperty("author")&&(A.author=e.author,a.oneofs&&(A._author="author")),e.title!=null&&e.hasOwnProperty("title")&&(A.title=e.title,a.oneofs&&(A._title="title")),e.artworkDirectPath!=null&&e.hasOwnProperty("artworkDirectPath")&&(A.artworkDirectPath=e.artworkDirectPath,a.oneofs&&(A._artworkDirectPath="artworkDirectPath")),e.artworkSha256!=null&&e.hasOwnProperty("artworkSha256")&&(A.artworkSha256=a.bytes===String?l.base64.encode(e.artworkSha256,0,e.artworkSha256.length):a.bytes===Array?Array.prototype.slice.call(e.artworkSha256):e.artworkSha256,a.oneofs&&(A._artworkSha256="artworkSha256")),e.artworkEncSha256!=null&&e.hasOwnProperty("artworkEncSha256")&&(A.artworkEncSha256=a.bytes===String?l.base64.encode(e.artworkEncSha256,0,e.artworkEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.artworkEncSha256):e.artworkEncSha256,a.oneofs&&(A._artworkEncSha256="artworkEncSha256")),e.artistAttribution!=null&&e.hasOwnProperty("artistAttribution")&&(A.artistAttribution=e.artistAttribution,a.oneofs&&(A._artistAttribution="artistAttribution")),e.countryBlocklist!=null&&e.hasOwnProperty("countryBlocklist")&&(A.countryBlocklist=a.bytes===String?l.base64.encode(e.countryBlocklist,0,e.countryBlocklist.length):a.bytes===Array?Array.prototype.slice.call(e.countryBlocklist):e.countryBlocklist,a.oneofs&&(A._countryBlocklist="countryBlocklist")),e.isExplicit!=null&&e.hasOwnProperty("isExplicit")&&(A.isExplicit=e.isExplicit,a.oneofs&&(A._isExplicit="isExplicit")),e.artworkMediaKey!=null&&e.hasOwnProperty("artworkMediaKey")&&(A.artworkMediaKey=a.bytes===String?l.base64.encode(e.artworkMediaKey,0,e.artworkMediaKey.length):a.bytes===Array?Array.prototype.slice.call(e.artworkMediaKey):e.artworkMediaKey,a.oneofs&&(A._artworkMediaKey="artworkMediaKey")),e.musicSongStartTimeInMs!=null&&e.hasOwnProperty("musicSongStartTimeInMs")&&(typeof e.musicSongStartTimeInMs=="number"?A.musicSongStartTimeInMs=a.longs===String?String(e.musicSongStartTimeInMs):e.musicSongStartTimeInMs:A.musicSongStartTimeInMs=a.longs===String?se(e.musicSongStartTimeInMs):a.longs===Number?ge(e.musicSongStartTimeInMs):e.musicSongStartTimeInMs,a.oneofs&&(A._musicSongStartTimeInMs="musicSongStartTimeInMs")),e.derivedContentStartTimeInMs!=null&&e.hasOwnProperty("derivedContentStartTimeInMs")&&(typeof e.derivedContentStartTimeInMs=="number"?A.derivedContentStartTimeInMs=a.longs===String?String(e.derivedContentStartTimeInMs):e.derivedContentStartTimeInMs:A.derivedContentStartTimeInMs=a.longs===String?se(e.derivedContentStartTimeInMs):a.longs===Number?ge(e.derivedContentStartTimeInMs):e.derivedContentStartTimeInMs,a.oneofs&&(A._derivedContentStartTimeInMs="derivedContentStartTimeInMs")),e.overlapDurationInMs!=null&&e.hasOwnProperty("overlapDurationInMs")&&(typeof e.overlapDurationInMs=="number"?A.overlapDurationInMs=a.longs===String?String(e.overlapDurationInMs):e.overlapDurationInMs:A.overlapDurationInMs=a.longs===String?se(e.overlapDurationInMs):a.longs===Number?ge(e.overlapDurationInMs):e.overlapDurationInMs,a.oneofs&&(A._overlapDurationInMs="overlapDurationInMs")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EmbeddedMusic"},t})(),n.EncryptedPairingRequest=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encryptedPayload=e.bytes();break}case 2:{s.iv=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EncryptedPairingRequest)return e;var a=new p.proto.EncryptedPairingRequest;return e.encryptedPayload!=null&&(typeof e.encryptedPayload=="string"?l.base64.decode(e.encryptedPayload,a.encryptedPayload=l.newBuffer(l.base64.length(e.encryptedPayload)),0):e.encryptedPayload.length>=0&&(a.encryptedPayload=e.encryptedPayload)),e.iv!=null&&(typeof e.iv=="string"?l.base64.decode(e.iv,a.iv=l.newBuffer(l.base64.length(e.iv)),0):e.iv.length>=0&&(a.iv=e.iv)),a},t.toObject=function(e,a){a||(a={});var A={};return e.encryptedPayload!=null&&e.hasOwnProperty("encryptedPayload")&&(A.encryptedPayload=a.bytes===String?l.base64.encode(e.encryptedPayload,0,e.encryptedPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encryptedPayload):e.encryptedPayload,a.oneofs&&(A._encryptedPayload="encryptedPayload")),e.iv!=null&&e.hasOwnProperty("iv")&&(A.iv=a.bytes===String?l.base64.encode(e.iv,0,e.iv.length):a.bytes===Array?Array.prototype.slice.call(e.iv):e.iv,a.oneofs&&(A._iv="iv")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EncryptedPairingRequest"},t})(),n.EphemeralSetting=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.duration=e.sfixed32();break}case 2:{s.timestamp=e.sfixed64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EphemeralSetting)return e;var a=new p.proto.EphemeralSetting;return e.duration!=null&&(a.duration=e.duration|0),e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.duration!=null&&e.hasOwnProperty("duration")&&(A.duration=e.duration,a.oneofs&&(A._duration="duration")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp):a.longs===Number?ge(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EphemeralSetting"},t})(),n.EventAdditionalMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.isStale=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EventAdditionalMetadata)return e;var a=new p.proto.EventAdditionalMetadata;return e.isStale!=null&&(a.isStale=!!e.isStale),a},t.toObject=function(e,a){a||(a={});var A={};return e.isStale!=null&&e.hasOwnProperty("isStale")&&(A.isStale=e.isStale,a.oneofs&&(A._isStale="isStale")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EventAdditionalMetadata"},t})(),n.EventResponse=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.eventResponseMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.timestampMs=e.int64();break}case 3:{s.eventResponseMessage=p.proto.Message.EventResponseMessage.decode(e,e.uint32());break}case 4:{s.unread=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.EventResponse)return e;var a=new p.proto.EventResponse;if(e.eventResponseMessageKey!=null){if(typeof e.eventResponseMessageKey!="object")throw TypeError(".proto.EventResponse.eventResponseMessageKey: object expected");a.eventResponseMessageKey=p.proto.MessageKey.fromObject(e.eventResponseMessageKey)}if(e.timestampMs!=null&&(l.Long?(a.timestampMs=l.Long.fromValue(e.timestampMs)).unsigned=!1:typeof e.timestampMs=="string"?a.timestampMs=parseInt(e.timestampMs,10):typeof e.timestampMs=="number"?a.timestampMs=e.timestampMs:typeof e.timestampMs=="object"&&(a.timestampMs=new l.LongBits(e.timestampMs.low>>>0,e.timestampMs.high>>>0).toNumber())),e.eventResponseMessage!=null){if(typeof e.eventResponseMessage!="object")throw TypeError(".proto.EventResponse.eventResponseMessage: object expected");a.eventResponseMessage=p.proto.Message.EventResponseMessage.fromObject(e.eventResponseMessage)}return e.unread!=null&&(a.unread=!!e.unread),a},t.toObject=function(e,a){a||(a={});var A={};return e.eventResponseMessageKey!=null&&e.hasOwnProperty("eventResponseMessageKey")&&(A.eventResponseMessageKey=p.proto.MessageKey.toObject(e.eventResponseMessageKey,a),a.oneofs&&(A._eventResponseMessageKey="eventResponseMessageKey")),e.timestampMs!=null&&e.hasOwnProperty("timestampMs")&&(typeof e.timestampMs=="number"?A.timestampMs=a.longs===String?String(e.timestampMs):e.timestampMs:A.timestampMs=a.longs===String?se(e.timestampMs):a.longs===Number?ge(e.timestampMs):e.timestampMs,a.oneofs&&(A._timestampMs="timestampMs")),e.eventResponseMessage!=null&&e.hasOwnProperty("eventResponseMessage")&&(A.eventResponseMessage=p.proto.Message.EventResponseMessage.toObject(e.eventResponseMessage,a),a.oneofs&&(A._eventResponseMessage="eventResponseMessage")),e.unread!=null&&e.hasOwnProperty("unread")&&(A.unread=e.unread,a.oneofs&&(A._unread="unread")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.EventResponse"},t})(),n.ExitCode=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.code=e.uint64();break}case 2:{s.text=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ExitCode)return e;var a=new p.proto.ExitCode;return e.code!=null&&(l.Long?(a.code=l.Long.fromValue(e.code)).unsigned=!0:typeof e.code=="string"?a.code=parseInt(e.code,10):typeof e.code=="number"?a.code=e.code:typeof e.code=="object"&&(a.code=new l.LongBits(e.code.low>>>0,e.code.high>>>0).toNumber(!0))),e.text!=null&&(a.text=String(e.text)),a},t.toObject=function(e,a){a||(a={});var A={};return e.code!=null&&e.hasOwnProperty("code")&&(typeof e.code=="number"?A.code=a.longs===String?String(e.code):e.code:A.code=a.longs===String?se(e.code,!0):a.longs===Number?ge(e.code,!0):e.code,a.oneofs&&(A._code="code")),e.text!=null&&e.hasOwnProperty("text")&&(A.text=e.text,a.oneofs&&(A._text="text")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ExitCode"},t})(),n.ExternalBlobReference=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.mediaKey=e.bytes();break}case 2:{s.directPath=e.string();break}case 3:{s.handle=e.string();break}case 4:{s.fileSizeBytes=e.uint64();break}case 5:{s.fileSha256=e.bytes();break}case 6:{s.fileEncSha256=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ExternalBlobReference)return e;var a=new p.proto.ExternalBlobReference;return e.mediaKey!=null&&(typeof e.mediaKey=="string"?l.base64.decode(e.mediaKey,a.mediaKey=l.newBuffer(l.base64.length(e.mediaKey)),0):e.mediaKey.length>=0&&(a.mediaKey=e.mediaKey)),e.directPath!=null&&(a.directPath=String(e.directPath)),e.handle!=null&&(a.handle=String(e.handle)),e.fileSizeBytes!=null&&(l.Long?(a.fileSizeBytes=l.Long.fromValue(e.fileSizeBytes)).unsigned=!0:typeof e.fileSizeBytes=="string"?a.fileSizeBytes=parseInt(e.fileSizeBytes,10):typeof e.fileSizeBytes=="number"?a.fileSizeBytes=e.fileSizeBytes:typeof e.fileSizeBytes=="object"&&(a.fileSizeBytes=new l.LongBits(e.fileSizeBytes.low>>>0,e.fileSizeBytes.high>>>0).toNumber(!0))),e.fileSha256!=null&&(typeof e.fileSha256=="string"?l.base64.decode(e.fileSha256,a.fileSha256=l.newBuffer(l.base64.length(e.fileSha256)),0):e.fileSha256.length>=0&&(a.fileSha256=e.fileSha256)),e.fileEncSha256!=null&&(typeof e.fileEncSha256=="string"?l.base64.decode(e.fileEncSha256,a.fileEncSha256=l.newBuffer(l.base64.length(e.fileEncSha256)),0):e.fileEncSha256.length>=0&&(a.fileEncSha256=e.fileEncSha256)),a},t.toObject=function(e,a){a||(a={});var A={};return e.mediaKey!=null&&e.hasOwnProperty("mediaKey")&&(A.mediaKey=a.bytes===String?l.base64.encode(e.mediaKey,0,e.mediaKey.length):a.bytes===Array?Array.prototype.slice.call(e.mediaKey):e.mediaKey,a.oneofs&&(A._mediaKey="mediaKey")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.handle!=null&&e.hasOwnProperty("handle")&&(A.handle=e.handle,a.oneofs&&(A._handle="handle")),e.fileSizeBytes!=null&&e.hasOwnProperty("fileSizeBytes")&&(typeof e.fileSizeBytes=="number"?A.fileSizeBytes=a.longs===String?String(e.fileSizeBytes):e.fileSizeBytes:A.fileSizeBytes=a.longs===String?se(e.fileSizeBytes,!0):a.longs===Number?ge(e.fileSizeBytes,!0):e.fileSizeBytes,a.oneofs&&(A._fileSizeBytes="fileSizeBytes")),e.fileSha256!=null&&e.hasOwnProperty("fileSha256")&&(A.fileSha256=a.bytes===String?l.base64.encode(e.fileSha256,0,e.fileSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileSha256):e.fileSha256,a.oneofs&&(A._fileSha256="fileSha256")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=a.bytes===String?l.base64.encode(e.fileEncSha256,0,e.fileEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileEncSha256):e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ExternalBlobReference"},t})(),n.Field=(function(){function t(i){if(this.subfield={},i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.minVersion=e.uint32();break}case 2:{s.maxVersion=e.uint32();break}case 3:{s.notReportableMinVersion=e.uint32();break}case 4:{s.isMessage=e.bool();break}case 5:{s.subfield===l.emptyObject&&(s.subfield={});var d=e.uint32()+e.pos;for(g=0,c=null;e.pos>>3){case 1:g=e.uint32();break;case 2:c=p.proto.Field.decode(e,e.uint32());break;default:e.skipType(B&7);break}}s.subfield[g]=c;break}default:e.skipType(I&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Field)return e;var a=new p.proto.Field;if(e.minVersion!=null&&(a.minVersion=e.minVersion>>>0),e.maxVersion!=null&&(a.maxVersion=e.maxVersion>>>0),e.notReportableMinVersion!=null&&(a.notReportableMinVersion=e.notReportableMinVersion>>>0),e.isMessage!=null&&(a.isMessage=!!e.isMessage),e.subfield){if(typeof e.subfield!="object")throw TypeError(".proto.Field.subfield: object expected");a.subfield={};for(var A=Object.keys(e.subfield),r=0;r>>3){case 1:{s.botName=e.string();break}case 2:{s.botJid=e.string();break}case 3:{s.creatorName=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ForwardedAIBotMessageInfo)return e;var a=new p.proto.ForwardedAIBotMessageInfo;return e.botName!=null&&(a.botName=String(e.botName)),e.botJid!=null&&(a.botJid=String(e.botJid)),e.creatorName!=null&&(a.creatorName=String(e.creatorName)),a},t.toObject=function(e,a){a||(a={});var A={};return e.botName!=null&&e.hasOwnProperty("botName")&&(A.botName=e.botName,a.oneofs&&(A._botName="botName")),e.botJid!=null&&e.hasOwnProperty("botJid")&&(A.botJid=e.botJid,a.oneofs&&(A._botJid="botJid")),e.creatorName!=null&&e.hasOwnProperty("creatorName")&&(A.creatorName=e.creatorName,a.oneofs&&(A._creatorName="creatorName")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ForwardedAIBotMessageInfo"},t})(),n.GlobalSettings=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lightThemeWallpaper=p.proto.WallpaperSettings.decode(e,e.uint32());break}case 2:{s.mediaVisibility=e.int32();break}case 3:{s.darkThemeWallpaper=p.proto.WallpaperSettings.decode(e,e.uint32());break}case 4:{s.autoDownloadWiFi=p.proto.AutoDownloadSettings.decode(e,e.uint32());break}case 5:{s.autoDownloadCellular=p.proto.AutoDownloadSettings.decode(e,e.uint32());break}case 6:{s.autoDownloadRoaming=p.proto.AutoDownloadSettings.decode(e,e.uint32());break}case 7:{s.showIndividualNotificationsPreview=e.bool();break}case 8:{s.showGroupNotificationsPreview=e.bool();break}case 9:{s.disappearingModeDuration=e.int32();break}case 10:{s.disappearingModeTimestamp=e.int64();break}case 11:{s.avatarUserSettings=p.proto.AvatarUserSettings.decode(e,e.uint32());break}case 12:{s.fontSize=e.int32();break}case 13:{s.securityNotifications=e.bool();break}case 14:{s.autoUnarchiveChats=e.bool();break}case 15:{s.videoQualityMode=e.int32();break}case 16:{s.photoQualityMode=e.int32();break}case 17:{s.individualNotificationSettings=p.proto.NotificationSettings.decode(e,e.uint32());break}case 18:{s.groupNotificationSettings=p.proto.NotificationSettings.decode(e,e.uint32());break}case 19:{s.chatLockSettings=p.proto.ChatLockSettings.decode(e,e.uint32());break}case 20:{s.chatDbLidMigrationTimestamp=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.GlobalSettings)return e;var a=new p.proto.GlobalSettings;if(e.lightThemeWallpaper!=null){if(typeof e.lightThemeWallpaper!="object")throw TypeError(".proto.GlobalSettings.lightThemeWallpaper: object expected");a.lightThemeWallpaper=p.proto.WallpaperSettings.fromObject(e.lightThemeWallpaper)}switch(e.mediaVisibility){default:if(typeof e.mediaVisibility=="number"){a.mediaVisibility=e.mediaVisibility;break}break;case"DEFAULT":case 0:a.mediaVisibility=0;break;case"OFF":case 1:a.mediaVisibility=1;break;case"ON":case 2:a.mediaVisibility=2;break}if(e.darkThemeWallpaper!=null){if(typeof e.darkThemeWallpaper!="object")throw TypeError(".proto.GlobalSettings.darkThemeWallpaper: object expected");a.darkThemeWallpaper=p.proto.WallpaperSettings.fromObject(e.darkThemeWallpaper)}if(e.autoDownloadWiFi!=null){if(typeof e.autoDownloadWiFi!="object")throw TypeError(".proto.GlobalSettings.autoDownloadWiFi: object expected");a.autoDownloadWiFi=p.proto.AutoDownloadSettings.fromObject(e.autoDownloadWiFi)}if(e.autoDownloadCellular!=null){if(typeof e.autoDownloadCellular!="object")throw TypeError(".proto.GlobalSettings.autoDownloadCellular: object expected");a.autoDownloadCellular=p.proto.AutoDownloadSettings.fromObject(e.autoDownloadCellular)}if(e.autoDownloadRoaming!=null){if(typeof e.autoDownloadRoaming!="object")throw TypeError(".proto.GlobalSettings.autoDownloadRoaming: object expected");a.autoDownloadRoaming=p.proto.AutoDownloadSettings.fromObject(e.autoDownloadRoaming)}if(e.showIndividualNotificationsPreview!=null&&(a.showIndividualNotificationsPreview=!!e.showIndividualNotificationsPreview),e.showGroupNotificationsPreview!=null&&(a.showGroupNotificationsPreview=!!e.showGroupNotificationsPreview),e.disappearingModeDuration!=null&&(a.disappearingModeDuration=e.disappearingModeDuration|0),e.disappearingModeTimestamp!=null&&(l.Long?(a.disappearingModeTimestamp=l.Long.fromValue(e.disappearingModeTimestamp)).unsigned=!1:typeof e.disappearingModeTimestamp=="string"?a.disappearingModeTimestamp=parseInt(e.disappearingModeTimestamp,10):typeof e.disappearingModeTimestamp=="number"?a.disappearingModeTimestamp=e.disappearingModeTimestamp:typeof e.disappearingModeTimestamp=="object"&&(a.disappearingModeTimestamp=new l.LongBits(e.disappearingModeTimestamp.low>>>0,e.disappearingModeTimestamp.high>>>0).toNumber())),e.avatarUserSettings!=null){if(typeof e.avatarUserSettings!="object")throw TypeError(".proto.GlobalSettings.avatarUserSettings: object expected");a.avatarUserSettings=p.proto.AvatarUserSettings.fromObject(e.avatarUserSettings)}if(e.fontSize!=null&&(a.fontSize=e.fontSize|0),e.securityNotifications!=null&&(a.securityNotifications=!!e.securityNotifications),e.autoUnarchiveChats!=null&&(a.autoUnarchiveChats=!!e.autoUnarchiveChats),e.videoQualityMode!=null&&(a.videoQualityMode=e.videoQualityMode|0),e.photoQualityMode!=null&&(a.photoQualityMode=e.photoQualityMode|0),e.individualNotificationSettings!=null){if(typeof e.individualNotificationSettings!="object")throw TypeError(".proto.GlobalSettings.individualNotificationSettings: object expected");a.individualNotificationSettings=p.proto.NotificationSettings.fromObject(e.individualNotificationSettings)}if(e.groupNotificationSettings!=null){if(typeof e.groupNotificationSettings!="object")throw TypeError(".proto.GlobalSettings.groupNotificationSettings: object expected");a.groupNotificationSettings=p.proto.NotificationSettings.fromObject(e.groupNotificationSettings)}if(e.chatLockSettings!=null){if(typeof e.chatLockSettings!="object")throw TypeError(".proto.GlobalSettings.chatLockSettings: object expected");a.chatLockSettings=p.proto.ChatLockSettings.fromObject(e.chatLockSettings)}return e.chatDbLidMigrationTimestamp!=null&&(l.Long?(a.chatDbLidMigrationTimestamp=l.Long.fromValue(e.chatDbLidMigrationTimestamp)).unsigned=!1:typeof e.chatDbLidMigrationTimestamp=="string"?a.chatDbLidMigrationTimestamp=parseInt(e.chatDbLidMigrationTimestamp,10):typeof e.chatDbLidMigrationTimestamp=="number"?a.chatDbLidMigrationTimestamp=e.chatDbLidMigrationTimestamp:typeof e.chatDbLidMigrationTimestamp=="object"&&(a.chatDbLidMigrationTimestamp=new l.LongBits(e.chatDbLidMigrationTimestamp.low>>>0,e.chatDbLidMigrationTimestamp.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.lightThemeWallpaper!=null&&e.hasOwnProperty("lightThemeWallpaper")&&(A.lightThemeWallpaper=p.proto.WallpaperSettings.toObject(e.lightThemeWallpaper,a),a.oneofs&&(A._lightThemeWallpaper="lightThemeWallpaper")),e.mediaVisibility!=null&&e.hasOwnProperty("mediaVisibility")&&(A.mediaVisibility=a.enums===String?p.proto.MediaVisibility[e.mediaVisibility]===void 0?e.mediaVisibility:p.proto.MediaVisibility[e.mediaVisibility]:e.mediaVisibility,a.oneofs&&(A._mediaVisibility="mediaVisibility")),e.darkThemeWallpaper!=null&&e.hasOwnProperty("darkThemeWallpaper")&&(A.darkThemeWallpaper=p.proto.WallpaperSettings.toObject(e.darkThemeWallpaper,a),a.oneofs&&(A._darkThemeWallpaper="darkThemeWallpaper")),e.autoDownloadWiFi!=null&&e.hasOwnProperty("autoDownloadWiFi")&&(A.autoDownloadWiFi=p.proto.AutoDownloadSettings.toObject(e.autoDownloadWiFi,a),a.oneofs&&(A._autoDownloadWiFi="autoDownloadWiFi")),e.autoDownloadCellular!=null&&e.hasOwnProperty("autoDownloadCellular")&&(A.autoDownloadCellular=p.proto.AutoDownloadSettings.toObject(e.autoDownloadCellular,a),a.oneofs&&(A._autoDownloadCellular="autoDownloadCellular")),e.autoDownloadRoaming!=null&&e.hasOwnProperty("autoDownloadRoaming")&&(A.autoDownloadRoaming=p.proto.AutoDownloadSettings.toObject(e.autoDownloadRoaming,a),a.oneofs&&(A._autoDownloadRoaming="autoDownloadRoaming")),e.showIndividualNotificationsPreview!=null&&e.hasOwnProperty("showIndividualNotificationsPreview")&&(A.showIndividualNotificationsPreview=e.showIndividualNotificationsPreview,a.oneofs&&(A._showIndividualNotificationsPreview="showIndividualNotificationsPreview")),e.showGroupNotificationsPreview!=null&&e.hasOwnProperty("showGroupNotificationsPreview")&&(A.showGroupNotificationsPreview=e.showGroupNotificationsPreview,a.oneofs&&(A._showGroupNotificationsPreview="showGroupNotificationsPreview")),e.disappearingModeDuration!=null&&e.hasOwnProperty("disappearingModeDuration")&&(A.disappearingModeDuration=e.disappearingModeDuration,a.oneofs&&(A._disappearingModeDuration="disappearingModeDuration")),e.disappearingModeTimestamp!=null&&e.hasOwnProperty("disappearingModeTimestamp")&&(typeof e.disappearingModeTimestamp=="number"?A.disappearingModeTimestamp=a.longs===String?String(e.disappearingModeTimestamp):e.disappearingModeTimestamp:A.disappearingModeTimestamp=a.longs===String?se(e.disappearingModeTimestamp):a.longs===Number?ge(e.disappearingModeTimestamp):e.disappearingModeTimestamp,a.oneofs&&(A._disappearingModeTimestamp="disappearingModeTimestamp")),e.avatarUserSettings!=null&&e.hasOwnProperty("avatarUserSettings")&&(A.avatarUserSettings=p.proto.AvatarUserSettings.toObject(e.avatarUserSettings,a),a.oneofs&&(A._avatarUserSettings="avatarUserSettings")),e.fontSize!=null&&e.hasOwnProperty("fontSize")&&(A.fontSize=e.fontSize,a.oneofs&&(A._fontSize="fontSize")),e.securityNotifications!=null&&e.hasOwnProperty("securityNotifications")&&(A.securityNotifications=e.securityNotifications,a.oneofs&&(A._securityNotifications="securityNotifications")),e.autoUnarchiveChats!=null&&e.hasOwnProperty("autoUnarchiveChats")&&(A.autoUnarchiveChats=e.autoUnarchiveChats,a.oneofs&&(A._autoUnarchiveChats="autoUnarchiveChats")),e.videoQualityMode!=null&&e.hasOwnProperty("videoQualityMode")&&(A.videoQualityMode=e.videoQualityMode,a.oneofs&&(A._videoQualityMode="videoQualityMode")),e.photoQualityMode!=null&&e.hasOwnProperty("photoQualityMode")&&(A.photoQualityMode=e.photoQualityMode,a.oneofs&&(A._photoQualityMode="photoQualityMode")),e.individualNotificationSettings!=null&&e.hasOwnProperty("individualNotificationSettings")&&(A.individualNotificationSettings=p.proto.NotificationSettings.toObject(e.individualNotificationSettings,a),a.oneofs&&(A._individualNotificationSettings="individualNotificationSettings")),e.groupNotificationSettings!=null&&e.hasOwnProperty("groupNotificationSettings")&&(A.groupNotificationSettings=p.proto.NotificationSettings.toObject(e.groupNotificationSettings,a),a.oneofs&&(A._groupNotificationSettings="groupNotificationSettings")),e.chatLockSettings!=null&&e.hasOwnProperty("chatLockSettings")&&(A.chatLockSettings=p.proto.ChatLockSettings.toObject(e.chatLockSettings,a),a.oneofs&&(A._chatLockSettings="chatLockSettings")),e.chatDbLidMigrationTimestamp!=null&&e.hasOwnProperty("chatDbLidMigrationTimestamp")&&(typeof e.chatDbLidMigrationTimestamp=="number"?A.chatDbLidMigrationTimestamp=a.longs===String?String(e.chatDbLidMigrationTimestamp):e.chatDbLidMigrationTimestamp:A.chatDbLidMigrationTimestamp=a.longs===String?se(e.chatDbLidMigrationTimestamp):a.longs===Number?ge(e.chatDbLidMigrationTimestamp):e.chatDbLidMigrationTimestamp,a.oneofs&&(A._chatDbLidMigrationTimestamp="chatDbLidMigrationTimestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GlobalSettings"},t})(),n.GroupHistoryBundleInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.deprecatedMessageHistoryBundle=p.proto.Message.MessageHistoryBundle.decode(e,e.uint32());break}case 2:{s.processState=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.GroupHistoryBundleInfo)return e;var a=new p.proto.GroupHistoryBundleInfo;if(e.deprecatedMessageHistoryBundle!=null){if(typeof e.deprecatedMessageHistoryBundle!="object")throw TypeError(".proto.GroupHistoryBundleInfo.deprecatedMessageHistoryBundle: object expected");a.deprecatedMessageHistoryBundle=p.proto.Message.MessageHistoryBundle.fromObject(e.deprecatedMessageHistoryBundle)}switch(e.processState){default:if(typeof e.processState=="number"){a.processState=e.processState;break}break;case"NOT_INJECTED":case 0:a.processState=0;break;case"INJECTED":case 1:a.processState=1;break;case"INJECTED_PARTIAL":case 2:a.processState=2;break;case"INJECTION_FAILED":case 3:a.processState=3;break;case"INJECTION_FAILED_NO_RETRY":case 4:a.processState=4;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.deprecatedMessageHistoryBundle!=null&&e.hasOwnProperty("deprecatedMessageHistoryBundle")&&(A.deprecatedMessageHistoryBundle=p.proto.Message.MessageHistoryBundle.toObject(e.deprecatedMessageHistoryBundle,a),a.oneofs&&(A._deprecatedMessageHistoryBundle="deprecatedMessageHistoryBundle")),e.processState!=null&&e.hasOwnProperty("processState")&&(A.processState=a.enums===String?p.proto.GroupHistoryBundleInfo.ProcessState[e.processState]===void 0?e.processState:p.proto.GroupHistoryBundleInfo.ProcessState[e.processState]:e.processState,a.oneofs&&(A._processState="processState")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupHistoryBundleInfo"},t.ProcessState=(function(){let i={},e=Object.create(i);return e[i[0]="NOT_INJECTED"]=0,e[i[1]="INJECTED"]=1,e[i[2]="INJECTED_PARTIAL"]=2,e[i[3]="INJECTION_FAILED"]=3,e[i[4]="INJECTION_FAILED_NO_RETRY"]=4,e})(),t})(),n.GroupHistoryIndividualMessageInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.bundleMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.editedAfterReceivedAsHistory=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.GroupHistoryIndividualMessageInfo)return e;var a=new p.proto.GroupHistoryIndividualMessageInfo;if(e.bundleMessageKey!=null){if(typeof e.bundleMessageKey!="object")throw TypeError(".proto.GroupHistoryIndividualMessageInfo.bundleMessageKey: object expected");a.bundleMessageKey=p.proto.MessageKey.fromObject(e.bundleMessageKey)}return e.editedAfterReceivedAsHistory!=null&&(a.editedAfterReceivedAsHistory=!!e.editedAfterReceivedAsHistory),a},t.toObject=function(e,a){a||(a={});var A={};return e.bundleMessageKey!=null&&e.hasOwnProperty("bundleMessageKey")&&(A.bundleMessageKey=p.proto.MessageKey.toObject(e.bundleMessageKey,a),a.oneofs&&(A._bundleMessageKey="bundleMessageKey")),e.editedAfterReceivedAsHistory!=null&&e.hasOwnProperty("editedAfterReceivedAsHistory")&&(A.editedAfterReceivedAsHistory=e.editedAfterReceivedAsHistory,a.oneofs&&(A._editedAfterReceivedAsHistory="editedAfterReceivedAsHistory")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupHistoryIndividualMessageInfo"},t})(),n.GroupMention=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.groupJid=e.string();break}case 2:{s.groupSubject=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.GroupMention)return e;var a=new p.proto.GroupMention;return e.groupJid!=null&&(a.groupJid=String(e.groupJid)),e.groupSubject!=null&&(a.groupSubject=String(e.groupSubject)),a},t.toObject=function(e,a){a||(a={});var A={};return e.groupJid!=null&&e.hasOwnProperty("groupJid")&&(A.groupJid=e.groupJid,a.oneofs&&(A._groupJid="groupJid")),e.groupSubject!=null&&e.hasOwnProperty("groupSubject")&&(A.groupSubject=e.groupSubject,a.oneofs&&(A._groupSubject="groupSubject")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupMention"},t})(),n.GroupParticipant=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.userJid=e.string();break}case 2:{s.rank=e.int32();break}case 3:{s.memberLabel=p.proto.MemberLabel.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.GroupParticipant)return e;var a=new p.proto.GroupParticipant;switch(e.userJid!=null&&(a.userJid=String(e.userJid)),e.rank){default:if(typeof e.rank=="number"){a.rank=e.rank;break}break;case"REGULAR":case 0:a.rank=0;break;case"ADMIN":case 1:a.rank=1;break;case"SUPERADMIN":case 2:a.rank=2;break}if(e.memberLabel!=null){if(typeof e.memberLabel!="object")throw TypeError(".proto.GroupParticipant.memberLabel: object expected");a.memberLabel=p.proto.MemberLabel.fromObject(e.memberLabel)}return a},t.toObject=function(e,a){a||(a={});var A={};return a.defaults&&(A.userJid=""),e.userJid!=null&&e.hasOwnProperty("userJid")&&(A.userJid=e.userJid),e.rank!=null&&e.hasOwnProperty("rank")&&(A.rank=a.enums===String?p.proto.GroupParticipant.Rank[e.rank]===void 0?e.rank:p.proto.GroupParticipant.Rank[e.rank]:e.rank,a.oneofs&&(A._rank="rank")),e.memberLabel!=null&&e.hasOwnProperty("memberLabel")&&(A.memberLabel=p.proto.MemberLabel.toObject(e.memberLabel,a),a.oneofs&&(A._memberLabel="memberLabel")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.GroupParticipant"},t.Rank=(function(){let i={},e=Object.create(i);return e[i[0]="REGULAR"]=0,e[i[1]="ADMIN"]=1,e[i[2]="SUPERADMIN"]=2,e})(),t})(),n.HandshakeMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 2:{s.clientHello=p.proto.HandshakeMessage.ClientHello.decode(e,e.uint32());break}case 3:{s.serverHello=p.proto.HandshakeMessage.ServerHello.decode(e,e.uint32());break}case 4:{s.clientFinish=p.proto.HandshakeMessage.ClientFinish.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.HandshakeMessage)return e;var a=new p.proto.HandshakeMessage;if(e.clientHello!=null){if(typeof e.clientHello!="object")throw TypeError(".proto.HandshakeMessage.clientHello: object expected");a.clientHello=p.proto.HandshakeMessage.ClientHello.fromObject(e.clientHello)}if(e.serverHello!=null){if(typeof e.serverHello!="object")throw TypeError(".proto.HandshakeMessage.serverHello: object expected");a.serverHello=p.proto.HandshakeMessage.ServerHello.fromObject(e.serverHello)}if(e.clientFinish!=null){if(typeof e.clientFinish!="object")throw TypeError(".proto.HandshakeMessage.clientFinish: object expected");a.clientFinish=p.proto.HandshakeMessage.ClientFinish.fromObject(e.clientFinish)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.clientHello!=null&&e.hasOwnProperty("clientHello")&&(A.clientHello=p.proto.HandshakeMessage.ClientHello.toObject(e.clientHello,a),a.oneofs&&(A._clientHello="clientHello")),e.serverHello!=null&&e.hasOwnProperty("serverHello")&&(A.serverHello=p.proto.HandshakeMessage.ServerHello.toObject(e.serverHello,a),a.oneofs&&(A._serverHello="serverHello")),e.clientFinish!=null&&e.hasOwnProperty("clientFinish")&&(A.clientFinish=p.proto.HandshakeMessage.ClientFinish.toObject(e.clientFinish,a),a.oneofs&&(A._clientFinish="clientFinish")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.HandshakeMessage"},t.ClientFinish=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.static=A.bytes();break}case 2:{c.payload=A.bytes();break}case 3:{c.extendedCiphertext=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HandshakeMessage.ClientFinish)return A;var r=new p.proto.HandshakeMessage.ClientFinish;return A.static!=null&&(typeof A.static=="string"?l.base64.decode(A.static,r.static=l.newBuffer(l.base64.length(A.static)),0):A.static.length>=0&&(r.static=A.static)),A.payload!=null&&(typeof A.payload=="string"?l.base64.decode(A.payload,r.payload=l.newBuffer(l.base64.length(A.payload)),0):A.payload.length>=0&&(r.payload=A.payload)),A.extendedCiphertext!=null&&(typeof A.extendedCiphertext=="string"?l.base64.decode(A.extendedCiphertext,r.extendedCiphertext=l.newBuffer(l.base64.length(A.extendedCiphertext)),0):A.extendedCiphertext.length>=0&&(r.extendedCiphertext=A.extendedCiphertext)),r},i.toObject=function(A,r){r||(r={});var s={};return A.static!=null&&A.hasOwnProperty("static")&&(s.static=r.bytes===String?l.base64.encode(A.static,0,A.static.length):r.bytes===Array?Array.prototype.slice.call(A.static):A.static,r.oneofs&&(s._static="static")),A.payload!=null&&A.hasOwnProperty("payload")&&(s.payload=r.bytes===String?l.base64.encode(A.payload,0,A.payload.length):r.bytes===Array?Array.prototype.slice.call(A.payload):A.payload,r.oneofs&&(s._payload="payload")),A.extendedCiphertext!=null&&A.hasOwnProperty("extendedCiphertext")&&(s.extendedCiphertext=r.bytes===String?l.base64.encode(A.extendedCiphertext,0,A.extendedCiphertext.length):r.bytes===Array?Array.prototype.slice.call(A.extendedCiphertext):A.extendedCiphertext,r.oneofs&&(s._extendedCiphertext="extendedCiphertext")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HandshakeMessage.ClientFinish"},i})(),t.ClientHello=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.ephemeral=A.bytes();break}case 2:{c.static=A.bytes();break}case 3:{c.payload=A.bytes();break}case 4:{c.useExtended=A.bool();break}case 5:{c.extendedCiphertext=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HandshakeMessage.ClientHello)return A;var r=new p.proto.HandshakeMessage.ClientHello;return A.ephemeral!=null&&(typeof A.ephemeral=="string"?l.base64.decode(A.ephemeral,r.ephemeral=l.newBuffer(l.base64.length(A.ephemeral)),0):A.ephemeral.length>=0&&(r.ephemeral=A.ephemeral)),A.static!=null&&(typeof A.static=="string"?l.base64.decode(A.static,r.static=l.newBuffer(l.base64.length(A.static)),0):A.static.length>=0&&(r.static=A.static)),A.payload!=null&&(typeof A.payload=="string"?l.base64.decode(A.payload,r.payload=l.newBuffer(l.base64.length(A.payload)),0):A.payload.length>=0&&(r.payload=A.payload)),A.useExtended!=null&&(r.useExtended=!!A.useExtended),A.extendedCiphertext!=null&&(typeof A.extendedCiphertext=="string"?l.base64.decode(A.extendedCiphertext,r.extendedCiphertext=l.newBuffer(l.base64.length(A.extendedCiphertext)),0):A.extendedCiphertext.length>=0&&(r.extendedCiphertext=A.extendedCiphertext)),r},i.toObject=function(A,r){r||(r={});var s={};return A.ephemeral!=null&&A.hasOwnProperty("ephemeral")&&(s.ephemeral=r.bytes===String?l.base64.encode(A.ephemeral,0,A.ephemeral.length):r.bytes===Array?Array.prototype.slice.call(A.ephemeral):A.ephemeral,r.oneofs&&(s._ephemeral="ephemeral")),A.static!=null&&A.hasOwnProperty("static")&&(s.static=r.bytes===String?l.base64.encode(A.static,0,A.static.length):r.bytes===Array?Array.prototype.slice.call(A.static):A.static,r.oneofs&&(s._static="static")),A.payload!=null&&A.hasOwnProperty("payload")&&(s.payload=r.bytes===String?l.base64.encode(A.payload,0,A.payload.length):r.bytes===Array?Array.prototype.slice.call(A.payload):A.payload,r.oneofs&&(s._payload="payload")),A.useExtended!=null&&A.hasOwnProperty("useExtended")&&(s.useExtended=A.useExtended,r.oneofs&&(s._useExtended="useExtended")),A.extendedCiphertext!=null&&A.hasOwnProperty("extendedCiphertext")&&(s.extendedCiphertext=r.bytes===String?l.base64.encode(A.extendedCiphertext,0,A.extendedCiphertext.length):r.bytes===Array?Array.prototype.slice.call(A.extendedCiphertext):A.extendedCiphertext,r.oneofs&&(s._extendedCiphertext="extendedCiphertext")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HandshakeMessage.ClientHello"},i})(),t.ServerHello=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.ephemeral=A.bytes();break}case 2:{c.static=A.bytes();break}case 3:{c.payload=A.bytes();break}case 4:{c.extendedStatic=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HandshakeMessage.ServerHello)return A;var r=new p.proto.HandshakeMessage.ServerHello;return A.ephemeral!=null&&(typeof A.ephemeral=="string"?l.base64.decode(A.ephemeral,r.ephemeral=l.newBuffer(l.base64.length(A.ephemeral)),0):A.ephemeral.length>=0&&(r.ephemeral=A.ephemeral)),A.static!=null&&(typeof A.static=="string"?l.base64.decode(A.static,r.static=l.newBuffer(l.base64.length(A.static)),0):A.static.length>=0&&(r.static=A.static)),A.payload!=null&&(typeof A.payload=="string"?l.base64.decode(A.payload,r.payload=l.newBuffer(l.base64.length(A.payload)),0):A.payload.length>=0&&(r.payload=A.payload)),A.extendedStatic!=null&&(typeof A.extendedStatic=="string"?l.base64.decode(A.extendedStatic,r.extendedStatic=l.newBuffer(l.base64.length(A.extendedStatic)),0):A.extendedStatic.length>=0&&(r.extendedStatic=A.extendedStatic)),r},i.toObject=function(A,r){r||(r={});var s={};return A.ephemeral!=null&&A.hasOwnProperty("ephemeral")&&(s.ephemeral=r.bytes===String?l.base64.encode(A.ephemeral,0,A.ephemeral.length):r.bytes===Array?Array.prototype.slice.call(A.ephemeral):A.ephemeral,r.oneofs&&(s._ephemeral="ephemeral")),A.static!=null&&A.hasOwnProperty("static")&&(s.static=r.bytes===String?l.base64.encode(A.static,0,A.static.length):r.bytes===Array?Array.prototype.slice.call(A.static):A.static,r.oneofs&&(s._static="static")),A.payload!=null&&A.hasOwnProperty("payload")&&(s.payload=r.bytes===String?l.base64.encode(A.payload,0,A.payload.length):r.bytes===Array?Array.prototype.slice.call(A.payload):A.payload,r.oneofs&&(s._payload="payload")),A.extendedStatic!=null&&A.hasOwnProperty("extendedStatic")&&(s.extendedStatic=r.bytes===String?l.base64.encode(A.extendedStatic,0,A.extendedStatic.length):r.bytes===Array?Array.prototype.slice.call(A.extendedStatic):A.extendedStatic,r.oneofs&&(s._extendedStatic="extendedStatic")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HandshakeMessage.ServerHello"},i})(),t})(),n.HistorySync=(function(){function t(i){if(this.conversations=[],this.statusV3Messages=[],this.pushnames=[],this.recentStickers=[],this.pastParticipants=[],this.callLogRecords=[],this.phoneNumberToLidMappings=[],this.accounts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.syncType=e.int32();break}case 2:{s.conversations&&s.conversations.length||(s.conversations=[]),s.conversations.push(p.proto.Conversation.decode(e,e.uint32()));break}case 3:{s.statusV3Messages&&s.statusV3Messages.length||(s.statusV3Messages=[]),s.statusV3Messages.push(p.proto.WebMessageInfo.decode(e,e.uint32()));break}case 5:{s.chunkOrder=e.uint32();break}case 6:{s.progress=e.uint32();break}case 7:{s.pushnames&&s.pushnames.length||(s.pushnames=[]),s.pushnames.push(p.proto.Pushname.decode(e,e.uint32()));break}case 8:{s.globalSettings=p.proto.GlobalSettings.decode(e,e.uint32());break}case 9:{s.threadIdUserSecret=e.bytes();break}case 10:{s.threadDsTimeframeOffset=e.uint32();break}case 11:{s.recentStickers&&s.recentStickers.length||(s.recentStickers=[]),s.recentStickers.push(p.proto.StickerMetadata.decode(e,e.uint32()));break}case 12:{s.pastParticipants&&s.pastParticipants.length||(s.pastParticipants=[]),s.pastParticipants.push(p.proto.PastParticipants.decode(e,e.uint32()));break}case 13:{s.callLogRecords&&s.callLogRecords.length||(s.callLogRecords=[]),s.callLogRecords.push(p.proto.CallLogRecord.decode(e,e.uint32()));break}case 14:{s.aiWaitListState=e.int32();break}case 15:{s.phoneNumberToLidMappings&&s.phoneNumberToLidMappings.length||(s.phoneNumberToLidMappings=[]),s.phoneNumberToLidMappings.push(p.proto.PhoneNumberToLIDMapping.decode(e,e.uint32()));break}case 16:{s.companionMetaNonce=e.string();break}case 17:{s.shareableChatIdentifierEncryptionKey=e.bytes();break}case 18:{s.accounts&&s.accounts.length||(s.accounts=[]),s.accounts.push(p.proto.Account.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.HistorySync)return e;var a=new p.proto.HistorySync;switch(e.syncType){default:if(typeof e.syncType=="number"){a.syncType=e.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:a.syncType=0;break;case"INITIAL_STATUS_V3":case 1:a.syncType=1;break;case"FULL":case 2:a.syncType=2;break;case"RECENT":case 3:a.syncType=3;break;case"PUSH_NAME":case 4:a.syncType=4;break;case"NON_BLOCKING_DATA":case 5:a.syncType=5;break;case"ON_DEMAND":case 6:a.syncType=6;break}if(e.conversations){if(!Array.isArray(e.conversations))throw TypeError(".proto.HistorySync.conversations: array expected");a.conversations=[];for(var A=0;A>>0),e.progress!=null&&(a.progress=e.progress>>>0),e.pushnames){if(!Array.isArray(e.pushnames))throw TypeError(".proto.HistorySync.pushnames: array expected");a.pushnames=[];for(var A=0;A=0&&(a.threadIdUserSecret=e.threadIdUserSecret)),e.threadDsTimeframeOffset!=null&&(a.threadDsTimeframeOffset=e.threadDsTimeframeOffset>>>0),e.recentStickers){if(!Array.isArray(e.recentStickers))throw TypeError(".proto.HistorySync.recentStickers: array expected");a.recentStickers=[];for(var A=0;A=0&&(a.shareableChatIdentifierEncryptionKey=e.shareableChatIdentifierEncryptionKey)),e.accounts){if(!Array.isArray(e.accounts))throw TypeError(".proto.HistorySync.accounts: array expected");a.accounts=[];for(var A=0;A>>3){case 1:{s.message=p.proto.WebMessageInfo.decode(e,e.uint32());break}case 2:{s.msgOrderId=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.HistorySyncMsg)return e;var a=new p.proto.HistorySyncMsg;if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.HistorySyncMsg.message: object expected");a.message=p.proto.WebMessageInfo.fromObject(e.message)}return e.msgOrderId!=null&&(l.Long?(a.msgOrderId=l.Long.fromValue(e.msgOrderId)).unsigned=!0:typeof e.msgOrderId=="string"?a.msgOrderId=parseInt(e.msgOrderId,10):typeof e.msgOrderId=="number"?a.msgOrderId=e.msgOrderId:typeof e.msgOrderId=="object"&&(a.msgOrderId=new l.LongBits(e.msgOrderId.low>>>0,e.msgOrderId.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};return e.message!=null&&e.hasOwnProperty("message")&&(A.message=p.proto.WebMessageInfo.toObject(e.message,a),a.oneofs&&(A._message="message")),e.msgOrderId!=null&&e.hasOwnProperty("msgOrderId")&&(typeof e.msgOrderId=="number"?A.msgOrderId=a.longs===String?String(e.msgOrderId):e.msgOrderId:A.msgOrderId=a.longs===String?se(e.msgOrderId,!0):a.longs===Number?ge(e.msgOrderId,!0):e.msgOrderId,a.oneofs&&(A._msgOrderId="msgOrderId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.HistorySyncMsg"},t})(),n.HydratedTemplateButton=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 4:{s.index=e.uint32();break}case 1:{s.quickReplyButton=p.proto.HydratedTemplateButton.HydratedQuickReplyButton.decode(e,e.uint32());break}case 2:{s.urlButton=p.proto.HydratedTemplateButton.HydratedURLButton.decode(e,e.uint32());break}case 3:{s.callButton=p.proto.HydratedTemplateButton.HydratedCallButton.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.HydratedTemplateButton)return e;var a=new p.proto.HydratedTemplateButton;if(e.index!=null&&(a.index=e.index>>>0),e.quickReplyButton!=null){if(typeof e.quickReplyButton!="object")throw TypeError(".proto.HydratedTemplateButton.quickReplyButton: object expected");a.quickReplyButton=p.proto.HydratedTemplateButton.HydratedQuickReplyButton.fromObject(e.quickReplyButton)}if(e.urlButton!=null){if(typeof e.urlButton!="object")throw TypeError(".proto.HydratedTemplateButton.urlButton: object expected");a.urlButton=p.proto.HydratedTemplateButton.HydratedURLButton.fromObject(e.urlButton)}if(e.callButton!=null){if(typeof e.callButton!="object")throw TypeError(".proto.HydratedTemplateButton.callButton: object expected");a.callButton=p.proto.HydratedTemplateButton.HydratedCallButton.fromObject(e.callButton)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.quickReplyButton!=null&&e.hasOwnProperty("quickReplyButton")&&(A.quickReplyButton=p.proto.HydratedTemplateButton.HydratedQuickReplyButton.toObject(e.quickReplyButton,a),a.oneofs&&(A.hydratedButton="quickReplyButton")),e.urlButton!=null&&e.hasOwnProperty("urlButton")&&(A.urlButton=p.proto.HydratedTemplateButton.HydratedURLButton.toObject(e.urlButton,a),a.oneofs&&(A.hydratedButton="urlButton")),e.callButton!=null&&e.hasOwnProperty("callButton")&&(A.callButton=p.proto.HydratedTemplateButton.HydratedCallButton.toObject(e.callButton,a),a.oneofs&&(A.hydratedButton="callButton")),e.index!=null&&e.hasOwnProperty("index")&&(A.index=e.index,a.oneofs&&(A._index="index")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.HydratedTemplateButton"},t.HydratedCallButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=A.string();break}case 2:{c.phoneNumber=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HydratedTemplateButton.HydratedCallButton)return A;var r=new p.proto.HydratedTemplateButton.HydratedCallButton;return A.displayText!=null&&(r.displayText=String(A.displayText)),A.phoneNumber!=null&&(r.phoneNumber=String(A.phoneNumber)),r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=A.displayText,r.oneofs&&(s._displayText="displayText")),A.phoneNumber!=null&&A.hasOwnProperty("phoneNumber")&&(s.phoneNumber=A.phoneNumber,r.oneofs&&(s._phoneNumber="phoneNumber")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HydratedTemplateButton.HydratedCallButton"},i})(),t.HydratedQuickReplyButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=A.string();break}case 2:{c.id=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HydratedTemplateButton.HydratedQuickReplyButton)return A;var r=new p.proto.HydratedTemplateButton.HydratedQuickReplyButton;return A.displayText!=null&&(r.displayText=String(A.displayText)),A.id!=null&&(r.id=String(A.id)),r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=A.displayText,r.oneofs&&(s._displayText="displayText")),A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,r.oneofs&&(s._id="id")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HydratedTemplateButton.HydratedQuickReplyButton"},i})(),t.HydratedURLButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=A.string();break}case 2:{c.url=A.string();break}case 3:{c.consentedUsersUrl=A.string();break}case 4:{c.webviewPresentation=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.HydratedTemplateButton.HydratedURLButton)return A;var r=new p.proto.HydratedTemplateButton.HydratedURLButton;switch(A.displayText!=null&&(r.displayText=String(A.displayText)),A.url!=null&&(r.url=String(A.url)),A.consentedUsersUrl!=null&&(r.consentedUsersUrl=String(A.consentedUsersUrl)),A.webviewPresentation){default:if(typeof A.webviewPresentation=="number"){r.webviewPresentation=A.webviewPresentation;break}break;case"FULL":case 1:r.webviewPresentation=1;break;case"TALL":case 2:r.webviewPresentation=2;break;case"COMPACT":case 3:r.webviewPresentation=3;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=A.displayText,r.oneofs&&(s._displayText="displayText")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.consentedUsersUrl!=null&&A.hasOwnProperty("consentedUsersUrl")&&(s.consentedUsersUrl=A.consentedUsersUrl,r.oneofs&&(s._consentedUsersUrl="consentedUsersUrl")),A.webviewPresentation!=null&&A.hasOwnProperty("webviewPresentation")&&(s.webviewPresentation=r.enums===String?p.proto.HydratedTemplateButton.HydratedURLButton.WebviewPresentationType[A.webviewPresentation]===void 0?A.webviewPresentation:p.proto.HydratedTemplateButton.HydratedURLButton.WebviewPresentationType[A.webviewPresentation]:A.webviewPresentation,r.oneofs&&(s._webviewPresentation="webviewPresentation")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.HydratedTemplateButton.HydratedURLButton"},i.WebviewPresentationType=(function(){let a={},A=Object.create(a);return A[a[1]="FULL"]=1,A[a[2]="TALL"]=2,A[a[3]="COMPACT"]=3,A})(),i})(),t})(),n.IdentityKeyPairStructure=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.privateKey=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.IdentityKeyPairStructure)return e;var a=new p.proto.IdentityKeyPairStructure;return e.publicKey!=null&&(typeof e.publicKey=="string"?l.base64.decode(e.publicKey,a.publicKey=l.newBuffer(l.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.privateKey!=null&&(typeof e.privateKey=="string"?l.base64.decode(e.privateKey,a.privateKey=l.newBuffer(l.base64.length(e.privateKey)),0):e.privateKey.length>=0&&(a.privateKey=e.privateKey)),a},t.toObject=function(e,a){a||(a={});var A={};return e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?l.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.privateKey!=null&&e.hasOwnProperty("privateKey")&&(A.privateKey=a.bytes===String?l.base64.encode(e.privateKey,0,e.privateKey.length):a.bytes===Array?Array.prototype.slice.call(e.privateKey):e.privateKey,a.oneofs&&(A._privateKey="privateKey")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.IdentityKeyPairStructure"},t})(),n.InThreadSurveyMetadata=(function(){function t(i){if(this.questions=[],this.privacyStatementParts=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.tessaSessionId=e.string();break}case 2:{s.simonSessionId=e.string();break}case 3:{s.simonSurveyId=e.string();break}case 4:{s.tessaRootId=e.string();break}case 5:{s.requestId=e.string();break}case 6:{s.tessaEvent=e.string();break}case 7:{s.invitationHeaderText=e.string();break}case 8:{s.invitationBodyText=e.string();break}case 9:{s.invitationCtaText=e.string();break}case 10:{s.invitationCtaUrl=e.string();break}case 11:{s.surveyTitle=e.string();break}case 12:{s.questions&&s.questions.length||(s.questions=[]),s.questions.push(p.proto.InThreadSurveyMetadata.InThreadSurveyQuestion.decode(e,e.uint32()));break}case 13:{s.surveyContinueButtonText=e.string();break}case 14:{s.surveySubmitButtonText=e.string();break}case 15:{s.privacyStatementFull=e.string();break}case 16:{s.privacyStatementParts&&s.privacyStatementParts.length||(s.privacyStatementParts=[]),s.privacyStatementParts.push(p.proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart.decode(e,e.uint32()));break}case 17:{s.feedbackToastText=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.InThreadSurveyMetadata)return e;var a=new p.proto.InThreadSurveyMetadata;if(e.tessaSessionId!=null&&(a.tessaSessionId=String(e.tessaSessionId)),e.simonSessionId!=null&&(a.simonSessionId=String(e.simonSessionId)),e.simonSurveyId!=null&&(a.simonSurveyId=String(e.simonSurveyId)),e.tessaRootId!=null&&(a.tessaRootId=String(e.tessaRootId)),e.requestId!=null&&(a.requestId=String(e.requestId)),e.tessaEvent!=null&&(a.tessaEvent=String(e.tessaEvent)),e.invitationHeaderText!=null&&(a.invitationHeaderText=String(e.invitationHeaderText)),e.invitationBodyText!=null&&(a.invitationBodyText=String(e.invitationBodyText)),e.invitationCtaText!=null&&(a.invitationCtaText=String(e.invitationCtaText)),e.invitationCtaUrl!=null&&(a.invitationCtaUrl=String(e.invitationCtaUrl)),e.surveyTitle!=null&&(a.surveyTitle=String(e.surveyTitle)),e.questions){if(!Array.isArray(e.questions))throw TypeError(".proto.InThreadSurveyMetadata.questions: array expected");a.questions=[];for(var A=0;A>>3){case 1:{c.stringValue=A.string();break}case 2:{c.numericValue=A.uint32();break}case 3:{c.textTranslated=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.InThreadSurveyMetadata.InThreadSurveyOption)return A;var r=new p.proto.InThreadSurveyMetadata.InThreadSurveyOption;return A.stringValue!=null&&(r.stringValue=String(A.stringValue)),A.numericValue!=null&&(r.numericValue=A.numericValue>>>0),A.textTranslated!=null&&(r.textTranslated=String(A.textTranslated)),r},i.toObject=function(A,r){r||(r={});var s={};return A.stringValue!=null&&A.hasOwnProperty("stringValue")&&(s.stringValue=A.stringValue,r.oneofs&&(s._stringValue="stringValue")),A.numericValue!=null&&A.hasOwnProperty("numericValue")&&(s.numericValue=A.numericValue,r.oneofs&&(s._numericValue="numericValue")),A.textTranslated!=null&&A.hasOwnProperty("textTranslated")&&(s.textTranslated=A.textTranslated,r.oneofs&&(s._textTranslated="textTranslated")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.InThreadSurveyMetadata.InThreadSurveyOption"},i})(),t.InThreadSurveyPrivacyStatementPart=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.text=A.string();break}case 2:{c.url=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart)return A;var r=new p.proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart;return A.text!=null&&(r.text=String(A.text)),A.url!=null&&(r.url=String(A.url)),r},i.toObject=function(A,r){r||(r={});var s={};return A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.InThreadSurveyMetadata.InThreadSurveyPrivacyStatementPart"},i})(),t.InThreadSurveyQuestion=(function(){function i(a){if(this.questionOptions=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.questionText=A.string();break}case 2:{c.questionId=A.string();break}case 3:{c.questionOptions&&c.questionOptions.length||(c.questionOptions=[]),c.questionOptions.push(p.proto.InThreadSurveyMetadata.InThreadSurveyOption.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.InThreadSurveyMetadata.InThreadSurveyQuestion)return A;var r=new p.proto.InThreadSurveyMetadata.InThreadSurveyQuestion;if(A.questionText!=null&&(r.questionText=String(A.questionText)),A.questionId!=null&&(r.questionId=String(A.questionId)),A.questionOptions){if(!Array.isArray(A.questionOptions))throw TypeError(".proto.InThreadSurveyMetadata.InThreadSurveyQuestion.questionOptions: array expected");r.questionOptions=[];for(var s=0;s>>3){case 1:{s.polygonVertices&&s.polygonVertices.length||(s.polygonVertices=[]),s.polygonVertices.push(p.proto.Point.decode(e,e.uint32()));break}case 4:{s.shouldSkipConfirmation=e.bool();break}case 5:{s.embeddedContent=p.proto.EmbeddedContent.decode(e,e.uint32());break}case 8:{s.statusLinkType=e.int32();break}case 2:{s.location=p.proto.Location.decode(e,e.uint32());break}case 3:{s.newsletter=p.proto.ContextInfo.ForwardedNewsletterMessageInfo.decode(e,e.uint32());break}case 6:{s.embeddedAction=e.bool();break}case 7:{s.tapAction=p.proto.TapLinkAction.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.InteractiveAnnotation)return e;var a=new p.proto.InteractiveAnnotation;if(e.polygonVertices){if(!Array.isArray(e.polygonVertices))throw TypeError(".proto.InteractiveAnnotation.polygonVertices: array expected");a.polygonVertices=[];for(var A=0;A>>3){case 1:{s.isGalaxyFlowCompleted=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.InteractiveMessageAdditionalMetadata)return e;var a=new p.proto.InteractiveMessageAdditionalMetadata;return e.isGalaxyFlowCompleted!=null&&(a.isGalaxyFlowCompleted=!!e.isGalaxyFlowCompleted),a},t.toObject=function(e,a){a||(a={});var A={};return e.isGalaxyFlowCompleted!=null&&e.hasOwnProperty("isGalaxyFlowCompleted")&&(A.isGalaxyFlowCompleted=e.isGalaxyFlowCompleted,a.oneofs&&(A._isGalaxyFlowCompleted="isGalaxyFlowCompleted")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.InteractiveMessageAdditionalMetadata"},t})(),n.KeepInChat=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.keepType=e.int32();break}case 2:{s.serverTimestamp=e.int64();break}case 3:{s.key=p.proto.MessageKey.decode(e,e.uint32());break}case 4:{s.deviceJid=e.string();break}case 5:{s.clientTimestampMs=e.int64();break}case 6:{s.serverTimestampMs=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.KeepInChat)return e;var a=new p.proto.KeepInChat;switch(e.keepType){default:if(typeof e.keepType=="number"){a.keepType=e.keepType;break}break;case"UNKNOWN":case 0:a.keepType=0;break;case"KEEP_FOR_ALL":case 1:a.keepType=1;break;case"UNDO_KEEP_FOR_ALL":case 2:a.keepType=2;break}if(e.serverTimestamp!=null&&(l.Long?(a.serverTimestamp=l.Long.fromValue(e.serverTimestamp)).unsigned=!1:typeof e.serverTimestamp=="string"?a.serverTimestamp=parseInt(e.serverTimestamp,10):typeof e.serverTimestamp=="number"?a.serverTimestamp=e.serverTimestamp:typeof e.serverTimestamp=="object"&&(a.serverTimestamp=new l.LongBits(e.serverTimestamp.low>>>0,e.serverTimestamp.high>>>0).toNumber())),e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.KeepInChat.key: object expected");a.key=p.proto.MessageKey.fromObject(e.key)}return e.deviceJid!=null&&(a.deviceJid=String(e.deviceJid)),e.clientTimestampMs!=null&&(l.Long?(a.clientTimestampMs=l.Long.fromValue(e.clientTimestampMs)).unsigned=!1:typeof e.clientTimestampMs=="string"?a.clientTimestampMs=parseInt(e.clientTimestampMs,10):typeof e.clientTimestampMs=="number"?a.clientTimestampMs=e.clientTimestampMs:typeof e.clientTimestampMs=="object"&&(a.clientTimestampMs=new l.LongBits(e.clientTimestampMs.low>>>0,e.clientTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(l.Long?(a.serverTimestampMs=l.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new l.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.keepType!=null&&e.hasOwnProperty("keepType")&&(A.keepType=a.enums===String?p.proto.KeepType[e.keepType]===void 0?e.keepType:p.proto.KeepType[e.keepType]:e.keepType,a.oneofs&&(A._keepType="keepType")),e.serverTimestamp!=null&&e.hasOwnProperty("serverTimestamp")&&(typeof e.serverTimestamp=="number"?A.serverTimestamp=a.longs===String?String(e.serverTimestamp):e.serverTimestamp:A.serverTimestamp=a.longs===String?se(e.serverTimestamp):a.longs===Number?ge(e.serverTimestamp):e.serverTimestamp,a.oneofs&&(A._serverTimestamp="serverTimestamp")),e.key!=null&&e.hasOwnProperty("key")&&(A.key=p.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.deviceJid!=null&&e.hasOwnProperty("deviceJid")&&(A.deviceJid=e.deviceJid,a.oneofs&&(A._deviceJid="deviceJid")),e.clientTimestampMs!=null&&e.hasOwnProperty("clientTimestampMs")&&(typeof e.clientTimestampMs=="number"?A.clientTimestampMs=a.longs===String?String(e.clientTimestampMs):e.clientTimestampMs:A.clientTimestampMs=a.longs===String?se(e.clientTimestampMs):a.longs===Number?ge(e.clientTimestampMs):e.clientTimestampMs,a.oneofs&&(A._clientTimestampMs="clientTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?se(e.serverTimestampMs):a.longs===Number?ge(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.KeepInChat"},t})(),n.KeepType=(function(){let t={},o=Object.create(t);return o[t[0]="UNKNOWN"]=0,o[t[1]="KEEP_FOR_ALL"]=1,o[t[2]="UNDO_KEEP_FOR_ALL"]=2,o})(),n.KeyExchangeMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.baseKey=e.bytes();break}case 3:{s.ratchetKey=e.bytes();break}case 4:{s.identityKey=e.bytes();break}case 5:{s.baseKeySignature=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.KeyExchangeMessage)return e;var a=new p.proto.KeyExchangeMessage;return e.id!=null&&(a.id=e.id>>>0),e.baseKey!=null&&(typeof e.baseKey=="string"?l.base64.decode(e.baseKey,a.baseKey=l.newBuffer(l.base64.length(e.baseKey)),0):e.baseKey.length>=0&&(a.baseKey=e.baseKey)),e.ratchetKey!=null&&(typeof e.ratchetKey=="string"?l.base64.decode(e.ratchetKey,a.ratchetKey=l.newBuffer(l.base64.length(e.ratchetKey)),0):e.ratchetKey.length>=0&&(a.ratchetKey=e.ratchetKey)),e.identityKey!=null&&(typeof e.identityKey=="string"?l.base64.decode(e.identityKey,a.identityKey=l.newBuffer(l.base64.length(e.identityKey)),0):e.identityKey.length>=0&&(a.identityKey=e.identityKey)),e.baseKeySignature!=null&&(typeof e.baseKeySignature=="string"?l.base64.decode(e.baseKeySignature,a.baseKeySignature=l.newBuffer(l.base64.length(e.baseKeySignature)),0):e.baseKeySignature.length>=0&&(a.baseKeySignature=e.baseKeySignature)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.baseKey!=null&&e.hasOwnProperty("baseKey")&&(A.baseKey=a.bytes===String?l.base64.encode(e.baseKey,0,e.baseKey.length):a.bytes===Array?Array.prototype.slice.call(e.baseKey):e.baseKey,a.oneofs&&(A._baseKey="baseKey")),e.ratchetKey!=null&&e.hasOwnProperty("ratchetKey")&&(A.ratchetKey=a.bytes===String?l.base64.encode(e.ratchetKey,0,e.ratchetKey.length):a.bytes===Array?Array.prototype.slice.call(e.ratchetKey):e.ratchetKey,a.oneofs&&(A._ratchetKey="ratchetKey")),e.identityKey!=null&&e.hasOwnProperty("identityKey")&&(A.identityKey=a.bytes===String?l.base64.encode(e.identityKey,0,e.identityKey.length):a.bytes===Array?Array.prototype.slice.call(e.identityKey):e.identityKey,a.oneofs&&(A._identityKey="identityKey")),e.baseKeySignature!=null&&e.hasOwnProperty("baseKeySignature")&&(A.baseKeySignature=a.bytes===String?l.base64.encode(e.baseKeySignature,0,e.baseKeySignature.length):a.bytes===Array?Array.prototype.slice.call(e.baseKeySignature):e.baseKeySignature,a.oneofs&&(A._baseKeySignature="baseKeySignature")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.KeyExchangeMessage"},t})(),n.KeyId=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.KeyId)return e;var a=new p.proto.KeyId;return e.id!=null&&(typeof e.id=="string"?l.base64.decode(e.id,a.id=l.newBuffer(l.base64.length(e.id)),0):e.id.length>=0&&(a.id=e.id)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=a.bytes===String?l.base64.encode(e.id,0,e.id.length):a.bytes===Array?Array.prototype.slice.call(e.id):e.id,a.oneofs&&(A._id="id")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.KeyId"},t})(),n.LIDMigrationMapping=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pn=e.uint64();break}case 2:{s.assignedLid=e.uint64();break}case 3:{s.latestLid=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LIDMigrationMapping)return e;var a=new p.proto.LIDMigrationMapping;return e.pn!=null&&(l.Long?(a.pn=l.Long.fromValue(e.pn)).unsigned=!0:typeof e.pn=="string"?a.pn=parseInt(e.pn,10):typeof e.pn=="number"?a.pn=e.pn:typeof e.pn=="object"&&(a.pn=new l.LongBits(e.pn.low>>>0,e.pn.high>>>0).toNumber(!0))),e.assignedLid!=null&&(l.Long?(a.assignedLid=l.Long.fromValue(e.assignedLid)).unsigned=!0:typeof e.assignedLid=="string"?a.assignedLid=parseInt(e.assignedLid,10):typeof e.assignedLid=="number"?a.assignedLid=e.assignedLid:typeof e.assignedLid=="object"&&(a.assignedLid=new l.LongBits(e.assignedLid.low>>>0,e.assignedLid.high>>>0).toNumber(!0))),e.latestLid!=null&&(l.Long?(a.latestLid=l.Long.fromValue(e.latestLid)).unsigned=!0:typeof e.latestLid=="string"?a.latestLid=parseInt(e.latestLid,10):typeof e.latestLid=="number"?a.latestLid=e.latestLid:typeof e.latestLid=="object"&&(a.latestLid=new l.LongBits(e.latestLid.low>>>0,e.latestLid.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};if(a.defaults){if(l.Long){var r=new l.Long(0,0,!0);A.pn=a.longs===String?r.toString():a.longs===Number?r.toNumber():r}else A.pn=a.longs===String?"0":0;if(l.Long){var r=new l.Long(0,0,!0);A.assignedLid=a.longs===String?r.toString():a.longs===Number?r.toNumber():r}else A.assignedLid=a.longs===String?"0":0}return e.pn!=null&&e.hasOwnProperty("pn")&&(typeof e.pn=="number"?A.pn=a.longs===String?String(e.pn):e.pn:A.pn=a.longs===String?se(e.pn,!0):a.longs===Number?ge(e.pn,!0):e.pn),e.assignedLid!=null&&e.hasOwnProperty("assignedLid")&&(typeof e.assignedLid=="number"?A.assignedLid=a.longs===String?String(e.assignedLid):e.assignedLid:A.assignedLid=a.longs===String?se(e.assignedLid,!0):a.longs===Number?ge(e.assignedLid,!0):e.assignedLid),e.latestLid!=null&&e.hasOwnProperty("latestLid")&&(typeof e.latestLid=="number"?A.latestLid=a.longs===String?String(e.latestLid):e.latestLid:A.latestLid=a.longs===String?se(e.latestLid,!0):a.longs===Number?ge(e.latestLid,!0):e.latestLid,a.oneofs&&(A._latestLid="latestLid")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LIDMigrationMapping"},t})(),n.LIDMigrationMappingSyncMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encodedMappingPayload=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LIDMigrationMappingSyncMessage)return e;var a=new p.proto.LIDMigrationMappingSyncMessage;return e.encodedMappingPayload!=null&&(typeof e.encodedMappingPayload=="string"?l.base64.decode(e.encodedMappingPayload,a.encodedMappingPayload=l.newBuffer(l.base64.length(e.encodedMappingPayload)),0):e.encodedMappingPayload.length>=0&&(a.encodedMappingPayload=e.encodedMappingPayload)),a},t.toObject=function(e,a){a||(a={});var A={};return e.encodedMappingPayload!=null&&e.hasOwnProperty("encodedMappingPayload")&&(A.encodedMappingPayload=a.bytes===String?l.base64.encode(e.encodedMappingPayload,0,e.encodedMappingPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encodedMappingPayload):e.encodedMappingPayload,a.oneofs&&(A._encodedMappingPayload="encodedMappingPayload")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LIDMigrationMappingSyncMessage"},t})(),n.LIDMigrationMappingSyncPayload=(function(){function t(i){if(this.pnToLidMappings=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pnToLidMappings&&s.pnToLidMappings.length||(s.pnToLidMappings=[]),s.pnToLidMappings.push(p.proto.LIDMigrationMapping.decode(e,e.uint32()));break}case 2:{s.chatDbMigrationTimestamp=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LIDMigrationMappingSyncPayload)return e;var a=new p.proto.LIDMigrationMappingSyncPayload;if(e.pnToLidMappings){if(!Array.isArray(e.pnToLidMappings))throw TypeError(".proto.LIDMigrationMappingSyncPayload.pnToLidMappings: array expected");a.pnToLidMappings=[];for(var A=0;A>>0,e.chatDbMigrationTimestamp.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.pnToLidMappings=[]),e.pnToLidMappings&&e.pnToLidMappings.length){A.pnToLidMappings=[];for(var r=0;r>>3){case 1:{s.eventResponseMessage=p.proto.Message.EventResponseMessage.decode(e,e.uint32());break}case 2:{s.pollVote=p.proto.Message.PollVoteMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LegacyMessage)return e;var a=new p.proto.LegacyMessage;if(e.eventResponseMessage!=null){if(typeof e.eventResponseMessage!="object")throw TypeError(".proto.LegacyMessage.eventResponseMessage: object expected");a.eventResponseMessage=p.proto.Message.EventResponseMessage.fromObject(e.eventResponseMessage)}if(e.pollVote!=null){if(typeof e.pollVote!="object")throw TypeError(".proto.LegacyMessage.pollVote: object expected");a.pollVote=p.proto.Message.PollVoteMessage.fromObject(e.pollVote)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.eventResponseMessage!=null&&e.hasOwnProperty("eventResponseMessage")&&(A.eventResponseMessage=p.proto.Message.EventResponseMessage.toObject(e.eventResponseMessage,a),a.oneofs&&(A._eventResponseMessage="eventResponseMessage")),e.pollVote!=null&&e.hasOwnProperty("pollVote")&&(A.pollVote=p.proto.Message.PollVoteMessage.toObject(e.pollVote,a),a.oneofs&&(A._pollVote="pollVote")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LegacyMessage"},t})(),n.LimitSharing=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.sharingLimited=e.bool();break}case 2:{s.trigger=e.int32();break}case 3:{s.limitSharingSettingTimestamp=e.int64();break}case 4:{s.initiatedByMe=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LimitSharing)return e;var a=new p.proto.LimitSharing;switch(e.sharingLimited!=null&&(a.sharingLimited=!!e.sharingLimited),e.trigger){default:if(typeof e.trigger=="number"){a.trigger=e.trigger;break}break;case"UNKNOWN":case 0:a.trigger=0;break;case"CHAT_SETTING":case 1:a.trigger=1;break;case"BIZ_SUPPORTS_FB_HOSTING":case 2:a.trigger=2;break;case"UNKNOWN_GROUP":case 3:a.trigger=3;break}return e.limitSharingSettingTimestamp!=null&&(l.Long?(a.limitSharingSettingTimestamp=l.Long.fromValue(e.limitSharingSettingTimestamp)).unsigned=!1:typeof e.limitSharingSettingTimestamp=="string"?a.limitSharingSettingTimestamp=parseInt(e.limitSharingSettingTimestamp,10):typeof e.limitSharingSettingTimestamp=="number"?a.limitSharingSettingTimestamp=e.limitSharingSettingTimestamp:typeof e.limitSharingSettingTimestamp=="object"&&(a.limitSharingSettingTimestamp=new l.LongBits(e.limitSharingSettingTimestamp.low>>>0,e.limitSharingSettingTimestamp.high>>>0).toNumber())),e.initiatedByMe!=null&&(a.initiatedByMe=!!e.initiatedByMe),a},t.toObject=function(e,a){a||(a={});var A={};return e.sharingLimited!=null&&e.hasOwnProperty("sharingLimited")&&(A.sharingLimited=e.sharingLimited,a.oneofs&&(A._sharingLimited="sharingLimited")),e.trigger!=null&&e.hasOwnProperty("trigger")&&(A.trigger=a.enums===String?p.proto.LimitSharing.TriggerType[e.trigger]===void 0?e.trigger:p.proto.LimitSharing.TriggerType[e.trigger]:e.trigger,a.oneofs&&(A._trigger="trigger")),e.limitSharingSettingTimestamp!=null&&e.hasOwnProperty("limitSharingSettingTimestamp")&&(typeof e.limitSharingSettingTimestamp=="number"?A.limitSharingSettingTimestamp=a.longs===String?String(e.limitSharingSettingTimestamp):e.limitSharingSettingTimestamp:A.limitSharingSettingTimestamp=a.longs===String?se(e.limitSharingSettingTimestamp):a.longs===Number?ge(e.limitSharingSettingTimestamp):e.limitSharingSettingTimestamp,a.oneofs&&(A._limitSharingSettingTimestamp="limitSharingSettingTimestamp")),e.initiatedByMe!=null&&e.hasOwnProperty("initiatedByMe")&&(A.initiatedByMe=e.initiatedByMe,a.oneofs&&(A._initiatedByMe="initiatedByMe")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LimitSharing"},t.TriggerType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="CHAT_SETTING"]=1,e[i[2]="BIZ_SUPPORTS_FB_HOSTING"]=2,e[i[3]="UNKNOWN_GROUP"]=3,e})(),t})(),n.LocalizedName=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.lg=e.string();break}case 2:{s.lc=e.string();break}case 3:{s.verifiedName=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.LocalizedName)return e;var a=new p.proto.LocalizedName;return e.lg!=null&&(a.lg=String(e.lg)),e.lc!=null&&(a.lc=String(e.lc)),e.verifiedName!=null&&(a.verifiedName=String(e.verifiedName)),a},t.toObject=function(e,a){a||(a={});var A={};return e.lg!=null&&e.hasOwnProperty("lg")&&(A.lg=e.lg,a.oneofs&&(A._lg="lg")),e.lc!=null&&e.hasOwnProperty("lc")&&(A.lc=e.lc,a.oneofs&&(A._lc="lc")),e.verifiedName!=null&&e.hasOwnProperty("verifiedName")&&(A.verifiedName=e.verifiedName,a.oneofs&&(A._verifiedName="verifiedName")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.LocalizedName"},t})(),n.Location=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.degreesLatitude=e.double();break}case 2:{s.degreesLongitude=e.double();break}case 3:{s.name=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Location)return e;var a=new p.proto.Location;return e.degreesLatitude!=null&&(a.degreesLatitude=Number(e.degreesLatitude)),e.degreesLongitude!=null&&(a.degreesLongitude=Number(e.degreesLongitude)),e.name!=null&&(a.name=String(e.name)),a},t.toObject=function(e,a){a||(a={});var A={};return e.degreesLatitude!=null&&e.hasOwnProperty("degreesLatitude")&&(A.degreesLatitude=a.json&&!isFinite(e.degreesLatitude)?String(e.degreesLatitude):e.degreesLatitude,a.oneofs&&(A._degreesLatitude="degreesLatitude")),e.degreesLongitude!=null&&e.hasOwnProperty("degreesLongitude")&&(A.degreesLongitude=a.json&&!isFinite(e.degreesLongitude)?String(e.degreesLongitude):e.degreesLongitude,a.oneofs&&(A._degreesLongitude="degreesLongitude")),e.name!=null&&e.hasOwnProperty("name")&&(A.name=e.name,a.oneofs&&(A._name="name")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Location"},t})(),n.MediaData=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.localPath=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MediaData)return e;var a=new p.proto.MediaData;return e.localPath!=null&&(a.localPath=String(e.localPath)),a},t.toObject=function(e,a){a||(a={});var A={};return e.localPath!=null&&e.hasOwnProperty("localPath")&&(A.localPath=e.localPath,a.oneofs&&(A._localPath="localPath")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MediaData"},t})(),n.MediaNotifyMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.expressPathUrl=e.string();break}case 2:{s.fileEncSha256=e.bytes();break}case 3:{s.fileLength=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MediaNotifyMessage)return e;var a=new p.proto.MediaNotifyMessage;return e.expressPathUrl!=null&&(a.expressPathUrl=String(e.expressPathUrl)),e.fileEncSha256!=null&&(typeof e.fileEncSha256=="string"?l.base64.decode(e.fileEncSha256,a.fileEncSha256=l.newBuffer(l.base64.length(e.fileEncSha256)),0):e.fileEncSha256.length>=0&&(a.fileEncSha256=e.fileEncSha256)),e.fileLength!=null&&(l.Long?(a.fileLength=l.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new l.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};return e.expressPathUrl!=null&&e.hasOwnProperty("expressPathUrl")&&(A.expressPathUrl=e.expressPathUrl,a.oneofs&&(A._expressPathUrl="expressPathUrl")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=a.bytes===String?l.base64.encode(e.fileEncSha256,0,e.fileEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileEncSha256):e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),e.fileLength!=null&&e.hasOwnProperty("fileLength")&&(typeof e.fileLength=="number"?A.fileLength=a.longs===String?String(e.fileLength):e.fileLength:A.fileLength=a.longs===String?se(e.fileLength,!0):a.longs===Number?ge(e.fileLength,!0):e.fileLength,a.oneofs&&(A._fileLength="fileLength")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MediaNotifyMessage"},t})(),n.MediaRetryNotification=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.stanzaId=e.string();break}case 2:{s.directPath=e.string();break}case 3:{s.result=e.int32();break}case 4:{s.messageSecret=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MediaRetryNotification)return e;var a=new p.proto.MediaRetryNotification;switch(e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),e.directPath!=null&&(a.directPath=String(e.directPath)),e.result){default:if(typeof e.result=="number"){a.result=e.result;break}break;case"GENERAL_ERROR":case 0:a.result=0;break;case"SUCCESS":case 1:a.result=1;break;case"NOT_FOUND":case 2:a.result=2;break;case"DECRYPTION_ERROR":case 3:a.result=3;break}return e.messageSecret!=null&&(typeof e.messageSecret=="string"?l.base64.decode(e.messageSecret,a.messageSecret=l.newBuffer(l.base64.length(e.messageSecret)),0):e.messageSecret.length>=0&&(a.messageSecret=e.messageSecret)),a},t.toObject=function(e,a){a||(a={});var A={};return e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.result!=null&&e.hasOwnProperty("result")&&(A.result=a.enums===String?p.proto.MediaRetryNotification.ResultType[e.result]===void 0?e.result:p.proto.MediaRetryNotification.ResultType[e.result]:e.result,a.oneofs&&(A._result="result")),e.messageSecret!=null&&e.hasOwnProperty("messageSecret")&&(A.messageSecret=a.bytes===String?l.base64.encode(e.messageSecret,0,e.messageSecret.length):a.bytes===Array?Array.prototype.slice.call(e.messageSecret):e.messageSecret,a.oneofs&&(A._messageSecret="messageSecret")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MediaRetryNotification"},t.ResultType=(function(){let i={},e=Object.create(i);return e[i[0]="GENERAL_ERROR"]=0,e[i[1]="SUCCESS"]=1,e[i[2]="NOT_FOUND"]=2,e[i[3]="DECRYPTION_ERROR"]=3,e})(),t})(),n.MediaVisibility=(function(){let t={},o=Object.create(t);return o[t[0]="DEFAULT"]=0,o[t[1]="OFF"]=1,o[t[2]="ON"]=2,o})(),n.MemberLabel=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.label=e.string();break}case 2:{s.labelTimestamp=e.int64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MemberLabel)return e;var a=new p.proto.MemberLabel;return e.label!=null&&(a.label=String(e.label)),e.labelTimestamp!=null&&(l.Long?(a.labelTimestamp=l.Long.fromValue(e.labelTimestamp)).unsigned=!1:typeof e.labelTimestamp=="string"?a.labelTimestamp=parseInt(e.labelTimestamp,10):typeof e.labelTimestamp=="number"?a.labelTimestamp=e.labelTimestamp:typeof e.labelTimestamp=="object"&&(a.labelTimestamp=new l.LongBits(e.labelTimestamp.low>>>0,e.labelTimestamp.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.label!=null&&e.hasOwnProperty("label")&&(A.label=e.label,a.oneofs&&(A._label="label")),e.labelTimestamp!=null&&e.hasOwnProperty("labelTimestamp")&&(typeof e.labelTimestamp=="number"?A.labelTimestamp=a.longs===String?String(e.labelTimestamp):e.labelTimestamp:A.labelTimestamp=a.longs===String?se(e.labelTimestamp):a.longs===Number?ge(e.labelTimestamp):e.labelTimestamp,a.oneofs&&(A._labelTimestamp="labelTimestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MemberLabel"},t})(),n.Message=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.conversation=e.string();break}case 2:{s.senderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.decode(e,e.uint32());break}case 3:{s.imageMessage=p.proto.Message.ImageMessage.decode(e,e.uint32());break}case 4:{s.contactMessage=p.proto.Message.ContactMessage.decode(e,e.uint32());break}case 5:{s.locationMessage=p.proto.Message.LocationMessage.decode(e,e.uint32());break}case 6:{s.extendedTextMessage=p.proto.Message.ExtendedTextMessage.decode(e,e.uint32());break}case 7:{s.documentMessage=p.proto.Message.DocumentMessage.decode(e,e.uint32());break}case 8:{s.audioMessage=p.proto.Message.AudioMessage.decode(e,e.uint32());break}case 9:{s.videoMessage=p.proto.Message.VideoMessage.decode(e,e.uint32());break}case 10:{s.call=p.proto.Message.Call.decode(e,e.uint32());break}case 11:{s.chat=p.proto.Message.Chat.decode(e,e.uint32());break}case 12:{s.protocolMessage=p.proto.Message.ProtocolMessage.decode(e,e.uint32());break}case 13:{s.contactsArrayMessage=p.proto.Message.ContactsArrayMessage.decode(e,e.uint32());break}case 14:{s.highlyStructuredMessage=p.proto.Message.HighlyStructuredMessage.decode(e,e.uint32());break}case 15:{s.fastRatchetKeySenderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.decode(e,e.uint32());break}case 16:{s.sendPaymentMessage=p.proto.Message.SendPaymentMessage.decode(e,e.uint32());break}case 18:{s.liveLocationMessage=p.proto.Message.LiveLocationMessage.decode(e,e.uint32());break}case 22:{s.requestPaymentMessage=p.proto.Message.RequestPaymentMessage.decode(e,e.uint32());break}case 23:{s.declinePaymentRequestMessage=p.proto.Message.DeclinePaymentRequestMessage.decode(e,e.uint32());break}case 24:{s.cancelPaymentRequestMessage=p.proto.Message.CancelPaymentRequestMessage.decode(e,e.uint32());break}case 25:{s.templateMessage=p.proto.Message.TemplateMessage.decode(e,e.uint32());break}case 26:{s.stickerMessage=p.proto.Message.StickerMessage.decode(e,e.uint32());break}case 28:{s.groupInviteMessage=p.proto.Message.GroupInviteMessage.decode(e,e.uint32());break}case 29:{s.templateButtonReplyMessage=p.proto.Message.TemplateButtonReplyMessage.decode(e,e.uint32());break}case 30:{s.productMessage=p.proto.Message.ProductMessage.decode(e,e.uint32());break}case 31:{s.deviceSentMessage=p.proto.Message.DeviceSentMessage.decode(e,e.uint32());break}case 35:{s.messageContextInfo=p.proto.MessageContextInfo.decode(e,e.uint32());break}case 36:{s.listMessage=p.proto.Message.ListMessage.decode(e,e.uint32());break}case 37:{s.viewOnceMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 38:{s.orderMessage=p.proto.Message.OrderMessage.decode(e,e.uint32());break}case 39:{s.listResponseMessage=p.proto.Message.ListResponseMessage.decode(e,e.uint32());break}case 40:{s.ephemeralMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 41:{s.invoiceMessage=p.proto.Message.InvoiceMessage.decode(e,e.uint32());break}case 42:{s.buttonsMessage=p.proto.Message.ButtonsMessage.decode(e,e.uint32());break}case 43:{s.buttonsResponseMessage=p.proto.Message.ButtonsResponseMessage.decode(e,e.uint32());break}case 44:{s.paymentInviteMessage=p.proto.Message.PaymentInviteMessage.decode(e,e.uint32());break}case 45:{s.interactiveMessage=p.proto.Message.InteractiveMessage.decode(e,e.uint32());break}case 46:{s.reactionMessage=p.proto.Message.ReactionMessage.decode(e,e.uint32());break}case 47:{s.stickerSyncRmrMessage=p.proto.Message.StickerSyncRMRMessage.decode(e,e.uint32());break}case 48:{s.interactiveResponseMessage=p.proto.Message.InteractiveResponseMessage.decode(e,e.uint32());break}case 49:{s.pollCreationMessage=p.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 50:{s.pollUpdateMessage=p.proto.Message.PollUpdateMessage.decode(e,e.uint32());break}case 51:{s.keepInChatMessage=p.proto.Message.KeepInChatMessage.decode(e,e.uint32());break}case 53:{s.documentWithCaptionMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 54:{s.requestPhoneNumberMessage=p.proto.Message.RequestPhoneNumberMessage.decode(e,e.uint32());break}case 55:{s.viewOnceMessageV2=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 56:{s.encReactionMessage=p.proto.Message.EncReactionMessage.decode(e,e.uint32());break}case 58:{s.editedMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 59:{s.viewOnceMessageV2Extension=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 60:{s.pollCreationMessageV2=p.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 61:{s.scheduledCallCreationMessage=p.proto.Message.ScheduledCallCreationMessage.decode(e,e.uint32());break}case 62:{s.groupMentionedMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 63:{s.pinInChatMessage=p.proto.Message.PinInChatMessage.decode(e,e.uint32());break}case 64:{s.pollCreationMessageV3=p.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 65:{s.scheduledCallEditMessage=p.proto.Message.ScheduledCallEditMessage.decode(e,e.uint32());break}case 66:{s.ptvMessage=p.proto.Message.VideoMessage.decode(e,e.uint32());break}case 67:{s.botInvokeMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 69:{s.callLogMesssage=p.proto.Message.CallLogMessage.decode(e,e.uint32());break}case 70:{s.messageHistoryBundle=p.proto.Message.MessageHistoryBundle.decode(e,e.uint32());break}case 71:{s.encCommentMessage=p.proto.Message.EncCommentMessage.decode(e,e.uint32());break}case 72:{s.bcallMessage=p.proto.Message.BCallMessage.decode(e,e.uint32());break}case 74:{s.lottieStickerMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 75:{s.eventMessage=p.proto.Message.EventMessage.decode(e,e.uint32());break}case 76:{s.encEventResponseMessage=p.proto.Message.EncEventResponseMessage.decode(e,e.uint32());break}case 77:{s.commentMessage=p.proto.Message.CommentMessage.decode(e,e.uint32());break}case 78:{s.newsletterAdminInviteMessage=p.proto.Message.NewsletterAdminInviteMessage.decode(e,e.uint32());break}case 80:{s.placeholderMessage=p.proto.Message.PlaceholderMessage.decode(e,e.uint32());break}case 82:{s.secretEncryptedMessage=p.proto.Message.SecretEncryptedMessage.decode(e,e.uint32());break}case 83:{s.albumMessage=p.proto.Message.AlbumMessage.decode(e,e.uint32());break}case 85:{s.eventCoverImage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 86:{s.stickerPackMessage=p.proto.Message.StickerPackMessage.decode(e,e.uint32());break}case 87:{s.statusMentionMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 88:{s.pollResultSnapshotMessage=p.proto.Message.PollResultSnapshotMessage.decode(e,e.uint32());break}case 90:{s.pollCreationOptionImageMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 91:{s.associatedChildMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 92:{s.groupStatusMentionMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 93:{s.pollCreationMessageV4=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 95:{s.statusAddYours=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 96:{s.groupStatusMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 97:{s.richResponseMessage=p.proto.AIRichResponseMessage.decode(e,e.uint32());break}case 98:{s.statusNotificationMessage=p.proto.Message.StatusNotificationMessage.decode(e,e.uint32());break}case 99:{s.limitSharingMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 100:{s.botTaskMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 101:{s.questionMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 102:{s.messageHistoryNotice=p.proto.Message.MessageHistoryNotice.decode(e,e.uint32());break}case 103:{s.groupStatusMessageV2=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 104:{s.botForwardedMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 105:{s.statusQuestionAnswerMessage=p.proto.Message.StatusQuestionAnswerMessage.decode(e,e.uint32());break}case 106:{s.questionReplyMessage=p.proto.Message.FutureProofMessage.decode(e,e.uint32());break}case 107:{s.questionResponseMessage=p.proto.Message.QuestionResponseMessage.decode(e,e.uint32());break}case 109:{s.statusQuotedMessage=p.proto.Message.StatusQuotedMessage.decode(e,e.uint32());break}case 110:{s.statusStickerInteractionMessage=p.proto.Message.StatusStickerInteractionMessage.decode(e,e.uint32());break}case 111:{s.pollCreationMessageV5=p.proto.Message.PollCreationMessage.decode(e,e.uint32());break}case 113:{s.newsletterFollowerInviteMessageV2=p.proto.Message.NewsletterFollowerInviteMessage.decode(e,e.uint32());break}case 114:{s.pollResultSnapshotMessageV3=p.proto.Message.PollResultSnapshotMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Message)return e;var a=new p.proto.Message;if(e.conversation!=null&&(a.conversation=String(e.conversation)),e.senderKeyDistributionMessage!=null){if(typeof e.senderKeyDistributionMessage!="object")throw TypeError(".proto.Message.senderKeyDistributionMessage: object expected");a.senderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.fromObject(e.senderKeyDistributionMessage)}if(e.imageMessage!=null){if(typeof e.imageMessage!="object")throw TypeError(".proto.Message.imageMessage: object expected");a.imageMessage=p.proto.Message.ImageMessage.fromObject(e.imageMessage)}if(e.contactMessage!=null){if(typeof e.contactMessage!="object")throw TypeError(".proto.Message.contactMessage: object expected");a.contactMessage=p.proto.Message.ContactMessage.fromObject(e.contactMessage)}if(e.locationMessage!=null){if(typeof e.locationMessage!="object")throw TypeError(".proto.Message.locationMessage: object expected");a.locationMessage=p.proto.Message.LocationMessage.fromObject(e.locationMessage)}if(e.extendedTextMessage!=null){if(typeof e.extendedTextMessage!="object")throw TypeError(".proto.Message.extendedTextMessage: object expected");a.extendedTextMessage=p.proto.Message.ExtendedTextMessage.fromObject(e.extendedTextMessage)}if(e.documentMessage!=null){if(typeof e.documentMessage!="object")throw TypeError(".proto.Message.documentMessage: object expected");a.documentMessage=p.proto.Message.DocumentMessage.fromObject(e.documentMessage)}if(e.audioMessage!=null){if(typeof e.audioMessage!="object")throw TypeError(".proto.Message.audioMessage: object expected");a.audioMessage=p.proto.Message.AudioMessage.fromObject(e.audioMessage)}if(e.videoMessage!=null){if(typeof e.videoMessage!="object")throw TypeError(".proto.Message.videoMessage: object expected");a.videoMessage=p.proto.Message.VideoMessage.fromObject(e.videoMessage)}if(e.call!=null){if(typeof e.call!="object")throw TypeError(".proto.Message.call: object expected");a.call=p.proto.Message.Call.fromObject(e.call)}if(e.chat!=null){if(typeof e.chat!="object")throw TypeError(".proto.Message.chat: object expected");a.chat=p.proto.Message.Chat.fromObject(e.chat)}if(e.protocolMessage!=null){if(typeof e.protocolMessage!="object")throw TypeError(".proto.Message.protocolMessage: object expected");a.protocolMessage=p.proto.Message.ProtocolMessage.fromObject(e.protocolMessage)}if(e.contactsArrayMessage!=null){if(typeof e.contactsArrayMessage!="object")throw TypeError(".proto.Message.contactsArrayMessage: object expected");a.contactsArrayMessage=p.proto.Message.ContactsArrayMessage.fromObject(e.contactsArrayMessage)}if(e.highlyStructuredMessage!=null){if(typeof e.highlyStructuredMessage!="object")throw TypeError(".proto.Message.highlyStructuredMessage: object expected");a.highlyStructuredMessage=p.proto.Message.HighlyStructuredMessage.fromObject(e.highlyStructuredMessage)}if(e.fastRatchetKeySenderKeyDistributionMessage!=null){if(typeof e.fastRatchetKeySenderKeyDistributionMessage!="object")throw TypeError(".proto.Message.fastRatchetKeySenderKeyDistributionMessage: object expected");a.fastRatchetKeySenderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.fromObject(e.fastRatchetKeySenderKeyDistributionMessage)}if(e.sendPaymentMessage!=null){if(typeof e.sendPaymentMessage!="object")throw TypeError(".proto.Message.sendPaymentMessage: object expected");a.sendPaymentMessage=p.proto.Message.SendPaymentMessage.fromObject(e.sendPaymentMessage)}if(e.liveLocationMessage!=null){if(typeof e.liveLocationMessage!="object")throw TypeError(".proto.Message.liveLocationMessage: object expected");a.liveLocationMessage=p.proto.Message.LiveLocationMessage.fromObject(e.liveLocationMessage)}if(e.requestPaymentMessage!=null){if(typeof e.requestPaymentMessage!="object")throw TypeError(".proto.Message.requestPaymentMessage: object expected");a.requestPaymentMessage=p.proto.Message.RequestPaymentMessage.fromObject(e.requestPaymentMessage)}if(e.declinePaymentRequestMessage!=null){if(typeof e.declinePaymentRequestMessage!="object")throw TypeError(".proto.Message.declinePaymentRequestMessage: object expected");a.declinePaymentRequestMessage=p.proto.Message.DeclinePaymentRequestMessage.fromObject(e.declinePaymentRequestMessage)}if(e.cancelPaymentRequestMessage!=null){if(typeof e.cancelPaymentRequestMessage!="object")throw TypeError(".proto.Message.cancelPaymentRequestMessage: object expected");a.cancelPaymentRequestMessage=p.proto.Message.CancelPaymentRequestMessage.fromObject(e.cancelPaymentRequestMessage)}if(e.templateMessage!=null){if(typeof e.templateMessage!="object")throw TypeError(".proto.Message.templateMessage: object expected");a.templateMessage=p.proto.Message.TemplateMessage.fromObject(e.templateMessage)}if(e.stickerMessage!=null){if(typeof e.stickerMessage!="object")throw TypeError(".proto.Message.stickerMessage: object expected");a.stickerMessage=p.proto.Message.StickerMessage.fromObject(e.stickerMessage)}if(e.groupInviteMessage!=null){if(typeof e.groupInviteMessage!="object")throw TypeError(".proto.Message.groupInviteMessage: object expected");a.groupInviteMessage=p.proto.Message.GroupInviteMessage.fromObject(e.groupInviteMessage)}if(e.templateButtonReplyMessage!=null){if(typeof e.templateButtonReplyMessage!="object")throw TypeError(".proto.Message.templateButtonReplyMessage: object expected");a.templateButtonReplyMessage=p.proto.Message.TemplateButtonReplyMessage.fromObject(e.templateButtonReplyMessage)}if(e.productMessage!=null){if(typeof e.productMessage!="object")throw TypeError(".proto.Message.productMessage: object expected");a.productMessage=p.proto.Message.ProductMessage.fromObject(e.productMessage)}if(e.deviceSentMessage!=null){if(typeof e.deviceSentMessage!="object")throw TypeError(".proto.Message.deviceSentMessage: object expected");a.deviceSentMessage=p.proto.Message.DeviceSentMessage.fromObject(e.deviceSentMessage)}if(e.messageContextInfo!=null){if(typeof e.messageContextInfo!="object")throw TypeError(".proto.Message.messageContextInfo: object expected");a.messageContextInfo=p.proto.MessageContextInfo.fromObject(e.messageContextInfo)}if(e.listMessage!=null){if(typeof e.listMessage!="object")throw TypeError(".proto.Message.listMessage: object expected");a.listMessage=p.proto.Message.ListMessage.fromObject(e.listMessage)}if(e.viewOnceMessage!=null){if(typeof e.viewOnceMessage!="object")throw TypeError(".proto.Message.viewOnceMessage: object expected");a.viewOnceMessage=p.proto.Message.FutureProofMessage.fromObject(e.viewOnceMessage)}if(e.orderMessage!=null){if(typeof e.orderMessage!="object")throw TypeError(".proto.Message.orderMessage: object expected");a.orderMessage=p.proto.Message.OrderMessage.fromObject(e.orderMessage)}if(e.listResponseMessage!=null){if(typeof e.listResponseMessage!="object")throw TypeError(".proto.Message.listResponseMessage: object expected");a.listResponseMessage=p.proto.Message.ListResponseMessage.fromObject(e.listResponseMessage)}if(e.ephemeralMessage!=null){if(typeof e.ephemeralMessage!="object")throw TypeError(".proto.Message.ephemeralMessage: object expected");a.ephemeralMessage=p.proto.Message.FutureProofMessage.fromObject(e.ephemeralMessage)}if(e.invoiceMessage!=null){if(typeof e.invoiceMessage!="object")throw TypeError(".proto.Message.invoiceMessage: object expected");a.invoiceMessage=p.proto.Message.InvoiceMessage.fromObject(e.invoiceMessage)}if(e.buttonsMessage!=null){if(typeof e.buttonsMessage!="object")throw TypeError(".proto.Message.buttonsMessage: object expected");a.buttonsMessage=p.proto.Message.ButtonsMessage.fromObject(e.buttonsMessage)}if(e.buttonsResponseMessage!=null){if(typeof e.buttonsResponseMessage!="object")throw TypeError(".proto.Message.buttonsResponseMessage: object expected");a.buttonsResponseMessage=p.proto.Message.ButtonsResponseMessage.fromObject(e.buttonsResponseMessage)}if(e.paymentInviteMessage!=null){if(typeof e.paymentInviteMessage!="object")throw TypeError(".proto.Message.paymentInviteMessage: object expected");a.paymentInviteMessage=p.proto.Message.PaymentInviteMessage.fromObject(e.paymentInviteMessage)}if(e.interactiveMessage!=null){if(typeof e.interactiveMessage!="object")throw TypeError(".proto.Message.interactiveMessage: object expected");a.interactiveMessage=p.proto.Message.InteractiveMessage.fromObject(e.interactiveMessage)}if(e.reactionMessage!=null){if(typeof e.reactionMessage!="object")throw TypeError(".proto.Message.reactionMessage: object expected");a.reactionMessage=p.proto.Message.ReactionMessage.fromObject(e.reactionMessage)}if(e.stickerSyncRmrMessage!=null){if(typeof e.stickerSyncRmrMessage!="object")throw TypeError(".proto.Message.stickerSyncRmrMessage: object expected");a.stickerSyncRmrMessage=p.proto.Message.StickerSyncRMRMessage.fromObject(e.stickerSyncRmrMessage)}if(e.interactiveResponseMessage!=null){if(typeof e.interactiveResponseMessage!="object")throw TypeError(".proto.Message.interactiveResponseMessage: object expected");a.interactiveResponseMessage=p.proto.Message.InteractiveResponseMessage.fromObject(e.interactiveResponseMessage)}if(e.pollCreationMessage!=null){if(typeof e.pollCreationMessage!="object")throw TypeError(".proto.Message.pollCreationMessage: object expected");a.pollCreationMessage=p.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessage)}if(e.pollUpdateMessage!=null){if(typeof e.pollUpdateMessage!="object")throw TypeError(".proto.Message.pollUpdateMessage: object expected");a.pollUpdateMessage=p.proto.Message.PollUpdateMessage.fromObject(e.pollUpdateMessage)}if(e.keepInChatMessage!=null){if(typeof e.keepInChatMessage!="object")throw TypeError(".proto.Message.keepInChatMessage: object expected");a.keepInChatMessage=p.proto.Message.KeepInChatMessage.fromObject(e.keepInChatMessage)}if(e.documentWithCaptionMessage!=null){if(typeof e.documentWithCaptionMessage!="object")throw TypeError(".proto.Message.documentWithCaptionMessage: object expected");a.documentWithCaptionMessage=p.proto.Message.FutureProofMessage.fromObject(e.documentWithCaptionMessage)}if(e.requestPhoneNumberMessage!=null){if(typeof e.requestPhoneNumberMessage!="object")throw TypeError(".proto.Message.requestPhoneNumberMessage: object expected");a.requestPhoneNumberMessage=p.proto.Message.RequestPhoneNumberMessage.fromObject(e.requestPhoneNumberMessage)}if(e.viewOnceMessageV2!=null){if(typeof e.viewOnceMessageV2!="object")throw TypeError(".proto.Message.viewOnceMessageV2: object expected");a.viewOnceMessageV2=p.proto.Message.FutureProofMessage.fromObject(e.viewOnceMessageV2)}if(e.encReactionMessage!=null){if(typeof e.encReactionMessage!="object")throw TypeError(".proto.Message.encReactionMessage: object expected");a.encReactionMessage=p.proto.Message.EncReactionMessage.fromObject(e.encReactionMessage)}if(e.editedMessage!=null){if(typeof e.editedMessage!="object")throw TypeError(".proto.Message.editedMessage: object expected");a.editedMessage=p.proto.Message.FutureProofMessage.fromObject(e.editedMessage)}if(e.viewOnceMessageV2Extension!=null){if(typeof e.viewOnceMessageV2Extension!="object")throw TypeError(".proto.Message.viewOnceMessageV2Extension: object expected");a.viewOnceMessageV2Extension=p.proto.Message.FutureProofMessage.fromObject(e.viewOnceMessageV2Extension)}if(e.pollCreationMessageV2!=null){if(typeof e.pollCreationMessageV2!="object")throw TypeError(".proto.Message.pollCreationMessageV2: object expected");a.pollCreationMessageV2=p.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessageV2)}if(e.scheduledCallCreationMessage!=null){if(typeof e.scheduledCallCreationMessage!="object")throw TypeError(".proto.Message.scheduledCallCreationMessage: object expected");a.scheduledCallCreationMessage=p.proto.Message.ScheduledCallCreationMessage.fromObject(e.scheduledCallCreationMessage)}if(e.groupMentionedMessage!=null){if(typeof e.groupMentionedMessage!="object")throw TypeError(".proto.Message.groupMentionedMessage: object expected");a.groupMentionedMessage=p.proto.Message.FutureProofMessage.fromObject(e.groupMentionedMessage)}if(e.pinInChatMessage!=null){if(typeof e.pinInChatMessage!="object")throw TypeError(".proto.Message.pinInChatMessage: object expected");a.pinInChatMessage=p.proto.Message.PinInChatMessage.fromObject(e.pinInChatMessage)}if(e.pollCreationMessageV3!=null){if(typeof e.pollCreationMessageV3!="object")throw TypeError(".proto.Message.pollCreationMessageV3: object expected");a.pollCreationMessageV3=p.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessageV3)}if(e.scheduledCallEditMessage!=null){if(typeof e.scheduledCallEditMessage!="object")throw TypeError(".proto.Message.scheduledCallEditMessage: object expected");a.scheduledCallEditMessage=p.proto.Message.ScheduledCallEditMessage.fromObject(e.scheduledCallEditMessage)}if(e.ptvMessage!=null){if(typeof e.ptvMessage!="object")throw TypeError(".proto.Message.ptvMessage: object expected");a.ptvMessage=p.proto.Message.VideoMessage.fromObject(e.ptvMessage)}if(e.botInvokeMessage!=null){if(typeof e.botInvokeMessage!="object")throw TypeError(".proto.Message.botInvokeMessage: object expected");a.botInvokeMessage=p.proto.Message.FutureProofMessage.fromObject(e.botInvokeMessage)}if(e.callLogMesssage!=null){if(typeof e.callLogMesssage!="object")throw TypeError(".proto.Message.callLogMesssage: object expected");a.callLogMesssage=p.proto.Message.CallLogMessage.fromObject(e.callLogMesssage)}if(e.messageHistoryBundle!=null){if(typeof e.messageHistoryBundle!="object")throw TypeError(".proto.Message.messageHistoryBundle: object expected");a.messageHistoryBundle=p.proto.Message.MessageHistoryBundle.fromObject(e.messageHistoryBundle)}if(e.encCommentMessage!=null){if(typeof e.encCommentMessage!="object")throw TypeError(".proto.Message.encCommentMessage: object expected");a.encCommentMessage=p.proto.Message.EncCommentMessage.fromObject(e.encCommentMessage)}if(e.bcallMessage!=null){if(typeof e.bcallMessage!="object")throw TypeError(".proto.Message.bcallMessage: object expected");a.bcallMessage=p.proto.Message.BCallMessage.fromObject(e.bcallMessage)}if(e.lottieStickerMessage!=null){if(typeof e.lottieStickerMessage!="object")throw TypeError(".proto.Message.lottieStickerMessage: object expected");a.lottieStickerMessage=p.proto.Message.FutureProofMessage.fromObject(e.lottieStickerMessage)}if(e.eventMessage!=null){if(typeof e.eventMessage!="object")throw TypeError(".proto.Message.eventMessage: object expected");a.eventMessage=p.proto.Message.EventMessage.fromObject(e.eventMessage)}if(e.encEventResponseMessage!=null){if(typeof e.encEventResponseMessage!="object")throw TypeError(".proto.Message.encEventResponseMessage: object expected");a.encEventResponseMessage=p.proto.Message.EncEventResponseMessage.fromObject(e.encEventResponseMessage)}if(e.commentMessage!=null){if(typeof e.commentMessage!="object")throw TypeError(".proto.Message.commentMessage: object expected");a.commentMessage=p.proto.Message.CommentMessage.fromObject(e.commentMessage)}if(e.newsletterAdminInviteMessage!=null){if(typeof e.newsletterAdminInviteMessage!="object")throw TypeError(".proto.Message.newsletterAdminInviteMessage: object expected");a.newsletterAdminInviteMessage=p.proto.Message.NewsletterAdminInviteMessage.fromObject(e.newsletterAdminInviteMessage)}if(e.placeholderMessage!=null){if(typeof e.placeholderMessage!="object")throw TypeError(".proto.Message.placeholderMessage: object expected");a.placeholderMessage=p.proto.Message.PlaceholderMessage.fromObject(e.placeholderMessage)}if(e.secretEncryptedMessage!=null){if(typeof e.secretEncryptedMessage!="object")throw TypeError(".proto.Message.secretEncryptedMessage: object expected");a.secretEncryptedMessage=p.proto.Message.SecretEncryptedMessage.fromObject(e.secretEncryptedMessage)}if(e.albumMessage!=null){if(typeof e.albumMessage!="object")throw TypeError(".proto.Message.albumMessage: object expected");a.albumMessage=p.proto.Message.AlbumMessage.fromObject(e.albumMessage)}if(e.eventCoverImage!=null){if(typeof e.eventCoverImage!="object")throw TypeError(".proto.Message.eventCoverImage: object expected");a.eventCoverImage=p.proto.Message.FutureProofMessage.fromObject(e.eventCoverImage)}if(e.stickerPackMessage!=null){if(typeof e.stickerPackMessage!="object")throw TypeError(".proto.Message.stickerPackMessage: object expected");a.stickerPackMessage=p.proto.Message.StickerPackMessage.fromObject(e.stickerPackMessage)}if(e.statusMentionMessage!=null){if(typeof e.statusMentionMessage!="object")throw TypeError(".proto.Message.statusMentionMessage: object expected");a.statusMentionMessage=p.proto.Message.FutureProofMessage.fromObject(e.statusMentionMessage)}if(e.pollResultSnapshotMessage!=null){if(typeof e.pollResultSnapshotMessage!="object")throw TypeError(".proto.Message.pollResultSnapshotMessage: object expected");a.pollResultSnapshotMessage=p.proto.Message.PollResultSnapshotMessage.fromObject(e.pollResultSnapshotMessage)}if(e.pollCreationOptionImageMessage!=null){if(typeof e.pollCreationOptionImageMessage!="object")throw TypeError(".proto.Message.pollCreationOptionImageMessage: object expected");a.pollCreationOptionImageMessage=p.proto.Message.FutureProofMessage.fromObject(e.pollCreationOptionImageMessage)}if(e.associatedChildMessage!=null){if(typeof e.associatedChildMessage!="object")throw TypeError(".proto.Message.associatedChildMessage: object expected");a.associatedChildMessage=p.proto.Message.FutureProofMessage.fromObject(e.associatedChildMessage)}if(e.groupStatusMentionMessage!=null){if(typeof e.groupStatusMentionMessage!="object")throw TypeError(".proto.Message.groupStatusMentionMessage: object expected");a.groupStatusMentionMessage=p.proto.Message.FutureProofMessage.fromObject(e.groupStatusMentionMessage)}if(e.pollCreationMessageV4!=null){if(typeof e.pollCreationMessageV4!="object")throw TypeError(".proto.Message.pollCreationMessageV4: object expected");a.pollCreationMessageV4=p.proto.Message.FutureProofMessage.fromObject(e.pollCreationMessageV4)}if(e.statusAddYours!=null){if(typeof e.statusAddYours!="object")throw TypeError(".proto.Message.statusAddYours: object expected");a.statusAddYours=p.proto.Message.FutureProofMessage.fromObject(e.statusAddYours)}if(e.groupStatusMessage!=null){if(typeof e.groupStatusMessage!="object")throw TypeError(".proto.Message.groupStatusMessage: object expected");a.groupStatusMessage=p.proto.Message.FutureProofMessage.fromObject(e.groupStatusMessage)}if(e.richResponseMessage!=null){if(typeof e.richResponseMessage!="object")throw TypeError(".proto.Message.richResponseMessage: object expected");a.richResponseMessage=p.proto.AIRichResponseMessage.fromObject(e.richResponseMessage)}if(e.statusNotificationMessage!=null){if(typeof e.statusNotificationMessage!="object")throw TypeError(".proto.Message.statusNotificationMessage: object expected");a.statusNotificationMessage=p.proto.Message.StatusNotificationMessage.fromObject(e.statusNotificationMessage)}if(e.limitSharingMessage!=null){if(typeof e.limitSharingMessage!="object")throw TypeError(".proto.Message.limitSharingMessage: object expected");a.limitSharingMessage=p.proto.Message.FutureProofMessage.fromObject(e.limitSharingMessage)}if(e.botTaskMessage!=null){if(typeof e.botTaskMessage!="object")throw TypeError(".proto.Message.botTaskMessage: object expected");a.botTaskMessage=p.proto.Message.FutureProofMessage.fromObject(e.botTaskMessage)}if(e.questionMessage!=null){if(typeof e.questionMessage!="object")throw TypeError(".proto.Message.questionMessage: object expected");a.questionMessage=p.proto.Message.FutureProofMessage.fromObject(e.questionMessage)}if(e.messageHistoryNotice!=null){if(typeof e.messageHistoryNotice!="object")throw TypeError(".proto.Message.messageHistoryNotice: object expected");a.messageHistoryNotice=p.proto.Message.MessageHistoryNotice.fromObject(e.messageHistoryNotice)}if(e.groupStatusMessageV2!=null){if(typeof e.groupStatusMessageV2!="object")throw TypeError(".proto.Message.groupStatusMessageV2: object expected");a.groupStatusMessageV2=p.proto.Message.FutureProofMessage.fromObject(e.groupStatusMessageV2)}if(e.botForwardedMessage!=null){if(typeof e.botForwardedMessage!="object")throw TypeError(".proto.Message.botForwardedMessage: object expected");a.botForwardedMessage=p.proto.Message.FutureProofMessage.fromObject(e.botForwardedMessage)}if(e.statusQuestionAnswerMessage!=null){if(typeof e.statusQuestionAnswerMessage!="object")throw TypeError(".proto.Message.statusQuestionAnswerMessage: object expected");a.statusQuestionAnswerMessage=p.proto.Message.StatusQuestionAnswerMessage.fromObject(e.statusQuestionAnswerMessage)}if(e.questionReplyMessage!=null){if(typeof e.questionReplyMessage!="object")throw TypeError(".proto.Message.questionReplyMessage: object expected");a.questionReplyMessage=p.proto.Message.FutureProofMessage.fromObject(e.questionReplyMessage)}if(e.questionResponseMessage!=null){if(typeof e.questionResponseMessage!="object")throw TypeError(".proto.Message.questionResponseMessage: object expected");a.questionResponseMessage=p.proto.Message.QuestionResponseMessage.fromObject(e.questionResponseMessage)}if(e.statusQuotedMessage!=null){if(typeof e.statusQuotedMessage!="object")throw TypeError(".proto.Message.statusQuotedMessage: object expected");a.statusQuotedMessage=p.proto.Message.StatusQuotedMessage.fromObject(e.statusQuotedMessage)}if(e.statusStickerInteractionMessage!=null){if(typeof e.statusStickerInteractionMessage!="object")throw TypeError(".proto.Message.statusStickerInteractionMessage: object expected");a.statusStickerInteractionMessage=p.proto.Message.StatusStickerInteractionMessage.fromObject(e.statusStickerInteractionMessage)}if(e.pollCreationMessageV5!=null){if(typeof e.pollCreationMessageV5!="object")throw TypeError(".proto.Message.pollCreationMessageV5: object expected");a.pollCreationMessageV5=p.proto.Message.PollCreationMessage.fromObject(e.pollCreationMessageV5)}if(e.newsletterFollowerInviteMessageV2!=null){if(typeof e.newsletterFollowerInviteMessageV2!="object")throw TypeError(".proto.Message.newsletterFollowerInviteMessageV2: object expected");a.newsletterFollowerInviteMessageV2=p.proto.Message.NewsletterFollowerInviteMessage.fromObject(e.newsletterFollowerInviteMessageV2)}if(e.pollResultSnapshotMessageV3!=null){if(typeof e.pollResultSnapshotMessageV3!="object")throw TypeError(".proto.Message.pollResultSnapshotMessageV3: object expected");a.pollResultSnapshotMessageV3=p.proto.Message.PollResultSnapshotMessage.fromObject(e.pollResultSnapshotMessageV3)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.conversation!=null&&e.hasOwnProperty("conversation")&&(A.conversation=e.conversation,a.oneofs&&(A._conversation="conversation")),e.senderKeyDistributionMessage!=null&&e.hasOwnProperty("senderKeyDistributionMessage")&&(A.senderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.toObject(e.senderKeyDistributionMessage,a),a.oneofs&&(A._senderKeyDistributionMessage="senderKeyDistributionMessage")),e.imageMessage!=null&&e.hasOwnProperty("imageMessage")&&(A.imageMessage=p.proto.Message.ImageMessage.toObject(e.imageMessage,a),a.oneofs&&(A._imageMessage="imageMessage")),e.contactMessage!=null&&e.hasOwnProperty("contactMessage")&&(A.contactMessage=p.proto.Message.ContactMessage.toObject(e.contactMessage,a),a.oneofs&&(A._contactMessage="contactMessage")),e.locationMessage!=null&&e.hasOwnProperty("locationMessage")&&(A.locationMessage=p.proto.Message.LocationMessage.toObject(e.locationMessage,a),a.oneofs&&(A._locationMessage="locationMessage")),e.extendedTextMessage!=null&&e.hasOwnProperty("extendedTextMessage")&&(A.extendedTextMessage=p.proto.Message.ExtendedTextMessage.toObject(e.extendedTextMessage,a),a.oneofs&&(A._extendedTextMessage="extendedTextMessage")),e.documentMessage!=null&&e.hasOwnProperty("documentMessage")&&(A.documentMessage=p.proto.Message.DocumentMessage.toObject(e.documentMessage,a),a.oneofs&&(A._documentMessage="documentMessage")),e.audioMessage!=null&&e.hasOwnProperty("audioMessage")&&(A.audioMessage=p.proto.Message.AudioMessage.toObject(e.audioMessage,a),a.oneofs&&(A._audioMessage="audioMessage")),e.videoMessage!=null&&e.hasOwnProperty("videoMessage")&&(A.videoMessage=p.proto.Message.VideoMessage.toObject(e.videoMessage,a),a.oneofs&&(A._videoMessage="videoMessage")),e.call!=null&&e.hasOwnProperty("call")&&(A.call=p.proto.Message.Call.toObject(e.call,a),a.oneofs&&(A._call="call")),e.chat!=null&&e.hasOwnProperty("chat")&&(A.chat=p.proto.Message.Chat.toObject(e.chat,a),a.oneofs&&(A._chat="chat")),e.protocolMessage!=null&&e.hasOwnProperty("protocolMessage")&&(A.protocolMessage=p.proto.Message.ProtocolMessage.toObject(e.protocolMessage,a),a.oneofs&&(A._protocolMessage="protocolMessage")),e.contactsArrayMessage!=null&&e.hasOwnProperty("contactsArrayMessage")&&(A.contactsArrayMessage=p.proto.Message.ContactsArrayMessage.toObject(e.contactsArrayMessage,a),a.oneofs&&(A._contactsArrayMessage="contactsArrayMessage")),e.highlyStructuredMessage!=null&&e.hasOwnProperty("highlyStructuredMessage")&&(A.highlyStructuredMessage=p.proto.Message.HighlyStructuredMessage.toObject(e.highlyStructuredMessage,a),a.oneofs&&(A._highlyStructuredMessage="highlyStructuredMessage")),e.fastRatchetKeySenderKeyDistributionMessage!=null&&e.hasOwnProperty("fastRatchetKeySenderKeyDistributionMessage")&&(A.fastRatchetKeySenderKeyDistributionMessage=p.proto.Message.SenderKeyDistributionMessage.toObject(e.fastRatchetKeySenderKeyDistributionMessage,a),a.oneofs&&(A._fastRatchetKeySenderKeyDistributionMessage="fastRatchetKeySenderKeyDistributionMessage")),e.sendPaymentMessage!=null&&e.hasOwnProperty("sendPaymentMessage")&&(A.sendPaymentMessage=p.proto.Message.SendPaymentMessage.toObject(e.sendPaymentMessage,a),a.oneofs&&(A._sendPaymentMessage="sendPaymentMessage")),e.liveLocationMessage!=null&&e.hasOwnProperty("liveLocationMessage")&&(A.liveLocationMessage=p.proto.Message.LiveLocationMessage.toObject(e.liveLocationMessage,a),a.oneofs&&(A._liveLocationMessage="liveLocationMessage")),e.requestPaymentMessage!=null&&e.hasOwnProperty("requestPaymentMessage")&&(A.requestPaymentMessage=p.proto.Message.RequestPaymentMessage.toObject(e.requestPaymentMessage,a),a.oneofs&&(A._requestPaymentMessage="requestPaymentMessage")),e.declinePaymentRequestMessage!=null&&e.hasOwnProperty("declinePaymentRequestMessage")&&(A.declinePaymentRequestMessage=p.proto.Message.DeclinePaymentRequestMessage.toObject(e.declinePaymentRequestMessage,a),a.oneofs&&(A._declinePaymentRequestMessage="declinePaymentRequestMessage")),e.cancelPaymentRequestMessage!=null&&e.hasOwnProperty("cancelPaymentRequestMessage")&&(A.cancelPaymentRequestMessage=p.proto.Message.CancelPaymentRequestMessage.toObject(e.cancelPaymentRequestMessage,a),a.oneofs&&(A._cancelPaymentRequestMessage="cancelPaymentRequestMessage")),e.templateMessage!=null&&e.hasOwnProperty("templateMessage")&&(A.templateMessage=p.proto.Message.TemplateMessage.toObject(e.templateMessage,a),a.oneofs&&(A._templateMessage="templateMessage")),e.stickerMessage!=null&&e.hasOwnProperty("stickerMessage")&&(A.stickerMessage=p.proto.Message.StickerMessage.toObject(e.stickerMessage,a),a.oneofs&&(A._stickerMessage="stickerMessage")),e.groupInviteMessage!=null&&e.hasOwnProperty("groupInviteMessage")&&(A.groupInviteMessage=p.proto.Message.GroupInviteMessage.toObject(e.groupInviteMessage,a),a.oneofs&&(A._groupInviteMessage="groupInviteMessage")),e.templateButtonReplyMessage!=null&&e.hasOwnProperty("templateButtonReplyMessage")&&(A.templateButtonReplyMessage=p.proto.Message.TemplateButtonReplyMessage.toObject(e.templateButtonReplyMessage,a),a.oneofs&&(A._templateButtonReplyMessage="templateButtonReplyMessage")),e.productMessage!=null&&e.hasOwnProperty("productMessage")&&(A.productMessage=p.proto.Message.ProductMessage.toObject(e.productMessage,a),a.oneofs&&(A._productMessage="productMessage")),e.deviceSentMessage!=null&&e.hasOwnProperty("deviceSentMessage")&&(A.deviceSentMessage=p.proto.Message.DeviceSentMessage.toObject(e.deviceSentMessage,a),a.oneofs&&(A._deviceSentMessage="deviceSentMessage")),e.messageContextInfo!=null&&e.hasOwnProperty("messageContextInfo")&&(A.messageContextInfo=p.proto.MessageContextInfo.toObject(e.messageContextInfo,a),a.oneofs&&(A._messageContextInfo="messageContextInfo")),e.listMessage!=null&&e.hasOwnProperty("listMessage")&&(A.listMessage=p.proto.Message.ListMessage.toObject(e.listMessage,a),a.oneofs&&(A._listMessage="listMessage")),e.viewOnceMessage!=null&&e.hasOwnProperty("viewOnceMessage")&&(A.viewOnceMessage=p.proto.Message.FutureProofMessage.toObject(e.viewOnceMessage,a),a.oneofs&&(A._viewOnceMessage="viewOnceMessage")),e.orderMessage!=null&&e.hasOwnProperty("orderMessage")&&(A.orderMessage=p.proto.Message.OrderMessage.toObject(e.orderMessage,a),a.oneofs&&(A._orderMessage="orderMessage")),e.listResponseMessage!=null&&e.hasOwnProperty("listResponseMessage")&&(A.listResponseMessage=p.proto.Message.ListResponseMessage.toObject(e.listResponseMessage,a),a.oneofs&&(A._listResponseMessage="listResponseMessage")),e.ephemeralMessage!=null&&e.hasOwnProperty("ephemeralMessage")&&(A.ephemeralMessage=p.proto.Message.FutureProofMessage.toObject(e.ephemeralMessage,a),a.oneofs&&(A._ephemeralMessage="ephemeralMessage")),e.invoiceMessage!=null&&e.hasOwnProperty("invoiceMessage")&&(A.invoiceMessage=p.proto.Message.InvoiceMessage.toObject(e.invoiceMessage,a),a.oneofs&&(A._invoiceMessage="invoiceMessage")),e.buttonsMessage!=null&&e.hasOwnProperty("buttonsMessage")&&(A.buttonsMessage=p.proto.Message.ButtonsMessage.toObject(e.buttonsMessage,a),a.oneofs&&(A._buttonsMessage="buttonsMessage")),e.buttonsResponseMessage!=null&&e.hasOwnProperty("buttonsResponseMessage")&&(A.buttonsResponseMessage=p.proto.Message.ButtonsResponseMessage.toObject(e.buttonsResponseMessage,a),a.oneofs&&(A._buttonsResponseMessage="buttonsResponseMessage")),e.paymentInviteMessage!=null&&e.hasOwnProperty("paymentInviteMessage")&&(A.paymentInviteMessage=p.proto.Message.PaymentInviteMessage.toObject(e.paymentInviteMessage,a),a.oneofs&&(A._paymentInviteMessage="paymentInviteMessage")),e.interactiveMessage!=null&&e.hasOwnProperty("interactiveMessage")&&(A.interactiveMessage=p.proto.Message.InteractiveMessage.toObject(e.interactiveMessage,a),a.oneofs&&(A._interactiveMessage="interactiveMessage")),e.reactionMessage!=null&&e.hasOwnProperty("reactionMessage")&&(A.reactionMessage=p.proto.Message.ReactionMessage.toObject(e.reactionMessage,a),a.oneofs&&(A._reactionMessage="reactionMessage")),e.stickerSyncRmrMessage!=null&&e.hasOwnProperty("stickerSyncRmrMessage")&&(A.stickerSyncRmrMessage=p.proto.Message.StickerSyncRMRMessage.toObject(e.stickerSyncRmrMessage,a),a.oneofs&&(A._stickerSyncRmrMessage="stickerSyncRmrMessage")),e.interactiveResponseMessage!=null&&e.hasOwnProperty("interactiveResponseMessage")&&(A.interactiveResponseMessage=p.proto.Message.InteractiveResponseMessage.toObject(e.interactiveResponseMessage,a),a.oneofs&&(A._interactiveResponseMessage="interactiveResponseMessage")),e.pollCreationMessage!=null&&e.hasOwnProperty("pollCreationMessage")&&(A.pollCreationMessage=p.proto.Message.PollCreationMessage.toObject(e.pollCreationMessage,a),a.oneofs&&(A._pollCreationMessage="pollCreationMessage")),e.pollUpdateMessage!=null&&e.hasOwnProperty("pollUpdateMessage")&&(A.pollUpdateMessage=p.proto.Message.PollUpdateMessage.toObject(e.pollUpdateMessage,a),a.oneofs&&(A._pollUpdateMessage="pollUpdateMessage")),e.keepInChatMessage!=null&&e.hasOwnProperty("keepInChatMessage")&&(A.keepInChatMessage=p.proto.Message.KeepInChatMessage.toObject(e.keepInChatMessage,a),a.oneofs&&(A._keepInChatMessage="keepInChatMessage")),e.documentWithCaptionMessage!=null&&e.hasOwnProperty("documentWithCaptionMessage")&&(A.documentWithCaptionMessage=p.proto.Message.FutureProofMessage.toObject(e.documentWithCaptionMessage,a),a.oneofs&&(A._documentWithCaptionMessage="documentWithCaptionMessage")),e.requestPhoneNumberMessage!=null&&e.hasOwnProperty("requestPhoneNumberMessage")&&(A.requestPhoneNumberMessage=p.proto.Message.RequestPhoneNumberMessage.toObject(e.requestPhoneNumberMessage,a),a.oneofs&&(A._requestPhoneNumberMessage="requestPhoneNumberMessage")),e.viewOnceMessageV2!=null&&e.hasOwnProperty("viewOnceMessageV2")&&(A.viewOnceMessageV2=p.proto.Message.FutureProofMessage.toObject(e.viewOnceMessageV2,a),a.oneofs&&(A._viewOnceMessageV2="viewOnceMessageV2")),e.encReactionMessage!=null&&e.hasOwnProperty("encReactionMessage")&&(A.encReactionMessage=p.proto.Message.EncReactionMessage.toObject(e.encReactionMessage,a),a.oneofs&&(A._encReactionMessage="encReactionMessage")),e.editedMessage!=null&&e.hasOwnProperty("editedMessage")&&(A.editedMessage=p.proto.Message.FutureProofMessage.toObject(e.editedMessage,a),a.oneofs&&(A._editedMessage="editedMessage")),e.viewOnceMessageV2Extension!=null&&e.hasOwnProperty("viewOnceMessageV2Extension")&&(A.viewOnceMessageV2Extension=p.proto.Message.FutureProofMessage.toObject(e.viewOnceMessageV2Extension,a),a.oneofs&&(A._viewOnceMessageV2Extension="viewOnceMessageV2Extension")),e.pollCreationMessageV2!=null&&e.hasOwnProperty("pollCreationMessageV2")&&(A.pollCreationMessageV2=p.proto.Message.PollCreationMessage.toObject(e.pollCreationMessageV2,a),a.oneofs&&(A._pollCreationMessageV2="pollCreationMessageV2")),e.scheduledCallCreationMessage!=null&&e.hasOwnProperty("scheduledCallCreationMessage")&&(A.scheduledCallCreationMessage=p.proto.Message.ScheduledCallCreationMessage.toObject(e.scheduledCallCreationMessage,a),a.oneofs&&(A._scheduledCallCreationMessage="scheduledCallCreationMessage")),e.groupMentionedMessage!=null&&e.hasOwnProperty("groupMentionedMessage")&&(A.groupMentionedMessage=p.proto.Message.FutureProofMessage.toObject(e.groupMentionedMessage,a),a.oneofs&&(A._groupMentionedMessage="groupMentionedMessage")),e.pinInChatMessage!=null&&e.hasOwnProperty("pinInChatMessage")&&(A.pinInChatMessage=p.proto.Message.PinInChatMessage.toObject(e.pinInChatMessage,a),a.oneofs&&(A._pinInChatMessage="pinInChatMessage")),e.pollCreationMessageV3!=null&&e.hasOwnProperty("pollCreationMessageV3")&&(A.pollCreationMessageV3=p.proto.Message.PollCreationMessage.toObject(e.pollCreationMessageV3,a),a.oneofs&&(A._pollCreationMessageV3="pollCreationMessageV3")),e.scheduledCallEditMessage!=null&&e.hasOwnProperty("scheduledCallEditMessage")&&(A.scheduledCallEditMessage=p.proto.Message.ScheduledCallEditMessage.toObject(e.scheduledCallEditMessage,a),a.oneofs&&(A._scheduledCallEditMessage="scheduledCallEditMessage")),e.ptvMessage!=null&&e.hasOwnProperty("ptvMessage")&&(A.ptvMessage=p.proto.Message.VideoMessage.toObject(e.ptvMessage,a),a.oneofs&&(A._ptvMessage="ptvMessage")),e.botInvokeMessage!=null&&e.hasOwnProperty("botInvokeMessage")&&(A.botInvokeMessage=p.proto.Message.FutureProofMessage.toObject(e.botInvokeMessage,a),a.oneofs&&(A._botInvokeMessage="botInvokeMessage")),e.callLogMesssage!=null&&e.hasOwnProperty("callLogMesssage")&&(A.callLogMesssage=p.proto.Message.CallLogMessage.toObject(e.callLogMesssage,a),a.oneofs&&(A._callLogMesssage="callLogMesssage")),e.messageHistoryBundle!=null&&e.hasOwnProperty("messageHistoryBundle")&&(A.messageHistoryBundle=p.proto.Message.MessageHistoryBundle.toObject(e.messageHistoryBundle,a),a.oneofs&&(A._messageHistoryBundle="messageHistoryBundle")),e.encCommentMessage!=null&&e.hasOwnProperty("encCommentMessage")&&(A.encCommentMessage=p.proto.Message.EncCommentMessage.toObject(e.encCommentMessage,a),a.oneofs&&(A._encCommentMessage="encCommentMessage")),e.bcallMessage!=null&&e.hasOwnProperty("bcallMessage")&&(A.bcallMessage=p.proto.Message.BCallMessage.toObject(e.bcallMessage,a),a.oneofs&&(A._bcallMessage="bcallMessage")),e.lottieStickerMessage!=null&&e.hasOwnProperty("lottieStickerMessage")&&(A.lottieStickerMessage=p.proto.Message.FutureProofMessage.toObject(e.lottieStickerMessage,a),a.oneofs&&(A._lottieStickerMessage="lottieStickerMessage")),e.eventMessage!=null&&e.hasOwnProperty("eventMessage")&&(A.eventMessage=p.proto.Message.EventMessage.toObject(e.eventMessage,a),a.oneofs&&(A._eventMessage="eventMessage")),e.encEventResponseMessage!=null&&e.hasOwnProperty("encEventResponseMessage")&&(A.encEventResponseMessage=p.proto.Message.EncEventResponseMessage.toObject(e.encEventResponseMessage,a),a.oneofs&&(A._encEventResponseMessage="encEventResponseMessage")),e.commentMessage!=null&&e.hasOwnProperty("commentMessage")&&(A.commentMessage=p.proto.Message.CommentMessage.toObject(e.commentMessage,a),a.oneofs&&(A._commentMessage="commentMessage")),e.newsletterAdminInviteMessage!=null&&e.hasOwnProperty("newsletterAdminInviteMessage")&&(A.newsletterAdminInviteMessage=p.proto.Message.NewsletterAdminInviteMessage.toObject(e.newsletterAdminInviteMessage,a),a.oneofs&&(A._newsletterAdminInviteMessage="newsletterAdminInviteMessage")),e.placeholderMessage!=null&&e.hasOwnProperty("placeholderMessage")&&(A.placeholderMessage=p.proto.Message.PlaceholderMessage.toObject(e.placeholderMessage,a),a.oneofs&&(A._placeholderMessage="placeholderMessage")),e.secretEncryptedMessage!=null&&e.hasOwnProperty("secretEncryptedMessage")&&(A.secretEncryptedMessage=p.proto.Message.SecretEncryptedMessage.toObject(e.secretEncryptedMessage,a),a.oneofs&&(A._secretEncryptedMessage="secretEncryptedMessage")),e.albumMessage!=null&&e.hasOwnProperty("albumMessage")&&(A.albumMessage=p.proto.Message.AlbumMessage.toObject(e.albumMessage,a),a.oneofs&&(A._albumMessage="albumMessage")),e.eventCoverImage!=null&&e.hasOwnProperty("eventCoverImage")&&(A.eventCoverImage=p.proto.Message.FutureProofMessage.toObject(e.eventCoverImage,a),a.oneofs&&(A._eventCoverImage="eventCoverImage")),e.stickerPackMessage!=null&&e.hasOwnProperty("stickerPackMessage")&&(A.stickerPackMessage=p.proto.Message.StickerPackMessage.toObject(e.stickerPackMessage,a),a.oneofs&&(A._stickerPackMessage="stickerPackMessage")),e.statusMentionMessage!=null&&e.hasOwnProperty("statusMentionMessage")&&(A.statusMentionMessage=p.proto.Message.FutureProofMessage.toObject(e.statusMentionMessage,a),a.oneofs&&(A._statusMentionMessage="statusMentionMessage")),e.pollResultSnapshotMessage!=null&&e.hasOwnProperty("pollResultSnapshotMessage")&&(A.pollResultSnapshotMessage=p.proto.Message.PollResultSnapshotMessage.toObject(e.pollResultSnapshotMessage,a),a.oneofs&&(A._pollResultSnapshotMessage="pollResultSnapshotMessage")),e.pollCreationOptionImageMessage!=null&&e.hasOwnProperty("pollCreationOptionImageMessage")&&(A.pollCreationOptionImageMessage=p.proto.Message.FutureProofMessage.toObject(e.pollCreationOptionImageMessage,a),a.oneofs&&(A._pollCreationOptionImageMessage="pollCreationOptionImageMessage")),e.associatedChildMessage!=null&&e.hasOwnProperty("associatedChildMessage")&&(A.associatedChildMessage=p.proto.Message.FutureProofMessage.toObject(e.associatedChildMessage,a),a.oneofs&&(A._associatedChildMessage="associatedChildMessage")),e.groupStatusMentionMessage!=null&&e.hasOwnProperty("groupStatusMentionMessage")&&(A.groupStatusMentionMessage=p.proto.Message.FutureProofMessage.toObject(e.groupStatusMentionMessage,a),a.oneofs&&(A._groupStatusMentionMessage="groupStatusMentionMessage")),e.pollCreationMessageV4!=null&&e.hasOwnProperty("pollCreationMessageV4")&&(A.pollCreationMessageV4=p.proto.Message.FutureProofMessage.toObject(e.pollCreationMessageV4,a),a.oneofs&&(A._pollCreationMessageV4="pollCreationMessageV4")),e.statusAddYours!=null&&e.hasOwnProperty("statusAddYours")&&(A.statusAddYours=p.proto.Message.FutureProofMessage.toObject(e.statusAddYours,a),a.oneofs&&(A._statusAddYours="statusAddYours")),e.groupStatusMessage!=null&&e.hasOwnProperty("groupStatusMessage")&&(A.groupStatusMessage=p.proto.Message.FutureProofMessage.toObject(e.groupStatusMessage,a),a.oneofs&&(A._groupStatusMessage="groupStatusMessage")),e.richResponseMessage!=null&&e.hasOwnProperty("richResponseMessage")&&(A.richResponseMessage=p.proto.AIRichResponseMessage.toObject(e.richResponseMessage,a),a.oneofs&&(A._richResponseMessage="richResponseMessage")),e.statusNotificationMessage!=null&&e.hasOwnProperty("statusNotificationMessage")&&(A.statusNotificationMessage=p.proto.Message.StatusNotificationMessage.toObject(e.statusNotificationMessage,a),a.oneofs&&(A._statusNotificationMessage="statusNotificationMessage")),e.limitSharingMessage!=null&&e.hasOwnProperty("limitSharingMessage")&&(A.limitSharingMessage=p.proto.Message.FutureProofMessage.toObject(e.limitSharingMessage,a),a.oneofs&&(A._limitSharingMessage="limitSharingMessage")),e.botTaskMessage!=null&&e.hasOwnProperty("botTaskMessage")&&(A.botTaskMessage=p.proto.Message.FutureProofMessage.toObject(e.botTaskMessage,a),a.oneofs&&(A._botTaskMessage="botTaskMessage")),e.questionMessage!=null&&e.hasOwnProperty("questionMessage")&&(A.questionMessage=p.proto.Message.FutureProofMessage.toObject(e.questionMessage,a),a.oneofs&&(A._questionMessage="questionMessage")),e.messageHistoryNotice!=null&&e.hasOwnProperty("messageHistoryNotice")&&(A.messageHistoryNotice=p.proto.Message.MessageHistoryNotice.toObject(e.messageHistoryNotice,a),a.oneofs&&(A._messageHistoryNotice="messageHistoryNotice")),e.groupStatusMessageV2!=null&&e.hasOwnProperty("groupStatusMessageV2")&&(A.groupStatusMessageV2=p.proto.Message.FutureProofMessage.toObject(e.groupStatusMessageV2,a),a.oneofs&&(A._groupStatusMessageV2="groupStatusMessageV2")),e.botForwardedMessage!=null&&e.hasOwnProperty("botForwardedMessage")&&(A.botForwardedMessage=p.proto.Message.FutureProofMessage.toObject(e.botForwardedMessage,a),a.oneofs&&(A._botForwardedMessage="botForwardedMessage")),e.statusQuestionAnswerMessage!=null&&e.hasOwnProperty("statusQuestionAnswerMessage")&&(A.statusQuestionAnswerMessage=p.proto.Message.StatusQuestionAnswerMessage.toObject(e.statusQuestionAnswerMessage,a),a.oneofs&&(A._statusQuestionAnswerMessage="statusQuestionAnswerMessage")),e.questionReplyMessage!=null&&e.hasOwnProperty("questionReplyMessage")&&(A.questionReplyMessage=p.proto.Message.FutureProofMessage.toObject(e.questionReplyMessage,a),a.oneofs&&(A._questionReplyMessage="questionReplyMessage")),e.questionResponseMessage!=null&&e.hasOwnProperty("questionResponseMessage")&&(A.questionResponseMessage=p.proto.Message.QuestionResponseMessage.toObject(e.questionResponseMessage,a),a.oneofs&&(A._questionResponseMessage="questionResponseMessage")),e.statusQuotedMessage!=null&&e.hasOwnProperty("statusQuotedMessage")&&(A.statusQuotedMessage=p.proto.Message.StatusQuotedMessage.toObject(e.statusQuotedMessage,a),a.oneofs&&(A._statusQuotedMessage="statusQuotedMessage")),e.statusStickerInteractionMessage!=null&&e.hasOwnProperty("statusStickerInteractionMessage")&&(A.statusStickerInteractionMessage=p.proto.Message.StatusStickerInteractionMessage.toObject(e.statusStickerInteractionMessage,a),a.oneofs&&(A._statusStickerInteractionMessage="statusStickerInteractionMessage")),e.pollCreationMessageV5!=null&&e.hasOwnProperty("pollCreationMessageV5")&&(A.pollCreationMessageV5=p.proto.Message.PollCreationMessage.toObject(e.pollCreationMessageV5,a),a.oneofs&&(A._pollCreationMessageV5="pollCreationMessageV5")),e.newsletterFollowerInviteMessageV2!=null&&e.hasOwnProperty("newsletterFollowerInviteMessageV2")&&(A.newsletterFollowerInviteMessageV2=p.proto.Message.NewsletterFollowerInviteMessage.toObject(e.newsletterFollowerInviteMessageV2,a),a.oneofs&&(A._newsletterFollowerInviteMessageV2="newsletterFollowerInviteMessageV2")),e.pollResultSnapshotMessageV3!=null&&e.hasOwnProperty("pollResultSnapshotMessageV3")&&(A.pollResultSnapshotMessageV3=p.proto.Message.PollResultSnapshotMessage.toObject(e.pollResultSnapshotMessageV3,a),a.oneofs&&(A._pollResultSnapshotMessageV3="pollResultSnapshotMessageV3")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Message"},t.AlbumMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 2:{c.expectedImageCount=A.uint32();break}case 3:{c.expectedVideoCount=A.uint32();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AlbumMessage)return A;var r=new p.proto.Message.AlbumMessage;if(A.expectedImageCount!=null&&(r.expectedImageCount=A.expectedImageCount>>>0),A.expectedVideoCount!=null&&(r.expectedVideoCount=A.expectedVideoCount>>>0),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.AlbumMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.expectedImageCount!=null&&A.hasOwnProperty("expectedImageCount")&&(s.expectedImageCount=A.expectedImageCount,r.oneofs&&(s._expectedImageCount="expectedImageCount")),A.expectedVideoCount!=null&&A.hasOwnProperty("expectedVideoCount")&&(s.expectedVideoCount=A.expectedVideoCount,r.oneofs&&(s._expectedVideoCount="expectedVideoCount")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AlbumMessage"},i})(),t.AppStateFatalExceptionNotification=(function(){function i(a){if(this.collectionNames=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.collectionNames&&c.collectionNames.length||(c.collectionNames=[]),c.collectionNames.push(A.string());break}case 2:{c.timestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AppStateFatalExceptionNotification)return A;var r=new p.proto.Message.AppStateFatalExceptionNotification;if(A.collectionNames){if(!Array.isArray(A.collectionNames))throw TypeError(".proto.Message.AppStateFatalExceptionNotification.collectionNames: array expected");r.collectionNames=[];for(var s=0;s>>0,A.timestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.collectionNames=[]),A.collectionNames&&A.collectionNames.length){s.collectionNames=[];for(var g=0;g>>3){case 1:{c.keyId=p.proto.Message.AppStateSyncKeyId.decode(A,A.uint32());break}case 2:{c.keyData=p.proto.Message.AppStateSyncKeyData.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AppStateSyncKey)return A;var r=new p.proto.Message.AppStateSyncKey;if(A.keyId!=null){if(typeof A.keyId!="object")throw TypeError(".proto.Message.AppStateSyncKey.keyId: object expected");r.keyId=p.proto.Message.AppStateSyncKeyId.fromObject(A.keyId)}if(A.keyData!=null){if(typeof A.keyData!="object")throw TypeError(".proto.Message.AppStateSyncKey.keyData: object expected");r.keyData=p.proto.Message.AppStateSyncKeyData.fromObject(A.keyData)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.keyId!=null&&A.hasOwnProperty("keyId")&&(s.keyId=p.proto.Message.AppStateSyncKeyId.toObject(A.keyId,r),r.oneofs&&(s._keyId="keyId")),A.keyData!=null&&A.hasOwnProperty("keyData")&&(s.keyData=p.proto.Message.AppStateSyncKeyData.toObject(A.keyData,r),r.oneofs&&(s._keyData="keyData")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AppStateSyncKey"},i})(),t.AppStateSyncKeyData=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.keyData=A.bytes();break}case 2:{c.fingerprint=p.proto.Message.AppStateSyncKeyFingerprint.decode(A,A.uint32());break}case 3:{c.timestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AppStateSyncKeyData)return A;var r=new p.proto.Message.AppStateSyncKeyData;if(A.keyData!=null&&(typeof A.keyData=="string"?l.base64.decode(A.keyData,r.keyData=l.newBuffer(l.base64.length(A.keyData)),0):A.keyData.length>=0&&(r.keyData=A.keyData)),A.fingerprint!=null){if(typeof A.fingerprint!="object")throw TypeError(".proto.Message.AppStateSyncKeyData.fingerprint: object expected");r.fingerprint=p.proto.Message.AppStateSyncKeyFingerprint.fromObject(A.fingerprint)}return A.timestamp!=null&&(l.Long?(r.timestamp=l.Long.fromValue(A.timestamp)).unsigned=!1:typeof A.timestamp=="string"?r.timestamp=parseInt(A.timestamp,10):typeof A.timestamp=="number"?r.timestamp=A.timestamp:typeof A.timestamp=="object"&&(r.timestamp=new l.LongBits(A.timestamp.low>>>0,A.timestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.keyData!=null&&A.hasOwnProperty("keyData")&&(s.keyData=r.bytes===String?l.base64.encode(A.keyData,0,A.keyData.length):r.bytes===Array?Array.prototype.slice.call(A.keyData):A.keyData,r.oneofs&&(s._keyData="keyData")),A.fingerprint!=null&&A.hasOwnProperty("fingerprint")&&(s.fingerprint=p.proto.Message.AppStateSyncKeyFingerprint.toObject(A.fingerprint,r),r.oneofs&&(s._fingerprint="fingerprint")),A.timestamp!=null&&A.hasOwnProperty("timestamp")&&(typeof A.timestamp=="number"?s.timestamp=r.longs===String?String(A.timestamp):A.timestamp:s.timestamp=r.longs===String?se(A.timestamp):r.longs===Number?ge(A.timestamp):A.timestamp,r.oneofs&&(s._timestamp="timestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AppStateSyncKeyData"},i})(),t.AppStateSyncKeyFingerprint=(function(){function i(a){if(this.deviceIndexes=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.rawId=A.uint32();break}case 2:{c.currentIndex=A.uint32();break}case 3:{if(c.deviceIndexes&&c.deviceIndexes.length||(c.deviceIndexes=[]),(I&7)===2)for(var d=A.uint32()+A.pos;A.pos>>0),A.currentIndex!=null&&(r.currentIndex=A.currentIndex>>>0),A.deviceIndexes){if(!Array.isArray(A.deviceIndexes))throw TypeError(".proto.Message.AppStateSyncKeyFingerprint.deviceIndexes: array expected");r.deviceIndexes=[];for(var s=0;s>>0}return r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.deviceIndexes=[]),A.rawId!=null&&A.hasOwnProperty("rawId")&&(s.rawId=A.rawId,r.oneofs&&(s._rawId="rawId")),A.currentIndex!=null&&A.hasOwnProperty("currentIndex")&&(s.currentIndex=A.currentIndex,r.oneofs&&(s._currentIndex="currentIndex")),A.deviceIndexes&&A.deviceIndexes.length){s.deviceIndexes=[];for(var g=0;g>>3){case 1:{c.keyId=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AppStateSyncKeyId)return A;var r=new p.proto.Message.AppStateSyncKeyId;return A.keyId!=null&&(typeof A.keyId=="string"?l.base64.decode(A.keyId,r.keyId=l.newBuffer(l.base64.length(A.keyId)),0):A.keyId.length>=0&&(r.keyId=A.keyId)),r},i.toObject=function(A,r){r||(r={});var s={};return A.keyId!=null&&A.hasOwnProperty("keyId")&&(s.keyId=r.bytes===String?l.base64.encode(A.keyId,0,A.keyId.length):r.bytes===Array?Array.prototype.slice.call(A.keyId):A.keyId,r.oneofs&&(s._keyId="keyId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AppStateSyncKeyId"},i})(),t.AppStateSyncKeyRequest=(function(){function i(e){if(this.keyIds=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.keyIds&&g.keyIds.length||(g.keyIds=[]),g.keyIds.push(p.proto.Message.AppStateSyncKeyId.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.Message.AppStateSyncKeyRequest)return a;var A=new p.proto.Message.AppStateSyncKeyRequest;if(a.keyIds){if(!Array.isArray(a.keyIds))throw TypeError(".proto.Message.AppStateSyncKeyRequest.keyIds: array expected");A.keyIds=[];for(var r=0;r>>3){case 1:{g.keys&&g.keys.length||(g.keys=[]),g.keys.push(p.proto.Message.AppStateSyncKey.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.Message.AppStateSyncKeyShare)return a;var A=new p.proto.Message.AppStateSyncKeyShare;if(a.keys){if(!Array.isArray(a.keys))throw TypeError(".proto.Message.AppStateSyncKeyShare.keys: array expected");A.keys=[];for(var r=0;r>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.fileSha256=A.bytes();break}case 4:{c.fileLength=A.uint64();break}case 5:{c.seconds=A.uint32();break}case 6:{c.ptt=A.bool();break}case 7:{c.mediaKey=A.bytes();break}case 8:{c.fileEncSha256=A.bytes();break}case 9:{c.directPath=A.string();break}case 10:{c.mediaKeyTimestamp=A.int64();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.streamingSidecar=A.bytes();break}case 19:{c.waveform=A.bytes();break}case 20:{c.backgroundArgb=A.fixed32();break}case 21:{c.viewOnce=A.bool();break}case 22:{c.accessibilityLabel=A.string();break}case 23:{c.mediaKeyDomain=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.AudioMessage)return A;var r=new p.proto.Message.AudioMessage;if(A.url!=null&&(r.url=String(A.url)),A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.seconds!=null&&(r.seconds=A.seconds>>>0),A.ptt!=null&&(r.ptt=!!A.ptt),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(r.directPath=String(A.directPath)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.AudioMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.streamingSidecar!=null&&(typeof A.streamingSidecar=="string"?l.base64.decode(A.streamingSidecar,r.streamingSidecar=l.newBuffer(l.base64.length(A.streamingSidecar)),0):A.streamingSidecar.length>=0&&(r.streamingSidecar=A.streamingSidecar)),A.waveform!=null&&(typeof A.waveform=="string"?l.base64.decode(A.waveform,r.waveform=l.newBuffer(l.base64.length(A.waveform)),0):A.waveform.length>=0&&(r.waveform=A.waveform)),A.backgroundArgb!=null&&(r.backgroundArgb=A.backgroundArgb>>>0),A.viewOnce!=null&&(r.viewOnce=!!A.viewOnce),A.accessibilityLabel!=null&&(r.accessibilityLabel=String(A.accessibilityLabel)),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){r.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:r.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:r.mediaKeyDomain=1;break;case"STATUS":case 2:r.mediaKeyDomain=2;break;case"CAPI":case 3:r.mediaKeyDomain=3;break;case"BOT":case 4:r.mediaKeyDomain=4;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.seconds!=null&&A.hasOwnProperty("seconds")&&(s.seconds=A.seconds,r.oneofs&&(s._seconds="seconds")),A.ptt!=null&&A.hasOwnProperty("ptt")&&(s.ptt=A.ptt,r.oneofs&&(s._ptt="ptt")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.streamingSidecar!=null&&A.hasOwnProperty("streamingSidecar")&&(s.streamingSidecar=r.bytes===String?l.base64.encode(A.streamingSidecar,0,A.streamingSidecar.length):r.bytes===Array?Array.prototype.slice.call(A.streamingSidecar):A.streamingSidecar,r.oneofs&&(s._streamingSidecar="streamingSidecar")),A.waveform!=null&&A.hasOwnProperty("waveform")&&(s.waveform=r.bytes===String?l.base64.encode(A.waveform,0,A.waveform.length):r.bytes===Array?Array.prototype.slice.call(A.waveform):A.waveform,r.oneofs&&(s._waveform="waveform")),A.backgroundArgb!=null&&A.hasOwnProperty("backgroundArgb")&&(s.backgroundArgb=A.backgroundArgb,r.oneofs&&(s._backgroundArgb="backgroundArgb")),A.viewOnce!=null&&A.hasOwnProperty("viewOnce")&&(s.viewOnce=A.viewOnce,r.oneofs&&(s._viewOnce="viewOnce")),A.accessibilityLabel!=null&&A.hasOwnProperty("accessibilityLabel")&&(s.accessibilityLabel=A.accessibilityLabel,r.oneofs&&(s._accessibilityLabel="accessibilityLabel")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=r.enums===String?p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,r.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.AudioMessage"},i})(),t.BCallMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.sessionId=A.string();break}case 2:{c.mediaType=A.int32();break}case 3:{c.masterKey=A.bytes();break}case 4:{c.caption=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.BCallMessage)return A;var r=new p.proto.Message.BCallMessage;switch(A.sessionId!=null&&(r.sessionId=String(A.sessionId)),A.mediaType){default:if(typeof A.mediaType=="number"){r.mediaType=A.mediaType;break}break;case"UNKNOWN":case 0:r.mediaType=0;break;case"AUDIO":case 1:r.mediaType=1;break;case"VIDEO":case 2:r.mediaType=2;break}return A.masterKey!=null&&(typeof A.masterKey=="string"?l.base64.decode(A.masterKey,r.masterKey=l.newBuffer(l.base64.length(A.masterKey)),0):A.masterKey.length>=0&&(r.masterKey=A.masterKey)),A.caption!=null&&(r.caption=String(A.caption)),r},i.toObject=function(A,r){r||(r={});var s={};return A.sessionId!=null&&A.hasOwnProperty("sessionId")&&(s.sessionId=A.sessionId,r.oneofs&&(s._sessionId="sessionId")),A.mediaType!=null&&A.hasOwnProperty("mediaType")&&(s.mediaType=r.enums===String?p.proto.Message.BCallMessage.MediaType[A.mediaType]===void 0?A.mediaType:p.proto.Message.BCallMessage.MediaType[A.mediaType]:A.mediaType,r.oneofs&&(s._mediaType="mediaType")),A.masterKey!=null&&A.hasOwnProperty("masterKey")&&(s.masterKey=r.bytes===String?l.base64.encode(A.masterKey,0,A.masterKey.length):r.bytes===Array?Array.prototype.slice.call(A.masterKey):A.masterKey,r.oneofs&&(s._masterKey="masterKey")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.BCallMessage"},i.MediaType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="AUDIO"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),t.ButtonsMessage=(function(){function i(a){if(this.buttons=[],a)for(var A=Object.keys(a),r=0;r>>3){case 6:{c.contentText=A.string();break}case 7:{c.footerText=A.string();break}case 8:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 9:{c.buttons&&c.buttons.length||(c.buttons=[]),c.buttons.push(p.proto.Message.ButtonsMessage.Button.decode(A,A.uint32()));break}case 10:{c.headerType=A.int32();break}case 1:{c.text=A.string();break}case 2:{c.documentMessage=p.proto.Message.DocumentMessage.decode(A,A.uint32());break}case 3:{c.imageMessage=p.proto.Message.ImageMessage.decode(A,A.uint32());break}case 4:{c.videoMessage=p.proto.Message.VideoMessage.decode(A,A.uint32());break}case 5:{c.locationMessage=p.proto.Message.LocationMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ButtonsMessage)return A;var r=new p.proto.Message.ButtonsMessage;if(A.contentText!=null&&(r.contentText=String(A.contentText)),A.footerText!=null&&(r.footerText=String(A.footerText)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ButtonsMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.buttons){if(!Array.isArray(A.buttons))throw TypeError(".proto.Message.ButtonsMessage.buttons: array expected");r.buttons=[];for(var s=0;s>>3){case 1:{d.buttonId=s.string();break}case 2:{d.buttonText=p.proto.Message.ButtonsMessage.Button.ButtonText.decode(s,s.uint32());break}case 3:{d.type=s.int32();break}case 4:{d.nativeFlowInfo=p.proto.Message.ButtonsMessage.Button.NativeFlowInfo.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ButtonsMessage.Button)return s;var g=new p.proto.Message.ButtonsMessage.Button;if(s.buttonId!=null&&(g.buttonId=String(s.buttonId)),s.buttonText!=null){if(typeof s.buttonText!="object")throw TypeError(".proto.Message.ButtonsMessage.Button.buttonText: object expected");g.buttonText=p.proto.Message.ButtonsMessage.Button.ButtonText.fromObject(s.buttonText)}switch(s.type){default:if(typeof s.type=="number"){g.type=s.type;break}break;case"UNKNOWN":case 0:g.type=0;break;case"RESPONSE":case 1:g.type=1;break;case"NATIVE_FLOW":case 2:g.type=2;break}if(s.nativeFlowInfo!=null){if(typeof s.nativeFlowInfo!="object")throw TypeError(".proto.Message.ButtonsMessage.Button.nativeFlowInfo: object expected");g.nativeFlowInfo=p.proto.Message.ButtonsMessage.Button.NativeFlowInfo.fromObject(s.nativeFlowInfo)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.buttonId!=null&&s.hasOwnProperty("buttonId")&&(c.buttonId=s.buttonId,g.oneofs&&(c._buttonId="buttonId")),s.buttonText!=null&&s.hasOwnProperty("buttonText")&&(c.buttonText=p.proto.Message.ButtonsMessage.Button.ButtonText.toObject(s.buttonText,g),g.oneofs&&(c._buttonText="buttonText")),s.type!=null&&s.hasOwnProperty("type")&&(c.type=g.enums===String?p.proto.Message.ButtonsMessage.Button.Type[s.type]===void 0?s.type:p.proto.Message.ButtonsMessage.Button.Type[s.type]:s.type,g.oneofs&&(c._type="type")),s.nativeFlowInfo!=null&&s.hasOwnProperty("nativeFlowInfo")&&(c.nativeFlowInfo=p.proto.Message.ButtonsMessage.Button.NativeFlowInfo.toObject(s.nativeFlowInfo,g),g.oneofs&&(c._nativeFlowInfo="nativeFlowInfo")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ButtonsMessage.Button"},a.ButtonText=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.displayText=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.ButtonsMessage.Button.ButtonText)return c;var I=new p.proto.Message.ButtonsMessage.Button.ButtonText;return c.displayText!=null&&(I.displayText=String(c.displayText)),I},r.toObject=function(c,I){I||(I={});var d={};return c.displayText!=null&&c.hasOwnProperty("displayText")&&(d.displayText=c.displayText,I.oneofs&&(d._displayText="displayText")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.ButtonsMessage.Button.ButtonText"},r})(),a.NativeFlowInfo=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.name=c.string();break}case 2:{f.paramsJson=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.ButtonsMessage.Button.NativeFlowInfo)return c;var I=new p.proto.Message.ButtonsMessage.Button.NativeFlowInfo;return c.name!=null&&(I.name=String(c.name)),c.paramsJson!=null&&(I.paramsJson=String(c.paramsJson)),I},r.toObject=function(c,I){I||(I={});var d={};return c.name!=null&&c.hasOwnProperty("name")&&(d.name=c.name,I.oneofs&&(d._name="name")),c.paramsJson!=null&&c.hasOwnProperty("paramsJson")&&(d.paramsJson=c.paramsJson,I.oneofs&&(d._paramsJson="paramsJson")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.ButtonsMessage.Button.NativeFlowInfo"},r})(),a.Type=(function(){let r={},s=Object.create(r);return s[r[0]="UNKNOWN"]=0,s[r[1]="RESPONSE"]=1,s[r[2]="NATIVE_FLOW"]=2,s})(),a})(),i.HeaderType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="EMPTY"]=1,A[a[2]="TEXT"]=2,A[a[3]="DOCUMENT"]=3,A[a[4]="IMAGE"]=4,A[a[5]="VIDEO"]=5,A[a[6]="LOCATION"]=6,A})(),i})(),t.ButtonsResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.selectedButtonId=A.string();break}case 3:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.type=A.int32();break}case 2:{c.selectedDisplayText=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ButtonsResponseMessage)return A;var r=new p.proto.Message.ButtonsResponseMessage;if(A.selectedButtonId!=null&&(r.selectedButtonId=String(A.selectedButtonId)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ButtonsResponseMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNKNOWN":case 0:r.type=0;break;case"DISPLAY_TEXT":case 1:r.type=1;break}return A.selectedDisplayText!=null&&(r.selectedDisplayText=String(A.selectedDisplayText)),r},i.toObject=function(A,r){r||(r={});var s={};return A.selectedButtonId!=null&&A.hasOwnProperty("selectedButtonId")&&(s.selectedButtonId=A.selectedButtonId,r.oneofs&&(s._selectedButtonId="selectedButtonId")),A.selectedDisplayText!=null&&A.hasOwnProperty("selectedDisplayText")&&(s.selectedDisplayText=A.selectedDisplayText,r.oneofs&&(s.response="selectedDisplayText")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.ButtonsResponseMessage.Type[A.type]===void 0?A.type:p.proto.Message.ButtonsResponseMessage.Type[A.type]:A.type,r.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ButtonsResponseMessage"},i.Type=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="DISPLAY_TEXT"]=1,A})(),i})(),t.Call=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.callKey=A.bytes();break}case 2:{c.conversionSource=A.string();break}case 3:{c.conversionData=A.bytes();break}case 4:{c.conversionDelaySeconds=A.uint32();break}case 5:{c.ctwaSignals=A.string();break}case 6:{c.ctwaPayload=A.bytes();break}case 7:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 8:{c.nativeFlowCallButtonPayload=A.string();break}case 9:{c.deeplinkPayload=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.Call)return A;var r=new p.proto.Message.Call;if(A.callKey!=null&&(typeof A.callKey=="string"?l.base64.decode(A.callKey,r.callKey=l.newBuffer(l.base64.length(A.callKey)),0):A.callKey.length>=0&&(r.callKey=A.callKey)),A.conversionSource!=null&&(r.conversionSource=String(A.conversionSource)),A.conversionData!=null&&(typeof A.conversionData=="string"?l.base64.decode(A.conversionData,r.conversionData=l.newBuffer(l.base64.length(A.conversionData)),0):A.conversionData.length>=0&&(r.conversionData=A.conversionData)),A.conversionDelaySeconds!=null&&(r.conversionDelaySeconds=A.conversionDelaySeconds>>>0),A.ctwaSignals!=null&&(r.ctwaSignals=String(A.ctwaSignals)),A.ctwaPayload!=null&&(typeof A.ctwaPayload=="string"?l.base64.decode(A.ctwaPayload,r.ctwaPayload=l.newBuffer(l.base64.length(A.ctwaPayload)),0):A.ctwaPayload.length>=0&&(r.ctwaPayload=A.ctwaPayload)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.Call.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return A.nativeFlowCallButtonPayload!=null&&(r.nativeFlowCallButtonPayload=String(A.nativeFlowCallButtonPayload)),A.deeplinkPayload!=null&&(r.deeplinkPayload=String(A.deeplinkPayload)),r},i.toObject=function(A,r){r||(r={});var s={};return A.callKey!=null&&A.hasOwnProperty("callKey")&&(s.callKey=r.bytes===String?l.base64.encode(A.callKey,0,A.callKey.length):r.bytes===Array?Array.prototype.slice.call(A.callKey):A.callKey,r.oneofs&&(s._callKey="callKey")),A.conversionSource!=null&&A.hasOwnProperty("conversionSource")&&(s.conversionSource=A.conversionSource,r.oneofs&&(s._conversionSource="conversionSource")),A.conversionData!=null&&A.hasOwnProperty("conversionData")&&(s.conversionData=r.bytes===String?l.base64.encode(A.conversionData,0,A.conversionData.length):r.bytes===Array?Array.prototype.slice.call(A.conversionData):A.conversionData,r.oneofs&&(s._conversionData="conversionData")),A.conversionDelaySeconds!=null&&A.hasOwnProperty("conversionDelaySeconds")&&(s.conversionDelaySeconds=A.conversionDelaySeconds,r.oneofs&&(s._conversionDelaySeconds="conversionDelaySeconds")),A.ctwaSignals!=null&&A.hasOwnProperty("ctwaSignals")&&(s.ctwaSignals=A.ctwaSignals,r.oneofs&&(s._ctwaSignals="ctwaSignals")),A.ctwaPayload!=null&&A.hasOwnProperty("ctwaPayload")&&(s.ctwaPayload=r.bytes===String?l.base64.encode(A.ctwaPayload,0,A.ctwaPayload.length):r.bytes===Array?Array.prototype.slice.call(A.ctwaPayload):A.ctwaPayload,r.oneofs&&(s._ctwaPayload="ctwaPayload")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.nativeFlowCallButtonPayload!=null&&A.hasOwnProperty("nativeFlowCallButtonPayload")&&(s.nativeFlowCallButtonPayload=A.nativeFlowCallButtonPayload,r.oneofs&&(s._nativeFlowCallButtonPayload="nativeFlowCallButtonPayload")),A.deeplinkPayload!=null&&A.hasOwnProperty("deeplinkPayload")&&(s.deeplinkPayload=A.deeplinkPayload,r.oneofs&&(s._deeplinkPayload="deeplinkPayload")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.Call"},i})(),t.CallLogMessage=(function(){function i(a){if(this.participants=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isVideo=A.bool();break}case 2:{c.callOutcome=A.int32();break}case 3:{c.durationSecs=A.int64();break}case 4:{c.callType=A.int32();break}case 5:{c.participants&&c.participants.length||(c.participants=[]),c.participants.push(p.proto.Message.CallLogMessage.CallParticipant.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.CallLogMessage)return A;var r=new p.proto.Message.CallLogMessage;switch(A.isVideo!=null&&(r.isVideo=!!A.isVideo),A.callOutcome){default:if(typeof A.callOutcome=="number"){r.callOutcome=A.callOutcome;break}break;case"CONNECTED":case 0:r.callOutcome=0;break;case"MISSED":case 1:r.callOutcome=1;break;case"FAILED":case 2:r.callOutcome=2;break;case"REJECTED":case 3:r.callOutcome=3;break;case"ACCEPTED_ELSEWHERE":case 4:r.callOutcome=4;break;case"ONGOING":case 5:r.callOutcome=5;break;case"SILENCED_BY_DND":case 6:r.callOutcome=6;break;case"SILENCED_UNKNOWN_CALLER":case 7:r.callOutcome=7;break}switch(A.durationSecs!=null&&(l.Long?(r.durationSecs=l.Long.fromValue(A.durationSecs)).unsigned=!1:typeof A.durationSecs=="string"?r.durationSecs=parseInt(A.durationSecs,10):typeof A.durationSecs=="number"?r.durationSecs=A.durationSecs:typeof A.durationSecs=="object"&&(r.durationSecs=new l.LongBits(A.durationSecs.low>>>0,A.durationSecs.high>>>0).toNumber())),A.callType){default:if(typeof A.callType=="number"){r.callType=A.callType;break}break;case"REGULAR":case 0:r.callType=0;break;case"SCHEDULED_CALL":case 1:r.callType=1;break;case"VOICE_CHAT":case 2:r.callType=2;break}if(A.participants){if(!Array.isArray(A.participants))throw TypeError(".proto.Message.CallLogMessage.participants: array expected");r.participants=[];for(var s=0;s>>3){case 1:{d.jid=s.string();break}case 2:{d.callOutcome=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.CallLogMessage.CallParticipant)return s;var g=new p.proto.Message.CallLogMessage.CallParticipant;switch(s.jid!=null&&(g.jid=String(s.jid)),s.callOutcome){default:if(typeof s.callOutcome=="number"){g.callOutcome=s.callOutcome;break}break;case"CONNECTED":case 0:g.callOutcome=0;break;case"MISSED":case 1:g.callOutcome=1;break;case"FAILED":case 2:g.callOutcome=2;break;case"REJECTED":case 3:g.callOutcome=3;break;case"ACCEPTED_ELSEWHERE":case 4:g.callOutcome=4;break;case"ONGOING":case 5:g.callOutcome=5;break;case"SILENCED_BY_DND":case 6:g.callOutcome=6;break;case"SILENCED_UNKNOWN_CALLER":case 7:g.callOutcome=7;break}return g},a.toObject=function(s,g){g||(g={});var c={};return s.jid!=null&&s.hasOwnProperty("jid")&&(c.jid=s.jid,g.oneofs&&(c._jid="jid")),s.callOutcome!=null&&s.hasOwnProperty("callOutcome")&&(c.callOutcome=g.enums===String?p.proto.Message.CallLogMessage.CallOutcome[s.callOutcome]===void 0?s.callOutcome:p.proto.Message.CallLogMessage.CallOutcome[s.callOutcome]:s.callOutcome,g.oneofs&&(c._callOutcome="callOutcome")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.CallLogMessage.CallParticipant"},a})(),i.CallType=(function(){let a={},A=Object.create(a);return A[a[0]="REGULAR"]=0,A[a[1]="SCHEDULED_CALL"]=1,A[a[2]="VOICE_CHAT"]=2,A})(),i})(),t.CancelPaymentRequestMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.CancelPaymentRequestMessage)return A;var r=new p.proto.Message.CancelPaymentRequestMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.CancelPaymentRequestMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.CancelPaymentRequestMessage"},i})(),t.Chat=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayName=A.string();break}case 2:{c.id=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.Chat)return A;var r=new p.proto.Message.Chat;return A.displayName!=null&&(r.displayName=String(A.displayName)),A.id!=null&&(r.id=String(A.id)),r},i.toObject=function(A,r){r||(r={});var s={};return A.displayName!=null&&A.hasOwnProperty("displayName")&&(s.displayName=A.displayName,r.oneofs&&(s._displayName="displayName")),A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,r.oneofs&&(s._id="id")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.Chat"},i})(),t.CloudAPIThreadControlNotification=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.status=A.int32();break}case 2:{c.senderNotificationTimestampMs=A.int64();break}case 3:{c.consumerLid=A.string();break}case 4:{c.consumerPhoneNumber=A.string();break}case 5:{c.notificationContent=p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent.decode(A,A.uint32());break}case 6:{c.shouldSuppressNotification=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.CloudAPIThreadControlNotification)return A;var r=new p.proto.Message.CloudAPIThreadControlNotification;switch(A.status){default:if(typeof A.status=="number"){r.status=A.status;break}break;case"UNKNOWN":case 0:r.status=0;break;case"CONTROL_PASSED":case 1:r.status=1;break;case"CONTROL_TAKEN":case 2:r.status=2;break}if(A.senderNotificationTimestampMs!=null&&(l.Long?(r.senderNotificationTimestampMs=l.Long.fromValue(A.senderNotificationTimestampMs)).unsigned=!1:typeof A.senderNotificationTimestampMs=="string"?r.senderNotificationTimestampMs=parseInt(A.senderNotificationTimestampMs,10):typeof A.senderNotificationTimestampMs=="number"?r.senderNotificationTimestampMs=A.senderNotificationTimestampMs:typeof A.senderNotificationTimestampMs=="object"&&(r.senderNotificationTimestampMs=new l.LongBits(A.senderNotificationTimestampMs.low>>>0,A.senderNotificationTimestampMs.high>>>0).toNumber())),A.consumerLid!=null&&(r.consumerLid=String(A.consumerLid)),A.consumerPhoneNumber!=null&&(r.consumerPhoneNumber=String(A.consumerPhoneNumber)),A.notificationContent!=null){if(typeof A.notificationContent!="object")throw TypeError(".proto.Message.CloudAPIThreadControlNotification.notificationContent: object expected");r.notificationContent=p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent.fromObject(A.notificationContent)}return A.shouldSuppressNotification!=null&&(r.shouldSuppressNotification=!!A.shouldSuppressNotification),r},i.toObject=function(A,r){r||(r={});var s={};return A.status!=null&&A.hasOwnProperty("status")&&(s.status=r.enums===String?p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControl[A.status]===void 0?A.status:p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControl[A.status]:A.status,r.oneofs&&(s._status="status")),A.senderNotificationTimestampMs!=null&&A.hasOwnProperty("senderNotificationTimestampMs")&&(typeof A.senderNotificationTimestampMs=="number"?s.senderNotificationTimestampMs=r.longs===String?String(A.senderNotificationTimestampMs):A.senderNotificationTimestampMs:s.senderNotificationTimestampMs=r.longs===String?se(A.senderNotificationTimestampMs):r.longs===Number?ge(A.senderNotificationTimestampMs):A.senderNotificationTimestampMs,r.oneofs&&(s._senderNotificationTimestampMs="senderNotificationTimestampMs")),A.consumerLid!=null&&A.hasOwnProperty("consumerLid")&&(s.consumerLid=A.consumerLid,r.oneofs&&(s._consumerLid="consumerLid")),A.consumerPhoneNumber!=null&&A.hasOwnProperty("consumerPhoneNumber")&&(s.consumerPhoneNumber=A.consumerPhoneNumber,r.oneofs&&(s._consumerPhoneNumber="consumerPhoneNumber")),A.notificationContent!=null&&A.hasOwnProperty("notificationContent")&&(s.notificationContent=p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent.toObject(A.notificationContent,r),r.oneofs&&(s._notificationContent="notificationContent")),A.shouldSuppressNotification!=null&&A.hasOwnProperty("shouldSuppressNotification")&&(s.shouldSuppressNotification=A.shouldSuppressNotification,r.oneofs&&(s._shouldSuppressNotification="shouldSuppressNotification")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.CloudAPIThreadControlNotification"},i.CloudAPIThreadControl=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="CONTROL_PASSED"]=1,A[a[2]="CONTROL_TAKEN"]=2,A})(),i.CloudAPIThreadControlNotificationContent=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.handoffNotificationText=s.string();break}case 2:{d.extraJson=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent)return s;var g=new p.proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent;return s.handoffNotificationText!=null&&(g.handoffNotificationText=String(s.handoffNotificationText)),s.extraJson!=null&&(g.extraJson=String(s.extraJson)),g},a.toObject=function(s,g){g||(g={});var c={};return s.handoffNotificationText!=null&&s.hasOwnProperty("handoffNotificationText")&&(c.handoffNotificationText=s.handoffNotificationText,g.oneofs&&(c._handoffNotificationText="handoffNotificationText")),s.extraJson!=null&&s.hasOwnProperty("extraJson")&&(c.extraJson=s.extraJson,g.oneofs&&(c._extraJson="extraJson")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.CloudAPIThreadControlNotification.CloudAPIThreadControlNotificationContent"},a})(),i})(),t.CommentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.message=p.proto.Message.decode(A,A.uint32());break}case 2:{c.targetMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.CommentMessage)return A;var r=new p.proto.Message.CommentMessage;if(A.message!=null){if(typeof A.message!="object")throw TypeError(".proto.Message.CommentMessage.message: object expected");r.message=p.proto.Message.fromObject(A.message)}if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.CommentMessage.targetMessageKey: object expected");r.targetMessageKey=p.proto.MessageKey.fromObject(A.targetMessageKey)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.message!=null&&A.hasOwnProperty("message")&&(s.message=p.proto.Message.toObject(A.message,r),r.oneofs&&(s._message="message")),A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=p.proto.MessageKey.toObject(A.targetMessageKey,r),r.oneofs&&(s._targetMessageKey="targetMessageKey")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.CommentMessage"},i})(),t.ContactMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayName=A.string();break}case 16:{c.vcard=A.string();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ContactMessage)return A;var r=new p.proto.Message.ContactMessage;if(A.displayName!=null&&(r.displayName=String(A.displayName)),A.vcard!=null&&(r.vcard=String(A.vcard)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ContactMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.displayName!=null&&A.hasOwnProperty("displayName")&&(s.displayName=A.displayName,r.oneofs&&(s._displayName="displayName")),A.vcard!=null&&A.hasOwnProperty("vcard")&&(s.vcard=A.vcard,r.oneofs&&(s._vcard="vcard")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ContactMessage"},i})(),t.ContactsArrayMessage=(function(){function i(a){if(this.contacts=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayName=A.string();break}case 2:{c.contacts&&c.contacts.length||(c.contacts=[]),c.contacts.push(p.proto.Message.ContactMessage.decode(A,A.uint32()));break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ContactsArrayMessage)return A;var r=new p.proto.Message.ContactsArrayMessage;if(A.displayName!=null&&(r.displayName=String(A.displayName)),A.contacts){if(!Array.isArray(A.contacts))throw TypeError(".proto.Message.ContactsArrayMessage.contacts: array expected");r.contacts=[];for(var s=0;s>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.DeclinePaymentRequestMessage)return A;var r=new p.proto.Message.DeclinePaymentRequestMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.DeclinePaymentRequestMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.DeclinePaymentRequestMessage"},i})(),t.DeviceSentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.destinationJid=A.string();break}case 2:{c.message=p.proto.Message.decode(A,A.uint32());break}case 3:{c.phash=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.DeviceSentMessage)return A;var r=new p.proto.Message.DeviceSentMessage;if(A.destinationJid!=null&&(r.destinationJid=String(A.destinationJid)),A.message!=null){if(typeof A.message!="object")throw TypeError(".proto.Message.DeviceSentMessage.message: object expected");r.message=p.proto.Message.fromObject(A.message)}return A.phash!=null&&(r.phash=String(A.phash)),r},i.toObject=function(A,r){r||(r={});var s={};return A.destinationJid!=null&&A.hasOwnProperty("destinationJid")&&(s.destinationJid=A.destinationJid,r.oneofs&&(s._destinationJid="destinationJid")),A.message!=null&&A.hasOwnProperty("message")&&(s.message=p.proto.Message.toObject(A.message,r),r.oneofs&&(s._message="message")),A.phash!=null&&A.hasOwnProperty("phash")&&(s.phash=A.phash,r.oneofs&&(s._phash="phash")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.DeviceSentMessage"},i})(),t.DocumentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.title=A.string();break}case 4:{c.fileSha256=A.bytes();break}case 5:{c.fileLength=A.uint64();break}case 6:{c.pageCount=A.uint32();break}case 7:{c.mediaKey=A.bytes();break}case 8:{c.fileName=A.string();break}case 9:{c.fileEncSha256=A.bytes();break}case 10:{c.directPath=A.string();break}case 11:{c.mediaKeyTimestamp=A.int64();break}case 12:{c.contactVcard=A.bool();break}case 13:{c.thumbnailDirectPath=A.string();break}case 14:{c.thumbnailSha256=A.bytes();break}case 15:{c.thumbnailEncSha256=A.bytes();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.thumbnailHeight=A.uint32();break}case 19:{c.thumbnailWidth=A.uint32();break}case 20:{c.caption=A.string();break}case 21:{c.accessibilityLabel=A.string();break}case 22:{c.mediaKeyDomain=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.DocumentMessage)return A;var r=new p.proto.Message.DocumentMessage;if(A.url!=null&&(r.url=String(A.url)),A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.title!=null&&(r.title=String(A.title)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.pageCount!=null&&(r.pageCount=A.pageCount>>>0),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.fileName!=null&&(r.fileName=String(A.fileName)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(r.directPath=String(A.directPath)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.contactVcard!=null&&(r.contactVcard=!!A.contactVcard),A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.DocumentMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.thumbnailHeight!=null&&(r.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(r.thumbnailWidth=A.thumbnailWidth>>>0),A.caption!=null&&(r.caption=String(A.caption)),A.accessibilityLabel!=null&&(r.accessibilityLabel=String(A.accessibilityLabel)),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){r.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:r.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:r.mediaKeyDomain=1;break;case"STATUS":case 2:r.mediaKeyDomain=2;break;case"CAPI":case 3:r.mediaKeyDomain=3;break;case"BOT":case 4:r.mediaKeyDomain=4;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.pageCount!=null&&A.hasOwnProperty("pageCount")&&(s.pageCount=A.pageCount,r.oneofs&&(s._pageCount="pageCount")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.fileName!=null&&A.hasOwnProperty("fileName")&&(s.fileName=A.fileName,r.oneofs&&(s._fileName="fileName")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.contactVcard!=null&&A.hasOwnProperty("contactVcard")&&(s.contactVcard=A.contactVcard,r.oneofs&&(s._contactVcard="contactVcard")),A.thumbnailDirectPath!=null&&A.hasOwnProperty("thumbnailDirectPath")&&(s.thumbnailDirectPath=A.thumbnailDirectPath,r.oneofs&&(s._thumbnailDirectPath="thumbnailDirectPath")),A.thumbnailSha256!=null&&A.hasOwnProperty("thumbnailSha256")&&(s.thumbnailSha256=r.bytes===String?l.base64.encode(A.thumbnailSha256,0,A.thumbnailSha256.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnailSha256):A.thumbnailSha256,r.oneofs&&(s._thumbnailSha256="thumbnailSha256")),A.thumbnailEncSha256!=null&&A.hasOwnProperty("thumbnailEncSha256")&&(s.thumbnailEncSha256=r.bytes===String?l.base64.encode(A.thumbnailEncSha256,0,A.thumbnailEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnailEncSha256):A.thumbnailEncSha256,r.oneofs&&(s._thumbnailEncSha256="thumbnailEncSha256")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.thumbnailHeight!=null&&A.hasOwnProperty("thumbnailHeight")&&(s.thumbnailHeight=A.thumbnailHeight,r.oneofs&&(s._thumbnailHeight="thumbnailHeight")),A.thumbnailWidth!=null&&A.hasOwnProperty("thumbnailWidth")&&(s.thumbnailWidth=A.thumbnailWidth,r.oneofs&&(s._thumbnailWidth="thumbnailWidth")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.accessibilityLabel!=null&&A.hasOwnProperty("accessibilityLabel")&&(s.accessibilityLabel=A.accessibilityLabel,r.oneofs&&(s._accessibilityLabel="accessibilityLabel")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=r.enums===String?p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,r.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.DocumentMessage"},i})(),t.EncCommentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.targetMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.EncCommentMessage)return A;var r=new p.proto.Message.EncCommentMessage;if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.EncCommentMessage.targetMessageKey: object expected");r.targetMessageKey=p.proto.MessageKey.fromObject(A.targetMessageKey)}return A.encPayload!=null&&(typeof A.encPayload=="string"?l.base64.decode(A.encPayload,r.encPayload=l.newBuffer(l.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(r.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?l.base64.decode(A.encIv,r.encIv=l.newBuffer(l.base64.length(A.encIv)),0):A.encIv.length>=0&&(r.encIv=A.encIv)),r},i.toObject=function(A,r){r||(r={});var s={};return A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=p.proto.MessageKey.toObject(A.targetMessageKey,r),r.oneofs&&(s._targetMessageKey="targetMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=r.bytes===String?l.base64.encode(A.encPayload,0,A.encPayload.length):r.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,r.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=r.bytes===String?l.base64.encode(A.encIv,0,A.encIv.length):r.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,r.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EncCommentMessage"},i})(),t.EncEventResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.eventCreationMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.EncEventResponseMessage)return A;var r=new p.proto.Message.EncEventResponseMessage;if(A.eventCreationMessageKey!=null){if(typeof A.eventCreationMessageKey!="object")throw TypeError(".proto.Message.EncEventResponseMessage.eventCreationMessageKey: object expected");r.eventCreationMessageKey=p.proto.MessageKey.fromObject(A.eventCreationMessageKey)}return A.encPayload!=null&&(typeof A.encPayload=="string"?l.base64.decode(A.encPayload,r.encPayload=l.newBuffer(l.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(r.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?l.base64.decode(A.encIv,r.encIv=l.newBuffer(l.base64.length(A.encIv)),0):A.encIv.length>=0&&(r.encIv=A.encIv)),r},i.toObject=function(A,r){r||(r={});var s={};return A.eventCreationMessageKey!=null&&A.hasOwnProperty("eventCreationMessageKey")&&(s.eventCreationMessageKey=p.proto.MessageKey.toObject(A.eventCreationMessageKey,r),r.oneofs&&(s._eventCreationMessageKey="eventCreationMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=r.bytes===String?l.base64.encode(A.encPayload,0,A.encPayload.length):r.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,r.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=r.bytes===String?l.base64.encode(A.encIv,0,A.encIv.length):r.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,r.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EncEventResponseMessage"},i})(),t.EncReactionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.targetMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.EncReactionMessage)return A;var r=new p.proto.Message.EncReactionMessage;if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.EncReactionMessage.targetMessageKey: object expected");r.targetMessageKey=p.proto.MessageKey.fromObject(A.targetMessageKey)}return A.encPayload!=null&&(typeof A.encPayload=="string"?l.base64.decode(A.encPayload,r.encPayload=l.newBuffer(l.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(r.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?l.base64.decode(A.encIv,r.encIv=l.newBuffer(l.base64.length(A.encIv)),0):A.encIv.length>=0&&(r.encIv=A.encIv)),r},i.toObject=function(A,r){r||(r={});var s={};return A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=p.proto.MessageKey.toObject(A.targetMessageKey,r),r.oneofs&&(s._targetMessageKey="targetMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=r.bytes===String?l.base64.encode(A.encPayload,0,A.encPayload.length):r.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,r.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=r.bytes===String?l.base64.encode(A.encIv,0,A.encIv.length):r.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,r.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EncReactionMessage"},i})(),t.EventMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 2:{c.isCanceled=A.bool();break}case 3:{c.name=A.string();break}case 4:{c.description=A.string();break}case 5:{c.location=p.proto.Message.LocationMessage.decode(A,A.uint32());break}case 6:{c.joinLink=A.string();break}case 7:{c.startTime=A.int64();break}case 8:{c.endTime=A.int64();break}case 9:{c.extraGuestsAllowed=A.bool();break}case 10:{c.isScheduleCall=A.bool();break}case 11:{c.hasReminder=A.bool();break}case 12:{c.reminderOffsetSec=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.EventMessage)return A;var r=new p.proto.Message.EventMessage;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.EventMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.isCanceled!=null&&(r.isCanceled=!!A.isCanceled),A.name!=null&&(r.name=String(A.name)),A.description!=null&&(r.description=String(A.description)),A.location!=null){if(typeof A.location!="object")throw TypeError(".proto.Message.EventMessage.location: object expected");r.location=p.proto.Message.LocationMessage.fromObject(A.location)}return A.joinLink!=null&&(r.joinLink=String(A.joinLink)),A.startTime!=null&&(l.Long?(r.startTime=l.Long.fromValue(A.startTime)).unsigned=!1:typeof A.startTime=="string"?r.startTime=parseInt(A.startTime,10):typeof A.startTime=="number"?r.startTime=A.startTime:typeof A.startTime=="object"&&(r.startTime=new l.LongBits(A.startTime.low>>>0,A.startTime.high>>>0).toNumber())),A.endTime!=null&&(l.Long?(r.endTime=l.Long.fromValue(A.endTime)).unsigned=!1:typeof A.endTime=="string"?r.endTime=parseInt(A.endTime,10):typeof A.endTime=="number"?r.endTime=A.endTime:typeof A.endTime=="object"&&(r.endTime=new l.LongBits(A.endTime.low>>>0,A.endTime.high>>>0).toNumber())),A.extraGuestsAllowed!=null&&(r.extraGuestsAllowed=!!A.extraGuestsAllowed),A.isScheduleCall!=null&&(r.isScheduleCall=!!A.isScheduleCall),A.hasReminder!=null&&(r.hasReminder=!!A.hasReminder),A.reminderOffsetSec!=null&&(l.Long?(r.reminderOffsetSec=l.Long.fromValue(A.reminderOffsetSec)).unsigned=!1:typeof A.reminderOffsetSec=="string"?r.reminderOffsetSec=parseInt(A.reminderOffsetSec,10):typeof A.reminderOffsetSec=="number"?r.reminderOffsetSec=A.reminderOffsetSec:typeof A.reminderOffsetSec=="object"&&(r.reminderOffsetSec=new l.LongBits(A.reminderOffsetSec.low>>>0,A.reminderOffsetSec.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.isCanceled!=null&&A.hasOwnProperty("isCanceled")&&(s.isCanceled=A.isCanceled,r.oneofs&&(s._isCanceled="isCanceled")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.description!=null&&A.hasOwnProperty("description")&&(s.description=A.description,r.oneofs&&(s._description="description")),A.location!=null&&A.hasOwnProperty("location")&&(s.location=p.proto.Message.LocationMessage.toObject(A.location,r),r.oneofs&&(s._location="location")),A.joinLink!=null&&A.hasOwnProperty("joinLink")&&(s.joinLink=A.joinLink,r.oneofs&&(s._joinLink="joinLink")),A.startTime!=null&&A.hasOwnProperty("startTime")&&(typeof A.startTime=="number"?s.startTime=r.longs===String?String(A.startTime):A.startTime:s.startTime=r.longs===String?se(A.startTime):r.longs===Number?ge(A.startTime):A.startTime,r.oneofs&&(s._startTime="startTime")),A.endTime!=null&&A.hasOwnProperty("endTime")&&(typeof A.endTime=="number"?s.endTime=r.longs===String?String(A.endTime):A.endTime:s.endTime=r.longs===String?se(A.endTime):r.longs===Number?ge(A.endTime):A.endTime,r.oneofs&&(s._endTime="endTime")),A.extraGuestsAllowed!=null&&A.hasOwnProperty("extraGuestsAllowed")&&(s.extraGuestsAllowed=A.extraGuestsAllowed,r.oneofs&&(s._extraGuestsAllowed="extraGuestsAllowed")),A.isScheduleCall!=null&&A.hasOwnProperty("isScheduleCall")&&(s.isScheduleCall=A.isScheduleCall,r.oneofs&&(s._isScheduleCall="isScheduleCall")),A.hasReminder!=null&&A.hasOwnProperty("hasReminder")&&(s.hasReminder=A.hasReminder,r.oneofs&&(s._hasReminder="hasReminder")),A.reminderOffsetSec!=null&&A.hasOwnProperty("reminderOffsetSec")&&(typeof A.reminderOffsetSec=="number"?s.reminderOffsetSec=r.longs===String?String(A.reminderOffsetSec):A.reminderOffsetSec:s.reminderOffsetSec=r.longs===String?se(A.reminderOffsetSec):r.longs===Number?ge(A.reminderOffsetSec):A.reminderOffsetSec,r.oneofs&&(s._reminderOffsetSec="reminderOffsetSec")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EventMessage"},i})(),t.EventResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.response=A.int32();break}case 2:{c.timestampMs=A.int64();break}case 3:{c.extraGuestCount=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.EventResponseMessage)return A;var r=new p.proto.Message.EventResponseMessage;switch(A.response){default:if(typeof A.response=="number"){r.response=A.response;break}break;case"UNKNOWN":case 0:r.response=0;break;case"GOING":case 1:r.response=1;break;case"NOT_GOING":case 2:r.response=2;break;case"MAYBE":case 3:r.response=3;break}return A.timestampMs!=null&&(l.Long?(r.timestampMs=l.Long.fromValue(A.timestampMs)).unsigned=!1:typeof A.timestampMs=="string"?r.timestampMs=parseInt(A.timestampMs,10):typeof A.timestampMs=="number"?r.timestampMs=A.timestampMs:typeof A.timestampMs=="object"&&(r.timestampMs=new l.LongBits(A.timestampMs.low>>>0,A.timestampMs.high>>>0).toNumber())),A.extraGuestCount!=null&&(r.extraGuestCount=A.extraGuestCount|0),r},i.toObject=function(A,r){r||(r={});var s={};return A.response!=null&&A.hasOwnProperty("response")&&(s.response=r.enums===String?p.proto.Message.EventResponseMessage.EventResponseType[A.response]===void 0?A.response:p.proto.Message.EventResponseMessage.EventResponseType[A.response]:A.response,r.oneofs&&(s._response="response")),A.timestampMs!=null&&A.hasOwnProperty("timestampMs")&&(typeof A.timestampMs=="number"?s.timestampMs=r.longs===String?String(A.timestampMs):A.timestampMs:s.timestampMs=r.longs===String?se(A.timestampMs):r.longs===Number?ge(A.timestampMs):A.timestampMs,r.oneofs&&(s._timestampMs="timestampMs")),A.extraGuestCount!=null&&A.hasOwnProperty("extraGuestCount")&&(s.extraGuestCount=A.extraGuestCount,r.oneofs&&(s._extraGuestCount="extraGuestCount")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.EventResponseMessage"},i.EventResponseType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="GOING"]=1,A[a[2]="NOT_GOING"]=2,A[a[3]="MAYBE"]=3,A})(),i})(),t.ExtendedTextMessage=(function(){function i(a){if(this.endCardTiles=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.text=A.string();break}case 2:{c.matchedText=A.string();break}case 5:{c.description=A.string();break}case 6:{c.title=A.string();break}case 7:{c.textArgb=A.fixed32();break}case 8:{c.backgroundArgb=A.fixed32();break}case 9:{c.font=A.int32();break}case 10:{c.previewType=A.int32();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.doNotPlayInline=A.bool();break}case 19:{c.thumbnailDirectPath=A.string();break}case 20:{c.thumbnailSha256=A.bytes();break}case 21:{c.thumbnailEncSha256=A.bytes();break}case 22:{c.mediaKey=A.bytes();break}case 23:{c.mediaKeyTimestamp=A.int64();break}case 24:{c.thumbnailHeight=A.uint32();break}case 25:{c.thumbnailWidth=A.uint32();break}case 26:{c.inviteLinkGroupType=A.int32();break}case 27:{c.inviteLinkParentGroupSubjectV2=A.string();break}case 28:{c.inviteLinkParentGroupThumbnailV2=A.bytes();break}case 29:{c.inviteLinkGroupTypeV2=A.int32();break}case 30:{c.viewOnce=A.bool();break}case 31:{c.videoHeight=A.uint32();break}case 32:{c.videoWidth=A.uint32();break}case 33:{c.faviconMMSMetadata=p.proto.Message.MMSThumbnailMetadata.decode(A,A.uint32());break}case 34:{c.linkPreviewMetadata=p.proto.Message.LinkPreviewMetadata.decode(A,A.uint32());break}case 35:{c.paymentLinkMetadata=p.proto.Message.PaymentLinkMetadata.decode(A,A.uint32());break}case 36:{c.endCardTiles&&c.endCardTiles.length||(c.endCardTiles=[]),c.endCardTiles.push(p.proto.Message.VideoEndCard.decode(A,A.uint32()));break}case 37:{c.videoContentUrl=A.string();break}case 38:{c.musicMetadata=p.proto.EmbeddedMusic.decode(A,A.uint32());break}case 39:{c.paymentExtendedMetadata=p.proto.Message.PaymentExtendedMetadata.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ExtendedTextMessage)return A;var r=new p.proto.Message.ExtendedTextMessage;switch(A.text!=null&&(r.text=String(A.text)),A.matchedText!=null&&(r.matchedText=String(A.matchedText)),A.description!=null&&(r.description=String(A.description)),A.title!=null&&(r.title=String(A.title)),A.textArgb!=null&&(r.textArgb=A.textArgb>>>0),A.backgroundArgb!=null&&(r.backgroundArgb=A.backgroundArgb>>>0),A.font){default:if(typeof A.font=="number"){r.font=A.font;break}break;case"SYSTEM":case 0:r.font=0;break;case"SYSTEM_TEXT":case 1:r.font=1;break;case"FB_SCRIPT":case 2:r.font=2;break;case"SYSTEM_BOLD":case 6:r.font=6;break;case"MORNINGBREEZE_REGULAR":case 7:r.font=7;break;case"CALISTOGA_REGULAR":case 8:r.font=8;break;case"EXO2_EXTRABOLD":case 9:r.font=9;break;case"COURIERPRIME_BOLD":case 10:r.font=10;break}switch(A.previewType){default:if(typeof A.previewType=="number"){r.previewType=A.previewType;break}break;case"NONE":case 0:r.previewType=0;break;case"VIDEO":case 1:r.previewType=1;break;case"PLACEHOLDER":case 4:r.previewType=4;break;case"IMAGE":case 5:r.previewType=5;break;case"PAYMENT_LINKS":case 6:r.previewType=6;break;case"PROFILE":case 7:r.previewType=7;break}if(A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ExtendedTextMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.doNotPlayInline!=null&&(r.doNotPlayInline=!!A.doNotPlayInline),A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.thumbnailHeight!=null&&(r.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(r.thumbnailWidth=A.thumbnailWidth>>>0),A.inviteLinkGroupType){default:if(typeof A.inviteLinkGroupType=="number"){r.inviteLinkGroupType=A.inviteLinkGroupType;break}break;case"DEFAULT":case 0:r.inviteLinkGroupType=0;break;case"PARENT":case 1:r.inviteLinkGroupType=1;break;case"SUB":case 2:r.inviteLinkGroupType=2;break;case"DEFAULT_SUB":case 3:r.inviteLinkGroupType=3;break}switch(A.inviteLinkParentGroupSubjectV2!=null&&(r.inviteLinkParentGroupSubjectV2=String(A.inviteLinkParentGroupSubjectV2)),A.inviteLinkParentGroupThumbnailV2!=null&&(typeof A.inviteLinkParentGroupThumbnailV2=="string"?l.base64.decode(A.inviteLinkParentGroupThumbnailV2,r.inviteLinkParentGroupThumbnailV2=l.newBuffer(l.base64.length(A.inviteLinkParentGroupThumbnailV2)),0):A.inviteLinkParentGroupThumbnailV2.length>=0&&(r.inviteLinkParentGroupThumbnailV2=A.inviteLinkParentGroupThumbnailV2)),A.inviteLinkGroupTypeV2){default:if(typeof A.inviteLinkGroupTypeV2=="number"){r.inviteLinkGroupTypeV2=A.inviteLinkGroupTypeV2;break}break;case"DEFAULT":case 0:r.inviteLinkGroupTypeV2=0;break;case"PARENT":case 1:r.inviteLinkGroupTypeV2=1;break;case"SUB":case 2:r.inviteLinkGroupTypeV2=2;break;case"DEFAULT_SUB":case 3:r.inviteLinkGroupTypeV2=3;break}if(A.viewOnce!=null&&(r.viewOnce=!!A.viewOnce),A.videoHeight!=null&&(r.videoHeight=A.videoHeight>>>0),A.videoWidth!=null&&(r.videoWidth=A.videoWidth>>>0),A.faviconMMSMetadata!=null){if(typeof A.faviconMMSMetadata!="object")throw TypeError(".proto.Message.ExtendedTextMessage.faviconMMSMetadata: object expected");r.faviconMMSMetadata=p.proto.Message.MMSThumbnailMetadata.fromObject(A.faviconMMSMetadata)}if(A.linkPreviewMetadata!=null){if(typeof A.linkPreviewMetadata!="object")throw TypeError(".proto.Message.ExtendedTextMessage.linkPreviewMetadata: object expected");r.linkPreviewMetadata=p.proto.Message.LinkPreviewMetadata.fromObject(A.linkPreviewMetadata)}if(A.paymentLinkMetadata!=null){if(typeof A.paymentLinkMetadata!="object")throw TypeError(".proto.Message.ExtendedTextMessage.paymentLinkMetadata: object expected");r.paymentLinkMetadata=p.proto.Message.PaymentLinkMetadata.fromObject(A.paymentLinkMetadata)}if(A.endCardTiles){if(!Array.isArray(A.endCardTiles))throw TypeError(".proto.Message.ExtendedTextMessage.endCardTiles: array expected");r.endCardTiles=[];for(var s=0;s>>3){case 1:{c.requestId=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.FullHistorySyncOnDemandRequestMetadata)return A;var r=new p.proto.Message.FullHistorySyncOnDemandRequestMetadata;return A.requestId!=null&&(r.requestId=String(A.requestId)),r},i.toObject=function(A,r){r||(r={});var s={};return A.requestId!=null&&A.hasOwnProperty("requestId")&&(s.requestId=A.requestId,r.oneofs&&(s._requestId="requestId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.FullHistorySyncOnDemandRequestMetadata"},i})(),t.FutureProofMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.message=p.proto.Message.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.FutureProofMessage)return A;var r=new p.proto.Message.FutureProofMessage;if(A.message!=null){if(typeof A.message!="object")throw TypeError(".proto.Message.FutureProofMessage.message: object expected");r.message=p.proto.Message.fromObject(A.message)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.message!=null&&A.hasOwnProperty("message")&&(s.message=p.proto.Message.toObject(A.message,r),r.oneofs&&(s._message="message")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.FutureProofMessage"},i})(),t.GroupInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.groupJid=A.string();break}case 2:{c.inviteCode=A.string();break}case 3:{c.inviteExpiration=A.int64();break}case 4:{c.groupName=A.string();break}case 5:{c.jpegThumbnail=A.bytes();break}case 6:{c.caption=A.string();break}case 7:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 8:{c.groupType=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.GroupInviteMessage)return A;var r=new p.proto.Message.GroupInviteMessage;if(A.groupJid!=null&&(r.groupJid=String(A.groupJid)),A.inviteCode!=null&&(r.inviteCode=String(A.inviteCode)),A.inviteExpiration!=null&&(l.Long?(r.inviteExpiration=l.Long.fromValue(A.inviteExpiration)).unsigned=!1:typeof A.inviteExpiration=="string"?r.inviteExpiration=parseInt(A.inviteExpiration,10):typeof A.inviteExpiration=="number"?r.inviteExpiration=A.inviteExpiration:typeof A.inviteExpiration=="object"&&(r.inviteExpiration=new l.LongBits(A.inviteExpiration.low>>>0,A.inviteExpiration.high>>>0).toNumber())),A.groupName!=null&&(r.groupName=String(A.groupName)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(r.caption=String(A.caption)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.GroupInviteMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.groupType){default:if(typeof A.groupType=="number"){r.groupType=A.groupType;break}break;case"DEFAULT":case 0:r.groupType=0;break;case"PARENT":case 1:r.groupType=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.groupJid!=null&&A.hasOwnProperty("groupJid")&&(s.groupJid=A.groupJid,r.oneofs&&(s._groupJid="groupJid")),A.inviteCode!=null&&A.hasOwnProperty("inviteCode")&&(s.inviteCode=A.inviteCode,r.oneofs&&(s._inviteCode="inviteCode")),A.inviteExpiration!=null&&A.hasOwnProperty("inviteExpiration")&&(typeof A.inviteExpiration=="number"?s.inviteExpiration=r.longs===String?String(A.inviteExpiration):A.inviteExpiration:s.inviteExpiration=r.longs===String?se(A.inviteExpiration):r.longs===Number?ge(A.inviteExpiration):A.inviteExpiration,r.oneofs&&(s._inviteExpiration="inviteExpiration")),A.groupName!=null&&A.hasOwnProperty("groupName")&&(s.groupName=A.groupName,r.oneofs&&(s._groupName="groupName")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.groupType!=null&&A.hasOwnProperty("groupType")&&(s.groupType=r.enums===String?p.proto.Message.GroupInviteMessage.GroupType[A.groupType]===void 0?A.groupType:p.proto.Message.GroupInviteMessage.GroupType[A.groupType]:A.groupType,r.oneofs&&(s._groupType="groupType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.GroupInviteMessage"},i.GroupType=(function(){let a={},A=Object.create(a);return A[a[0]="DEFAULT"]=0,A[a[1]="PARENT"]=1,A})(),i})(),t.HighlyStructuredMessage=(function(){function i(a){if(this.params=[],this.localizableParams=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.namespace=A.string();break}case 2:{c.elementName=A.string();break}case 3:{c.params&&c.params.length||(c.params=[]),c.params.push(A.string());break}case 4:{c.fallbackLg=A.string();break}case 5:{c.fallbackLc=A.string();break}case 6:{c.localizableParams&&c.localizableParams.length||(c.localizableParams=[]),c.localizableParams.push(p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.decode(A,A.uint32()));break}case 7:{c.deterministicLg=A.string();break}case 8:{c.deterministicLc=A.string();break}case 9:{c.hydratedHsm=p.proto.Message.TemplateMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.HighlyStructuredMessage)return A;var r=new p.proto.Message.HighlyStructuredMessage;if(A.namespace!=null&&(r.namespace=String(A.namespace)),A.elementName!=null&&(r.elementName=String(A.elementName)),A.params){if(!Array.isArray(A.params))throw TypeError(".proto.Message.HighlyStructuredMessage.params: array expected");r.params=[];for(var s=0;s>>3){case 1:{d.default=s.string();break}case 2:{d.currency=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency.decode(s,s.uint32());break}case 3:{d.dateTime=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter)return s;var g=new p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter;if(s.default!=null&&(g.default=String(s.default)),s.currency!=null){if(typeof s.currency!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.currency: object expected");g.currency=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency.fromObject(s.currency)}if(s.dateTime!=null){if(typeof s.dateTime!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.dateTime: object expected");g.dateTime=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.fromObject(s.dateTime)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.default!=null&&s.hasOwnProperty("default")&&(c.default=s.default,g.oneofs&&(c._default="default")),s.currency!=null&&s.hasOwnProperty("currency")&&(c.currency=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency.toObject(s.currency,g),g.oneofs&&(c.paramOneof="currency")),s.dateTime!=null&&s.hasOwnProperty("dateTime")&&(c.dateTime=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.toObject(s.dateTime,g),g.oneofs&&(c.paramOneof="dateTime")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter"},a.HSMCurrency=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.currencyCode=c.string();break}case 2:{f.amount1000=c.int64();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency)return c;var I=new p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency;return c.currencyCode!=null&&(I.currencyCode=String(c.currencyCode)),c.amount1000!=null&&(l.Long?(I.amount1000=l.Long.fromValue(c.amount1000)).unsigned=!1:typeof c.amount1000=="string"?I.amount1000=parseInt(c.amount1000,10):typeof c.amount1000=="number"?I.amount1000=c.amount1000:typeof c.amount1000=="object"&&(I.amount1000=new l.LongBits(c.amount1000.low>>>0,c.amount1000.high>>>0).toNumber())),I},r.toObject=function(c,I){I||(I={});var d={};return c.currencyCode!=null&&c.hasOwnProperty("currencyCode")&&(d.currencyCode=c.currencyCode,I.oneofs&&(d._currencyCode="currencyCode")),c.amount1000!=null&&c.hasOwnProperty("amount1000")&&(typeof c.amount1000=="number"?d.amount1000=I.longs===String?String(c.amount1000):c.amount1000:d.amount1000=I.longs===String?se(c.amount1000):I.longs===Number?ge(c.amount1000):c.amount1000,I.oneofs&&(d._amount1000="amount1000")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMCurrency"},r})(),a.HSMDateTime=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.component=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.decode(c,c.uint32());break}case 2:{f.unixEpoch=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch.decode(c,c.uint32());break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime)return c;var I=new p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime;if(c.component!=null){if(typeof c.component!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.component: object expected");I.component=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.fromObject(c.component)}if(c.unixEpoch!=null){if(typeof c.unixEpoch!="object")throw TypeError(".proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.unixEpoch: object expected");I.unixEpoch=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch.fromObject(c.unixEpoch)}return I},r.toObject=function(c,I){I||(I={});var d={};return c.component!=null&&c.hasOwnProperty("component")&&(d.component=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.toObject(c.component,I),I.oneofs&&(d.datetimeOneof="component")),c.unixEpoch!=null&&c.hasOwnProperty("unixEpoch")&&(d.unixEpoch=p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch.toObject(c.unixEpoch,I),I.oneofs&&(d.datetimeOneof="unixEpoch")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime"},r.HSMDateTimeComponent=(function(){function g(I){if(I)for(var d=Object.keys(I),B=0;B>>3){case 1:{y.dayOfWeek=d.int32();break}case 2:{y.year=d.uint32();break}case 3:{y.month=d.uint32();break}case 4:{y.dayOfMonth=d.uint32();break}case 5:{y.hour=d.uint32();break}case 6:{y.minute=d.uint32();break}case 7:{y.calendar=d.int32();break}default:d.skipType(m&7);break}}return y},g.fromObject=function(d){if(d instanceof p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent)return d;var B=new p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent;switch(d.dayOfWeek){default:if(typeof d.dayOfWeek=="number"){B.dayOfWeek=d.dayOfWeek;break}break;case"MONDAY":case 1:B.dayOfWeek=1;break;case"TUESDAY":case 2:B.dayOfWeek=2;break;case"WEDNESDAY":case 3:B.dayOfWeek=3;break;case"THURSDAY":case 4:B.dayOfWeek=4;break;case"FRIDAY":case 5:B.dayOfWeek=5;break;case"SATURDAY":case 6:B.dayOfWeek=6;break;case"SUNDAY":case 7:B.dayOfWeek=7;break}switch(d.year!=null&&(B.year=d.year>>>0),d.month!=null&&(B.month=d.month>>>0),d.dayOfMonth!=null&&(B.dayOfMonth=d.dayOfMonth>>>0),d.hour!=null&&(B.hour=d.hour>>>0),d.minute!=null&&(B.minute=d.minute>>>0),d.calendar){default:if(typeof d.calendar=="number"){B.calendar=d.calendar;break}break;case"GREGORIAN":case 1:B.calendar=1;break;case"SOLAR_HIJRI":case 2:B.calendar=2;break}return B},g.toObject=function(d,B){B||(B={});var f={};return d.dayOfWeek!=null&&d.hasOwnProperty("dayOfWeek")&&(f.dayOfWeek=B.enums===String?p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.DayOfWeekType[d.dayOfWeek]===void 0?d.dayOfWeek:p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.DayOfWeekType[d.dayOfWeek]:d.dayOfWeek,B.oneofs&&(f._dayOfWeek="dayOfWeek")),d.year!=null&&d.hasOwnProperty("year")&&(f.year=d.year,B.oneofs&&(f._year="year")),d.month!=null&&d.hasOwnProperty("month")&&(f.month=d.month,B.oneofs&&(f._month="month")),d.dayOfMonth!=null&&d.hasOwnProperty("dayOfMonth")&&(f.dayOfMonth=d.dayOfMonth,B.oneofs&&(f._dayOfMonth="dayOfMonth")),d.hour!=null&&d.hasOwnProperty("hour")&&(f.hour=d.hour,B.oneofs&&(f._hour="hour")),d.minute!=null&&d.hasOwnProperty("minute")&&(f.minute=d.minute,B.oneofs&&(f._minute="minute")),d.calendar!=null&&d.hasOwnProperty("calendar")&&(f.calendar=B.enums===String?p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.CalendarType[d.calendar]===void 0?d.calendar:p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent.CalendarType[d.calendar]:d.calendar,B.oneofs&&(f._calendar="calendar")),f},g.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},g.getTypeUrl=function(d){return d===void 0&&(d="type.googleapis.com"),d+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeComponent"},g.CalendarType=(function(){let I={},d=Object.create(I);return d[I[1]="GREGORIAN"]=1,d[I[2]="SOLAR_HIJRI"]=2,d})(),g.DayOfWeekType=(function(){let I={},d=Object.create(I);return d[I[1]="MONDAY"]=1,d[I[2]="TUESDAY"]=2,d[I[3]="WEDNESDAY"]=3,d[I[4]="THURSDAY"]=4,d[I[5]="FRIDAY"]=5,d[I[6]="SATURDAY"]=6,d[I[7]="SUNDAY"]=7,d})(),g})(),r.HSMDateTimeUnixEpoch=(function(){function g(I){if(I)for(var d=Object.keys(I),B=0;B>>3){case 1:{y.timestamp=d.int64();break}default:d.skipType(m&7);break}}return y},g.fromObject=function(d){if(d instanceof p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch)return d;var B=new p.proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch;return d.timestamp!=null&&(l.Long?(B.timestamp=l.Long.fromValue(d.timestamp)).unsigned=!1:typeof d.timestamp=="string"?B.timestamp=parseInt(d.timestamp,10):typeof d.timestamp=="number"?B.timestamp=d.timestamp:typeof d.timestamp=="object"&&(B.timestamp=new l.LongBits(d.timestamp.low>>>0,d.timestamp.high>>>0).toNumber())),B},g.toObject=function(d,B){B||(B={});var f={};return d.timestamp!=null&&d.hasOwnProperty("timestamp")&&(typeof d.timestamp=="number"?f.timestamp=B.longs===String?String(d.timestamp):d.timestamp:f.timestamp=B.longs===String?se(d.timestamp):B.longs===Number?ge(d.timestamp):d.timestamp,B.oneofs&&(f._timestamp="timestamp")),f},g.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},g.getTypeUrl=function(d){return d===void 0&&(d="type.googleapis.com"),d+"/proto.Message.HighlyStructuredMessage.HSMLocalizableParameter.HSMDateTime.HSMDateTimeUnixEpoch"},g})(),r})(),a})(),i})(),t.HistorySyncMessageAccessStatus=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.completeAccessGranted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.HistorySyncMessageAccessStatus)return A;var r=new p.proto.Message.HistorySyncMessageAccessStatus;return A.completeAccessGranted!=null&&(r.completeAccessGranted=!!A.completeAccessGranted),r},i.toObject=function(A,r){r||(r={});var s={};return A.completeAccessGranted!=null&&A.hasOwnProperty("completeAccessGranted")&&(s.completeAccessGranted=A.completeAccessGranted,r.oneofs&&(s._completeAccessGranted="completeAccessGranted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.HistorySyncMessageAccessStatus"},i})(),t.HistorySyncNotification=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.fileSha256=A.bytes();break}case 2:{c.fileLength=A.uint64();break}case 3:{c.mediaKey=A.bytes();break}case 4:{c.fileEncSha256=A.bytes();break}case 5:{c.directPath=A.string();break}case 6:{c.syncType=A.int32();break}case 7:{c.chunkOrder=A.uint32();break}case 8:{c.originalMessageId=A.string();break}case 9:{c.progress=A.uint32();break}case 10:{c.oldestMsgInChunkTimestampSec=A.int64();break}case 11:{c.initialHistBootstrapInlinePayload=A.bytes();break}case 12:{c.peerDataRequestSessionId=A.string();break}case 13:{c.fullHistorySyncOnDemandRequestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.decode(A,A.uint32());break}case 14:{c.encHandle=A.string();break}case 15:{c.messageAccessStatus=p.proto.Message.HistorySyncMessageAccessStatus.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.HistorySyncNotification)return A;var r=new p.proto.Message.HistorySyncNotification;switch(A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(r.directPath=String(A.directPath)),A.syncType){default:if(typeof A.syncType=="number"){r.syncType=A.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:r.syncType=0;break;case"INITIAL_STATUS_V3":case 1:r.syncType=1;break;case"FULL":case 2:r.syncType=2;break;case"RECENT":case 3:r.syncType=3;break;case"PUSH_NAME":case 4:r.syncType=4;break;case"NON_BLOCKING_DATA":case 5:r.syncType=5;break;case"ON_DEMAND":case 6:r.syncType=6;break;case"NO_HISTORY":case 7:r.syncType=7;break;case"MESSAGE_ACCESS_STATUS":case 8:r.syncType=8;break}if(A.chunkOrder!=null&&(r.chunkOrder=A.chunkOrder>>>0),A.originalMessageId!=null&&(r.originalMessageId=String(A.originalMessageId)),A.progress!=null&&(r.progress=A.progress>>>0),A.oldestMsgInChunkTimestampSec!=null&&(l.Long?(r.oldestMsgInChunkTimestampSec=l.Long.fromValue(A.oldestMsgInChunkTimestampSec)).unsigned=!1:typeof A.oldestMsgInChunkTimestampSec=="string"?r.oldestMsgInChunkTimestampSec=parseInt(A.oldestMsgInChunkTimestampSec,10):typeof A.oldestMsgInChunkTimestampSec=="number"?r.oldestMsgInChunkTimestampSec=A.oldestMsgInChunkTimestampSec:typeof A.oldestMsgInChunkTimestampSec=="object"&&(r.oldestMsgInChunkTimestampSec=new l.LongBits(A.oldestMsgInChunkTimestampSec.low>>>0,A.oldestMsgInChunkTimestampSec.high>>>0).toNumber())),A.initialHistBootstrapInlinePayload!=null&&(typeof A.initialHistBootstrapInlinePayload=="string"?l.base64.decode(A.initialHistBootstrapInlinePayload,r.initialHistBootstrapInlinePayload=l.newBuffer(l.base64.length(A.initialHistBootstrapInlinePayload)),0):A.initialHistBootstrapInlinePayload.length>=0&&(r.initialHistBootstrapInlinePayload=A.initialHistBootstrapInlinePayload)),A.peerDataRequestSessionId!=null&&(r.peerDataRequestSessionId=String(A.peerDataRequestSessionId)),A.fullHistorySyncOnDemandRequestMetadata!=null){if(typeof A.fullHistorySyncOnDemandRequestMetadata!="object")throw TypeError(".proto.Message.HistorySyncNotification.fullHistorySyncOnDemandRequestMetadata: object expected");r.fullHistorySyncOnDemandRequestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.fromObject(A.fullHistorySyncOnDemandRequestMetadata)}if(A.encHandle!=null&&(r.encHandle=String(A.encHandle)),A.messageAccessStatus!=null){if(typeof A.messageAccessStatus!="object")throw TypeError(".proto.Message.HistorySyncNotification.messageAccessStatus: object expected");r.messageAccessStatus=p.proto.Message.HistorySyncMessageAccessStatus.fromObject(A.messageAccessStatus)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.syncType!=null&&A.hasOwnProperty("syncType")&&(s.syncType=r.enums===String?p.proto.Message.HistorySyncType[A.syncType]===void 0?A.syncType:p.proto.Message.HistorySyncType[A.syncType]:A.syncType,r.oneofs&&(s._syncType="syncType")),A.chunkOrder!=null&&A.hasOwnProperty("chunkOrder")&&(s.chunkOrder=A.chunkOrder,r.oneofs&&(s._chunkOrder="chunkOrder")),A.originalMessageId!=null&&A.hasOwnProperty("originalMessageId")&&(s.originalMessageId=A.originalMessageId,r.oneofs&&(s._originalMessageId="originalMessageId")),A.progress!=null&&A.hasOwnProperty("progress")&&(s.progress=A.progress,r.oneofs&&(s._progress="progress")),A.oldestMsgInChunkTimestampSec!=null&&A.hasOwnProperty("oldestMsgInChunkTimestampSec")&&(typeof A.oldestMsgInChunkTimestampSec=="number"?s.oldestMsgInChunkTimestampSec=r.longs===String?String(A.oldestMsgInChunkTimestampSec):A.oldestMsgInChunkTimestampSec:s.oldestMsgInChunkTimestampSec=r.longs===String?se(A.oldestMsgInChunkTimestampSec):r.longs===Number?ge(A.oldestMsgInChunkTimestampSec):A.oldestMsgInChunkTimestampSec,r.oneofs&&(s._oldestMsgInChunkTimestampSec="oldestMsgInChunkTimestampSec")),A.initialHistBootstrapInlinePayload!=null&&A.hasOwnProperty("initialHistBootstrapInlinePayload")&&(s.initialHistBootstrapInlinePayload=r.bytes===String?l.base64.encode(A.initialHistBootstrapInlinePayload,0,A.initialHistBootstrapInlinePayload.length):r.bytes===Array?Array.prototype.slice.call(A.initialHistBootstrapInlinePayload):A.initialHistBootstrapInlinePayload,r.oneofs&&(s._initialHistBootstrapInlinePayload="initialHistBootstrapInlinePayload")),A.peerDataRequestSessionId!=null&&A.hasOwnProperty("peerDataRequestSessionId")&&(s.peerDataRequestSessionId=A.peerDataRequestSessionId,r.oneofs&&(s._peerDataRequestSessionId="peerDataRequestSessionId")),A.fullHistorySyncOnDemandRequestMetadata!=null&&A.hasOwnProperty("fullHistorySyncOnDemandRequestMetadata")&&(s.fullHistorySyncOnDemandRequestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.toObject(A.fullHistorySyncOnDemandRequestMetadata,r),r.oneofs&&(s._fullHistorySyncOnDemandRequestMetadata="fullHistorySyncOnDemandRequestMetadata")),A.encHandle!=null&&A.hasOwnProperty("encHandle")&&(s.encHandle=A.encHandle,r.oneofs&&(s._encHandle="encHandle")),A.messageAccessStatus!=null&&A.hasOwnProperty("messageAccessStatus")&&(s.messageAccessStatus=p.proto.Message.HistorySyncMessageAccessStatus.toObject(A.messageAccessStatus,r),r.oneofs&&(s._messageAccessStatus="messageAccessStatus")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.HistorySyncNotification"},i})(),t.HistorySyncType=(function(){let i={},e=Object.create(i);return e[i[0]="INITIAL_BOOTSTRAP"]=0,e[i[1]="INITIAL_STATUS_V3"]=1,e[i[2]="FULL"]=2,e[i[3]="RECENT"]=3,e[i[4]="PUSH_NAME"]=4,e[i[5]="NON_BLOCKING_DATA"]=5,e[i[6]="ON_DEMAND"]=6,e[i[7]="NO_HISTORY"]=7,e[i[8]="MESSAGE_ACCESS_STATUS"]=8,e})(),t.ImageMessage=(function(){function i(a){if(this.interactiveAnnotations=[],this.scanLengths=[],this.annotations=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.caption=A.string();break}case 4:{c.fileSha256=A.bytes();break}case 5:{c.fileLength=A.uint64();break}case 6:{c.height=A.uint32();break}case 7:{c.width=A.uint32();break}case 8:{c.mediaKey=A.bytes();break}case 9:{c.fileEncSha256=A.bytes();break}case 10:{c.interactiveAnnotations&&c.interactiveAnnotations.length||(c.interactiveAnnotations=[]),c.interactiveAnnotations.push(p.proto.InteractiveAnnotation.decode(A,A.uint32()));break}case 11:{c.directPath=A.string();break}case 12:{c.mediaKeyTimestamp=A.int64();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.firstScanSidecar=A.bytes();break}case 19:{c.firstScanLength=A.uint32();break}case 20:{c.experimentGroupId=A.uint32();break}case 21:{c.scansSidecar=A.bytes();break}case 22:{if(c.scanLengths&&c.scanLengths.length||(c.scanLengths=[]),(I&7)===2)for(var d=A.uint32()+A.pos;A.pos=0&&(r.fileSha256=A.fileSha256)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.height!=null&&(r.height=A.height>>>0),A.width!=null&&(r.width=A.width>>>0),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.interactiveAnnotations){if(!Array.isArray(A.interactiveAnnotations))throw TypeError(".proto.Message.ImageMessage.interactiveAnnotations: array expected");r.interactiveAnnotations=[];for(var s=0;s>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ImageMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.firstScanSidecar!=null&&(typeof A.firstScanSidecar=="string"?l.base64.decode(A.firstScanSidecar,r.firstScanSidecar=l.newBuffer(l.base64.length(A.firstScanSidecar)),0):A.firstScanSidecar.length>=0&&(r.firstScanSidecar=A.firstScanSidecar)),A.firstScanLength!=null&&(r.firstScanLength=A.firstScanLength>>>0),A.experimentGroupId!=null&&(r.experimentGroupId=A.experimentGroupId>>>0),A.scansSidecar!=null&&(typeof A.scansSidecar=="string"?l.base64.decode(A.scansSidecar,r.scansSidecar=l.newBuffer(l.base64.length(A.scansSidecar)),0):A.scansSidecar.length>=0&&(r.scansSidecar=A.scansSidecar)),A.scanLengths){if(!Array.isArray(A.scanLengths))throw TypeError(".proto.Message.ImageMessage.scanLengths: array expected");r.scanLengths=[];for(var s=0;s>>0}if(A.midQualityFileSha256!=null&&(typeof A.midQualityFileSha256=="string"?l.base64.decode(A.midQualityFileSha256,r.midQualityFileSha256=l.newBuffer(l.base64.length(A.midQualityFileSha256)),0):A.midQualityFileSha256.length>=0&&(r.midQualityFileSha256=A.midQualityFileSha256)),A.midQualityFileEncSha256!=null&&(typeof A.midQualityFileEncSha256=="string"?l.base64.decode(A.midQualityFileEncSha256,r.midQualityFileEncSha256=l.newBuffer(l.base64.length(A.midQualityFileEncSha256)),0):A.midQualityFileEncSha256.length>=0&&(r.midQualityFileEncSha256=A.midQualityFileEncSha256)),A.viewOnce!=null&&(r.viewOnce=!!A.viewOnce),A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.staticUrl!=null&&(r.staticUrl=String(A.staticUrl)),A.annotations){if(!Array.isArray(A.annotations))throw TypeError(".proto.Message.ImageMessage.annotations: array expected");r.annotations=[];for(var s=0;s>>3){case 1:{c.securityNotificationEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.InitialSecurityNotificationSettingSync)return A;var r=new p.proto.Message.InitialSecurityNotificationSettingSync;return A.securityNotificationEnabled!=null&&(r.securityNotificationEnabled=!!A.securityNotificationEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.securityNotificationEnabled!=null&&A.hasOwnProperty("securityNotificationEnabled")&&(s.securityNotificationEnabled=A.securityNotificationEnabled,r.oneofs&&(s._securityNotificationEnabled="securityNotificationEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InitialSecurityNotificationSettingSync"},i})(),t.InteractiveMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.header=p.proto.Message.InteractiveMessage.Header.decode(A,A.uint32());break}case 2:{c.body=p.proto.Message.InteractiveMessage.Body.decode(A,A.uint32());break}case 3:{c.footer=p.proto.Message.InteractiveMessage.Footer.decode(A,A.uint32());break}case 15:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 16:{c.urlTrackingMap=p.proto.UrlTrackingMap.decode(A,A.uint32());break}case 4:{c.shopStorefrontMessage=p.proto.Message.InteractiveMessage.ShopMessage.decode(A,A.uint32());break}case 5:{c.collectionMessage=p.proto.Message.InteractiveMessage.CollectionMessage.decode(A,A.uint32());break}case 6:{c.nativeFlowMessage=p.proto.Message.InteractiveMessage.NativeFlowMessage.decode(A,A.uint32());break}case 7:{c.carouselMessage=p.proto.Message.InteractiveMessage.CarouselMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.InteractiveMessage)return A;var r=new p.proto.Message.InteractiveMessage;if(A.header!=null){if(typeof A.header!="object")throw TypeError(".proto.Message.InteractiveMessage.header: object expected");r.header=p.proto.Message.InteractiveMessage.Header.fromObject(A.header)}if(A.body!=null){if(typeof A.body!="object")throw TypeError(".proto.Message.InteractiveMessage.body: object expected");r.body=p.proto.Message.InteractiveMessage.Body.fromObject(A.body)}if(A.footer!=null){if(typeof A.footer!="object")throw TypeError(".proto.Message.InteractiveMessage.footer: object expected");r.footer=p.proto.Message.InteractiveMessage.Footer.fromObject(A.footer)}if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.InteractiveMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.urlTrackingMap!=null){if(typeof A.urlTrackingMap!="object")throw TypeError(".proto.Message.InteractiveMessage.urlTrackingMap: object expected");r.urlTrackingMap=p.proto.UrlTrackingMap.fromObject(A.urlTrackingMap)}if(A.shopStorefrontMessage!=null){if(typeof A.shopStorefrontMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.shopStorefrontMessage: object expected");r.shopStorefrontMessage=p.proto.Message.InteractiveMessage.ShopMessage.fromObject(A.shopStorefrontMessage)}if(A.collectionMessage!=null){if(typeof A.collectionMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.collectionMessage: object expected");r.collectionMessage=p.proto.Message.InteractiveMessage.CollectionMessage.fromObject(A.collectionMessage)}if(A.nativeFlowMessage!=null){if(typeof A.nativeFlowMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.nativeFlowMessage: object expected");r.nativeFlowMessage=p.proto.Message.InteractiveMessage.NativeFlowMessage.fromObject(A.nativeFlowMessage)}if(A.carouselMessage!=null){if(typeof A.carouselMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.carouselMessage: object expected");r.carouselMessage=p.proto.Message.InteractiveMessage.CarouselMessage.fromObject(A.carouselMessage)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.header!=null&&A.hasOwnProperty("header")&&(s.header=p.proto.Message.InteractiveMessage.Header.toObject(A.header,r),r.oneofs&&(s._header="header")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=p.proto.Message.InteractiveMessage.Body.toObject(A.body,r),r.oneofs&&(s._body="body")),A.footer!=null&&A.hasOwnProperty("footer")&&(s.footer=p.proto.Message.InteractiveMessage.Footer.toObject(A.footer,r),r.oneofs&&(s._footer="footer")),A.shopStorefrontMessage!=null&&A.hasOwnProperty("shopStorefrontMessage")&&(s.shopStorefrontMessage=p.proto.Message.InteractiveMessage.ShopMessage.toObject(A.shopStorefrontMessage,r),r.oneofs&&(s.interactiveMessage="shopStorefrontMessage")),A.collectionMessage!=null&&A.hasOwnProperty("collectionMessage")&&(s.collectionMessage=p.proto.Message.InteractiveMessage.CollectionMessage.toObject(A.collectionMessage,r),r.oneofs&&(s.interactiveMessage="collectionMessage")),A.nativeFlowMessage!=null&&A.hasOwnProperty("nativeFlowMessage")&&(s.nativeFlowMessage=p.proto.Message.InteractiveMessage.NativeFlowMessage.toObject(A.nativeFlowMessage,r),r.oneofs&&(s.interactiveMessage="nativeFlowMessage")),A.carouselMessage!=null&&A.hasOwnProperty("carouselMessage")&&(s.carouselMessage=p.proto.Message.InteractiveMessage.CarouselMessage.toObject(A.carouselMessage,r),r.oneofs&&(s.interactiveMessage="carouselMessage")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.urlTrackingMap!=null&&A.hasOwnProperty("urlTrackingMap")&&(s.urlTrackingMap=p.proto.UrlTrackingMap.toObject(A.urlTrackingMap,r),r.oneofs&&(s._urlTrackingMap="urlTrackingMap")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InteractiveMessage"},i.Body=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.text=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.Body)return s;var g=new p.proto.Message.InteractiveMessage.Body;return s.text!=null&&(g.text=String(s.text)),g},a.toObject=function(s,g){g||(g={});var c={};return s.text!=null&&s.hasOwnProperty("text")&&(c.text=s.text,g.oneofs&&(c._text="text")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.Body"},a})(),i.CarouselMessage=(function(){function a(r){if(this.cards=[],r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.cards&&d.cards.length||(d.cards=[]),d.cards.push(p.proto.Message.InteractiveMessage.decode(s,s.uint32()));break}case 2:{d.messageVersion=s.int32();break}case 3:{d.carouselCardType=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.CarouselMessage)return s;var g=new p.proto.Message.InteractiveMessage.CarouselMessage;if(s.cards){if(!Array.isArray(s.cards))throw TypeError(".proto.Message.InteractiveMessage.CarouselMessage.cards: array expected");g.cards=[];for(var c=0;c>>3){case 1:{d.bizJid=s.string();break}case 2:{d.id=s.string();break}case 3:{d.messageVersion=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.CollectionMessage)return s;var g=new p.proto.Message.InteractiveMessage.CollectionMessage;return s.bizJid!=null&&(g.bizJid=String(s.bizJid)),s.id!=null&&(g.id=String(s.id)),s.messageVersion!=null&&(g.messageVersion=s.messageVersion|0),g},a.toObject=function(s,g){g||(g={});var c={};return s.bizJid!=null&&s.hasOwnProperty("bizJid")&&(c.bizJid=s.bizJid,g.oneofs&&(c._bizJid="bizJid")),s.id!=null&&s.hasOwnProperty("id")&&(c.id=s.id,g.oneofs&&(c._id="id")),s.messageVersion!=null&&s.hasOwnProperty("messageVersion")&&(c.messageVersion=s.messageVersion,g.oneofs&&(c._messageVersion="messageVersion")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.CollectionMessage"},a})(),i.Footer=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.text=s.string();break}case 3:{d.hasMediaAttachment=s.bool();break}case 2:{d.audioMessage=p.proto.Message.AudioMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.Footer)return s;var g=new p.proto.Message.InteractiveMessage.Footer;if(s.text!=null&&(g.text=String(s.text)),s.hasMediaAttachment!=null&&(g.hasMediaAttachment=!!s.hasMediaAttachment),s.audioMessage!=null){if(typeof s.audioMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Footer.audioMessage: object expected");g.audioMessage=p.proto.Message.AudioMessage.fromObject(s.audioMessage)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.text!=null&&s.hasOwnProperty("text")&&(c.text=s.text,g.oneofs&&(c._text="text")),s.audioMessage!=null&&s.hasOwnProperty("audioMessage")&&(c.audioMessage=p.proto.Message.AudioMessage.toObject(s.audioMessage,g),g.oneofs&&(c.media="audioMessage")),s.hasMediaAttachment!=null&&s.hasOwnProperty("hasMediaAttachment")&&(c.hasMediaAttachment=s.hasMediaAttachment,g.oneofs&&(c._hasMediaAttachment="hasMediaAttachment")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.Footer"},a})(),i.Header=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.title=s.string();break}case 2:{d.subtitle=s.string();break}case 5:{d.hasMediaAttachment=s.bool();break}case 3:{d.documentMessage=p.proto.Message.DocumentMessage.decode(s,s.uint32());break}case 4:{d.imageMessage=p.proto.Message.ImageMessage.decode(s,s.uint32());break}case 6:{d.jpegThumbnail=s.bytes();break}case 7:{d.videoMessage=p.proto.Message.VideoMessage.decode(s,s.uint32());break}case 8:{d.locationMessage=p.proto.Message.LocationMessage.decode(s,s.uint32());break}case 9:{d.productMessage=p.proto.Message.ProductMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.Header)return s;var g=new p.proto.Message.InteractiveMessage.Header;if(s.title!=null&&(g.title=String(s.title)),s.subtitle!=null&&(g.subtitle=String(s.subtitle)),s.hasMediaAttachment!=null&&(g.hasMediaAttachment=!!s.hasMediaAttachment),s.documentMessage!=null){if(typeof s.documentMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.documentMessage: object expected");g.documentMessage=p.proto.Message.DocumentMessage.fromObject(s.documentMessage)}if(s.imageMessage!=null){if(typeof s.imageMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.imageMessage: object expected");g.imageMessage=p.proto.Message.ImageMessage.fromObject(s.imageMessage)}if(s.jpegThumbnail!=null&&(typeof s.jpegThumbnail=="string"?l.base64.decode(s.jpegThumbnail,g.jpegThumbnail=l.newBuffer(l.base64.length(s.jpegThumbnail)),0):s.jpegThumbnail.length>=0&&(g.jpegThumbnail=s.jpegThumbnail)),s.videoMessage!=null){if(typeof s.videoMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.videoMessage: object expected");g.videoMessage=p.proto.Message.VideoMessage.fromObject(s.videoMessage)}if(s.locationMessage!=null){if(typeof s.locationMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.locationMessage: object expected");g.locationMessage=p.proto.Message.LocationMessage.fromObject(s.locationMessage)}if(s.productMessage!=null){if(typeof s.productMessage!="object")throw TypeError(".proto.Message.InteractiveMessage.Header.productMessage: object expected");g.productMessage=p.proto.Message.ProductMessage.fromObject(s.productMessage)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.subtitle!=null&&s.hasOwnProperty("subtitle")&&(c.subtitle=s.subtitle,g.oneofs&&(c._subtitle="subtitle")),s.documentMessage!=null&&s.hasOwnProperty("documentMessage")&&(c.documentMessage=p.proto.Message.DocumentMessage.toObject(s.documentMessage,g),g.oneofs&&(c.media="documentMessage")),s.imageMessage!=null&&s.hasOwnProperty("imageMessage")&&(c.imageMessage=p.proto.Message.ImageMessage.toObject(s.imageMessage,g),g.oneofs&&(c.media="imageMessage")),s.hasMediaAttachment!=null&&s.hasOwnProperty("hasMediaAttachment")&&(c.hasMediaAttachment=s.hasMediaAttachment,g.oneofs&&(c._hasMediaAttachment="hasMediaAttachment")),s.jpegThumbnail!=null&&s.hasOwnProperty("jpegThumbnail")&&(c.jpegThumbnail=g.bytes===String?l.base64.encode(s.jpegThumbnail,0,s.jpegThumbnail.length):g.bytes===Array?Array.prototype.slice.call(s.jpegThumbnail):s.jpegThumbnail,g.oneofs&&(c.media="jpegThumbnail")),s.videoMessage!=null&&s.hasOwnProperty("videoMessage")&&(c.videoMessage=p.proto.Message.VideoMessage.toObject(s.videoMessage,g),g.oneofs&&(c.media="videoMessage")),s.locationMessage!=null&&s.hasOwnProperty("locationMessage")&&(c.locationMessage=p.proto.Message.LocationMessage.toObject(s.locationMessage,g),g.oneofs&&(c.media="locationMessage")),s.productMessage!=null&&s.hasOwnProperty("productMessage")&&(c.productMessage=p.proto.Message.ProductMessage.toObject(s.productMessage,g),g.oneofs&&(c.media="productMessage")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.Header"},a})(),i.NativeFlowMessage=(function(){function a(r){if(this.buttons=[],r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.buttons&&d.buttons.length||(d.buttons=[]),d.buttons.push(p.proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton.decode(s,s.uint32()));break}case 2:{d.messageParamsJson=s.string();break}case 3:{d.messageVersion=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.NativeFlowMessage)return s;var g=new p.proto.Message.InteractiveMessage.NativeFlowMessage;if(s.buttons){if(!Array.isArray(s.buttons))throw TypeError(".proto.Message.InteractiveMessage.NativeFlowMessage.buttons: array expected");g.buttons=[];for(var c=0;c>>3){case 1:{f.name=c.string();break}case 2:{f.buttonParamsJson=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton)return c;var I=new p.proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton;return c.name!=null&&(I.name=String(c.name)),c.buttonParamsJson!=null&&(I.buttonParamsJson=String(c.buttonParamsJson)),I},r.toObject=function(c,I){I||(I={});var d={};return c.name!=null&&c.hasOwnProperty("name")&&(d.name=c.name,I.oneofs&&(d._name="name")),c.buttonParamsJson!=null&&c.hasOwnProperty("buttonParamsJson")&&(d.buttonParamsJson=c.buttonParamsJson,I.oneofs&&(d._buttonParamsJson="buttonParamsJson")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.InteractiveMessage.NativeFlowMessage.NativeFlowButton"},r})(),a})(),i.ShopMessage=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.id=s.string();break}case 2:{d.surface=s.int32();break}case 3:{d.messageVersion=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveMessage.ShopMessage)return s;var g=new p.proto.Message.InteractiveMessage.ShopMessage;switch(s.id!=null&&(g.id=String(s.id)),s.surface){default:if(typeof s.surface=="number"){g.surface=s.surface;break}break;case"UNKNOWN_SURFACE":case 0:g.surface=0;break;case"FB":case 1:g.surface=1;break;case"IG":case 2:g.surface=2;break;case"WA":case 3:g.surface=3;break}return s.messageVersion!=null&&(g.messageVersion=s.messageVersion|0),g},a.toObject=function(s,g){g||(g={});var c={};return s.id!=null&&s.hasOwnProperty("id")&&(c.id=s.id,g.oneofs&&(c._id="id")),s.surface!=null&&s.hasOwnProperty("surface")&&(c.surface=g.enums===String?p.proto.Message.InteractiveMessage.ShopMessage.Surface[s.surface]===void 0?s.surface:p.proto.Message.InteractiveMessage.ShopMessage.Surface[s.surface]:s.surface,g.oneofs&&(c._surface="surface")),s.messageVersion!=null&&s.hasOwnProperty("messageVersion")&&(c.messageVersion=s.messageVersion,g.oneofs&&(c._messageVersion="messageVersion")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveMessage.ShopMessage"},a.Surface=(function(){let r={},s=Object.create(r);return s[r[0]="UNKNOWN_SURFACE"]=0,s[r[1]="FB"]=1,s[r[2]="IG"]=2,s[r[3]="WA"]=3,s})(),a})(),i})(),t.InteractiveResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.body=p.proto.Message.InteractiveResponseMessage.Body.decode(A,A.uint32());break}case 15:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 2:{c.nativeFlowResponseMessage=p.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.InteractiveResponseMessage)return A;var r=new p.proto.Message.InteractiveResponseMessage;if(A.body!=null){if(typeof A.body!="object")throw TypeError(".proto.Message.InteractiveResponseMessage.body: object expected");r.body=p.proto.Message.InteractiveResponseMessage.Body.fromObject(A.body)}if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.InteractiveResponseMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.nativeFlowResponseMessage!=null){if(typeof A.nativeFlowResponseMessage!="object")throw TypeError(".proto.Message.InteractiveResponseMessage.nativeFlowResponseMessage: object expected");r.nativeFlowResponseMessage=p.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage.fromObject(A.nativeFlowResponseMessage)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.body!=null&&A.hasOwnProperty("body")&&(s.body=p.proto.Message.InteractiveResponseMessage.Body.toObject(A.body,r),r.oneofs&&(s._body="body")),A.nativeFlowResponseMessage!=null&&A.hasOwnProperty("nativeFlowResponseMessage")&&(s.nativeFlowResponseMessage=p.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage.toObject(A.nativeFlowResponseMessage,r),r.oneofs&&(s.interactiveResponseMessage="nativeFlowResponseMessage")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InteractiveResponseMessage"},i.Body=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.text=s.string();break}case 2:{d.format=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveResponseMessage.Body)return s;var g=new p.proto.Message.InteractiveResponseMessage.Body;switch(s.text!=null&&(g.text=String(s.text)),s.format){default:if(typeof s.format=="number"){g.format=s.format;break}break;case"DEFAULT":case 0:g.format=0;break;case"EXTENSIONS_1":case 1:g.format=1;break}return g},a.toObject=function(s,g){g||(g={});var c={};return s.text!=null&&s.hasOwnProperty("text")&&(c.text=s.text,g.oneofs&&(c._text="text")),s.format!=null&&s.hasOwnProperty("format")&&(c.format=g.enums===String?p.proto.Message.InteractiveResponseMessage.Body.Format[s.format]===void 0?s.format:p.proto.Message.InteractiveResponseMessage.Body.Format[s.format]:s.format,g.oneofs&&(c._format="format")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveResponseMessage.Body"},a.Format=(function(){let r={},s=Object.create(r);return s[r[0]="DEFAULT"]=0,s[r[1]="EXTENSIONS_1"]=1,s})(),a})(),i.NativeFlowResponseMessage=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.name=s.string();break}case 2:{d.paramsJson=s.string();break}case 3:{d.version=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage)return s;var g=new p.proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage;return s.name!=null&&(g.name=String(s.name)),s.paramsJson!=null&&(g.paramsJson=String(s.paramsJson)),s.version!=null&&(g.version=s.version|0),g},a.toObject=function(s,g){g||(g={});var c={};return s.name!=null&&s.hasOwnProperty("name")&&(c.name=s.name,g.oneofs&&(c._name="name")),s.paramsJson!=null&&s.hasOwnProperty("paramsJson")&&(c.paramsJson=s.paramsJson,g.oneofs&&(c._paramsJson="paramsJson")),s.version!=null&&s.hasOwnProperty("version")&&(c.version=s.version,g.oneofs&&(c._version="version")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.InteractiveResponseMessage.NativeFlowResponseMessage"},a})(),i})(),t.InvoiceMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.note=A.string();break}case 2:{c.token=A.string();break}case 3:{c.attachmentType=A.int32();break}case 4:{c.attachmentMimetype=A.string();break}case 5:{c.attachmentMediaKey=A.bytes();break}case 6:{c.attachmentMediaKeyTimestamp=A.int64();break}case 7:{c.attachmentFileSha256=A.bytes();break}case 8:{c.attachmentFileEncSha256=A.bytes();break}case 9:{c.attachmentDirectPath=A.string();break}case 10:{c.attachmentJpegThumbnail=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.InvoiceMessage)return A;var r=new p.proto.Message.InvoiceMessage;switch(A.note!=null&&(r.note=String(A.note)),A.token!=null&&(r.token=String(A.token)),A.attachmentType){default:if(typeof A.attachmentType=="number"){r.attachmentType=A.attachmentType;break}break;case"IMAGE":case 0:r.attachmentType=0;break;case"PDF":case 1:r.attachmentType=1;break}return A.attachmentMimetype!=null&&(r.attachmentMimetype=String(A.attachmentMimetype)),A.attachmentMediaKey!=null&&(typeof A.attachmentMediaKey=="string"?l.base64.decode(A.attachmentMediaKey,r.attachmentMediaKey=l.newBuffer(l.base64.length(A.attachmentMediaKey)),0):A.attachmentMediaKey.length>=0&&(r.attachmentMediaKey=A.attachmentMediaKey)),A.attachmentMediaKeyTimestamp!=null&&(l.Long?(r.attachmentMediaKeyTimestamp=l.Long.fromValue(A.attachmentMediaKeyTimestamp)).unsigned=!1:typeof A.attachmentMediaKeyTimestamp=="string"?r.attachmentMediaKeyTimestamp=parseInt(A.attachmentMediaKeyTimestamp,10):typeof A.attachmentMediaKeyTimestamp=="number"?r.attachmentMediaKeyTimestamp=A.attachmentMediaKeyTimestamp:typeof A.attachmentMediaKeyTimestamp=="object"&&(r.attachmentMediaKeyTimestamp=new l.LongBits(A.attachmentMediaKeyTimestamp.low>>>0,A.attachmentMediaKeyTimestamp.high>>>0).toNumber())),A.attachmentFileSha256!=null&&(typeof A.attachmentFileSha256=="string"?l.base64.decode(A.attachmentFileSha256,r.attachmentFileSha256=l.newBuffer(l.base64.length(A.attachmentFileSha256)),0):A.attachmentFileSha256.length>=0&&(r.attachmentFileSha256=A.attachmentFileSha256)),A.attachmentFileEncSha256!=null&&(typeof A.attachmentFileEncSha256=="string"?l.base64.decode(A.attachmentFileEncSha256,r.attachmentFileEncSha256=l.newBuffer(l.base64.length(A.attachmentFileEncSha256)),0):A.attachmentFileEncSha256.length>=0&&(r.attachmentFileEncSha256=A.attachmentFileEncSha256)),A.attachmentDirectPath!=null&&(r.attachmentDirectPath=String(A.attachmentDirectPath)),A.attachmentJpegThumbnail!=null&&(typeof A.attachmentJpegThumbnail=="string"?l.base64.decode(A.attachmentJpegThumbnail,r.attachmentJpegThumbnail=l.newBuffer(l.base64.length(A.attachmentJpegThumbnail)),0):A.attachmentJpegThumbnail.length>=0&&(r.attachmentJpegThumbnail=A.attachmentJpegThumbnail)),r},i.toObject=function(A,r){r||(r={});var s={};return A.note!=null&&A.hasOwnProperty("note")&&(s.note=A.note,r.oneofs&&(s._note="note")),A.token!=null&&A.hasOwnProperty("token")&&(s.token=A.token,r.oneofs&&(s._token="token")),A.attachmentType!=null&&A.hasOwnProperty("attachmentType")&&(s.attachmentType=r.enums===String?p.proto.Message.InvoiceMessage.AttachmentType[A.attachmentType]===void 0?A.attachmentType:p.proto.Message.InvoiceMessage.AttachmentType[A.attachmentType]:A.attachmentType,r.oneofs&&(s._attachmentType="attachmentType")),A.attachmentMimetype!=null&&A.hasOwnProperty("attachmentMimetype")&&(s.attachmentMimetype=A.attachmentMimetype,r.oneofs&&(s._attachmentMimetype="attachmentMimetype")),A.attachmentMediaKey!=null&&A.hasOwnProperty("attachmentMediaKey")&&(s.attachmentMediaKey=r.bytes===String?l.base64.encode(A.attachmentMediaKey,0,A.attachmentMediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.attachmentMediaKey):A.attachmentMediaKey,r.oneofs&&(s._attachmentMediaKey="attachmentMediaKey")),A.attachmentMediaKeyTimestamp!=null&&A.hasOwnProperty("attachmentMediaKeyTimestamp")&&(typeof A.attachmentMediaKeyTimestamp=="number"?s.attachmentMediaKeyTimestamp=r.longs===String?String(A.attachmentMediaKeyTimestamp):A.attachmentMediaKeyTimestamp:s.attachmentMediaKeyTimestamp=r.longs===String?se(A.attachmentMediaKeyTimestamp):r.longs===Number?ge(A.attachmentMediaKeyTimestamp):A.attachmentMediaKeyTimestamp,r.oneofs&&(s._attachmentMediaKeyTimestamp="attachmentMediaKeyTimestamp")),A.attachmentFileSha256!=null&&A.hasOwnProperty("attachmentFileSha256")&&(s.attachmentFileSha256=r.bytes===String?l.base64.encode(A.attachmentFileSha256,0,A.attachmentFileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.attachmentFileSha256):A.attachmentFileSha256,r.oneofs&&(s._attachmentFileSha256="attachmentFileSha256")),A.attachmentFileEncSha256!=null&&A.hasOwnProperty("attachmentFileEncSha256")&&(s.attachmentFileEncSha256=r.bytes===String?l.base64.encode(A.attachmentFileEncSha256,0,A.attachmentFileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.attachmentFileEncSha256):A.attachmentFileEncSha256,r.oneofs&&(s._attachmentFileEncSha256="attachmentFileEncSha256")),A.attachmentDirectPath!=null&&A.hasOwnProperty("attachmentDirectPath")&&(s.attachmentDirectPath=A.attachmentDirectPath,r.oneofs&&(s._attachmentDirectPath="attachmentDirectPath")),A.attachmentJpegThumbnail!=null&&A.hasOwnProperty("attachmentJpegThumbnail")&&(s.attachmentJpegThumbnail=r.bytes===String?l.base64.encode(A.attachmentJpegThumbnail,0,A.attachmentJpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.attachmentJpegThumbnail):A.attachmentJpegThumbnail,r.oneofs&&(s._attachmentJpegThumbnail="attachmentJpegThumbnail")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.InvoiceMessage"},i.AttachmentType=(function(){let a={},A=Object.create(a);return A[a[0]="IMAGE"]=0,A[a[1]="PDF"]=1,A})(),i})(),t.KeepInChatMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.keepType=A.int32();break}case 3:{c.timestampMs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.KeepInChatMessage)return A;var r=new p.proto.Message.KeepInChatMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.KeepInChatMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}switch(A.keepType){default:if(typeof A.keepType=="number"){r.keepType=A.keepType;break}break;case"UNKNOWN":case 0:r.keepType=0;break;case"KEEP_FOR_ALL":case 1:r.keepType=1;break;case"UNDO_KEEP_FOR_ALL":case 2:r.keepType=2;break}return A.timestampMs!=null&&(l.Long?(r.timestampMs=l.Long.fromValue(A.timestampMs)).unsigned=!1:typeof A.timestampMs=="string"?r.timestampMs=parseInt(A.timestampMs,10):typeof A.timestampMs=="number"?r.timestampMs=A.timestampMs:typeof A.timestampMs=="object"&&(r.timestampMs=new l.LongBits(A.timestampMs.low>>>0,A.timestampMs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.keepType!=null&&A.hasOwnProperty("keepType")&&(s.keepType=r.enums===String?p.proto.KeepType[A.keepType]===void 0?A.keepType:p.proto.KeepType[A.keepType]:A.keepType,r.oneofs&&(s._keepType="keepType")),A.timestampMs!=null&&A.hasOwnProperty("timestampMs")&&(typeof A.timestampMs=="number"?s.timestampMs=r.longs===String?String(A.timestampMs):A.timestampMs:s.timestampMs=r.longs===String?se(A.timestampMs):r.longs===Number?ge(A.timestampMs):A.timestampMs,r.oneofs&&(s._timestampMs="timestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.KeepInChatMessage"},i})(),t.LinkPreviewMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.paymentLinkMetadata=p.proto.Message.PaymentLinkMetadata.decode(A,A.uint32());break}case 2:{c.urlMetadata=p.proto.Message.URLMetadata.decode(A,A.uint32());break}case 3:{c.fbExperimentId=A.uint32();break}case 4:{c.linkMediaDuration=A.uint32();break}case 5:{c.socialMediaPostType=A.int32();break}case 6:{c.linkInlineVideoMuted=A.bool();break}case 7:{c.videoContentUrl=A.string();break}case 8:{c.musicMetadata=p.proto.EmbeddedMusic.decode(A,A.uint32());break}case 9:{c.videoContentCaption=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.LinkPreviewMetadata)return A;var r=new p.proto.Message.LinkPreviewMetadata;if(A.paymentLinkMetadata!=null){if(typeof A.paymentLinkMetadata!="object")throw TypeError(".proto.Message.LinkPreviewMetadata.paymentLinkMetadata: object expected");r.paymentLinkMetadata=p.proto.Message.PaymentLinkMetadata.fromObject(A.paymentLinkMetadata)}if(A.urlMetadata!=null){if(typeof A.urlMetadata!="object")throw TypeError(".proto.Message.LinkPreviewMetadata.urlMetadata: object expected");r.urlMetadata=p.proto.Message.URLMetadata.fromObject(A.urlMetadata)}switch(A.fbExperimentId!=null&&(r.fbExperimentId=A.fbExperimentId>>>0),A.linkMediaDuration!=null&&(r.linkMediaDuration=A.linkMediaDuration>>>0),A.socialMediaPostType){default:if(typeof A.socialMediaPostType=="number"){r.socialMediaPostType=A.socialMediaPostType;break}break;case"NONE":case 0:r.socialMediaPostType=0;break;case"REEL":case 1:r.socialMediaPostType=1;break;case"LIVE_VIDEO":case 2:r.socialMediaPostType=2;break;case"LONG_VIDEO":case 3:r.socialMediaPostType=3;break;case"SINGLE_IMAGE":case 4:r.socialMediaPostType=4;break;case"CAROUSEL":case 5:r.socialMediaPostType=5;break}if(A.linkInlineVideoMuted!=null&&(r.linkInlineVideoMuted=!!A.linkInlineVideoMuted),A.videoContentUrl!=null&&(r.videoContentUrl=String(A.videoContentUrl)),A.musicMetadata!=null){if(typeof A.musicMetadata!="object")throw TypeError(".proto.Message.LinkPreviewMetadata.musicMetadata: object expected");r.musicMetadata=p.proto.EmbeddedMusic.fromObject(A.musicMetadata)}return A.videoContentCaption!=null&&(r.videoContentCaption=String(A.videoContentCaption)),r},i.toObject=function(A,r){r||(r={});var s={};return A.paymentLinkMetadata!=null&&A.hasOwnProperty("paymentLinkMetadata")&&(s.paymentLinkMetadata=p.proto.Message.PaymentLinkMetadata.toObject(A.paymentLinkMetadata,r),r.oneofs&&(s._paymentLinkMetadata="paymentLinkMetadata")),A.urlMetadata!=null&&A.hasOwnProperty("urlMetadata")&&(s.urlMetadata=p.proto.Message.URLMetadata.toObject(A.urlMetadata,r),r.oneofs&&(s._urlMetadata="urlMetadata")),A.fbExperimentId!=null&&A.hasOwnProperty("fbExperimentId")&&(s.fbExperimentId=A.fbExperimentId,r.oneofs&&(s._fbExperimentId="fbExperimentId")),A.linkMediaDuration!=null&&A.hasOwnProperty("linkMediaDuration")&&(s.linkMediaDuration=A.linkMediaDuration,r.oneofs&&(s._linkMediaDuration="linkMediaDuration")),A.socialMediaPostType!=null&&A.hasOwnProperty("socialMediaPostType")&&(s.socialMediaPostType=r.enums===String?p.proto.Message.LinkPreviewMetadata.SocialMediaPostType[A.socialMediaPostType]===void 0?A.socialMediaPostType:p.proto.Message.LinkPreviewMetadata.SocialMediaPostType[A.socialMediaPostType]:A.socialMediaPostType,r.oneofs&&(s._socialMediaPostType="socialMediaPostType")),A.linkInlineVideoMuted!=null&&A.hasOwnProperty("linkInlineVideoMuted")&&(s.linkInlineVideoMuted=A.linkInlineVideoMuted,r.oneofs&&(s._linkInlineVideoMuted="linkInlineVideoMuted")),A.videoContentUrl!=null&&A.hasOwnProperty("videoContentUrl")&&(s.videoContentUrl=A.videoContentUrl,r.oneofs&&(s._videoContentUrl="videoContentUrl")),A.musicMetadata!=null&&A.hasOwnProperty("musicMetadata")&&(s.musicMetadata=p.proto.EmbeddedMusic.toObject(A.musicMetadata,r),r.oneofs&&(s._musicMetadata="musicMetadata")),A.videoContentCaption!=null&&A.hasOwnProperty("videoContentCaption")&&(s.videoContentCaption=A.videoContentCaption,r.oneofs&&(s._videoContentCaption="videoContentCaption")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.LinkPreviewMetadata"},i.SocialMediaPostType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="REEL"]=1,A[a[2]="LIVE_VIDEO"]=2,A[a[3]="LONG_VIDEO"]=3,A[a[4]="SINGLE_IMAGE"]=4,A[a[5]="CAROUSEL"]=5,A})(),i})(),t.ListMessage=(function(){function i(a){if(this.sections=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.title=A.string();break}case 2:{c.description=A.string();break}case 3:{c.buttonText=A.string();break}case 4:{c.listType=A.int32();break}case 5:{c.sections&&c.sections.length||(c.sections=[]),c.sections.push(p.proto.Message.ListMessage.Section.decode(A,A.uint32()));break}case 6:{c.productListInfo=p.proto.Message.ListMessage.ProductListInfo.decode(A,A.uint32());break}case 7:{c.footerText=A.string();break}case 8:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ListMessage)return A;var r=new p.proto.Message.ListMessage;switch(A.title!=null&&(r.title=String(A.title)),A.description!=null&&(r.description=String(A.description)),A.buttonText!=null&&(r.buttonText=String(A.buttonText)),A.listType){default:if(typeof A.listType=="number"){r.listType=A.listType;break}break;case"UNKNOWN":case 0:r.listType=0;break;case"SINGLE_SELECT":case 1:r.listType=1;break;case"PRODUCT_LIST":case 2:r.listType=2;break}if(A.sections){if(!Array.isArray(A.sections))throw TypeError(".proto.Message.ListMessage.sections: array expected");r.sections=[];for(var s=0;s>>3){case 1:{d.productId=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.Product)return s;var g=new p.proto.Message.ListMessage.Product;return s.productId!=null&&(g.productId=String(s.productId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.productId!=null&&s.hasOwnProperty("productId")&&(c.productId=s.productId,g.oneofs&&(c._productId="productId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListMessage.Product"},a})(),i.ProductListHeaderImage=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.productId=s.string();break}case 2:{d.jpegThumbnail=s.bytes();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.ProductListHeaderImage)return s;var g=new p.proto.Message.ListMessage.ProductListHeaderImage;return s.productId!=null&&(g.productId=String(s.productId)),s.jpegThumbnail!=null&&(typeof s.jpegThumbnail=="string"?l.base64.decode(s.jpegThumbnail,g.jpegThumbnail=l.newBuffer(l.base64.length(s.jpegThumbnail)),0):s.jpegThumbnail.length>=0&&(g.jpegThumbnail=s.jpegThumbnail)),g},a.toObject=function(s,g){g||(g={});var c={};return s.productId!=null&&s.hasOwnProperty("productId")&&(c.productId=s.productId,g.oneofs&&(c._productId="productId")),s.jpegThumbnail!=null&&s.hasOwnProperty("jpegThumbnail")&&(c.jpegThumbnail=g.bytes===String?l.base64.encode(s.jpegThumbnail,0,s.jpegThumbnail.length):g.bytes===Array?Array.prototype.slice.call(s.jpegThumbnail):s.jpegThumbnail,g.oneofs&&(c._jpegThumbnail="jpegThumbnail")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListMessage.ProductListHeaderImage"},a})(),i.ProductListInfo=(function(){function a(r){if(this.productSections=[],r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.productSections&&d.productSections.length||(d.productSections=[]),d.productSections.push(p.proto.Message.ListMessage.ProductSection.decode(s,s.uint32()));break}case 2:{d.headerImage=p.proto.Message.ListMessage.ProductListHeaderImage.decode(s,s.uint32());break}case 3:{d.businessOwnerJid=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.ProductListInfo)return s;var g=new p.proto.Message.ListMessage.ProductListInfo;if(s.productSections){if(!Array.isArray(s.productSections))throw TypeError(".proto.Message.ListMessage.ProductListInfo.productSections: array expected");g.productSections=[];for(var c=0;c>>3){case 1:{d.title=s.string();break}case 2:{d.products&&d.products.length||(d.products=[]),d.products.push(p.proto.Message.ListMessage.Product.decode(s,s.uint32()));break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.ProductSection)return s;var g=new p.proto.Message.ListMessage.ProductSection;if(s.title!=null&&(g.title=String(s.title)),s.products){if(!Array.isArray(s.products))throw TypeError(".proto.Message.ListMessage.ProductSection.products: array expected");g.products=[];for(var c=0;c>>3){case 1:{d.title=s.string();break}case 2:{d.description=s.string();break}case 3:{d.rowId=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.Row)return s;var g=new p.proto.Message.ListMessage.Row;return s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),s.rowId!=null&&(g.rowId=String(s.rowId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),s.rowId!=null&&s.hasOwnProperty("rowId")&&(c.rowId=s.rowId,g.oneofs&&(c._rowId="rowId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListMessage.Row"},a})(),i.Section=(function(){function a(r){if(this.rows=[],r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.title=s.string();break}case 2:{d.rows&&d.rows.length||(d.rows=[]),d.rows.push(p.proto.Message.ListMessage.Row.decode(s,s.uint32()));break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListMessage.Section)return s;var g=new p.proto.Message.ListMessage.Section;if(s.title!=null&&(g.title=String(s.title)),s.rows){if(!Array.isArray(s.rows))throw TypeError(".proto.Message.ListMessage.Section.rows: array expected");g.rows=[];for(var c=0;c>>3){case 1:{c.title=A.string();break}case 2:{c.listType=A.int32();break}case 3:{c.singleSelectReply=p.proto.Message.ListResponseMessage.SingleSelectReply.decode(A,A.uint32());break}case 4:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 5:{c.description=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ListResponseMessage)return A;var r=new p.proto.Message.ListResponseMessage;switch(A.title!=null&&(r.title=String(A.title)),A.listType){default:if(typeof A.listType=="number"){r.listType=A.listType;break}break;case"UNKNOWN":case 0:r.listType=0;break;case"SINGLE_SELECT":case 1:r.listType=1;break}if(A.singleSelectReply!=null){if(typeof A.singleSelectReply!="object")throw TypeError(".proto.Message.ListResponseMessage.singleSelectReply: object expected");r.singleSelectReply=p.proto.Message.ListResponseMessage.SingleSelectReply.fromObject(A.singleSelectReply)}if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ListResponseMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return A.description!=null&&(r.description=String(A.description)),r},i.toObject=function(A,r){r||(r={});var s={};return A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.listType!=null&&A.hasOwnProperty("listType")&&(s.listType=r.enums===String?p.proto.Message.ListResponseMessage.ListType[A.listType]===void 0?A.listType:p.proto.Message.ListResponseMessage.ListType[A.listType]:A.listType,r.oneofs&&(s._listType="listType")),A.singleSelectReply!=null&&A.hasOwnProperty("singleSelectReply")&&(s.singleSelectReply=p.proto.Message.ListResponseMessage.SingleSelectReply.toObject(A.singleSelectReply,r),r.oneofs&&(s._singleSelectReply="singleSelectReply")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.description!=null&&A.hasOwnProperty("description")&&(s.description=A.description,r.oneofs&&(s._description="description")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ListResponseMessage"},i.ListType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="SINGLE_SELECT"]=1,A})(),i.SingleSelectReply=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.selectedRowId=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ListResponseMessage.SingleSelectReply)return s;var g=new p.proto.Message.ListResponseMessage.SingleSelectReply;return s.selectedRowId!=null&&(g.selectedRowId=String(s.selectedRowId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.selectedRowId!=null&&s.hasOwnProperty("selectedRowId")&&(c.selectedRowId=s.selectedRowId,g.oneofs&&(c._selectedRowId="selectedRowId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ListResponseMessage.SingleSelectReply"},a})(),i})(),t.LiveLocationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.degreesLatitude=A.double();break}case 2:{c.degreesLongitude=A.double();break}case 3:{c.accuracyInMeters=A.uint32();break}case 4:{c.speedInMps=A.float();break}case 5:{c.degreesClockwiseFromMagneticNorth=A.uint32();break}case 6:{c.caption=A.string();break}case 7:{c.sequenceNumber=A.int64();break}case 8:{c.timeOffset=A.uint32();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.LiveLocationMessage)return A;var r=new p.proto.Message.LiveLocationMessage;if(A.degreesLatitude!=null&&(r.degreesLatitude=Number(A.degreesLatitude)),A.degreesLongitude!=null&&(r.degreesLongitude=Number(A.degreesLongitude)),A.accuracyInMeters!=null&&(r.accuracyInMeters=A.accuracyInMeters>>>0),A.speedInMps!=null&&(r.speedInMps=Number(A.speedInMps)),A.degreesClockwiseFromMagneticNorth!=null&&(r.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth>>>0),A.caption!=null&&(r.caption=String(A.caption)),A.sequenceNumber!=null&&(l.Long?(r.sequenceNumber=l.Long.fromValue(A.sequenceNumber)).unsigned=!1:typeof A.sequenceNumber=="string"?r.sequenceNumber=parseInt(A.sequenceNumber,10):typeof A.sequenceNumber=="number"?r.sequenceNumber=A.sequenceNumber:typeof A.sequenceNumber=="object"&&(r.sequenceNumber=new l.LongBits(A.sequenceNumber.low>>>0,A.sequenceNumber.high>>>0).toNumber())),A.timeOffset!=null&&(r.timeOffset=A.timeOffset>>>0),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.LiveLocationMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.degreesLatitude!=null&&A.hasOwnProperty("degreesLatitude")&&(s.degreesLatitude=r.json&&!isFinite(A.degreesLatitude)?String(A.degreesLatitude):A.degreesLatitude,r.oneofs&&(s._degreesLatitude="degreesLatitude")),A.degreesLongitude!=null&&A.hasOwnProperty("degreesLongitude")&&(s.degreesLongitude=r.json&&!isFinite(A.degreesLongitude)?String(A.degreesLongitude):A.degreesLongitude,r.oneofs&&(s._degreesLongitude="degreesLongitude")),A.accuracyInMeters!=null&&A.hasOwnProperty("accuracyInMeters")&&(s.accuracyInMeters=A.accuracyInMeters,r.oneofs&&(s._accuracyInMeters="accuracyInMeters")),A.speedInMps!=null&&A.hasOwnProperty("speedInMps")&&(s.speedInMps=r.json&&!isFinite(A.speedInMps)?String(A.speedInMps):A.speedInMps,r.oneofs&&(s._speedInMps="speedInMps")),A.degreesClockwiseFromMagneticNorth!=null&&A.hasOwnProperty("degreesClockwiseFromMagneticNorth")&&(s.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth,r.oneofs&&(s._degreesClockwiseFromMagneticNorth="degreesClockwiseFromMagneticNorth")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.sequenceNumber!=null&&A.hasOwnProperty("sequenceNumber")&&(typeof A.sequenceNumber=="number"?s.sequenceNumber=r.longs===String?String(A.sequenceNumber):A.sequenceNumber:s.sequenceNumber=r.longs===String?se(A.sequenceNumber):r.longs===Number?ge(A.sequenceNumber):A.sequenceNumber,r.oneofs&&(s._sequenceNumber="sequenceNumber")),A.timeOffset!=null&&A.hasOwnProperty("timeOffset")&&(s.timeOffset=A.timeOffset,r.oneofs&&(s._timeOffset="timeOffset")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.LiveLocationMessage"},i})(),t.LocationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.degreesLatitude=A.double();break}case 2:{c.degreesLongitude=A.double();break}case 3:{c.name=A.string();break}case 4:{c.address=A.string();break}case 5:{c.url=A.string();break}case 6:{c.isLive=A.bool();break}case 7:{c.accuracyInMeters=A.uint32();break}case 8:{c.speedInMps=A.float();break}case 9:{c.degreesClockwiseFromMagneticNorth=A.uint32();break}case 11:{c.comment=A.string();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.LocationMessage)return A;var r=new p.proto.Message.LocationMessage;if(A.degreesLatitude!=null&&(r.degreesLatitude=Number(A.degreesLatitude)),A.degreesLongitude!=null&&(r.degreesLongitude=Number(A.degreesLongitude)),A.name!=null&&(r.name=String(A.name)),A.address!=null&&(r.address=String(A.address)),A.url!=null&&(r.url=String(A.url)),A.isLive!=null&&(r.isLive=!!A.isLive),A.accuracyInMeters!=null&&(r.accuracyInMeters=A.accuracyInMeters>>>0),A.speedInMps!=null&&(r.speedInMps=Number(A.speedInMps)),A.degreesClockwiseFromMagneticNorth!=null&&(r.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth>>>0),A.comment!=null&&(r.comment=String(A.comment)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.LocationMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.degreesLatitude!=null&&A.hasOwnProperty("degreesLatitude")&&(s.degreesLatitude=r.json&&!isFinite(A.degreesLatitude)?String(A.degreesLatitude):A.degreesLatitude,r.oneofs&&(s._degreesLatitude="degreesLatitude")),A.degreesLongitude!=null&&A.hasOwnProperty("degreesLongitude")&&(s.degreesLongitude=r.json&&!isFinite(A.degreesLongitude)?String(A.degreesLongitude):A.degreesLongitude,r.oneofs&&(s._degreesLongitude="degreesLongitude")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.address!=null&&A.hasOwnProperty("address")&&(s.address=A.address,r.oneofs&&(s._address="address")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.isLive!=null&&A.hasOwnProperty("isLive")&&(s.isLive=A.isLive,r.oneofs&&(s._isLive="isLive")),A.accuracyInMeters!=null&&A.hasOwnProperty("accuracyInMeters")&&(s.accuracyInMeters=A.accuracyInMeters,r.oneofs&&(s._accuracyInMeters="accuracyInMeters")),A.speedInMps!=null&&A.hasOwnProperty("speedInMps")&&(s.speedInMps=r.json&&!isFinite(A.speedInMps)?String(A.speedInMps):A.speedInMps,r.oneofs&&(s._speedInMps="speedInMps")),A.degreesClockwiseFromMagneticNorth!=null&&A.hasOwnProperty("degreesClockwiseFromMagneticNorth")&&(s.degreesClockwiseFromMagneticNorth=A.degreesClockwiseFromMagneticNorth,r.oneofs&&(s._degreesClockwiseFromMagneticNorth="degreesClockwiseFromMagneticNorth")),A.comment!=null&&A.hasOwnProperty("comment")&&(s.comment=A.comment,r.oneofs&&(s._comment="comment")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.LocationMessage"},i})(),t.MMSThumbnailMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.thumbnailDirectPath=A.string();break}case 2:{c.thumbnailSha256=A.bytes();break}case 3:{c.thumbnailEncSha256=A.bytes();break}case 4:{c.mediaKey=A.bytes();break}case 5:{c.mediaKeyTimestamp=A.int64();break}case 6:{c.thumbnailHeight=A.uint32();break}case 7:{c.thumbnailWidth=A.uint32();break}case 8:{c.mediaKeyDomain=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.MMSThumbnailMetadata)return A;var r=new p.proto.Message.MMSThumbnailMetadata;switch(A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.thumbnailHeight!=null&&(r.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(r.thumbnailWidth=A.thumbnailWidth>>>0),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){r.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:r.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:r.mediaKeyDomain=1;break;case"STATUS":case 2:r.mediaKeyDomain=2;break;case"CAPI":case 3:r.mediaKeyDomain=3;break;case"BOT":case 4:r.mediaKeyDomain=4;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.thumbnailDirectPath!=null&&A.hasOwnProperty("thumbnailDirectPath")&&(s.thumbnailDirectPath=A.thumbnailDirectPath,r.oneofs&&(s._thumbnailDirectPath="thumbnailDirectPath")),A.thumbnailSha256!=null&&A.hasOwnProperty("thumbnailSha256")&&(s.thumbnailSha256=r.bytes===String?l.base64.encode(A.thumbnailSha256,0,A.thumbnailSha256.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnailSha256):A.thumbnailSha256,r.oneofs&&(s._thumbnailSha256="thumbnailSha256")),A.thumbnailEncSha256!=null&&A.hasOwnProperty("thumbnailEncSha256")&&(s.thumbnailEncSha256=r.bytes===String?l.base64.encode(A.thumbnailEncSha256,0,A.thumbnailEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnailEncSha256):A.thumbnailEncSha256,r.oneofs&&(s._thumbnailEncSha256="thumbnailEncSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.thumbnailHeight!=null&&A.hasOwnProperty("thumbnailHeight")&&(s.thumbnailHeight=A.thumbnailHeight,r.oneofs&&(s._thumbnailHeight="thumbnailHeight")),A.thumbnailWidth!=null&&A.hasOwnProperty("thumbnailWidth")&&(s.thumbnailWidth=A.thumbnailWidth,r.oneofs&&(s._thumbnailWidth="thumbnailWidth")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=r.enums===String?p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,r.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.MMSThumbnailMetadata"},i})(),t.MediaKeyDomain=(function(){let i={},e=Object.create(i);return e[i[0]="UNSET"]=0,e[i[1]="E2EE_CHAT"]=1,e[i[2]="STATUS"]=2,e[i[3]="CAPI"]=3,e[i[4]="BOT"]=4,e})(),t.MessageHistoryBundle=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.mimetype=A.string();break}case 2:{c.fileSha256=A.bytes();break}case 3:{c.mediaKey=A.bytes();break}case 4:{c.fileEncSha256=A.bytes();break}case 5:{c.directPath=A.string();break}case 6:{c.mediaKeyTimestamp=A.int64();break}case 7:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 8:{c.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.MessageHistoryBundle)return A;var r=new p.proto.Message.MessageHistoryBundle;if(A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(r.directPath=String(A.directPath)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.MessageHistoryBundle.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.messageHistoryMetadata!=null){if(typeof A.messageHistoryMetadata!="object")throw TypeError(".proto.Message.MessageHistoryBundle.messageHistoryMetadata: object expected");r.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.fromObject(A.messageHistoryMetadata)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.messageHistoryMetadata!=null&&A.hasOwnProperty("messageHistoryMetadata")&&(s.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.toObject(A.messageHistoryMetadata,r),r.oneofs&&(s._messageHistoryMetadata="messageHistoryMetadata")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.MessageHistoryBundle"},i})(),t.MessageHistoryMetadata=(function(){function i(a){if(this.historyReceivers=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.historyReceivers&&c.historyReceivers.length||(c.historyReceivers=[]),c.historyReceivers.push(A.string());break}case 2:{c.oldestMessageTimestamp=A.int64();break}case 3:{c.messageCount=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.MessageHistoryMetadata)return A;var r=new p.proto.Message.MessageHistoryMetadata;if(A.historyReceivers){if(!Array.isArray(A.historyReceivers))throw TypeError(".proto.Message.MessageHistoryMetadata.historyReceivers: array expected");r.historyReceivers=[];for(var s=0;s>>0,A.oldestMessageTimestamp.high>>>0).toNumber())),A.messageCount!=null&&(l.Long?(r.messageCount=l.Long.fromValue(A.messageCount)).unsigned=!1:typeof A.messageCount=="string"?r.messageCount=parseInt(A.messageCount,10):typeof A.messageCount=="number"?r.messageCount=A.messageCount:typeof A.messageCount=="object"&&(r.messageCount=new l.LongBits(A.messageCount.low>>>0,A.messageCount.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.historyReceivers=[]),A.historyReceivers&&A.historyReceivers.length){s.historyReceivers=[];for(var g=0;g>>3){case 1:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 2:{c.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.MessageHistoryNotice)return A;var r=new p.proto.Message.MessageHistoryNotice;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.MessageHistoryNotice.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.messageHistoryMetadata!=null){if(typeof A.messageHistoryMetadata!="object")throw TypeError(".proto.Message.MessageHistoryNotice.messageHistoryMetadata: object expected");r.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.fromObject(A.messageHistoryMetadata)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.messageHistoryMetadata!=null&&A.hasOwnProperty("messageHistoryMetadata")&&(s.messageHistoryMetadata=p.proto.Message.MessageHistoryMetadata.toObject(A.messageHistoryMetadata,r),r.oneofs&&(s._messageHistoryMetadata="messageHistoryMetadata")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.MessageHistoryNotice"},i})(),t.NewsletterAdminInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.newsletterJid=A.string();break}case 2:{c.newsletterName=A.string();break}case 3:{c.jpegThumbnail=A.bytes();break}case 4:{c.caption=A.string();break}case 5:{c.inviteExpiration=A.int64();break}case 6:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.NewsletterAdminInviteMessage)return A;var r=new p.proto.Message.NewsletterAdminInviteMessage;if(A.newsletterJid!=null&&(r.newsletterJid=String(A.newsletterJid)),A.newsletterName!=null&&(r.newsletterName=String(A.newsletterName)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(r.caption=String(A.caption)),A.inviteExpiration!=null&&(l.Long?(r.inviteExpiration=l.Long.fromValue(A.inviteExpiration)).unsigned=!1:typeof A.inviteExpiration=="string"?r.inviteExpiration=parseInt(A.inviteExpiration,10):typeof A.inviteExpiration=="number"?r.inviteExpiration=A.inviteExpiration:typeof A.inviteExpiration=="object"&&(r.inviteExpiration=new l.LongBits(A.inviteExpiration.low>>>0,A.inviteExpiration.high>>>0).toNumber())),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.NewsletterAdminInviteMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.newsletterJid!=null&&A.hasOwnProperty("newsletterJid")&&(s.newsletterJid=A.newsletterJid,r.oneofs&&(s._newsletterJid="newsletterJid")),A.newsletterName!=null&&A.hasOwnProperty("newsletterName")&&(s.newsletterName=A.newsletterName,r.oneofs&&(s._newsletterName="newsletterName")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.inviteExpiration!=null&&A.hasOwnProperty("inviteExpiration")&&(typeof A.inviteExpiration=="number"?s.inviteExpiration=r.longs===String?String(A.inviteExpiration):A.inviteExpiration:s.inviteExpiration=r.longs===String?se(A.inviteExpiration):r.longs===Number?ge(A.inviteExpiration):A.inviteExpiration,r.oneofs&&(s._inviteExpiration="inviteExpiration")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.NewsletterAdminInviteMessage"},i})(),t.NewsletterFollowerInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.newsletterJid=A.string();break}case 2:{c.newsletterName=A.string();break}case 3:{c.jpegThumbnail=A.bytes();break}case 4:{c.caption=A.string();break}case 5:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.NewsletterFollowerInviteMessage)return A;var r=new p.proto.Message.NewsletterFollowerInviteMessage;if(A.newsletterJid!=null&&(r.newsletterJid=String(A.newsletterJid)),A.newsletterName!=null&&(r.newsletterName=String(A.newsletterName)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.caption!=null&&(r.caption=String(A.caption)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.NewsletterFollowerInviteMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.newsletterJid!=null&&A.hasOwnProperty("newsletterJid")&&(s.newsletterJid=A.newsletterJid,r.oneofs&&(s._newsletterJid="newsletterJid")),A.newsletterName!=null&&A.hasOwnProperty("newsletterName")&&(s.newsletterName=A.newsletterName,r.oneofs&&(s._newsletterName="newsletterName")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.NewsletterFollowerInviteMessage"},i})(),t.OrderMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.orderId=A.string();break}case 2:{c.thumbnail=A.bytes();break}case 3:{c.itemCount=A.int32();break}case 4:{c.status=A.int32();break}case 5:{c.surface=A.int32();break}case 6:{c.message=A.string();break}case 7:{c.orderTitle=A.string();break}case 8:{c.sellerJid=A.string();break}case 9:{c.token=A.string();break}case 10:{c.totalAmount1000=A.int64();break}case 11:{c.totalCurrencyCode=A.string();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 12:{c.messageVersion=A.int32();break}case 13:{c.orderRequestMessageId=p.proto.MessageKey.decode(A,A.uint32());break}case 15:{c.catalogType=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.OrderMessage)return A;var r=new p.proto.Message.OrderMessage;switch(A.orderId!=null&&(r.orderId=String(A.orderId)),A.thumbnail!=null&&(typeof A.thumbnail=="string"?l.base64.decode(A.thumbnail,r.thumbnail=l.newBuffer(l.base64.length(A.thumbnail)),0):A.thumbnail.length>=0&&(r.thumbnail=A.thumbnail)),A.itemCount!=null&&(r.itemCount=A.itemCount|0),A.status){default:if(typeof A.status=="number"){r.status=A.status;break}break;case"INQUIRY":case 1:r.status=1;break;case"ACCEPTED":case 2:r.status=2;break;case"DECLINED":case 3:r.status=3;break}switch(A.surface){default:if(typeof A.surface=="number"){r.surface=A.surface;break}break;case"CATALOG":case 1:r.surface=1;break}if(A.message!=null&&(r.message=String(A.message)),A.orderTitle!=null&&(r.orderTitle=String(A.orderTitle)),A.sellerJid!=null&&(r.sellerJid=String(A.sellerJid)),A.token!=null&&(r.token=String(A.token)),A.totalAmount1000!=null&&(l.Long?(r.totalAmount1000=l.Long.fromValue(A.totalAmount1000)).unsigned=!1:typeof A.totalAmount1000=="string"?r.totalAmount1000=parseInt(A.totalAmount1000,10):typeof A.totalAmount1000=="number"?r.totalAmount1000=A.totalAmount1000:typeof A.totalAmount1000=="object"&&(r.totalAmount1000=new l.LongBits(A.totalAmount1000.low>>>0,A.totalAmount1000.high>>>0).toNumber())),A.totalCurrencyCode!=null&&(r.totalCurrencyCode=String(A.totalCurrencyCode)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.OrderMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.messageVersion!=null&&(r.messageVersion=A.messageVersion|0),A.orderRequestMessageId!=null){if(typeof A.orderRequestMessageId!="object")throw TypeError(".proto.Message.OrderMessage.orderRequestMessageId: object expected");r.orderRequestMessageId=p.proto.MessageKey.fromObject(A.orderRequestMessageId)}return A.catalogType!=null&&(r.catalogType=String(A.catalogType)),r},i.toObject=function(A,r){r||(r={});var s={};return A.orderId!=null&&A.hasOwnProperty("orderId")&&(s.orderId=A.orderId,r.oneofs&&(s._orderId="orderId")),A.thumbnail!=null&&A.hasOwnProperty("thumbnail")&&(s.thumbnail=r.bytes===String?l.base64.encode(A.thumbnail,0,A.thumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnail):A.thumbnail,r.oneofs&&(s._thumbnail="thumbnail")),A.itemCount!=null&&A.hasOwnProperty("itemCount")&&(s.itemCount=A.itemCount,r.oneofs&&(s._itemCount="itemCount")),A.status!=null&&A.hasOwnProperty("status")&&(s.status=r.enums===String?p.proto.Message.OrderMessage.OrderStatus[A.status]===void 0?A.status:p.proto.Message.OrderMessage.OrderStatus[A.status]:A.status,r.oneofs&&(s._status="status")),A.surface!=null&&A.hasOwnProperty("surface")&&(s.surface=r.enums===String?p.proto.Message.OrderMessage.OrderSurface[A.surface]===void 0?A.surface:p.proto.Message.OrderMessage.OrderSurface[A.surface]:A.surface,r.oneofs&&(s._surface="surface")),A.message!=null&&A.hasOwnProperty("message")&&(s.message=A.message,r.oneofs&&(s._message="message")),A.orderTitle!=null&&A.hasOwnProperty("orderTitle")&&(s.orderTitle=A.orderTitle,r.oneofs&&(s._orderTitle="orderTitle")),A.sellerJid!=null&&A.hasOwnProperty("sellerJid")&&(s.sellerJid=A.sellerJid,r.oneofs&&(s._sellerJid="sellerJid")),A.token!=null&&A.hasOwnProperty("token")&&(s.token=A.token,r.oneofs&&(s._token="token")),A.totalAmount1000!=null&&A.hasOwnProperty("totalAmount1000")&&(typeof A.totalAmount1000=="number"?s.totalAmount1000=r.longs===String?String(A.totalAmount1000):A.totalAmount1000:s.totalAmount1000=r.longs===String?se(A.totalAmount1000):r.longs===Number?ge(A.totalAmount1000):A.totalAmount1000,r.oneofs&&(s._totalAmount1000="totalAmount1000")),A.totalCurrencyCode!=null&&A.hasOwnProperty("totalCurrencyCode")&&(s.totalCurrencyCode=A.totalCurrencyCode,r.oneofs&&(s._totalCurrencyCode="totalCurrencyCode")),A.messageVersion!=null&&A.hasOwnProperty("messageVersion")&&(s.messageVersion=A.messageVersion,r.oneofs&&(s._messageVersion="messageVersion")),A.orderRequestMessageId!=null&&A.hasOwnProperty("orderRequestMessageId")&&(s.orderRequestMessageId=p.proto.MessageKey.toObject(A.orderRequestMessageId,r),r.oneofs&&(s._orderRequestMessageId="orderRequestMessageId")),A.catalogType!=null&&A.hasOwnProperty("catalogType")&&(s.catalogType=A.catalogType,r.oneofs&&(s._catalogType="catalogType")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.OrderMessage"},i.OrderStatus=(function(){let a={},A=Object.create(a);return A[a[1]="INQUIRY"]=1,A[a[2]="ACCEPTED"]=2,A[a[3]="DECLINED"]=3,A})(),i.OrderSurface=(function(){let a={},A=Object.create(a);return A[a[1]="CATALOG"]=1,A})(),i})(),t.PaymentExtendedMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.type=A.uint32();break}case 2:{c.platform=A.string();break}case 3:{c.messageParamsJson=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PaymentExtendedMetadata)return A;var r=new p.proto.Message.PaymentExtendedMetadata;return A.type!=null&&(r.type=A.type>>>0),A.platform!=null&&(r.platform=String(A.platform)),A.messageParamsJson!=null&&(r.messageParamsJson=String(A.messageParamsJson)),r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=A.type,r.oneofs&&(s._type="type")),A.platform!=null&&A.hasOwnProperty("platform")&&(s.platform=A.platform,r.oneofs&&(s._platform="platform")),A.messageParamsJson!=null&&A.hasOwnProperty("messageParamsJson")&&(s.messageParamsJson=A.messageParamsJson,r.oneofs&&(s._messageParamsJson="messageParamsJson")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PaymentExtendedMetadata"},i})(),t.PaymentInviteMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.serviceType=A.int32();break}case 2:{c.expiryTimestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PaymentInviteMessage)return A;var r=new p.proto.Message.PaymentInviteMessage;switch(A.serviceType){default:if(typeof A.serviceType=="number"){r.serviceType=A.serviceType;break}break;case"UNKNOWN":case 0:r.serviceType=0;break;case"FBPAY":case 1:r.serviceType=1;break;case"NOVI":case 2:r.serviceType=2;break;case"UPI":case 3:r.serviceType=3;break}return A.expiryTimestamp!=null&&(l.Long?(r.expiryTimestamp=l.Long.fromValue(A.expiryTimestamp)).unsigned=!1:typeof A.expiryTimestamp=="string"?r.expiryTimestamp=parseInt(A.expiryTimestamp,10):typeof A.expiryTimestamp=="number"?r.expiryTimestamp=A.expiryTimestamp:typeof A.expiryTimestamp=="object"&&(r.expiryTimestamp=new l.LongBits(A.expiryTimestamp.low>>>0,A.expiryTimestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.serviceType!=null&&A.hasOwnProperty("serviceType")&&(s.serviceType=r.enums===String?p.proto.Message.PaymentInviteMessage.ServiceType[A.serviceType]===void 0?A.serviceType:p.proto.Message.PaymentInviteMessage.ServiceType[A.serviceType]:A.serviceType,r.oneofs&&(s._serviceType="serviceType")),A.expiryTimestamp!=null&&A.hasOwnProperty("expiryTimestamp")&&(typeof A.expiryTimestamp=="number"?s.expiryTimestamp=r.longs===String?String(A.expiryTimestamp):A.expiryTimestamp:s.expiryTimestamp=r.longs===String?se(A.expiryTimestamp):r.longs===Number?ge(A.expiryTimestamp):A.expiryTimestamp,r.oneofs&&(s._expiryTimestamp="expiryTimestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PaymentInviteMessage"},i.ServiceType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="FBPAY"]=1,A[a[2]="NOVI"]=2,A[a[3]="UPI"]=3,A})(),i})(),t.PaymentLinkMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.button=p.proto.Message.PaymentLinkMetadata.PaymentLinkButton.decode(A,A.uint32());break}case 2:{c.header=p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.decode(A,A.uint32());break}case 3:{c.provider=p.proto.Message.PaymentLinkMetadata.PaymentLinkProvider.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PaymentLinkMetadata)return A;var r=new p.proto.Message.PaymentLinkMetadata;if(A.button!=null){if(typeof A.button!="object")throw TypeError(".proto.Message.PaymentLinkMetadata.button: object expected");r.button=p.proto.Message.PaymentLinkMetadata.PaymentLinkButton.fromObject(A.button)}if(A.header!=null){if(typeof A.header!="object")throw TypeError(".proto.Message.PaymentLinkMetadata.header: object expected");r.header=p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.fromObject(A.header)}if(A.provider!=null){if(typeof A.provider!="object")throw TypeError(".proto.Message.PaymentLinkMetadata.provider: object expected");r.provider=p.proto.Message.PaymentLinkMetadata.PaymentLinkProvider.fromObject(A.provider)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.button!=null&&A.hasOwnProperty("button")&&(s.button=p.proto.Message.PaymentLinkMetadata.PaymentLinkButton.toObject(A.button,r),r.oneofs&&(s._button="button")),A.header!=null&&A.hasOwnProperty("header")&&(s.header=p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.toObject(A.header,r),r.oneofs&&(s._header="header")),A.provider!=null&&A.hasOwnProperty("provider")&&(s.provider=p.proto.Message.PaymentLinkMetadata.PaymentLinkProvider.toObject(A.provider,r),r.oneofs&&(s._provider="provider")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PaymentLinkMetadata"},i.PaymentLinkButton=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.displayText=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PaymentLinkMetadata.PaymentLinkButton)return s;var g=new p.proto.Message.PaymentLinkMetadata.PaymentLinkButton;return s.displayText!=null&&(g.displayText=String(s.displayText)),g},a.toObject=function(s,g){g||(g={});var c={};return s.displayText!=null&&s.hasOwnProperty("displayText")&&(c.displayText=s.displayText,g.oneofs&&(c._displayText="displayText")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PaymentLinkMetadata.PaymentLinkButton"},a})(),i.PaymentLinkHeader=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.headerType=s.int32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader)return s;var g=new p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader;switch(s.headerType){default:if(typeof s.headerType=="number"){g.headerType=s.headerType;break}break;case"LINK_PREVIEW":case 0:g.headerType=0;break;case"ORDER":case 1:g.headerType=1;break}return g},a.toObject=function(s,g){g||(g={});var c={};return s.headerType!=null&&s.hasOwnProperty("headerType")&&(c.headerType=g.enums===String?p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.PaymentLinkHeaderType[s.headerType]===void 0?s.headerType:p.proto.Message.PaymentLinkMetadata.PaymentLinkHeader.PaymentLinkHeaderType[s.headerType]:s.headerType,g.oneofs&&(c._headerType="headerType")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PaymentLinkMetadata.PaymentLinkHeader"},a.PaymentLinkHeaderType=(function(){let r={},s=Object.create(r);return s[r[0]="LINK_PREVIEW"]=0,s[r[1]="ORDER"]=1,s})(),a})(),i.PaymentLinkProvider=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.paramsJson=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PaymentLinkMetadata.PaymentLinkProvider)return s;var g=new p.proto.Message.PaymentLinkMetadata.PaymentLinkProvider;return s.paramsJson!=null&&(g.paramsJson=String(s.paramsJson)),g},a.toObject=function(s,g){g||(g={});var c={};return s.paramsJson!=null&&s.hasOwnProperty("paramsJson")&&(c.paramsJson=s.paramsJson,g.oneofs&&(c._paramsJson="paramsJson")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PaymentLinkMetadata.PaymentLinkProvider"},a})(),i})(),t.PeerDataOperationRequestMessage=(function(){function i(a){if(this.requestStickerReupload=[],this.requestUrlPreview=[],this.placeholderMessageResendRequest=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.peerDataOperationRequestType=A.int32();break}case 2:{c.requestStickerReupload&&c.requestStickerReupload.length||(c.requestStickerReupload=[]),c.requestStickerReupload.push(p.proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload.decode(A,A.uint32()));break}case 3:{c.requestUrlPreview&&c.requestUrlPreview.length||(c.requestUrlPreview=[]),c.requestUrlPreview.push(p.proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview.decode(A,A.uint32()));break}case 4:{c.historySyncOnDemandRequest=p.proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest.decode(A,A.uint32());break}case 5:{c.placeholderMessageResendRequest&&c.placeholderMessageResendRequest.length||(c.placeholderMessageResendRequest=[]),c.placeholderMessageResendRequest.push(p.proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest.decode(A,A.uint32()));break}case 6:{c.fullHistorySyncOnDemandRequest=p.proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest.decode(A,A.uint32());break}case 7:{c.syncdCollectionFatalRecoveryRequest=p.proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest.decode(A,A.uint32());break}case 8:{c.historySyncChunkRetryRequest=p.proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest.decode(A,A.uint32());break}case 9:{c.galaxyFlowAction=p.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PeerDataOperationRequestMessage)return A;var r=new p.proto.Message.PeerDataOperationRequestMessage;switch(A.peerDataOperationRequestType){default:if(typeof A.peerDataOperationRequestType=="number"){r.peerDataOperationRequestType=A.peerDataOperationRequestType;break}break;case"UPLOAD_STICKER":case 0:r.peerDataOperationRequestType=0;break;case"SEND_RECENT_STICKER_BOOTSTRAP":case 1:r.peerDataOperationRequestType=1;break;case"GENERATE_LINK_PREVIEW":case 2:r.peerDataOperationRequestType=2;break;case"HISTORY_SYNC_ON_DEMAND":case 3:r.peerDataOperationRequestType=3;break;case"PLACEHOLDER_MESSAGE_RESEND":case 4:r.peerDataOperationRequestType=4;break;case"WAFFLE_LINKING_NONCE_FETCH":case 5:r.peerDataOperationRequestType=5;break;case"FULL_HISTORY_SYNC_ON_DEMAND":case 6:r.peerDataOperationRequestType=6;break;case"COMPANION_META_NONCE_FETCH":case 7:r.peerDataOperationRequestType=7;break;case"COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY":case 8:r.peerDataOperationRequestType=8;break;case"COMPANION_CANONICAL_USER_NONCE_FETCH":case 9:r.peerDataOperationRequestType=9;break;case"HISTORY_SYNC_CHUNK_RETRY":case 10:r.peerDataOperationRequestType=10;break;case"GALAXY_FLOW_ACTION":case 11:r.peerDataOperationRequestType=11;break}if(A.requestStickerReupload){if(!Array.isArray(A.requestStickerReupload))throw TypeError(".proto.Message.PeerDataOperationRequestMessage.requestStickerReupload: array expected");r.requestStickerReupload=[];for(var s=0;s>>3){case 1:{d.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.decode(s,s.uint32());break}case 2:{d.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest;if(s.requestMetadata!=null){if(typeof s.requestMetadata!="object")throw TypeError(".proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest.requestMetadata: object expected");g.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.fromObject(s.requestMetadata)}if(s.historySyncConfig!=null){if(typeof s.historySyncConfig!="object")throw TypeError(".proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest.historySyncConfig: object expected");g.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.fromObject(s.historySyncConfig)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.requestMetadata!=null&&s.hasOwnProperty("requestMetadata")&&(c.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.toObject(s.requestMetadata,g),g.oneofs&&(c._requestMetadata="requestMetadata")),s.historySyncConfig!=null&&s.hasOwnProperty("historySyncConfig")&&(c.historySyncConfig=p.proto.DeviceProps.HistorySyncConfig.toObject(s.historySyncConfig,g),g.oneofs&&(c._historySyncConfig="historySyncConfig")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.FullHistorySyncOnDemandRequest"},a})(),i.GalaxyFlowAction=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.type=s.int32();break}case 2:{d.flowId=s.string();break}case 3:{d.stanzaId=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction;switch(s.type){default:if(typeof s.type=="number"){g.type=s.type;break}break;case"NOTIFY_LAUNCH":case 1:g.type=1;break}return s.flowId!=null&&(g.flowId=String(s.flowId)),s.stanzaId!=null&&(g.stanzaId=String(s.stanzaId)),g},a.toObject=function(s,g){g||(g={});var c={};return s.type!=null&&s.hasOwnProperty("type")&&(c.type=g.enums===String?p.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction.GalaxyFlowActionType[s.type]===void 0?s.type:p.proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction.GalaxyFlowActionType[s.type]:s.type,g.oneofs&&(c._type="type")),s.flowId!=null&&s.hasOwnProperty("flowId")&&(c.flowId=s.flowId,g.oneofs&&(c._flowId="flowId")),s.stanzaId!=null&&s.hasOwnProperty("stanzaId")&&(c.stanzaId=s.stanzaId,g.oneofs&&(c._stanzaId="stanzaId")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.GalaxyFlowAction"},a.GalaxyFlowActionType=(function(){let r={},s=Object.create(r);return s[r[1]="NOTIFY_LAUNCH"]=1,s})(),a})(),i.HistorySyncChunkRetryRequest=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.syncType=s.int32();break}case 2:{d.chunkOrder=s.uint32();break}case 3:{d.chunkNotificationId=s.string();break}case 4:{d.regenerateChunk=s.bool();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest;switch(s.syncType){default:if(typeof s.syncType=="number"){g.syncType=s.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:g.syncType=0;break;case"INITIAL_STATUS_V3":case 1:g.syncType=1;break;case"FULL":case 2:g.syncType=2;break;case"RECENT":case 3:g.syncType=3;break;case"PUSH_NAME":case 4:g.syncType=4;break;case"NON_BLOCKING_DATA":case 5:g.syncType=5;break;case"ON_DEMAND":case 6:g.syncType=6;break;case"NO_HISTORY":case 7:g.syncType=7;break;case"MESSAGE_ACCESS_STATUS":case 8:g.syncType=8;break}return s.chunkOrder!=null&&(g.chunkOrder=s.chunkOrder>>>0),s.chunkNotificationId!=null&&(g.chunkNotificationId=String(s.chunkNotificationId)),s.regenerateChunk!=null&&(g.regenerateChunk=!!s.regenerateChunk),g},a.toObject=function(s,g){g||(g={});var c={};return s.syncType!=null&&s.hasOwnProperty("syncType")&&(c.syncType=g.enums===String?p.proto.Message.HistorySyncType[s.syncType]===void 0?s.syncType:p.proto.Message.HistorySyncType[s.syncType]:s.syncType,g.oneofs&&(c._syncType="syncType")),s.chunkOrder!=null&&s.hasOwnProperty("chunkOrder")&&(c.chunkOrder=s.chunkOrder,g.oneofs&&(c._chunkOrder="chunkOrder")),s.chunkNotificationId!=null&&s.hasOwnProperty("chunkNotificationId")&&(c.chunkNotificationId=s.chunkNotificationId,g.oneofs&&(c._chunkNotificationId="chunkNotificationId")),s.regenerateChunk!=null&&s.hasOwnProperty("regenerateChunk")&&(c.regenerateChunk=s.regenerateChunk,g.oneofs&&(c._regenerateChunk="regenerateChunk")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.HistorySyncChunkRetryRequest"},a})(),i.HistorySyncOnDemandRequest=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.chatJid=s.string();break}case 2:{d.oldestMsgId=s.string();break}case 3:{d.oldestMsgFromMe=s.bool();break}case 4:{d.onDemandMsgCount=s.int32();break}case 5:{d.oldestMsgTimestampMs=s.int64();break}case 6:{d.accountLid=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest;return s.chatJid!=null&&(g.chatJid=String(s.chatJid)),s.oldestMsgId!=null&&(g.oldestMsgId=String(s.oldestMsgId)),s.oldestMsgFromMe!=null&&(g.oldestMsgFromMe=!!s.oldestMsgFromMe),s.onDemandMsgCount!=null&&(g.onDemandMsgCount=s.onDemandMsgCount|0),s.oldestMsgTimestampMs!=null&&(l.Long?(g.oldestMsgTimestampMs=l.Long.fromValue(s.oldestMsgTimestampMs)).unsigned=!1:typeof s.oldestMsgTimestampMs=="string"?g.oldestMsgTimestampMs=parseInt(s.oldestMsgTimestampMs,10):typeof s.oldestMsgTimestampMs=="number"?g.oldestMsgTimestampMs=s.oldestMsgTimestampMs:typeof s.oldestMsgTimestampMs=="object"&&(g.oldestMsgTimestampMs=new l.LongBits(s.oldestMsgTimestampMs.low>>>0,s.oldestMsgTimestampMs.high>>>0).toNumber())),s.accountLid!=null&&(g.accountLid=String(s.accountLid)),g},a.toObject=function(s,g){g||(g={});var c={};return s.chatJid!=null&&s.hasOwnProperty("chatJid")&&(c.chatJid=s.chatJid,g.oneofs&&(c._chatJid="chatJid")),s.oldestMsgId!=null&&s.hasOwnProperty("oldestMsgId")&&(c.oldestMsgId=s.oldestMsgId,g.oneofs&&(c._oldestMsgId="oldestMsgId")),s.oldestMsgFromMe!=null&&s.hasOwnProperty("oldestMsgFromMe")&&(c.oldestMsgFromMe=s.oldestMsgFromMe,g.oneofs&&(c._oldestMsgFromMe="oldestMsgFromMe")),s.onDemandMsgCount!=null&&s.hasOwnProperty("onDemandMsgCount")&&(c.onDemandMsgCount=s.onDemandMsgCount,g.oneofs&&(c._onDemandMsgCount="onDemandMsgCount")),s.oldestMsgTimestampMs!=null&&s.hasOwnProperty("oldestMsgTimestampMs")&&(typeof s.oldestMsgTimestampMs=="number"?c.oldestMsgTimestampMs=g.longs===String?String(s.oldestMsgTimestampMs):s.oldestMsgTimestampMs:c.oldestMsgTimestampMs=g.longs===String?se(s.oldestMsgTimestampMs):g.longs===Number?ge(s.oldestMsgTimestampMs):s.oldestMsgTimestampMs,g.oneofs&&(c._oldestMsgTimestampMs="oldestMsgTimestampMs")),s.accountLid!=null&&s.hasOwnProperty("accountLid")&&(c.accountLid=s.accountLid,g.oneofs&&(c._accountLid="accountLid")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest"},a})(),i.PlaceholderMessageResendRequest=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.messageKey=p.proto.MessageKey.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest;if(s.messageKey!=null){if(typeof s.messageKey!="object")throw TypeError(".proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest.messageKey: object expected");g.messageKey=p.proto.MessageKey.fromObject(s.messageKey)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.messageKey!=null&&s.hasOwnProperty("messageKey")&&(c.messageKey=p.proto.MessageKey.toObject(s.messageKey,g),g.oneofs&&(c._messageKey="messageKey")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.PlaceholderMessageResendRequest"},a})(),i.RequestStickerReupload=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.fileSha256=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload;return s.fileSha256!=null&&(g.fileSha256=String(s.fileSha256)),g},a.toObject=function(s,g){g||(g={});var c={};return s.fileSha256!=null&&s.hasOwnProperty("fileSha256")&&(c.fileSha256=s.fileSha256,g.oneofs&&(c._fileSha256="fileSha256")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.RequestStickerReupload"},a})(),i.RequestUrlPreview=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.url=s.string();break}case 2:{d.includeHqThumbnail=s.bool();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview;return s.url!=null&&(g.url=String(s.url)),s.includeHqThumbnail!=null&&(g.includeHqThumbnail=!!s.includeHqThumbnail),g},a.toObject=function(s,g){g||(g={});var c={};return s.url!=null&&s.hasOwnProperty("url")&&(c.url=s.url,g.oneofs&&(c._url="url")),s.includeHqThumbnail!=null&&s.hasOwnProperty("includeHqThumbnail")&&(c.includeHqThumbnail=s.includeHqThumbnail,g.oneofs&&(c._includeHqThumbnail="includeHqThumbnail")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.RequestUrlPreview"},a})(),i.SyncDCollectionFatalRecoveryRequest=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.collectionName=s.string();break}case 2:{d.timestamp=s.int64();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest)return s;var g=new p.proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest;return s.collectionName!=null&&(g.collectionName=String(s.collectionName)),s.timestamp!=null&&(l.Long?(g.timestamp=l.Long.fromValue(s.timestamp)).unsigned=!1:typeof s.timestamp=="string"?g.timestamp=parseInt(s.timestamp,10):typeof s.timestamp=="number"?g.timestamp=s.timestamp:typeof s.timestamp=="object"&&(g.timestamp=new l.LongBits(s.timestamp.low>>>0,s.timestamp.high>>>0).toNumber())),g},a.toObject=function(s,g){g||(g={});var c={};return s.collectionName!=null&&s.hasOwnProperty("collectionName")&&(c.collectionName=s.collectionName,g.oneofs&&(c._collectionName="collectionName")),s.timestamp!=null&&s.hasOwnProperty("timestamp")&&(typeof s.timestamp=="number"?c.timestamp=g.longs===String?String(s.timestamp):s.timestamp:c.timestamp=g.longs===String?se(s.timestamp):g.longs===Number?ge(s.timestamp):s.timestamp,g.oneofs&&(c._timestamp="timestamp")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestMessage.SyncDCollectionFatalRecoveryRequest"},a})(),i})(),t.PeerDataOperationRequestResponseMessage=(function(){function i(a){if(this.peerDataOperationResult=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.peerDataOperationRequestType=A.int32();break}case 2:{c.stanzaId=A.string();break}case 3:{c.peerDataOperationResult&&c.peerDataOperationResult.length||(c.peerDataOperationResult=[]),c.peerDataOperationResult.push(p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PeerDataOperationRequestResponseMessage)return A;var r=new p.proto.Message.PeerDataOperationRequestResponseMessage;switch(A.peerDataOperationRequestType){default:if(typeof A.peerDataOperationRequestType=="number"){r.peerDataOperationRequestType=A.peerDataOperationRequestType;break}break;case"UPLOAD_STICKER":case 0:r.peerDataOperationRequestType=0;break;case"SEND_RECENT_STICKER_BOOTSTRAP":case 1:r.peerDataOperationRequestType=1;break;case"GENERATE_LINK_PREVIEW":case 2:r.peerDataOperationRequestType=2;break;case"HISTORY_SYNC_ON_DEMAND":case 3:r.peerDataOperationRequestType=3;break;case"PLACEHOLDER_MESSAGE_RESEND":case 4:r.peerDataOperationRequestType=4;break;case"WAFFLE_LINKING_NONCE_FETCH":case 5:r.peerDataOperationRequestType=5;break;case"FULL_HISTORY_SYNC_ON_DEMAND":case 6:r.peerDataOperationRequestType=6;break;case"COMPANION_META_NONCE_FETCH":case 7:r.peerDataOperationRequestType=7;break;case"COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY":case 8:r.peerDataOperationRequestType=8;break;case"COMPANION_CANONICAL_USER_NONCE_FETCH":case 9:r.peerDataOperationRequestType=9;break;case"HISTORY_SYNC_CHUNK_RETRY":case 10:r.peerDataOperationRequestType=10;break;case"GALAXY_FLOW_ACTION":case 11:r.peerDataOperationRequestType=11;break}if(A.stanzaId!=null&&(r.stanzaId=String(A.stanzaId)),A.peerDataOperationResult){if(!Array.isArray(A.peerDataOperationResult))throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.peerDataOperationResult: array expected");r.peerDataOperationResult=[];for(var s=0;s>>3){case 1:{d.mediaUploadResult=s.int32();break}case 2:{d.stickerMessage=p.proto.Message.StickerMessage.decode(s,s.uint32());break}case 3:{d.linkPreviewResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.decode(s,s.uint32());break}case 4:{d.placeholderMessageResendResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse.decode(s,s.uint32());break}case 5:{d.waffleNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse.decode(s,s.uint32());break}case 6:{d.fullHistorySyncOnDemandRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.decode(s,s.uint32());break}case 7:{d.companionMetaNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse.decode(s,s.uint32());break}case 8:{d.syncdSnapshotFatalRecoveryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse.decode(s,s.uint32());break}case 9:{d.companionCanonicalUserNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse.decode(s,s.uint32());break}case 10:{d.historySyncChunkRetryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult)return s;var g=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult;switch(s.mediaUploadResult){default:if(typeof s.mediaUploadResult=="number"){g.mediaUploadResult=s.mediaUploadResult;break}break;case"GENERAL_ERROR":case 0:g.mediaUploadResult=0;break;case"SUCCESS":case 1:g.mediaUploadResult=1;break;case"NOT_FOUND":case 2:g.mediaUploadResult=2;break;case"DECRYPTION_ERROR":case 3:g.mediaUploadResult=3;break}if(s.stickerMessage!=null){if(typeof s.stickerMessage!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.stickerMessage: object expected");g.stickerMessage=p.proto.Message.StickerMessage.fromObject(s.stickerMessage)}if(s.linkPreviewResponse!=null){if(typeof s.linkPreviewResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.linkPreviewResponse: object expected");g.linkPreviewResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.fromObject(s.linkPreviewResponse)}if(s.placeholderMessageResendResponse!=null){if(typeof s.placeholderMessageResendResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.placeholderMessageResendResponse: object expected");g.placeholderMessageResendResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse.fromObject(s.placeholderMessageResendResponse)}if(s.waffleNonceFetchRequestResponse!=null){if(typeof s.waffleNonceFetchRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.waffleNonceFetchRequestResponse: object expected");g.waffleNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse.fromObject(s.waffleNonceFetchRequestResponse)}if(s.fullHistorySyncOnDemandRequestResponse!=null){if(typeof s.fullHistorySyncOnDemandRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.fullHistorySyncOnDemandRequestResponse: object expected");g.fullHistorySyncOnDemandRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.fromObject(s.fullHistorySyncOnDemandRequestResponse)}if(s.companionMetaNonceFetchRequestResponse!=null){if(typeof s.companionMetaNonceFetchRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.companionMetaNonceFetchRequestResponse: object expected");g.companionMetaNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse.fromObject(s.companionMetaNonceFetchRequestResponse)}if(s.syncdSnapshotFatalRecoveryResponse!=null){if(typeof s.syncdSnapshotFatalRecoveryResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.syncdSnapshotFatalRecoveryResponse: object expected");g.syncdSnapshotFatalRecoveryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse.fromObject(s.syncdSnapshotFatalRecoveryResponse)}if(s.companionCanonicalUserNonceFetchRequestResponse!=null){if(typeof s.companionCanonicalUserNonceFetchRequestResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.companionCanonicalUserNonceFetchRequestResponse: object expected");g.companionCanonicalUserNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse.fromObject(s.companionCanonicalUserNonceFetchRequestResponse)}if(s.historySyncChunkRetryResponse!=null){if(typeof s.historySyncChunkRetryResponse!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.historySyncChunkRetryResponse: object expected");g.historySyncChunkRetryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse.fromObject(s.historySyncChunkRetryResponse)}return g},a.toObject=function(s,g){g||(g={});var c={};return s.mediaUploadResult!=null&&s.hasOwnProperty("mediaUploadResult")&&(c.mediaUploadResult=g.enums===String?p.proto.MediaRetryNotification.ResultType[s.mediaUploadResult]===void 0?s.mediaUploadResult:p.proto.MediaRetryNotification.ResultType[s.mediaUploadResult]:s.mediaUploadResult,g.oneofs&&(c._mediaUploadResult="mediaUploadResult")),s.stickerMessage!=null&&s.hasOwnProperty("stickerMessage")&&(c.stickerMessage=p.proto.Message.StickerMessage.toObject(s.stickerMessage,g),g.oneofs&&(c._stickerMessage="stickerMessage")),s.linkPreviewResponse!=null&&s.hasOwnProperty("linkPreviewResponse")&&(c.linkPreviewResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.toObject(s.linkPreviewResponse,g),g.oneofs&&(c._linkPreviewResponse="linkPreviewResponse")),s.placeholderMessageResendResponse!=null&&s.hasOwnProperty("placeholderMessageResendResponse")&&(c.placeholderMessageResendResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse.toObject(s.placeholderMessageResendResponse,g),g.oneofs&&(c._placeholderMessageResendResponse="placeholderMessageResendResponse")),s.waffleNonceFetchRequestResponse!=null&&s.hasOwnProperty("waffleNonceFetchRequestResponse")&&(c.waffleNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse.toObject(s.waffleNonceFetchRequestResponse,g),g.oneofs&&(c._waffleNonceFetchRequestResponse="waffleNonceFetchRequestResponse")),s.fullHistorySyncOnDemandRequestResponse!=null&&s.hasOwnProperty("fullHistorySyncOnDemandRequestResponse")&&(c.fullHistorySyncOnDemandRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.toObject(s.fullHistorySyncOnDemandRequestResponse,g),g.oneofs&&(c._fullHistorySyncOnDemandRequestResponse="fullHistorySyncOnDemandRequestResponse")),s.companionMetaNonceFetchRequestResponse!=null&&s.hasOwnProperty("companionMetaNonceFetchRequestResponse")&&(c.companionMetaNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse.toObject(s.companionMetaNonceFetchRequestResponse,g),g.oneofs&&(c._companionMetaNonceFetchRequestResponse="companionMetaNonceFetchRequestResponse")),s.syncdSnapshotFatalRecoveryResponse!=null&&s.hasOwnProperty("syncdSnapshotFatalRecoveryResponse")&&(c.syncdSnapshotFatalRecoveryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse.toObject(s.syncdSnapshotFatalRecoveryResponse,g),g.oneofs&&(c._syncdSnapshotFatalRecoveryResponse="syncdSnapshotFatalRecoveryResponse")),s.companionCanonicalUserNonceFetchRequestResponse!=null&&s.hasOwnProperty("companionCanonicalUserNonceFetchRequestResponse")&&(c.companionCanonicalUserNonceFetchRequestResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse.toObject(s.companionCanonicalUserNonceFetchRequestResponse,g),g.oneofs&&(c._companionCanonicalUserNonceFetchRequestResponse="companionCanonicalUserNonceFetchRequestResponse")),s.historySyncChunkRetryResponse!=null&&s.hasOwnProperty("historySyncChunkRetryResponse")&&(c.historySyncChunkRetryResponse=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse.toObject(s.historySyncChunkRetryResponse,g),g.oneofs&&(c._historySyncChunkRetryResponse="historySyncChunkRetryResponse")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult"},a.CompanionCanonicalUserNonceFetchResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.nonce=c.string();break}case 2:{f.waFbid=c.string();break}case 3:{f.forceRefresh=c.bool();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse;return c.nonce!=null&&(I.nonce=String(c.nonce)),c.waFbid!=null&&(I.waFbid=String(c.waFbid)),c.forceRefresh!=null&&(I.forceRefresh=!!c.forceRefresh),I},r.toObject=function(c,I){I||(I={});var d={};return c.nonce!=null&&c.hasOwnProperty("nonce")&&(d.nonce=c.nonce,I.oneofs&&(d._nonce="nonce")),c.waFbid!=null&&c.hasOwnProperty("waFbid")&&(d.waFbid=c.waFbid,I.oneofs&&(d._waFbid="waFbid")),c.forceRefresh!=null&&c.hasOwnProperty("forceRefresh")&&(d.forceRefresh=c.forceRefresh,I.oneofs&&(d._forceRefresh="forceRefresh")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionCanonicalUserNonceFetchResponse"},r})(),a.CompanionMetaNonceFetchResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.nonce=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse;return c.nonce!=null&&(I.nonce=String(c.nonce)),I},r.toObject=function(c,I){I||(I={});var d={};return c.nonce!=null&&c.hasOwnProperty("nonce")&&(d.nonce=c.nonce,I.oneofs&&(d._nonce="nonce")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.CompanionMetaNonceFetchResponse"},r})(),a.FullHistorySyncOnDemandRequestResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.decode(c,c.uint32());break}case 2:{f.responseCode=c.int32();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse;if(c.requestMetadata!=null){if(typeof c.requestMetadata!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse.requestMetadata: object expected");I.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.fromObject(c.requestMetadata)}switch(c.responseCode){default:if(typeof c.responseCode=="number"){I.responseCode=c.responseCode;break}break;case"REQUEST_SUCCESS":case 0:I.responseCode=0;break;case"REQUEST_TIME_EXPIRED":case 1:I.responseCode=1;break;case"DECLINED_SHARING_HISTORY":case 2:I.responseCode=2;break;case"GENERIC_ERROR":case 3:I.responseCode=3;break;case"ERROR_REQUEST_ON_NON_SMB_PRIMARY":case 4:I.responseCode=4;break;case"ERROR_HOSTED_DEVICE_NOT_CONNECTED":case 5:I.responseCode=5;break;case"ERROR_HOSTED_DEVICE_LOGIN_TIME_NOT_SET":case 6:I.responseCode=6;break}return I},r.toObject=function(c,I){I||(I={});var d={};return c.requestMetadata!=null&&c.hasOwnProperty("requestMetadata")&&(d.requestMetadata=p.proto.Message.FullHistorySyncOnDemandRequestMetadata.toObject(c.requestMetadata,I),I.oneofs&&(d._requestMetadata="requestMetadata")),c.responseCode!=null&&c.hasOwnProperty("responseCode")&&(d.responseCode=I.enums===String?p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandResponseCode[c.responseCode]===void 0?c.responseCode:p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandResponseCode[c.responseCode]:c.responseCode,I.oneofs&&(d._responseCode="responseCode")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.FullHistorySyncOnDemandRequestResponse"},r})(),a.FullHistorySyncOnDemandResponseCode=(function(){let r={},s=Object.create(r);return s[r[0]="REQUEST_SUCCESS"]=0,s[r[1]="REQUEST_TIME_EXPIRED"]=1,s[r[2]="DECLINED_SHARING_HISTORY"]=2,s[r[3]="GENERIC_ERROR"]=3,s[r[4]="ERROR_REQUEST_ON_NON_SMB_PRIMARY"]=4,s[r[5]="ERROR_HOSTED_DEVICE_NOT_CONNECTED"]=5,s[r[6]="ERROR_HOSTED_DEVICE_LOGIN_TIME_NOT_SET"]=6,s})(),a.HistorySyncChunkRetryResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.syncType=c.int32();break}case 2:{f.chunkOrder=c.uint32();break}case 3:{f.requestId=c.string();break}case 4:{f.responseCode=c.int32();break}case 5:{f.canRecover=c.bool();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse;switch(c.syncType){default:if(typeof c.syncType=="number"){I.syncType=c.syncType;break}break;case"INITIAL_BOOTSTRAP":case 0:I.syncType=0;break;case"INITIAL_STATUS_V3":case 1:I.syncType=1;break;case"FULL":case 2:I.syncType=2;break;case"RECENT":case 3:I.syncType=3;break;case"PUSH_NAME":case 4:I.syncType=4;break;case"NON_BLOCKING_DATA":case 5:I.syncType=5;break;case"ON_DEMAND":case 6:I.syncType=6;break;case"NO_HISTORY":case 7:I.syncType=7;break;case"MESSAGE_ACCESS_STATUS":case 8:I.syncType=8;break}switch(c.chunkOrder!=null&&(I.chunkOrder=c.chunkOrder>>>0),c.requestId!=null&&(I.requestId=String(c.requestId)),c.responseCode){default:if(typeof c.responseCode=="number"){I.responseCode=c.responseCode;break}break;case"GENERATION_ERROR":case 1:I.responseCode=1;break;case"CHUNK_CONSUMED":case 2:I.responseCode=2;break;case"TIMEOUT":case 3:I.responseCode=3;break;case"SESSION_EXHAUSTED":case 4:I.responseCode=4;break;case"CHUNK_EXHAUSTED":case 5:I.responseCode=5;break;case"DUPLICATED_REQUEST":case 6:I.responseCode=6;break}return c.canRecover!=null&&(I.canRecover=!!c.canRecover),I},r.toObject=function(c,I){I||(I={});var d={};return c.syncType!=null&&c.hasOwnProperty("syncType")&&(d.syncType=I.enums===String?p.proto.Message.HistorySyncType[c.syncType]===void 0?c.syncType:p.proto.Message.HistorySyncType[c.syncType]:c.syncType,I.oneofs&&(d._syncType="syncType")),c.chunkOrder!=null&&c.hasOwnProperty("chunkOrder")&&(d.chunkOrder=c.chunkOrder,I.oneofs&&(d._chunkOrder="chunkOrder")),c.requestId!=null&&c.hasOwnProperty("requestId")&&(d.requestId=c.requestId,I.oneofs&&(d._requestId="requestId")),c.responseCode!=null&&c.hasOwnProperty("responseCode")&&(d.responseCode=I.enums===String?p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponseCode[c.responseCode]===void 0?c.responseCode:p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponseCode[c.responseCode]:c.responseCode,I.oneofs&&(d._responseCode="responseCode")),c.canRecover!=null&&c.hasOwnProperty("canRecover")&&(d.canRecover=c.canRecover,I.oneofs&&(d._canRecover="canRecover")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.HistorySyncChunkRetryResponse"},r})(),a.HistorySyncChunkRetryResponseCode=(function(){let r={},s=Object.create(r);return s[r[1]="GENERATION_ERROR"]=1,s[r[2]="CHUNK_CONSUMED"]=2,s[r[3]="TIMEOUT"]=3,s[r[4]="SESSION_EXHAUSTED"]=4,s[r[5]="CHUNK_EXHAUSTED"]=5,s[r[6]="DUPLICATED_REQUEST"]=6,s})(),a.LinkPreviewResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.url=c.string();break}case 2:{f.title=c.string();break}case 3:{f.description=c.string();break}case 4:{f.thumbData=c.bytes();break}case 6:{f.matchText=c.string();break}case 7:{f.previewType=c.string();break}case 8:{f.hqThumbnail=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail.decode(c,c.uint32());break}case 9:{f.previewMetadata=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata.decode(c,c.uint32());break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse;if(c.url!=null&&(I.url=String(c.url)),c.title!=null&&(I.title=String(c.title)),c.description!=null&&(I.description=String(c.description)),c.thumbData!=null&&(typeof c.thumbData=="string"?l.base64.decode(c.thumbData,I.thumbData=l.newBuffer(l.base64.length(c.thumbData)),0):c.thumbData.length>=0&&(I.thumbData=c.thumbData)),c.matchText!=null&&(I.matchText=String(c.matchText)),c.previewType!=null&&(I.previewType=String(c.previewType)),c.hqThumbnail!=null){if(typeof c.hqThumbnail!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.hqThumbnail: object expected");I.hqThumbnail=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail.fromObject(c.hqThumbnail)}if(c.previewMetadata!=null){if(typeof c.previewMetadata!="object")throw TypeError(".proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.previewMetadata: object expected");I.previewMetadata=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata.fromObject(c.previewMetadata)}return I},r.toObject=function(c,I){I||(I={});var d={};return c.url!=null&&c.hasOwnProperty("url")&&(d.url=c.url,I.oneofs&&(d._url="url")),c.title!=null&&c.hasOwnProperty("title")&&(d.title=c.title,I.oneofs&&(d._title="title")),c.description!=null&&c.hasOwnProperty("description")&&(d.description=c.description,I.oneofs&&(d._description="description")),c.thumbData!=null&&c.hasOwnProperty("thumbData")&&(d.thumbData=I.bytes===String?l.base64.encode(c.thumbData,0,c.thumbData.length):I.bytes===Array?Array.prototype.slice.call(c.thumbData):c.thumbData,I.oneofs&&(d._thumbData="thumbData")),c.matchText!=null&&c.hasOwnProperty("matchText")&&(d.matchText=c.matchText,I.oneofs&&(d._matchText="matchText")),c.previewType!=null&&c.hasOwnProperty("previewType")&&(d.previewType=c.previewType,I.oneofs&&(d._previewType="previewType")),c.hqThumbnail!=null&&c.hasOwnProperty("hqThumbnail")&&(d.hqThumbnail=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail.toObject(c.hqThumbnail,I),I.oneofs&&(d._hqThumbnail="hqThumbnail")),c.previewMetadata!=null&&c.hasOwnProperty("previewMetadata")&&(d.previewMetadata=p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata.toObject(c.previewMetadata,I),I.oneofs&&(d._previewMetadata="previewMetadata")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse"},r.LinkPreviewHighQualityThumbnail=(function(){function g(I){if(I)for(var d=Object.keys(I),B=0;B>>3){case 1:{y.directPath=d.string();break}case 2:{y.thumbHash=d.string();break}case 3:{y.encThumbHash=d.string();break}case 4:{y.mediaKey=d.bytes();break}case 5:{y.mediaKeyTimestampMs=d.int64();break}case 6:{y.thumbWidth=d.int32();break}case 7:{y.thumbHeight=d.int32();break}default:d.skipType(m&7);break}}return y},g.fromObject=function(d){if(d instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail)return d;var B=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail;return d.directPath!=null&&(B.directPath=String(d.directPath)),d.thumbHash!=null&&(B.thumbHash=String(d.thumbHash)),d.encThumbHash!=null&&(B.encThumbHash=String(d.encThumbHash)),d.mediaKey!=null&&(typeof d.mediaKey=="string"?l.base64.decode(d.mediaKey,B.mediaKey=l.newBuffer(l.base64.length(d.mediaKey)),0):d.mediaKey.length>=0&&(B.mediaKey=d.mediaKey)),d.mediaKeyTimestampMs!=null&&(l.Long?(B.mediaKeyTimestampMs=l.Long.fromValue(d.mediaKeyTimestampMs)).unsigned=!1:typeof d.mediaKeyTimestampMs=="string"?B.mediaKeyTimestampMs=parseInt(d.mediaKeyTimestampMs,10):typeof d.mediaKeyTimestampMs=="number"?B.mediaKeyTimestampMs=d.mediaKeyTimestampMs:typeof d.mediaKeyTimestampMs=="object"&&(B.mediaKeyTimestampMs=new l.LongBits(d.mediaKeyTimestampMs.low>>>0,d.mediaKeyTimestampMs.high>>>0).toNumber())),d.thumbWidth!=null&&(B.thumbWidth=d.thumbWidth|0),d.thumbHeight!=null&&(B.thumbHeight=d.thumbHeight|0),B},g.toObject=function(d,B){B||(B={});var f={};return d.directPath!=null&&d.hasOwnProperty("directPath")&&(f.directPath=d.directPath,B.oneofs&&(f._directPath="directPath")),d.thumbHash!=null&&d.hasOwnProperty("thumbHash")&&(f.thumbHash=d.thumbHash,B.oneofs&&(f._thumbHash="thumbHash")),d.encThumbHash!=null&&d.hasOwnProperty("encThumbHash")&&(f.encThumbHash=d.encThumbHash,B.oneofs&&(f._encThumbHash="encThumbHash")),d.mediaKey!=null&&d.hasOwnProperty("mediaKey")&&(f.mediaKey=B.bytes===String?l.base64.encode(d.mediaKey,0,d.mediaKey.length):B.bytes===Array?Array.prototype.slice.call(d.mediaKey):d.mediaKey,B.oneofs&&(f._mediaKey="mediaKey")),d.mediaKeyTimestampMs!=null&&d.hasOwnProperty("mediaKeyTimestampMs")&&(typeof d.mediaKeyTimestampMs=="number"?f.mediaKeyTimestampMs=B.longs===String?String(d.mediaKeyTimestampMs):d.mediaKeyTimestampMs:f.mediaKeyTimestampMs=B.longs===String?se(d.mediaKeyTimestampMs):B.longs===Number?ge(d.mediaKeyTimestampMs):d.mediaKeyTimestampMs,B.oneofs&&(f._mediaKeyTimestampMs="mediaKeyTimestampMs")),d.thumbWidth!=null&&d.hasOwnProperty("thumbWidth")&&(f.thumbWidth=d.thumbWidth,B.oneofs&&(f._thumbWidth="thumbWidth")),d.thumbHeight!=null&&d.hasOwnProperty("thumbHeight")&&(f.thumbHeight=d.thumbHeight,B.oneofs&&(f._thumbHeight="thumbHeight")),f},g.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},g.getTypeUrl=function(d){return d===void 0&&(d="type.googleapis.com"),d+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.LinkPreviewHighQualityThumbnail"},g})(),r.PaymentLinkPreviewMetadata=(function(){function g(I){if(I)for(var d=Object.keys(I),B=0;B>>3){case 1:{y.isBusinessVerified=d.bool();break}case 2:{y.providerName=d.string();break}default:d.skipType(m&7);break}}return y},g.fromObject=function(d){if(d instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata)return d;var B=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata;return d.isBusinessVerified!=null&&(B.isBusinessVerified=!!d.isBusinessVerified),d.providerName!=null&&(B.providerName=String(d.providerName)),B},g.toObject=function(d,B){B||(B={});var f={};return d.isBusinessVerified!=null&&d.hasOwnProperty("isBusinessVerified")&&(f.isBusinessVerified=d.isBusinessVerified,B.oneofs&&(f._isBusinessVerified="isBusinessVerified")),d.providerName!=null&&d.hasOwnProperty("providerName")&&(f.providerName=d.providerName,B.oneofs&&(f._providerName="providerName")),f},g.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},g.getTypeUrl=function(d){return d===void 0&&(d="type.googleapis.com"),d+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.LinkPreviewResponse.PaymentLinkPreviewMetadata"},g})(),r})(),a.PlaceholderMessageResendResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.webMessageInfoBytes=c.bytes();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse;return c.webMessageInfoBytes!=null&&(typeof c.webMessageInfoBytes=="string"?l.base64.decode(c.webMessageInfoBytes,I.webMessageInfoBytes=l.newBuffer(l.base64.length(c.webMessageInfoBytes)),0):c.webMessageInfoBytes.length>=0&&(I.webMessageInfoBytes=c.webMessageInfoBytes)),I},r.toObject=function(c,I){I||(I={});var d={};return c.webMessageInfoBytes!=null&&c.hasOwnProperty("webMessageInfoBytes")&&(d.webMessageInfoBytes=I.bytes===String?l.base64.encode(c.webMessageInfoBytes,0,c.webMessageInfoBytes.length):I.bytes===Array?Array.prototype.slice.call(c.webMessageInfoBytes):c.webMessageInfoBytes,I.oneofs&&(d._webMessageInfoBytes="webMessageInfoBytes")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.PlaceholderMessageResendResponse"},r})(),a.SyncDSnapshotFatalRecoveryResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.collectionSnapshot=c.bytes();break}case 2:{f.isCompressed=c.bool();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse;return c.collectionSnapshot!=null&&(typeof c.collectionSnapshot=="string"?l.base64.decode(c.collectionSnapshot,I.collectionSnapshot=l.newBuffer(l.base64.length(c.collectionSnapshot)),0):c.collectionSnapshot.length>=0&&(I.collectionSnapshot=c.collectionSnapshot)),c.isCompressed!=null&&(I.isCompressed=!!c.isCompressed),I},r.toObject=function(c,I){I||(I={});var d={};return c.collectionSnapshot!=null&&c.hasOwnProperty("collectionSnapshot")&&(d.collectionSnapshot=I.bytes===String?l.base64.encode(c.collectionSnapshot,0,c.collectionSnapshot.length):I.bytes===Array?Array.prototype.slice.call(c.collectionSnapshot):c.collectionSnapshot,I.oneofs&&(d._collectionSnapshot="collectionSnapshot")),c.isCompressed!=null&&c.hasOwnProperty("isCompressed")&&(d.isCompressed=c.isCompressed,I.oneofs&&(d._isCompressed="isCompressed")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.SyncDSnapshotFatalRecoveryResponse"},r})(),a.WaffleNonceFetchResponse=(function(){function r(g){if(g)for(var c=Object.keys(g),I=0;I>>3){case 1:{f.nonce=c.string();break}case 2:{f.waEntFbid=c.string();break}default:c.skipType(Q&7);break}}return f},r.fromObject=function(c){if(c instanceof p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse)return c;var I=new p.proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse;return c.nonce!=null&&(I.nonce=String(c.nonce)),c.waEntFbid!=null&&(I.waEntFbid=String(c.waEntFbid)),I},r.toObject=function(c,I){I||(I={});var d={};return c.nonce!=null&&c.hasOwnProperty("nonce")&&(d.nonce=c.nonce,I.oneofs&&(d._nonce="nonce")),c.waEntFbid!=null&&c.hasOwnProperty("waEntFbid")&&(d.waEntFbid=c.waEntFbid,I.oneofs&&(d._waEntFbid="waEntFbid")),d},r.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},r.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.WaffleNonceFetchResponse"},r})(),a})(),i})(),t.PeerDataOperationRequestType=(function(){let i={},e=Object.create(i);return e[i[0]="UPLOAD_STICKER"]=0,e[i[1]="SEND_RECENT_STICKER_BOOTSTRAP"]=1,e[i[2]="GENERATE_LINK_PREVIEW"]=2,e[i[3]="HISTORY_SYNC_ON_DEMAND"]=3,e[i[4]="PLACEHOLDER_MESSAGE_RESEND"]=4,e[i[5]="WAFFLE_LINKING_NONCE_FETCH"]=5,e[i[6]="FULL_HISTORY_SYNC_ON_DEMAND"]=6,e[i[7]="COMPANION_META_NONCE_FETCH"]=7,e[i[8]="COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY"]=8,e[i[9]="COMPANION_CANONICAL_USER_NONCE_FETCH"]=9,e[i[10]="HISTORY_SYNC_CHUNK_RETRY"]=10,e[i[11]="GALAXY_FLOW_ACTION"]=11,e})(),t.PinInChatMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.type=A.int32();break}case 3:{c.senderTimestampMs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PinInChatMessage)return A;var r=new p.proto.Message.PinInChatMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.PinInChatMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNKNOWN_TYPE":case 0:r.type=0;break;case"PIN_FOR_ALL":case 1:r.type=1;break;case"UNPIN_FOR_ALL":case 2:r.type=2;break}return A.senderTimestampMs!=null&&(l.Long?(r.senderTimestampMs=l.Long.fromValue(A.senderTimestampMs)).unsigned=!1:typeof A.senderTimestampMs=="string"?r.senderTimestampMs=parseInt(A.senderTimestampMs,10):typeof A.senderTimestampMs=="number"?r.senderTimestampMs=A.senderTimestampMs:typeof A.senderTimestampMs=="object"&&(r.senderTimestampMs=new l.LongBits(A.senderTimestampMs.low>>>0,A.senderTimestampMs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.PinInChatMessage.Type[A.type]===void 0?A.type:p.proto.Message.PinInChatMessage.Type[A.type]:A.type,r.oneofs&&(s._type="type")),A.senderTimestampMs!=null&&A.hasOwnProperty("senderTimestampMs")&&(typeof A.senderTimestampMs=="number"?s.senderTimestampMs=r.longs===String?String(A.senderTimestampMs):A.senderTimestampMs:s.senderTimestampMs=r.longs===String?se(A.senderTimestampMs):r.longs===Number?ge(A.senderTimestampMs):A.senderTimestampMs,r.oneofs&&(s._senderTimestampMs="senderTimestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PinInChatMessage"},i.Type=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN_TYPE"]=0,A[a[1]="PIN_FOR_ALL"]=1,A[a[2]="UNPIN_FOR_ALL"]=2,A})(),i})(),t.PlaceholderMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.type=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PlaceholderMessage)return A;var r=new p.proto.Message.PlaceholderMessage;switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"MASK_LINKED_DEVICES":case 0:r.type=0;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.PlaceholderMessage.PlaceholderType[A.type]===void 0?A.type:p.proto.Message.PlaceholderMessage.PlaceholderType[A.type]:A.type,r.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PlaceholderMessage"},i.PlaceholderType=(function(){let a={},A=Object.create(a);return A[a[0]="MASK_LINKED_DEVICES"]=0,A})(),i})(),t.PollContentType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="TEXT"]=1,e[i[2]="IMAGE"]=2,e})(),t.PollCreationMessage=(function(){function i(a){if(this.options=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.encKey=A.bytes();break}case 2:{c.name=A.string();break}case 3:{c.options&&c.options.length||(c.options=[]),c.options.push(p.proto.Message.PollCreationMessage.Option.decode(A,A.uint32()));break}case 4:{c.selectableOptionsCount=A.uint32();break}case 5:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 6:{c.pollContentType=A.int32();break}case 7:{c.pollType=A.int32();break}case 8:{c.correctAnswer=p.proto.Message.PollCreationMessage.Option.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PollCreationMessage)return A;var r=new p.proto.Message.PollCreationMessage;if(A.encKey!=null&&(typeof A.encKey=="string"?l.base64.decode(A.encKey,r.encKey=l.newBuffer(l.base64.length(A.encKey)),0):A.encKey.length>=0&&(r.encKey=A.encKey)),A.name!=null&&(r.name=String(A.name)),A.options){if(!Array.isArray(A.options))throw TypeError(".proto.Message.PollCreationMessage.options: array expected");r.options=[];for(var s=0;s>>0),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.PollCreationMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.pollContentType){default:if(typeof A.pollContentType=="number"){r.pollContentType=A.pollContentType;break}break;case"UNKNOWN":case 0:r.pollContentType=0;break;case"TEXT":case 1:r.pollContentType=1;break;case"IMAGE":case 2:r.pollContentType=2;break}switch(A.pollType){default:if(typeof A.pollType=="number"){r.pollType=A.pollType;break}break;case"POLL":case 0:r.pollType=0;break;case"QUIZ":case 1:r.pollType=1;break}if(A.correctAnswer!=null){if(typeof A.correctAnswer!="object")throw TypeError(".proto.Message.PollCreationMessage.correctAnswer: object expected");r.correctAnswer=p.proto.Message.PollCreationMessage.Option.fromObject(A.correctAnswer)}return r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.options=[]),A.encKey!=null&&A.hasOwnProperty("encKey")&&(s.encKey=r.bytes===String?l.base64.encode(A.encKey,0,A.encKey.length):r.bytes===Array?Array.prototype.slice.call(A.encKey):A.encKey,r.oneofs&&(s._encKey="encKey")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.options&&A.options.length){s.options=[];for(var g=0;g>>3){case 1:{d.optionName=s.string();break}case 2:{d.optionHash=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PollCreationMessage.Option)return s;var g=new p.proto.Message.PollCreationMessage.Option;return s.optionName!=null&&(g.optionName=String(s.optionName)),s.optionHash!=null&&(g.optionHash=String(s.optionHash)),g},a.toObject=function(s,g){g||(g={});var c={};return s.optionName!=null&&s.hasOwnProperty("optionName")&&(c.optionName=s.optionName,g.oneofs&&(c._optionName="optionName")),s.optionHash!=null&&s.hasOwnProperty("optionHash")&&(c.optionHash=s.optionHash,g.oneofs&&(c._optionHash="optionHash")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PollCreationMessage.Option"},a})(),i})(),t.PollEncValue=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.encPayload=A.bytes();break}case 2:{c.encIv=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PollEncValue)return A;var r=new p.proto.Message.PollEncValue;return A.encPayload!=null&&(typeof A.encPayload=="string"?l.base64.decode(A.encPayload,r.encPayload=l.newBuffer(l.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(r.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?l.base64.decode(A.encIv,r.encIv=l.newBuffer(l.base64.length(A.encIv)),0):A.encIv.length>=0&&(r.encIv=A.encIv)),r},i.toObject=function(A,r){r||(r={});var s={};return A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=r.bytes===String?l.base64.encode(A.encPayload,0,A.encPayload.length):r.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,r.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=r.bytes===String?l.base64.encode(A.encIv,0,A.encIv.length):r.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,r.oneofs&&(s._encIv="encIv")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PollEncValue"},i})(),t.PollResultSnapshotMessage=(function(){function i(a){if(this.pollVotes=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}case 2:{c.pollVotes&&c.pollVotes.length||(c.pollVotes=[]),c.pollVotes.push(p.proto.Message.PollResultSnapshotMessage.PollVote.decode(A,A.uint32()));break}case 3:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.pollType=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PollResultSnapshotMessage)return A;var r=new p.proto.Message.PollResultSnapshotMessage;if(A.name!=null&&(r.name=String(A.name)),A.pollVotes){if(!Array.isArray(A.pollVotes))throw TypeError(".proto.Message.PollResultSnapshotMessage.pollVotes: array expected");r.pollVotes=[];for(var s=0;s>>3){case 1:{d.optionName=s.string();break}case 2:{d.optionVoteCount=s.int64();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.PollResultSnapshotMessage.PollVote)return s;var g=new p.proto.Message.PollResultSnapshotMessage.PollVote;return s.optionName!=null&&(g.optionName=String(s.optionName)),s.optionVoteCount!=null&&(l.Long?(g.optionVoteCount=l.Long.fromValue(s.optionVoteCount)).unsigned=!1:typeof s.optionVoteCount=="string"?g.optionVoteCount=parseInt(s.optionVoteCount,10):typeof s.optionVoteCount=="number"?g.optionVoteCount=s.optionVoteCount:typeof s.optionVoteCount=="object"&&(g.optionVoteCount=new l.LongBits(s.optionVoteCount.low>>>0,s.optionVoteCount.high>>>0).toNumber())),g},a.toObject=function(s,g){g||(g={});var c={};return s.optionName!=null&&s.hasOwnProperty("optionName")&&(c.optionName=s.optionName,g.oneofs&&(c._optionName="optionName")),s.optionVoteCount!=null&&s.hasOwnProperty("optionVoteCount")&&(typeof s.optionVoteCount=="number"?c.optionVoteCount=g.longs===String?String(s.optionVoteCount):s.optionVoteCount:c.optionVoteCount=g.longs===String?se(s.optionVoteCount):g.longs===Number?ge(s.optionVoteCount):s.optionVoteCount,g.oneofs&&(c._optionVoteCount="optionVoteCount")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.PollResultSnapshotMessage.PollVote"},a})(),i})(),t.PollType=(function(){let i={},e=Object.create(i);return e[i[0]="POLL"]=0,e[i[1]="QUIZ"]=1,e})(),t.PollUpdateMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.pollCreationMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.vote=p.proto.Message.PollEncValue.decode(A,A.uint32());break}case 3:{c.metadata=p.proto.Message.PollUpdateMessageMetadata.decode(A,A.uint32());break}case 4:{c.senderTimestampMs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.PollUpdateMessage)return A;var r=new p.proto.Message.PollUpdateMessage;if(A.pollCreationMessageKey!=null){if(typeof A.pollCreationMessageKey!="object")throw TypeError(".proto.Message.PollUpdateMessage.pollCreationMessageKey: object expected");r.pollCreationMessageKey=p.proto.MessageKey.fromObject(A.pollCreationMessageKey)}if(A.vote!=null){if(typeof A.vote!="object")throw TypeError(".proto.Message.PollUpdateMessage.vote: object expected");r.vote=p.proto.Message.PollEncValue.fromObject(A.vote)}if(A.metadata!=null){if(typeof A.metadata!="object")throw TypeError(".proto.Message.PollUpdateMessage.metadata: object expected");r.metadata=p.proto.Message.PollUpdateMessageMetadata.fromObject(A.metadata)}return A.senderTimestampMs!=null&&(l.Long?(r.senderTimestampMs=l.Long.fromValue(A.senderTimestampMs)).unsigned=!1:typeof A.senderTimestampMs=="string"?r.senderTimestampMs=parseInt(A.senderTimestampMs,10):typeof A.senderTimestampMs=="number"?r.senderTimestampMs=A.senderTimestampMs:typeof A.senderTimestampMs=="object"&&(r.senderTimestampMs=new l.LongBits(A.senderTimestampMs.low>>>0,A.senderTimestampMs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.pollCreationMessageKey!=null&&A.hasOwnProperty("pollCreationMessageKey")&&(s.pollCreationMessageKey=p.proto.MessageKey.toObject(A.pollCreationMessageKey,r),r.oneofs&&(s._pollCreationMessageKey="pollCreationMessageKey")),A.vote!=null&&A.hasOwnProperty("vote")&&(s.vote=p.proto.Message.PollEncValue.toObject(A.vote,r),r.oneofs&&(s._vote="vote")),A.metadata!=null&&A.hasOwnProperty("metadata")&&(s.metadata=p.proto.Message.PollUpdateMessageMetadata.toObject(A.metadata,r),r.oneofs&&(s._metadata="metadata")),A.senderTimestampMs!=null&&A.hasOwnProperty("senderTimestampMs")&&(typeof A.senderTimestampMs=="number"?s.senderTimestampMs=r.longs===String?String(A.senderTimestampMs):A.senderTimestampMs:s.senderTimestampMs=r.longs===String?se(A.senderTimestampMs):r.longs===Number?ge(A.senderTimestampMs):A.senderTimestampMs,r.oneofs&&(s._senderTimestampMs="senderTimestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.PollUpdateMessage"},i})(),t.PollUpdateMessageMetadata=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){default:a.skipType(c&7);break}}return g},i.fromObject=function(a){return a instanceof p.proto.Message.PollUpdateMessageMetadata?a:new p.proto.Message.PollUpdateMessageMetadata},i.toObject=function(){return{}},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Message.PollUpdateMessageMetadata"},i})(),t.PollVoteMessage=(function(){function i(e){if(this.selectedOptions=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.selectedOptions&&g.selectedOptions.length||(g.selectedOptions=[]),g.selectedOptions.push(a.bytes());break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.Message.PollVoteMessage)return a;var A=new p.proto.Message.PollVoteMessage;if(a.selectedOptions){if(!Array.isArray(a.selectedOptions))throw TypeError(".proto.Message.PollVoteMessage.selectedOptions: array expected");A.selectedOptions=[];for(var r=0;r=0&&(A.selectedOptions[r]=a.selectedOptions[r])}return A},i.toObject=function(a,A){A||(A={});var r={};if((A.arrays||A.defaults)&&(r.selectedOptions=[]),a.selectedOptions&&a.selectedOptions.length){r.selectedOptions=[];for(var s=0;s>>3){case 1:{c.product=p.proto.Message.ProductMessage.ProductSnapshot.decode(A,A.uint32());break}case 2:{c.businessOwnerJid=A.string();break}case 4:{c.catalog=p.proto.Message.ProductMessage.CatalogSnapshot.decode(A,A.uint32());break}case 5:{c.body=A.string();break}case 6:{c.footer=A.string();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ProductMessage)return A;var r=new p.proto.Message.ProductMessage;if(A.product!=null){if(typeof A.product!="object")throw TypeError(".proto.Message.ProductMessage.product: object expected");r.product=p.proto.Message.ProductMessage.ProductSnapshot.fromObject(A.product)}if(A.businessOwnerJid!=null&&(r.businessOwnerJid=String(A.businessOwnerJid)),A.catalog!=null){if(typeof A.catalog!="object")throw TypeError(".proto.Message.ProductMessage.catalog: object expected");r.catalog=p.proto.Message.ProductMessage.CatalogSnapshot.fromObject(A.catalog)}if(A.body!=null&&(r.body=String(A.body)),A.footer!=null&&(r.footer=String(A.footer)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.ProductMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.product!=null&&A.hasOwnProperty("product")&&(s.product=p.proto.Message.ProductMessage.ProductSnapshot.toObject(A.product,r),r.oneofs&&(s._product="product")),A.businessOwnerJid!=null&&A.hasOwnProperty("businessOwnerJid")&&(s.businessOwnerJid=A.businessOwnerJid,r.oneofs&&(s._businessOwnerJid="businessOwnerJid")),A.catalog!=null&&A.hasOwnProperty("catalog")&&(s.catalog=p.proto.Message.ProductMessage.CatalogSnapshot.toObject(A.catalog,r),r.oneofs&&(s._catalog="catalog")),A.body!=null&&A.hasOwnProperty("body")&&(s.body=A.body,r.oneofs&&(s._body="body")),A.footer!=null&&A.hasOwnProperty("footer")&&(s.footer=A.footer,r.oneofs&&(s._footer="footer")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ProductMessage"},i.CatalogSnapshot=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.catalogImage=p.proto.Message.ImageMessage.decode(s,s.uint32());break}case 2:{d.title=s.string();break}case 3:{d.description=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ProductMessage.CatalogSnapshot)return s;var g=new p.proto.Message.ProductMessage.CatalogSnapshot;if(s.catalogImage!=null){if(typeof s.catalogImage!="object")throw TypeError(".proto.Message.ProductMessage.CatalogSnapshot.catalogImage: object expected");g.catalogImage=p.proto.Message.ImageMessage.fromObject(s.catalogImage)}return s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),g},a.toObject=function(s,g){g||(g={});var c={};return s.catalogImage!=null&&s.hasOwnProperty("catalogImage")&&(c.catalogImage=p.proto.Message.ImageMessage.toObject(s.catalogImage,g),g.oneofs&&(c._catalogImage="catalogImage")),s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ProductMessage.CatalogSnapshot"},a})(),i.ProductSnapshot=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.productImage=p.proto.Message.ImageMessage.decode(s,s.uint32());break}case 2:{d.productId=s.string();break}case 3:{d.title=s.string();break}case 4:{d.description=s.string();break}case 5:{d.currencyCode=s.string();break}case 6:{d.priceAmount1000=s.int64();break}case 7:{d.retailerId=s.string();break}case 8:{d.url=s.string();break}case 9:{d.productImageCount=s.uint32();break}case 11:{d.firstImageId=s.string();break}case 12:{d.salePriceAmount1000=s.int64();break}case 13:{d.signedUrl=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.ProductMessage.ProductSnapshot)return s;var g=new p.proto.Message.ProductMessage.ProductSnapshot;if(s.productImage!=null){if(typeof s.productImage!="object")throw TypeError(".proto.Message.ProductMessage.ProductSnapshot.productImage: object expected");g.productImage=p.proto.Message.ImageMessage.fromObject(s.productImage)}return s.productId!=null&&(g.productId=String(s.productId)),s.title!=null&&(g.title=String(s.title)),s.description!=null&&(g.description=String(s.description)),s.currencyCode!=null&&(g.currencyCode=String(s.currencyCode)),s.priceAmount1000!=null&&(l.Long?(g.priceAmount1000=l.Long.fromValue(s.priceAmount1000)).unsigned=!1:typeof s.priceAmount1000=="string"?g.priceAmount1000=parseInt(s.priceAmount1000,10):typeof s.priceAmount1000=="number"?g.priceAmount1000=s.priceAmount1000:typeof s.priceAmount1000=="object"&&(g.priceAmount1000=new l.LongBits(s.priceAmount1000.low>>>0,s.priceAmount1000.high>>>0).toNumber())),s.retailerId!=null&&(g.retailerId=String(s.retailerId)),s.url!=null&&(g.url=String(s.url)),s.productImageCount!=null&&(g.productImageCount=s.productImageCount>>>0),s.firstImageId!=null&&(g.firstImageId=String(s.firstImageId)),s.salePriceAmount1000!=null&&(l.Long?(g.salePriceAmount1000=l.Long.fromValue(s.salePriceAmount1000)).unsigned=!1:typeof s.salePriceAmount1000=="string"?g.salePriceAmount1000=parseInt(s.salePriceAmount1000,10):typeof s.salePriceAmount1000=="number"?g.salePriceAmount1000=s.salePriceAmount1000:typeof s.salePriceAmount1000=="object"&&(g.salePriceAmount1000=new l.LongBits(s.salePriceAmount1000.low>>>0,s.salePriceAmount1000.high>>>0).toNumber())),s.signedUrl!=null&&(g.signedUrl=String(s.signedUrl)),g},a.toObject=function(s,g){g||(g={});var c={};return s.productImage!=null&&s.hasOwnProperty("productImage")&&(c.productImage=p.proto.Message.ImageMessage.toObject(s.productImage,g),g.oneofs&&(c._productImage="productImage")),s.productId!=null&&s.hasOwnProperty("productId")&&(c.productId=s.productId,g.oneofs&&(c._productId="productId")),s.title!=null&&s.hasOwnProperty("title")&&(c.title=s.title,g.oneofs&&(c._title="title")),s.description!=null&&s.hasOwnProperty("description")&&(c.description=s.description,g.oneofs&&(c._description="description")),s.currencyCode!=null&&s.hasOwnProperty("currencyCode")&&(c.currencyCode=s.currencyCode,g.oneofs&&(c._currencyCode="currencyCode")),s.priceAmount1000!=null&&s.hasOwnProperty("priceAmount1000")&&(typeof s.priceAmount1000=="number"?c.priceAmount1000=g.longs===String?String(s.priceAmount1000):s.priceAmount1000:c.priceAmount1000=g.longs===String?se(s.priceAmount1000):g.longs===Number?ge(s.priceAmount1000):s.priceAmount1000,g.oneofs&&(c._priceAmount1000="priceAmount1000")),s.retailerId!=null&&s.hasOwnProperty("retailerId")&&(c.retailerId=s.retailerId,g.oneofs&&(c._retailerId="retailerId")),s.url!=null&&s.hasOwnProperty("url")&&(c.url=s.url,g.oneofs&&(c._url="url")),s.productImageCount!=null&&s.hasOwnProperty("productImageCount")&&(c.productImageCount=s.productImageCount,g.oneofs&&(c._productImageCount="productImageCount")),s.firstImageId!=null&&s.hasOwnProperty("firstImageId")&&(c.firstImageId=s.firstImageId,g.oneofs&&(c._firstImageId="firstImageId")),s.salePriceAmount1000!=null&&s.hasOwnProperty("salePriceAmount1000")&&(typeof s.salePriceAmount1000=="number"?c.salePriceAmount1000=g.longs===String?String(s.salePriceAmount1000):s.salePriceAmount1000:c.salePriceAmount1000=g.longs===String?se(s.salePriceAmount1000):g.longs===Number?ge(s.salePriceAmount1000):s.salePriceAmount1000,g.oneofs&&(c._salePriceAmount1000="salePriceAmount1000")),s.signedUrl!=null&&s.hasOwnProperty("signedUrl")&&(c.signedUrl=s.signedUrl,g.oneofs&&(c._signedUrl="signedUrl")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.Message.ProductMessage.ProductSnapshot"},a})(),i})(),t.ProtocolMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.type=A.int32();break}case 4:{c.ephemeralExpiration=A.uint32();break}case 5:{c.ephemeralSettingTimestamp=A.int64();break}case 6:{c.historySyncNotification=p.proto.Message.HistorySyncNotification.decode(A,A.uint32());break}case 7:{c.appStateSyncKeyShare=p.proto.Message.AppStateSyncKeyShare.decode(A,A.uint32());break}case 8:{c.appStateSyncKeyRequest=p.proto.Message.AppStateSyncKeyRequest.decode(A,A.uint32());break}case 9:{c.initialSecurityNotificationSettingSync=p.proto.Message.InitialSecurityNotificationSettingSync.decode(A,A.uint32());break}case 10:{c.appStateFatalExceptionNotification=p.proto.Message.AppStateFatalExceptionNotification.decode(A,A.uint32());break}case 11:{c.disappearingMode=p.proto.DisappearingMode.decode(A,A.uint32());break}case 14:{c.editedMessage=p.proto.Message.decode(A,A.uint32());break}case 15:{c.timestampMs=A.int64();break}case 16:{c.peerDataOperationRequestMessage=p.proto.Message.PeerDataOperationRequestMessage.decode(A,A.uint32());break}case 17:{c.peerDataOperationRequestResponseMessage=p.proto.Message.PeerDataOperationRequestResponseMessage.decode(A,A.uint32());break}case 18:{c.botFeedbackMessage=p.proto.BotFeedbackMessage.decode(A,A.uint32());break}case 19:{c.invokerJid=A.string();break}case 20:{c.requestWelcomeMessageMetadata=p.proto.Message.RequestWelcomeMessageMetadata.decode(A,A.uint32());break}case 21:{c.mediaNotifyMessage=p.proto.MediaNotifyMessage.decode(A,A.uint32());break}case 22:{c.cloudApiThreadControlNotification=p.proto.Message.CloudAPIThreadControlNotification.decode(A,A.uint32());break}case 23:{c.lidMigrationMappingSyncMessage=p.proto.LIDMigrationMappingSyncMessage.decode(A,A.uint32());break}case 24:{c.limitSharing=p.proto.LimitSharing.decode(A,A.uint32());break}case 25:{c.aiPsiMetadata=A.bytes();break}case 26:{c.aiQueryFanout=p.proto.AIQueryFanout.decode(A,A.uint32());break}case 27:{c.memberLabel=p.proto.MemberLabel.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ProtocolMessage)return A;var r=new p.proto.Message.ProtocolMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.ProtocolMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"REVOKE":case 0:r.type=0;break;case"EPHEMERAL_SETTING":case 3:r.type=3;break;case"EPHEMERAL_SYNC_RESPONSE":case 4:r.type=4;break;case"HISTORY_SYNC_NOTIFICATION":case 5:r.type=5;break;case"APP_STATE_SYNC_KEY_SHARE":case 6:r.type=6;break;case"APP_STATE_SYNC_KEY_REQUEST":case 7:r.type=7;break;case"MSG_FANOUT_BACKFILL_REQUEST":case 8:r.type=8;break;case"INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC":case 9:r.type=9;break;case"APP_STATE_FATAL_EXCEPTION_NOTIFICATION":case 10:r.type=10;break;case"SHARE_PHONE_NUMBER":case 11:r.type=11;break;case"MESSAGE_EDIT":case 14:r.type=14;break;case"PEER_DATA_OPERATION_REQUEST_MESSAGE":case 16:r.type=16;break;case"PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE":case 17:r.type=17;break;case"REQUEST_WELCOME_MESSAGE":case 18:r.type=18;break;case"BOT_FEEDBACK_MESSAGE":case 19:r.type=19;break;case"MEDIA_NOTIFY_MESSAGE":case 20:r.type=20;break;case"CLOUD_API_THREAD_CONTROL_NOTIFICATION":case 21:r.type=21;break;case"LID_MIGRATION_MAPPING_SYNC":case 22:r.type=22;break;case"REMINDER_MESSAGE":case 23:r.type=23;break;case"BOT_MEMU_ONBOARDING_MESSAGE":case 24:r.type=24;break;case"STATUS_MENTION_MESSAGE":case 25:r.type=25;break;case"STOP_GENERATION_MESSAGE":case 26:r.type=26;break;case"LIMIT_SHARING":case 27:r.type=27;break;case"AI_PSI_METADATA":case 28:r.type=28;break;case"AI_QUERY_FANOUT":case 29:r.type=29;break;case"GROUP_MEMBER_LABEL_CHANGE":case 30:r.type=30;break}if(A.ephemeralExpiration!=null&&(r.ephemeralExpiration=A.ephemeralExpiration>>>0),A.ephemeralSettingTimestamp!=null&&(l.Long?(r.ephemeralSettingTimestamp=l.Long.fromValue(A.ephemeralSettingTimestamp)).unsigned=!1:typeof A.ephemeralSettingTimestamp=="string"?r.ephemeralSettingTimestamp=parseInt(A.ephemeralSettingTimestamp,10):typeof A.ephemeralSettingTimestamp=="number"?r.ephemeralSettingTimestamp=A.ephemeralSettingTimestamp:typeof A.ephemeralSettingTimestamp=="object"&&(r.ephemeralSettingTimestamp=new l.LongBits(A.ephemeralSettingTimestamp.low>>>0,A.ephemeralSettingTimestamp.high>>>0).toNumber())),A.historySyncNotification!=null){if(typeof A.historySyncNotification!="object")throw TypeError(".proto.Message.ProtocolMessage.historySyncNotification: object expected");r.historySyncNotification=p.proto.Message.HistorySyncNotification.fromObject(A.historySyncNotification)}if(A.appStateSyncKeyShare!=null){if(typeof A.appStateSyncKeyShare!="object")throw TypeError(".proto.Message.ProtocolMessage.appStateSyncKeyShare: object expected");r.appStateSyncKeyShare=p.proto.Message.AppStateSyncKeyShare.fromObject(A.appStateSyncKeyShare)}if(A.appStateSyncKeyRequest!=null){if(typeof A.appStateSyncKeyRequest!="object")throw TypeError(".proto.Message.ProtocolMessage.appStateSyncKeyRequest: object expected");r.appStateSyncKeyRequest=p.proto.Message.AppStateSyncKeyRequest.fromObject(A.appStateSyncKeyRequest)}if(A.initialSecurityNotificationSettingSync!=null){if(typeof A.initialSecurityNotificationSettingSync!="object")throw TypeError(".proto.Message.ProtocolMessage.initialSecurityNotificationSettingSync: object expected");r.initialSecurityNotificationSettingSync=p.proto.Message.InitialSecurityNotificationSettingSync.fromObject(A.initialSecurityNotificationSettingSync)}if(A.appStateFatalExceptionNotification!=null){if(typeof A.appStateFatalExceptionNotification!="object")throw TypeError(".proto.Message.ProtocolMessage.appStateFatalExceptionNotification: object expected");r.appStateFatalExceptionNotification=p.proto.Message.AppStateFatalExceptionNotification.fromObject(A.appStateFatalExceptionNotification)}if(A.disappearingMode!=null){if(typeof A.disappearingMode!="object")throw TypeError(".proto.Message.ProtocolMessage.disappearingMode: object expected");r.disappearingMode=p.proto.DisappearingMode.fromObject(A.disappearingMode)}if(A.editedMessage!=null){if(typeof A.editedMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.editedMessage: object expected");r.editedMessage=p.proto.Message.fromObject(A.editedMessage)}if(A.timestampMs!=null&&(l.Long?(r.timestampMs=l.Long.fromValue(A.timestampMs)).unsigned=!1:typeof A.timestampMs=="string"?r.timestampMs=parseInt(A.timestampMs,10):typeof A.timestampMs=="number"?r.timestampMs=A.timestampMs:typeof A.timestampMs=="object"&&(r.timestampMs=new l.LongBits(A.timestampMs.low>>>0,A.timestampMs.high>>>0).toNumber())),A.peerDataOperationRequestMessage!=null){if(typeof A.peerDataOperationRequestMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.peerDataOperationRequestMessage: object expected");r.peerDataOperationRequestMessage=p.proto.Message.PeerDataOperationRequestMessage.fromObject(A.peerDataOperationRequestMessage)}if(A.peerDataOperationRequestResponseMessage!=null){if(typeof A.peerDataOperationRequestResponseMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.peerDataOperationRequestResponseMessage: object expected");r.peerDataOperationRequestResponseMessage=p.proto.Message.PeerDataOperationRequestResponseMessage.fromObject(A.peerDataOperationRequestResponseMessage)}if(A.botFeedbackMessage!=null){if(typeof A.botFeedbackMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.botFeedbackMessage: object expected");r.botFeedbackMessage=p.proto.BotFeedbackMessage.fromObject(A.botFeedbackMessage)}if(A.invokerJid!=null&&(r.invokerJid=String(A.invokerJid)),A.requestWelcomeMessageMetadata!=null){if(typeof A.requestWelcomeMessageMetadata!="object")throw TypeError(".proto.Message.ProtocolMessage.requestWelcomeMessageMetadata: object expected");r.requestWelcomeMessageMetadata=p.proto.Message.RequestWelcomeMessageMetadata.fromObject(A.requestWelcomeMessageMetadata)}if(A.mediaNotifyMessage!=null){if(typeof A.mediaNotifyMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.mediaNotifyMessage: object expected");r.mediaNotifyMessage=p.proto.MediaNotifyMessage.fromObject(A.mediaNotifyMessage)}if(A.cloudApiThreadControlNotification!=null){if(typeof A.cloudApiThreadControlNotification!="object")throw TypeError(".proto.Message.ProtocolMessage.cloudApiThreadControlNotification: object expected");r.cloudApiThreadControlNotification=p.proto.Message.CloudAPIThreadControlNotification.fromObject(A.cloudApiThreadControlNotification)}if(A.lidMigrationMappingSyncMessage!=null){if(typeof A.lidMigrationMappingSyncMessage!="object")throw TypeError(".proto.Message.ProtocolMessage.lidMigrationMappingSyncMessage: object expected");r.lidMigrationMappingSyncMessage=p.proto.LIDMigrationMappingSyncMessage.fromObject(A.lidMigrationMappingSyncMessage)}if(A.limitSharing!=null){if(typeof A.limitSharing!="object")throw TypeError(".proto.Message.ProtocolMessage.limitSharing: object expected");r.limitSharing=p.proto.LimitSharing.fromObject(A.limitSharing)}if(A.aiPsiMetadata!=null&&(typeof A.aiPsiMetadata=="string"?l.base64.decode(A.aiPsiMetadata,r.aiPsiMetadata=l.newBuffer(l.base64.length(A.aiPsiMetadata)),0):A.aiPsiMetadata.length>=0&&(r.aiPsiMetadata=A.aiPsiMetadata)),A.aiQueryFanout!=null){if(typeof A.aiQueryFanout!="object")throw TypeError(".proto.Message.ProtocolMessage.aiQueryFanout: object expected");r.aiQueryFanout=p.proto.AIQueryFanout.fromObject(A.aiQueryFanout)}if(A.memberLabel!=null){if(typeof A.memberLabel!="object")throw TypeError(".proto.Message.ProtocolMessage.memberLabel: object expected");r.memberLabel=p.proto.MemberLabel.fromObject(A.memberLabel)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.ProtocolMessage.Type[A.type]===void 0?A.type:p.proto.Message.ProtocolMessage.Type[A.type]:A.type,r.oneofs&&(s._type="type")),A.ephemeralExpiration!=null&&A.hasOwnProperty("ephemeralExpiration")&&(s.ephemeralExpiration=A.ephemeralExpiration,r.oneofs&&(s._ephemeralExpiration="ephemeralExpiration")),A.ephemeralSettingTimestamp!=null&&A.hasOwnProperty("ephemeralSettingTimestamp")&&(typeof A.ephemeralSettingTimestamp=="number"?s.ephemeralSettingTimestamp=r.longs===String?String(A.ephemeralSettingTimestamp):A.ephemeralSettingTimestamp:s.ephemeralSettingTimestamp=r.longs===String?se(A.ephemeralSettingTimestamp):r.longs===Number?ge(A.ephemeralSettingTimestamp):A.ephemeralSettingTimestamp,r.oneofs&&(s._ephemeralSettingTimestamp="ephemeralSettingTimestamp")),A.historySyncNotification!=null&&A.hasOwnProperty("historySyncNotification")&&(s.historySyncNotification=p.proto.Message.HistorySyncNotification.toObject(A.historySyncNotification,r),r.oneofs&&(s._historySyncNotification="historySyncNotification")),A.appStateSyncKeyShare!=null&&A.hasOwnProperty("appStateSyncKeyShare")&&(s.appStateSyncKeyShare=p.proto.Message.AppStateSyncKeyShare.toObject(A.appStateSyncKeyShare,r),r.oneofs&&(s._appStateSyncKeyShare="appStateSyncKeyShare")),A.appStateSyncKeyRequest!=null&&A.hasOwnProperty("appStateSyncKeyRequest")&&(s.appStateSyncKeyRequest=p.proto.Message.AppStateSyncKeyRequest.toObject(A.appStateSyncKeyRequest,r),r.oneofs&&(s._appStateSyncKeyRequest="appStateSyncKeyRequest")),A.initialSecurityNotificationSettingSync!=null&&A.hasOwnProperty("initialSecurityNotificationSettingSync")&&(s.initialSecurityNotificationSettingSync=p.proto.Message.InitialSecurityNotificationSettingSync.toObject(A.initialSecurityNotificationSettingSync,r),r.oneofs&&(s._initialSecurityNotificationSettingSync="initialSecurityNotificationSettingSync")),A.appStateFatalExceptionNotification!=null&&A.hasOwnProperty("appStateFatalExceptionNotification")&&(s.appStateFatalExceptionNotification=p.proto.Message.AppStateFatalExceptionNotification.toObject(A.appStateFatalExceptionNotification,r),r.oneofs&&(s._appStateFatalExceptionNotification="appStateFatalExceptionNotification")),A.disappearingMode!=null&&A.hasOwnProperty("disappearingMode")&&(s.disappearingMode=p.proto.DisappearingMode.toObject(A.disappearingMode,r),r.oneofs&&(s._disappearingMode="disappearingMode")),A.editedMessage!=null&&A.hasOwnProperty("editedMessage")&&(s.editedMessage=p.proto.Message.toObject(A.editedMessage,r),r.oneofs&&(s._editedMessage="editedMessage")),A.timestampMs!=null&&A.hasOwnProperty("timestampMs")&&(typeof A.timestampMs=="number"?s.timestampMs=r.longs===String?String(A.timestampMs):A.timestampMs:s.timestampMs=r.longs===String?se(A.timestampMs):r.longs===Number?ge(A.timestampMs):A.timestampMs,r.oneofs&&(s._timestampMs="timestampMs")),A.peerDataOperationRequestMessage!=null&&A.hasOwnProperty("peerDataOperationRequestMessage")&&(s.peerDataOperationRequestMessage=p.proto.Message.PeerDataOperationRequestMessage.toObject(A.peerDataOperationRequestMessage,r),r.oneofs&&(s._peerDataOperationRequestMessage="peerDataOperationRequestMessage")),A.peerDataOperationRequestResponseMessage!=null&&A.hasOwnProperty("peerDataOperationRequestResponseMessage")&&(s.peerDataOperationRequestResponseMessage=p.proto.Message.PeerDataOperationRequestResponseMessage.toObject(A.peerDataOperationRequestResponseMessage,r),r.oneofs&&(s._peerDataOperationRequestResponseMessage="peerDataOperationRequestResponseMessage")),A.botFeedbackMessage!=null&&A.hasOwnProperty("botFeedbackMessage")&&(s.botFeedbackMessage=p.proto.BotFeedbackMessage.toObject(A.botFeedbackMessage,r),r.oneofs&&(s._botFeedbackMessage="botFeedbackMessage")),A.invokerJid!=null&&A.hasOwnProperty("invokerJid")&&(s.invokerJid=A.invokerJid,r.oneofs&&(s._invokerJid="invokerJid")),A.requestWelcomeMessageMetadata!=null&&A.hasOwnProperty("requestWelcomeMessageMetadata")&&(s.requestWelcomeMessageMetadata=p.proto.Message.RequestWelcomeMessageMetadata.toObject(A.requestWelcomeMessageMetadata,r),r.oneofs&&(s._requestWelcomeMessageMetadata="requestWelcomeMessageMetadata")),A.mediaNotifyMessage!=null&&A.hasOwnProperty("mediaNotifyMessage")&&(s.mediaNotifyMessage=p.proto.MediaNotifyMessage.toObject(A.mediaNotifyMessage,r),r.oneofs&&(s._mediaNotifyMessage="mediaNotifyMessage")),A.cloudApiThreadControlNotification!=null&&A.hasOwnProperty("cloudApiThreadControlNotification")&&(s.cloudApiThreadControlNotification=p.proto.Message.CloudAPIThreadControlNotification.toObject(A.cloudApiThreadControlNotification,r),r.oneofs&&(s._cloudApiThreadControlNotification="cloudApiThreadControlNotification")),A.lidMigrationMappingSyncMessage!=null&&A.hasOwnProperty("lidMigrationMappingSyncMessage")&&(s.lidMigrationMappingSyncMessage=p.proto.LIDMigrationMappingSyncMessage.toObject(A.lidMigrationMappingSyncMessage,r),r.oneofs&&(s._lidMigrationMappingSyncMessage="lidMigrationMappingSyncMessage")),A.limitSharing!=null&&A.hasOwnProperty("limitSharing")&&(s.limitSharing=p.proto.LimitSharing.toObject(A.limitSharing,r),r.oneofs&&(s._limitSharing="limitSharing")),A.aiPsiMetadata!=null&&A.hasOwnProperty("aiPsiMetadata")&&(s.aiPsiMetadata=r.bytes===String?l.base64.encode(A.aiPsiMetadata,0,A.aiPsiMetadata.length):r.bytes===Array?Array.prototype.slice.call(A.aiPsiMetadata):A.aiPsiMetadata,r.oneofs&&(s._aiPsiMetadata="aiPsiMetadata")),A.aiQueryFanout!=null&&A.hasOwnProperty("aiQueryFanout")&&(s.aiQueryFanout=p.proto.AIQueryFanout.toObject(A.aiQueryFanout,r),r.oneofs&&(s._aiQueryFanout="aiQueryFanout")),A.memberLabel!=null&&A.hasOwnProperty("memberLabel")&&(s.memberLabel=p.proto.MemberLabel.toObject(A.memberLabel,r),r.oneofs&&(s._memberLabel="memberLabel")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ProtocolMessage"},i.Type=(function(){let a={},A=Object.create(a);return A[a[0]="REVOKE"]=0,A[a[3]="EPHEMERAL_SETTING"]=3,A[a[4]="EPHEMERAL_SYNC_RESPONSE"]=4,A[a[5]="HISTORY_SYNC_NOTIFICATION"]=5,A[a[6]="APP_STATE_SYNC_KEY_SHARE"]=6,A[a[7]="APP_STATE_SYNC_KEY_REQUEST"]=7,A[a[8]="MSG_FANOUT_BACKFILL_REQUEST"]=8,A[a[9]="INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC"]=9,A[a[10]="APP_STATE_FATAL_EXCEPTION_NOTIFICATION"]=10,A[a[11]="SHARE_PHONE_NUMBER"]=11,A[a[14]="MESSAGE_EDIT"]=14,A[a[16]="PEER_DATA_OPERATION_REQUEST_MESSAGE"]=16,A[a[17]="PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]=17,A[a[18]="REQUEST_WELCOME_MESSAGE"]=18,A[a[19]="BOT_FEEDBACK_MESSAGE"]=19,A[a[20]="MEDIA_NOTIFY_MESSAGE"]=20,A[a[21]="CLOUD_API_THREAD_CONTROL_NOTIFICATION"]=21,A[a[22]="LID_MIGRATION_MAPPING_SYNC"]=22,A[a[23]="REMINDER_MESSAGE"]=23,A[a[24]="BOT_MEMU_ONBOARDING_MESSAGE"]=24,A[a[25]="STATUS_MENTION_MESSAGE"]=25,A[a[26]="STOP_GENERATION_MESSAGE"]=26,A[a[27]="LIMIT_SHARING"]=27,A[a[28]="AI_PSI_METADATA"]=28,A[a[29]="AI_QUERY_FANOUT"]=29,A[a[30]="GROUP_MEMBER_LABEL_CHANGE"]=30,A})(),i})(),t.QuestionResponseMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.text=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.QuestionResponseMessage)return A;var r=new p.proto.Message.QuestionResponseMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.QuestionResponseMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return A.text!=null&&(r.text=String(A.text)),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.QuestionResponseMessage"},i})(),t.ReactionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.text=A.string();break}case 3:{c.groupingKey=A.string();break}case 4:{c.senderTimestampMs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ReactionMessage)return A;var r=new p.proto.Message.ReactionMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.ReactionMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return A.text!=null&&(r.text=String(A.text)),A.groupingKey!=null&&(r.groupingKey=String(A.groupingKey)),A.senderTimestampMs!=null&&(l.Long?(r.senderTimestampMs=l.Long.fromValue(A.senderTimestampMs)).unsigned=!1:typeof A.senderTimestampMs=="string"?r.senderTimestampMs=parseInt(A.senderTimestampMs,10):typeof A.senderTimestampMs=="number"?r.senderTimestampMs=A.senderTimestampMs:typeof A.senderTimestampMs=="object"&&(r.senderTimestampMs=new l.LongBits(A.senderTimestampMs.low>>>0,A.senderTimestampMs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),A.groupingKey!=null&&A.hasOwnProperty("groupingKey")&&(s.groupingKey=A.groupingKey,r.oneofs&&(s._groupingKey="groupingKey")),A.senderTimestampMs!=null&&A.hasOwnProperty("senderTimestampMs")&&(typeof A.senderTimestampMs=="number"?s.senderTimestampMs=r.longs===String?String(A.senderTimestampMs):A.senderTimestampMs:s.senderTimestampMs=r.longs===String?se(A.senderTimestampMs):r.longs===Number?ge(A.senderTimestampMs):A.senderTimestampMs,r.oneofs&&(s._senderTimestampMs="senderTimestampMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ReactionMessage"},i})(),t.RequestPaymentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 4:{c.noteMessage=p.proto.Message.decode(A,A.uint32());break}case 1:{c.currencyCodeIso4217=A.string();break}case 2:{c.amount1000=A.uint64();break}case 3:{c.requestFrom=A.string();break}case 5:{c.expiryTimestamp=A.int64();break}case 6:{c.amount=p.proto.Money.decode(A,A.uint32());break}case 7:{c.background=p.proto.PaymentBackground.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.RequestPaymentMessage)return A;var r=new p.proto.Message.RequestPaymentMessage;if(A.noteMessage!=null){if(typeof A.noteMessage!="object")throw TypeError(".proto.Message.RequestPaymentMessage.noteMessage: object expected");r.noteMessage=p.proto.Message.fromObject(A.noteMessage)}if(A.currencyCodeIso4217!=null&&(r.currencyCodeIso4217=String(A.currencyCodeIso4217)),A.amount1000!=null&&(l.Long?(r.amount1000=l.Long.fromValue(A.amount1000)).unsigned=!0:typeof A.amount1000=="string"?r.amount1000=parseInt(A.amount1000,10):typeof A.amount1000=="number"?r.amount1000=A.amount1000:typeof A.amount1000=="object"&&(r.amount1000=new l.LongBits(A.amount1000.low>>>0,A.amount1000.high>>>0).toNumber(!0))),A.requestFrom!=null&&(r.requestFrom=String(A.requestFrom)),A.expiryTimestamp!=null&&(l.Long?(r.expiryTimestamp=l.Long.fromValue(A.expiryTimestamp)).unsigned=!1:typeof A.expiryTimestamp=="string"?r.expiryTimestamp=parseInt(A.expiryTimestamp,10):typeof A.expiryTimestamp=="number"?r.expiryTimestamp=A.expiryTimestamp:typeof A.expiryTimestamp=="object"&&(r.expiryTimestamp=new l.LongBits(A.expiryTimestamp.low>>>0,A.expiryTimestamp.high>>>0).toNumber())),A.amount!=null){if(typeof A.amount!="object")throw TypeError(".proto.Message.RequestPaymentMessage.amount: object expected");r.amount=p.proto.Money.fromObject(A.amount)}if(A.background!=null){if(typeof A.background!="object")throw TypeError(".proto.Message.RequestPaymentMessage.background: object expected");r.background=p.proto.PaymentBackground.fromObject(A.background)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.currencyCodeIso4217!=null&&A.hasOwnProperty("currencyCodeIso4217")&&(s.currencyCodeIso4217=A.currencyCodeIso4217,r.oneofs&&(s._currencyCodeIso4217="currencyCodeIso4217")),A.amount1000!=null&&A.hasOwnProperty("amount1000")&&(typeof A.amount1000=="number"?s.amount1000=r.longs===String?String(A.amount1000):A.amount1000:s.amount1000=r.longs===String?se(A.amount1000,!0):r.longs===Number?ge(A.amount1000,!0):A.amount1000,r.oneofs&&(s._amount1000="amount1000")),A.requestFrom!=null&&A.hasOwnProperty("requestFrom")&&(s.requestFrom=A.requestFrom,r.oneofs&&(s._requestFrom="requestFrom")),A.noteMessage!=null&&A.hasOwnProperty("noteMessage")&&(s.noteMessage=p.proto.Message.toObject(A.noteMessage,r),r.oneofs&&(s._noteMessage="noteMessage")),A.expiryTimestamp!=null&&A.hasOwnProperty("expiryTimestamp")&&(typeof A.expiryTimestamp=="number"?s.expiryTimestamp=r.longs===String?String(A.expiryTimestamp):A.expiryTimestamp:s.expiryTimestamp=r.longs===String?se(A.expiryTimestamp):r.longs===Number?ge(A.expiryTimestamp):A.expiryTimestamp,r.oneofs&&(s._expiryTimestamp="expiryTimestamp")),A.amount!=null&&A.hasOwnProperty("amount")&&(s.amount=p.proto.Money.toObject(A.amount,r),r.oneofs&&(s._amount="amount")),A.background!=null&&A.hasOwnProperty("background")&&(s.background=p.proto.PaymentBackground.toObject(A.background,r),r.oneofs&&(s._background="background")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.RequestPaymentMessage"},i})(),t.RequestPhoneNumberMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.RequestPhoneNumberMessage)return A;var r=new p.proto.Message.RequestPhoneNumberMessage;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.RequestPhoneNumberMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.RequestPhoneNumberMessage"},i})(),t.RequestWelcomeMessageMetadata=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.localChatState=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.RequestWelcomeMessageMetadata)return A;var r=new p.proto.Message.RequestWelcomeMessageMetadata;switch(A.localChatState){default:if(typeof A.localChatState=="number"){r.localChatState=A.localChatState;break}break;case"EMPTY":case 0:r.localChatState=0;break;case"NON_EMPTY":case 1:r.localChatState=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.localChatState!=null&&A.hasOwnProperty("localChatState")&&(s.localChatState=r.enums===String?p.proto.Message.RequestWelcomeMessageMetadata.LocalChatState[A.localChatState]===void 0?A.localChatState:p.proto.Message.RequestWelcomeMessageMetadata.LocalChatState[A.localChatState]:A.localChatState,r.oneofs&&(s._localChatState="localChatState")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.RequestWelcomeMessageMetadata"},i.LocalChatState=(function(){let a={},A=Object.create(a);return A[a[0]="EMPTY"]=0,A[a[1]="NON_EMPTY"]=1,A})(),i})(),t.ScheduledCallCreationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.scheduledTimestampMs=A.int64();break}case 2:{c.callType=A.int32();break}case 3:{c.title=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ScheduledCallCreationMessage)return A;var r=new p.proto.Message.ScheduledCallCreationMessage;switch(A.scheduledTimestampMs!=null&&(l.Long?(r.scheduledTimestampMs=l.Long.fromValue(A.scheduledTimestampMs)).unsigned=!1:typeof A.scheduledTimestampMs=="string"?r.scheduledTimestampMs=parseInt(A.scheduledTimestampMs,10):typeof A.scheduledTimestampMs=="number"?r.scheduledTimestampMs=A.scheduledTimestampMs:typeof A.scheduledTimestampMs=="object"&&(r.scheduledTimestampMs=new l.LongBits(A.scheduledTimestampMs.low>>>0,A.scheduledTimestampMs.high>>>0).toNumber())),A.callType){default:if(typeof A.callType=="number"){r.callType=A.callType;break}break;case"UNKNOWN":case 0:r.callType=0;break;case"VOICE":case 1:r.callType=1;break;case"VIDEO":case 2:r.callType=2;break}return A.title!=null&&(r.title=String(A.title)),r},i.toObject=function(A,r){r||(r={});var s={};return A.scheduledTimestampMs!=null&&A.hasOwnProperty("scheduledTimestampMs")&&(typeof A.scheduledTimestampMs=="number"?s.scheduledTimestampMs=r.longs===String?String(A.scheduledTimestampMs):A.scheduledTimestampMs:s.scheduledTimestampMs=r.longs===String?se(A.scheduledTimestampMs):r.longs===Number?ge(A.scheduledTimestampMs):A.scheduledTimestampMs,r.oneofs&&(s._scheduledTimestampMs="scheduledTimestampMs")),A.callType!=null&&A.hasOwnProperty("callType")&&(s.callType=r.enums===String?p.proto.Message.ScheduledCallCreationMessage.CallType[A.callType]===void 0?A.callType:p.proto.Message.ScheduledCallCreationMessage.CallType[A.callType]:A.callType,r.oneofs&&(s._callType="callType")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ScheduledCallCreationMessage"},i.CallType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="VOICE"]=1,A[a[2]="VIDEO"]=2,A})(),i})(),t.ScheduledCallEditMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.editType=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.ScheduledCallEditMessage)return A;var r=new p.proto.Message.ScheduledCallEditMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.ScheduledCallEditMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}switch(A.editType){default:if(typeof A.editType=="number"){r.editType=A.editType;break}break;case"UNKNOWN":case 0:r.editType=0;break;case"CANCEL":case 1:r.editType=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.editType!=null&&A.hasOwnProperty("editType")&&(s.editType=r.enums===String?p.proto.Message.ScheduledCallEditMessage.EditType[A.editType]===void 0?A.editType:p.proto.Message.ScheduledCallEditMessage.EditType[A.editType]:A.editType,r.oneofs&&(s._editType="editType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.ScheduledCallEditMessage"},i.EditType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="CANCEL"]=1,A})(),i})(),t.SecretEncryptedMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.targetMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.encPayload=A.bytes();break}case 3:{c.encIv=A.bytes();break}case 4:{c.secretEncType=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.SecretEncryptedMessage)return A;var r=new p.proto.Message.SecretEncryptedMessage;if(A.targetMessageKey!=null){if(typeof A.targetMessageKey!="object")throw TypeError(".proto.Message.SecretEncryptedMessage.targetMessageKey: object expected");r.targetMessageKey=p.proto.MessageKey.fromObject(A.targetMessageKey)}switch(A.encPayload!=null&&(typeof A.encPayload=="string"?l.base64.decode(A.encPayload,r.encPayload=l.newBuffer(l.base64.length(A.encPayload)),0):A.encPayload.length>=0&&(r.encPayload=A.encPayload)),A.encIv!=null&&(typeof A.encIv=="string"?l.base64.decode(A.encIv,r.encIv=l.newBuffer(l.base64.length(A.encIv)),0):A.encIv.length>=0&&(r.encIv=A.encIv)),A.secretEncType){default:if(typeof A.secretEncType=="number"){r.secretEncType=A.secretEncType;break}break;case"UNKNOWN":case 0:r.secretEncType=0;break;case"EVENT_EDIT":case 1:r.secretEncType=1;break;case"MESSAGE_EDIT":case 2:r.secretEncType=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.targetMessageKey!=null&&A.hasOwnProperty("targetMessageKey")&&(s.targetMessageKey=p.proto.MessageKey.toObject(A.targetMessageKey,r),r.oneofs&&(s._targetMessageKey="targetMessageKey")),A.encPayload!=null&&A.hasOwnProperty("encPayload")&&(s.encPayload=r.bytes===String?l.base64.encode(A.encPayload,0,A.encPayload.length):r.bytes===Array?Array.prototype.slice.call(A.encPayload):A.encPayload,r.oneofs&&(s._encPayload="encPayload")),A.encIv!=null&&A.hasOwnProperty("encIv")&&(s.encIv=r.bytes===String?l.base64.encode(A.encIv,0,A.encIv.length):r.bytes===Array?Array.prototype.slice.call(A.encIv):A.encIv,r.oneofs&&(s._encIv="encIv")),A.secretEncType!=null&&A.hasOwnProperty("secretEncType")&&(s.secretEncType=r.enums===String?p.proto.Message.SecretEncryptedMessage.SecretEncType[A.secretEncType]===void 0?A.secretEncType:p.proto.Message.SecretEncryptedMessage.SecretEncType[A.secretEncType]:A.secretEncType,r.oneofs&&(s._secretEncType="secretEncType")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.SecretEncryptedMessage"},i.SecretEncType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="EVENT_EDIT"]=1,A[a[2]="MESSAGE_EDIT"]=2,A})(),i})(),t.SendPaymentMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 2:{c.noteMessage=p.proto.Message.decode(A,A.uint32());break}case 3:{c.requestMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 4:{c.background=p.proto.PaymentBackground.decode(A,A.uint32());break}case 5:{c.transactionData=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.SendPaymentMessage)return A;var r=new p.proto.Message.SendPaymentMessage;if(A.noteMessage!=null){if(typeof A.noteMessage!="object")throw TypeError(".proto.Message.SendPaymentMessage.noteMessage: object expected");r.noteMessage=p.proto.Message.fromObject(A.noteMessage)}if(A.requestMessageKey!=null){if(typeof A.requestMessageKey!="object")throw TypeError(".proto.Message.SendPaymentMessage.requestMessageKey: object expected");r.requestMessageKey=p.proto.MessageKey.fromObject(A.requestMessageKey)}if(A.background!=null){if(typeof A.background!="object")throw TypeError(".proto.Message.SendPaymentMessage.background: object expected");r.background=p.proto.PaymentBackground.fromObject(A.background)}return A.transactionData!=null&&(r.transactionData=String(A.transactionData)),r},i.toObject=function(A,r){r||(r={});var s={};return A.noteMessage!=null&&A.hasOwnProperty("noteMessage")&&(s.noteMessage=p.proto.Message.toObject(A.noteMessage,r),r.oneofs&&(s._noteMessage="noteMessage")),A.requestMessageKey!=null&&A.hasOwnProperty("requestMessageKey")&&(s.requestMessageKey=p.proto.MessageKey.toObject(A.requestMessageKey,r),r.oneofs&&(s._requestMessageKey="requestMessageKey")),A.background!=null&&A.hasOwnProperty("background")&&(s.background=p.proto.PaymentBackground.toObject(A.background,r),r.oneofs&&(s._background="background")),A.transactionData!=null&&A.hasOwnProperty("transactionData")&&(s.transactionData=A.transactionData,r.oneofs&&(s._transactionData="transactionData")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.SendPaymentMessage"},i})(),t.SenderKeyDistributionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.groupId=A.string();break}case 2:{c.axolotlSenderKeyDistributionMessage=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.SenderKeyDistributionMessage)return A;var r=new p.proto.Message.SenderKeyDistributionMessage;return A.groupId!=null&&(r.groupId=String(A.groupId)),A.axolotlSenderKeyDistributionMessage!=null&&(typeof A.axolotlSenderKeyDistributionMessage=="string"?l.base64.decode(A.axolotlSenderKeyDistributionMessage,r.axolotlSenderKeyDistributionMessage=l.newBuffer(l.base64.length(A.axolotlSenderKeyDistributionMessage)),0):A.axolotlSenderKeyDistributionMessage.length>=0&&(r.axolotlSenderKeyDistributionMessage=A.axolotlSenderKeyDistributionMessage)),r},i.toObject=function(A,r){r||(r={});var s={};return A.groupId!=null&&A.hasOwnProperty("groupId")&&(s.groupId=A.groupId,r.oneofs&&(s._groupId="groupId")),A.axolotlSenderKeyDistributionMessage!=null&&A.hasOwnProperty("axolotlSenderKeyDistributionMessage")&&(s.axolotlSenderKeyDistributionMessage=r.bytes===String?l.base64.encode(A.axolotlSenderKeyDistributionMessage,0,A.axolotlSenderKeyDistributionMessage.length):r.bytes===Array?Array.prototype.slice.call(A.axolotlSenderKeyDistributionMessage):A.axolotlSenderKeyDistributionMessage,r.oneofs&&(s._axolotlSenderKeyDistributionMessage="axolotlSenderKeyDistributionMessage")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.SenderKeyDistributionMessage"},i})(),t.StatusNotificationMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.responseMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.originalMessageKey=p.proto.MessageKey.decode(A,A.uint32());break}case 3:{c.type=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StatusNotificationMessage)return A;var r=new p.proto.Message.StatusNotificationMessage;if(A.responseMessageKey!=null){if(typeof A.responseMessageKey!="object")throw TypeError(".proto.Message.StatusNotificationMessage.responseMessageKey: object expected");r.responseMessageKey=p.proto.MessageKey.fromObject(A.responseMessageKey)}if(A.originalMessageKey!=null){if(typeof A.originalMessageKey!="object")throw TypeError(".proto.Message.StatusNotificationMessage.originalMessageKey: object expected");r.originalMessageKey=p.proto.MessageKey.fromObject(A.originalMessageKey)}switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNKNOWN":case 0:r.type=0;break;case"STATUS_ADD_YOURS":case 1:r.type=1;break;case"STATUS_RESHARE":case 2:r.type=2;break;case"STATUS_QUESTION_ANSWER_RESHARE":case 3:r.type=3;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.responseMessageKey!=null&&A.hasOwnProperty("responseMessageKey")&&(s.responseMessageKey=p.proto.MessageKey.toObject(A.responseMessageKey,r),r.oneofs&&(s._responseMessageKey="responseMessageKey")),A.originalMessageKey!=null&&A.hasOwnProperty("originalMessageKey")&&(s.originalMessageKey=p.proto.MessageKey.toObject(A.originalMessageKey,r),r.oneofs&&(s._originalMessageKey="originalMessageKey")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.StatusNotificationMessage.StatusNotificationType[A.type]===void 0?A.type:p.proto.Message.StatusNotificationMessage.StatusNotificationType[A.type]:A.type,r.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusNotificationMessage"},i.StatusNotificationType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="STATUS_ADD_YOURS"]=1,A[a[2]="STATUS_RESHARE"]=2,A[a[3]="STATUS_QUESTION_ANSWER_RESHARE"]=3,A})(),i})(),t.StatusQuestionAnswerMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.text=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StatusQuestionAnswerMessage)return A;var r=new p.proto.Message.StatusQuestionAnswerMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.StatusQuestionAnswerMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return A.text!=null&&(r.text=String(A.text)),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusQuestionAnswerMessage"},i})(),t.StatusQuotedMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.type=A.int32();break}case 2:{c.text=A.string();break}case 3:{c.thumbnail=A.bytes();break}case 4:{c.originalStatusId=p.proto.MessageKey.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StatusQuotedMessage)return A;var r=new p.proto.Message.StatusQuotedMessage;switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"QUESTION_ANSWER":case 1:r.type=1;break}if(A.text!=null&&(r.text=String(A.text)),A.thumbnail!=null&&(typeof A.thumbnail=="string"?l.base64.decode(A.thumbnail,r.thumbnail=l.newBuffer(l.base64.length(A.thumbnail)),0):A.thumbnail.length>=0&&(r.thumbnail=A.thumbnail)),A.originalStatusId!=null){if(typeof A.originalStatusId!="object")throw TypeError(".proto.Message.StatusQuotedMessage.originalStatusId: object expected");r.originalStatusId=p.proto.MessageKey.fromObject(A.originalStatusId)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.StatusQuotedMessage.StatusQuotedMessageType[A.type]===void 0?A.type:p.proto.Message.StatusQuotedMessage.StatusQuotedMessageType[A.type]:A.type,r.oneofs&&(s._type="type")),A.text!=null&&A.hasOwnProperty("text")&&(s.text=A.text,r.oneofs&&(s._text="text")),A.thumbnail!=null&&A.hasOwnProperty("thumbnail")&&(s.thumbnail=r.bytes===String?l.base64.encode(A.thumbnail,0,A.thumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.thumbnail):A.thumbnail,r.oneofs&&(s._thumbnail="thumbnail")),A.originalStatusId!=null&&A.hasOwnProperty("originalStatusId")&&(s.originalStatusId=p.proto.MessageKey.toObject(A.originalStatusId,r),r.oneofs&&(s._originalStatusId="originalStatusId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusQuotedMessage"},i.StatusQuotedMessageType=(function(){let a={},A=Object.create(a);return A[a[1]="QUESTION_ANSWER"]=1,A})(),i})(),t.StatusStickerInteractionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.stickerKey=A.string();break}case 3:{c.type=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StatusStickerInteractionMessage)return A;var r=new p.proto.Message.StatusStickerInteractionMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.Message.StatusStickerInteractionMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}switch(A.stickerKey!=null&&(r.stickerKey=String(A.stickerKey)),A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNKNOWN":case 0:r.type=0;break;case"REACTION":case 1:r.type=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.stickerKey!=null&&A.hasOwnProperty("stickerKey")&&(s.stickerKey=A.stickerKey,r.oneofs&&(s._stickerKey="stickerKey")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.Message.StatusStickerInteractionMessage.StatusStickerType[A.type]===void 0?A.type:p.proto.Message.StatusStickerInteractionMessage.StatusStickerType[A.type]:A.type,r.oneofs&&(s._type="type")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StatusStickerInteractionMessage"},i.StatusStickerType=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="REACTION"]=1,A})(),i})(),t.StickerMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.url=A.string();break}case 2:{c.fileSha256=A.bytes();break}case 3:{c.fileEncSha256=A.bytes();break}case 4:{c.mediaKey=A.bytes();break}case 5:{c.mimetype=A.string();break}case 6:{c.height=A.uint32();break}case 7:{c.width=A.uint32();break}case 8:{c.directPath=A.string();break}case 9:{c.fileLength=A.uint64();break}case 10:{c.mediaKeyTimestamp=A.int64();break}case 11:{c.firstFrameLength=A.uint32();break}case 12:{c.firstFrameSidecar=A.bytes();break}case 13:{c.isAnimated=A.bool();break}case 16:{c.pngThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.stickerSentTs=A.int64();break}case 19:{c.isAvatar=A.bool();break}case 20:{c.isAiSticker=A.bool();break}case 21:{c.isLottie=A.bool();break}case 22:{c.accessibilityLabel=A.string();break}case 23:{c.mediaKeyDomain=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StickerMessage)return A;var r=new p.proto.Message.StickerMessage;if(A.url!=null&&(r.url=String(A.url)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.height!=null&&(r.height=A.height>>>0),A.width!=null&&(r.width=A.width>>>0),A.directPath!=null&&(r.directPath=String(A.directPath)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.firstFrameLength!=null&&(r.firstFrameLength=A.firstFrameLength>>>0),A.firstFrameSidecar!=null&&(typeof A.firstFrameSidecar=="string"?l.base64.decode(A.firstFrameSidecar,r.firstFrameSidecar=l.newBuffer(l.base64.length(A.firstFrameSidecar)),0):A.firstFrameSidecar.length>=0&&(r.firstFrameSidecar=A.firstFrameSidecar)),A.isAnimated!=null&&(r.isAnimated=!!A.isAnimated),A.pngThumbnail!=null&&(typeof A.pngThumbnail=="string"?l.base64.decode(A.pngThumbnail,r.pngThumbnail=l.newBuffer(l.base64.length(A.pngThumbnail)),0):A.pngThumbnail.length>=0&&(r.pngThumbnail=A.pngThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.StickerMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.stickerSentTs!=null&&(l.Long?(r.stickerSentTs=l.Long.fromValue(A.stickerSentTs)).unsigned=!1:typeof A.stickerSentTs=="string"?r.stickerSentTs=parseInt(A.stickerSentTs,10):typeof A.stickerSentTs=="number"?r.stickerSentTs=A.stickerSentTs:typeof A.stickerSentTs=="object"&&(r.stickerSentTs=new l.LongBits(A.stickerSentTs.low>>>0,A.stickerSentTs.high>>>0).toNumber())),A.isAvatar!=null&&(r.isAvatar=!!A.isAvatar),A.isAiSticker!=null&&(r.isAiSticker=!!A.isAiSticker),A.isLottie!=null&&(r.isLottie=!!A.isLottie),A.accessibilityLabel!=null&&(r.accessibilityLabel=String(A.accessibilityLabel)),A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){r.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:r.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:r.mediaKeyDomain=1;break;case"STATUS":case 2:r.mediaKeyDomain=2;break;case"CAPI":case 3:r.mediaKeyDomain=3;break;case"BOT":case 4:r.mediaKeyDomain=4;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=A.height,r.oneofs&&(s._height="height")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=A.width,r.oneofs&&(s._width="width")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.firstFrameLength!=null&&A.hasOwnProperty("firstFrameLength")&&(s.firstFrameLength=A.firstFrameLength,r.oneofs&&(s._firstFrameLength="firstFrameLength")),A.firstFrameSidecar!=null&&A.hasOwnProperty("firstFrameSidecar")&&(s.firstFrameSidecar=r.bytes===String?l.base64.encode(A.firstFrameSidecar,0,A.firstFrameSidecar.length):r.bytes===Array?Array.prototype.slice.call(A.firstFrameSidecar):A.firstFrameSidecar,r.oneofs&&(s._firstFrameSidecar="firstFrameSidecar")),A.isAnimated!=null&&A.hasOwnProperty("isAnimated")&&(s.isAnimated=A.isAnimated,r.oneofs&&(s._isAnimated="isAnimated")),A.pngThumbnail!=null&&A.hasOwnProperty("pngThumbnail")&&(s.pngThumbnail=r.bytes===String?l.base64.encode(A.pngThumbnail,0,A.pngThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.pngThumbnail):A.pngThumbnail,r.oneofs&&(s._pngThumbnail="pngThumbnail")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.stickerSentTs!=null&&A.hasOwnProperty("stickerSentTs")&&(typeof A.stickerSentTs=="number"?s.stickerSentTs=r.longs===String?String(A.stickerSentTs):A.stickerSentTs:s.stickerSentTs=r.longs===String?se(A.stickerSentTs):r.longs===Number?ge(A.stickerSentTs):A.stickerSentTs,r.oneofs&&(s._stickerSentTs="stickerSentTs")),A.isAvatar!=null&&A.hasOwnProperty("isAvatar")&&(s.isAvatar=A.isAvatar,r.oneofs&&(s._isAvatar="isAvatar")),A.isAiSticker!=null&&A.hasOwnProperty("isAiSticker")&&(s.isAiSticker=A.isAiSticker,r.oneofs&&(s._isAiSticker="isAiSticker")),A.isLottie!=null&&A.hasOwnProperty("isLottie")&&(s.isLottie=A.isLottie,r.oneofs&&(s._isLottie="isLottie")),A.accessibilityLabel!=null&&A.hasOwnProperty("accessibilityLabel")&&(s.accessibilityLabel=A.accessibilityLabel,r.oneofs&&(s._accessibilityLabel="accessibilityLabel")),A.mediaKeyDomain!=null&&A.hasOwnProperty("mediaKeyDomain")&&(s.mediaKeyDomain=r.enums===String?p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]===void 0?A.mediaKeyDomain:p.proto.Message.MediaKeyDomain[A.mediaKeyDomain]:A.mediaKeyDomain,r.oneofs&&(s._mediaKeyDomain="mediaKeyDomain")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.StickerMessage"},i})(),t.StickerPackMessage=(function(){function i(a){if(this.stickers=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.stickerPackId=A.string();break}case 2:{c.name=A.string();break}case 3:{c.publisher=A.string();break}case 4:{c.stickers&&c.stickers.length||(c.stickers=[]),c.stickers.push(p.proto.Message.StickerPackMessage.Sticker.decode(A,A.uint32()));break}case 5:{c.fileLength=A.uint64();break}case 6:{c.fileSha256=A.bytes();break}case 7:{c.fileEncSha256=A.bytes();break}case 8:{c.mediaKey=A.bytes();break}case 9:{c.directPath=A.string();break}case 10:{c.caption=A.string();break}case 11:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 12:{c.packDescription=A.string();break}case 13:{c.mediaKeyTimestamp=A.int64();break}case 14:{c.trayIconFileName=A.string();break}case 15:{c.thumbnailDirectPath=A.string();break}case 16:{c.thumbnailSha256=A.bytes();break}case 17:{c.thumbnailEncSha256=A.bytes();break}case 18:{c.thumbnailHeight=A.uint32();break}case 19:{c.thumbnailWidth=A.uint32();break}case 20:{c.imageDataHash=A.string();break}case 21:{c.stickerPackSize=A.uint64();break}case 22:{c.stickerPackOrigin=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StickerPackMessage)return A;var r=new p.proto.Message.StickerPackMessage;if(A.stickerPackId!=null&&(r.stickerPackId=String(A.stickerPackId)),A.name!=null&&(r.name=String(A.name)),A.publisher!=null&&(r.publisher=String(A.publisher)),A.stickers){if(!Array.isArray(A.stickers))throw TypeError(".proto.Message.StickerPackMessage.stickers: array expected");r.stickers=[];for(var s=0;s>>0,A.fileLength.high>>>0).toNumber(!0))),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.directPath!=null&&(r.directPath=String(A.directPath)),A.caption!=null&&(r.caption=String(A.caption)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.StickerPackMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.packDescription!=null&&(r.packDescription=String(A.packDescription)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.trayIconFileName!=null&&(r.trayIconFileName=String(A.trayIconFileName)),A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.thumbnailHeight!=null&&(r.thumbnailHeight=A.thumbnailHeight>>>0),A.thumbnailWidth!=null&&(r.thumbnailWidth=A.thumbnailWidth>>>0),A.imageDataHash!=null&&(r.imageDataHash=String(A.imageDataHash)),A.stickerPackSize!=null&&(l.Long?(r.stickerPackSize=l.Long.fromValue(A.stickerPackSize)).unsigned=!0:typeof A.stickerPackSize=="string"?r.stickerPackSize=parseInt(A.stickerPackSize,10):typeof A.stickerPackSize=="number"?r.stickerPackSize=A.stickerPackSize:typeof A.stickerPackSize=="object"&&(r.stickerPackSize=new l.LongBits(A.stickerPackSize.low>>>0,A.stickerPackSize.high>>>0).toNumber(!0))),A.stickerPackOrigin){default:if(typeof A.stickerPackOrigin=="number"){r.stickerPackOrigin=A.stickerPackOrigin;break}break;case"FIRST_PARTY":case 0:r.stickerPackOrigin=0;break;case"THIRD_PARTY":case 1:r.stickerPackOrigin=1;break;case"USER_CREATED":case 2:r.stickerPackOrigin=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.stickers=[]),A.stickerPackId!=null&&A.hasOwnProperty("stickerPackId")&&(s.stickerPackId=A.stickerPackId,r.oneofs&&(s._stickerPackId="stickerPackId")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.publisher!=null&&A.hasOwnProperty("publisher")&&(s.publisher=A.publisher,r.oneofs&&(s._publisher="publisher")),A.stickers&&A.stickers.length){s.stickers=[];for(var g=0;g>>3){case 1:{d.fileName=s.string();break}case 2:{d.isAnimated=s.bool();break}case 3:{d.emojis&&d.emojis.length||(d.emojis=[]),d.emojis.push(s.string());break}case 4:{d.accessibilityLabel=s.string();break}case 5:{d.isLottie=s.bool();break}case 6:{d.mimetype=s.string();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.StickerPackMessage.Sticker)return s;var g=new p.proto.Message.StickerPackMessage.Sticker;if(s.fileName!=null&&(g.fileName=String(s.fileName)),s.isAnimated!=null&&(g.isAnimated=!!s.isAnimated),s.emojis){if(!Array.isArray(s.emojis))throw TypeError(".proto.Message.StickerPackMessage.Sticker.emojis: array expected");g.emojis=[];for(var c=0;c>>3){case 1:{c.filehash&&c.filehash.length||(c.filehash=[]),c.filehash.push(A.string());break}case 2:{c.rmrSource=A.string();break}case 3:{c.requestTimestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.StickerSyncRMRMessage)return A;var r=new p.proto.Message.StickerSyncRMRMessage;if(A.filehash){if(!Array.isArray(A.filehash))throw TypeError(".proto.Message.StickerSyncRMRMessage.filehash: array expected");r.filehash=[];for(var s=0;s>>0,A.requestTimestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.filehash=[]),A.filehash&&A.filehash.length){s.filehash=[];for(var g=0;g>>3){case 1:{c.selectedId=A.string();break}case 2:{c.selectedDisplayText=A.string();break}case 3:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.selectedIndex=A.uint32();break}case 5:{c.selectedCarouselCardIndex=A.uint32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.TemplateButtonReplyMessage)return A;var r=new p.proto.Message.TemplateButtonReplyMessage;if(A.selectedId!=null&&(r.selectedId=String(A.selectedId)),A.selectedDisplayText!=null&&(r.selectedDisplayText=String(A.selectedDisplayText)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.TemplateButtonReplyMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}return A.selectedIndex!=null&&(r.selectedIndex=A.selectedIndex>>>0),A.selectedCarouselCardIndex!=null&&(r.selectedCarouselCardIndex=A.selectedCarouselCardIndex>>>0),r},i.toObject=function(A,r){r||(r={});var s={};return A.selectedId!=null&&A.hasOwnProperty("selectedId")&&(s.selectedId=A.selectedId,r.oneofs&&(s._selectedId="selectedId")),A.selectedDisplayText!=null&&A.hasOwnProperty("selectedDisplayText")&&(s.selectedDisplayText=A.selectedDisplayText,r.oneofs&&(s._selectedDisplayText="selectedDisplayText")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.selectedIndex!=null&&A.hasOwnProperty("selectedIndex")&&(s.selectedIndex=A.selectedIndex,r.oneofs&&(s._selectedIndex="selectedIndex")),A.selectedCarouselCardIndex!=null&&A.hasOwnProperty("selectedCarouselCardIndex")&&(s.selectedCarouselCardIndex=A.selectedCarouselCardIndex,r.oneofs&&(s._selectedCarouselCardIndex="selectedCarouselCardIndex")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.TemplateButtonReplyMessage"},i})(),t.TemplateMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 3:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 4:{c.hydratedTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.decode(A,A.uint32());break}case 9:{c.templateId=A.string();break}case 1:{c.fourRowTemplate=p.proto.Message.TemplateMessage.FourRowTemplate.decode(A,A.uint32());break}case 2:{c.hydratedFourRowTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.decode(A,A.uint32());break}case 5:{c.interactiveMessageTemplate=p.proto.Message.InteractiveMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.TemplateMessage)return A;var r=new p.proto.Message.TemplateMessage;if(A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.TemplateMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}if(A.hydratedTemplate!=null){if(typeof A.hydratedTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.hydratedTemplate: object expected");r.hydratedTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.fromObject(A.hydratedTemplate)}if(A.templateId!=null&&(r.templateId=String(A.templateId)),A.fourRowTemplate!=null){if(typeof A.fourRowTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.fourRowTemplate: object expected");r.fourRowTemplate=p.proto.Message.TemplateMessage.FourRowTemplate.fromObject(A.fourRowTemplate)}if(A.hydratedFourRowTemplate!=null){if(typeof A.hydratedFourRowTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.hydratedFourRowTemplate: object expected");r.hydratedFourRowTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.fromObject(A.hydratedFourRowTemplate)}if(A.interactiveMessageTemplate!=null){if(typeof A.interactiveMessageTemplate!="object")throw TypeError(".proto.Message.TemplateMessage.interactiveMessageTemplate: object expected");r.interactiveMessageTemplate=p.proto.Message.InteractiveMessage.fromObject(A.interactiveMessageTemplate)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.fourRowTemplate!=null&&A.hasOwnProperty("fourRowTemplate")&&(s.fourRowTemplate=p.proto.Message.TemplateMessage.FourRowTemplate.toObject(A.fourRowTemplate,r),r.oneofs&&(s.format="fourRowTemplate")),A.hydratedFourRowTemplate!=null&&A.hasOwnProperty("hydratedFourRowTemplate")&&(s.hydratedFourRowTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.toObject(A.hydratedFourRowTemplate,r),r.oneofs&&(s.format="hydratedFourRowTemplate")),A.contextInfo!=null&&A.hasOwnProperty("contextInfo")&&(s.contextInfo=p.proto.ContextInfo.toObject(A.contextInfo,r),r.oneofs&&(s._contextInfo="contextInfo")),A.hydratedTemplate!=null&&A.hasOwnProperty("hydratedTemplate")&&(s.hydratedTemplate=p.proto.Message.TemplateMessage.HydratedFourRowTemplate.toObject(A.hydratedTemplate,r),r.oneofs&&(s._hydratedTemplate="hydratedTemplate")),A.interactiveMessageTemplate!=null&&A.hasOwnProperty("interactiveMessageTemplate")&&(s.interactiveMessageTemplate=p.proto.Message.InteractiveMessage.toObject(A.interactiveMessageTemplate,r),r.oneofs&&(s.format="interactiveMessageTemplate")),A.templateId!=null&&A.hasOwnProperty("templateId")&&(s.templateId=A.templateId,r.oneofs&&(s._templateId="templateId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.TemplateMessage"},i.FourRowTemplate=(function(){function a(r){if(this.buttons=[],r)for(var s=Object.keys(r),g=0;g>>3){case 6:{d.content=p.proto.Message.HighlyStructuredMessage.decode(s,s.uint32());break}case 7:{d.footer=p.proto.Message.HighlyStructuredMessage.decode(s,s.uint32());break}case 8:{d.buttons&&d.buttons.length||(d.buttons=[]),d.buttons.push(p.proto.TemplateButton.decode(s,s.uint32()));break}case 1:{d.documentMessage=p.proto.Message.DocumentMessage.decode(s,s.uint32());break}case 2:{d.highlyStructuredMessage=p.proto.Message.HighlyStructuredMessage.decode(s,s.uint32());break}case 3:{d.imageMessage=p.proto.Message.ImageMessage.decode(s,s.uint32());break}case 4:{d.videoMessage=p.proto.Message.VideoMessage.decode(s,s.uint32());break}case 5:{d.locationMessage=p.proto.Message.LocationMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.TemplateMessage.FourRowTemplate)return s;var g=new p.proto.Message.TemplateMessage.FourRowTemplate;if(s.content!=null){if(typeof s.content!="object")throw TypeError(".proto.Message.TemplateMessage.FourRowTemplate.content: object expected");g.content=p.proto.Message.HighlyStructuredMessage.fromObject(s.content)}if(s.footer!=null){if(typeof s.footer!="object")throw TypeError(".proto.Message.TemplateMessage.FourRowTemplate.footer: object expected");g.footer=p.proto.Message.HighlyStructuredMessage.fromObject(s.footer)}if(s.buttons){if(!Array.isArray(s.buttons))throw TypeError(".proto.Message.TemplateMessage.FourRowTemplate.buttons: array expected");g.buttons=[];for(var c=0;c>>3){case 6:{d.hydratedContentText=s.string();break}case 7:{d.hydratedFooterText=s.string();break}case 8:{d.hydratedButtons&&d.hydratedButtons.length||(d.hydratedButtons=[]),d.hydratedButtons.push(p.proto.HydratedTemplateButton.decode(s,s.uint32()));break}case 9:{d.templateId=s.string();break}case 10:{d.maskLinkedDevices=s.bool();break}case 1:{d.documentMessage=p.proto.Message.DocumentMessage.decode(s,s.uint32());break}case 2:{d.hydratedTitleText=s.string();break}case 3:{d.imageMessage=p.proto.Message.ImageMessage.decode(s,s.uint32());break}case 4:{d.videoMessage=p.proto.Message.VideoMessage.decode(s,s.uint32());break}case 5:{d.locationMessage=p.proto.Message.LocationMessage.decode(s,s.uint32());break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.Message.TemplateMessage.HydratedFourRowTemplate)return s;var g=new p.proto.Message.TemplateMessage.HydratedFourRowTemplate;if(s.hydratedContentText!=null&&(g.hydratedContentText=String(s.hydratedContentText)),s.hydratedFooterText!=null&&(g.hydratedFooterText=String(s.hydratedFooterText)),s.hydratedButtons){if(!Array.isArray(s.hydratedButtons))throw TypeError(".proto.Message.TemplateMessage.HydratedFourRowTemplate.hydratedButtons: array expected");g.hydratedButtons=[];for(var c=0;c>>3){case 1:{c.fbExperimentId=A.uint32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.URLMetadata)return A;var r=new p.proto.Message.URLMetadata;return A.fbExperimentId!=null&&(r.fbExperimentId=A.fbExperimentId>>>0),r},i.toObject=function(A,r){r||(r={});var s={};return A.fbExperimentId!=null&&A.hasOwnProperty("fbExperimentId")&&(s.fbExperimentId=A.fbExperimentId,r.oneofs&&(s._fbExperimentId="fbExperimentId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.Message.URLMetadata"},i})(),t.VideoEndCard=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.username=a.string();break}case 2:{g.caption=a.string();break}case 3:{g.thumbnailImageUrl=a.string();break}case 4:{g.profilePictureUrl=a.string();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.Message.VideoEndCard)return a;var A=new p.proto.Message.VideoEndCard;return a.username!=null&&(A.username=String(a.username)),a.caption!=null&&(A.caption=String(a.caption)),a.thumbnailImageUrl!=null&&(A.thumbnailImageUrl=String(a.thumbnailImageUrl)),a.profilePictureUrl!=null&&(A.profilePictureUrl=String(a.profilePictureUrl)),A},i.toObject=function(a,A){A||(A={});var r={};return A.defaults&&(r.username="",r.caption="",r.thumbnailImageUrl="",r.profilePictureUrl=""),a.username!=null&&a.hasOwnProperty("username")&&(r.username=a.username),a.caption!=null&&a.hasOwnProperty("caption")&&(r.caption=a.caption),a.thumbnailImageUrl!=null&&a.hasOwnProperty("thumbnailImageUrl")&&(r.thumbnailImageUrl=a.thumbnailImageUrl),a.profilePictureUrl!=null&&a.hasOwnProperty("profilePictureUrl")&&(r.profilePictureUrl=a.profilePictureUrl),r},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Message.VideoEndCard"},i})(),t.VideoMessage=(function(){function i(a){if(this.interactiveAnnotations=[],this.annotations=[],this.processedVideos=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.url=A.string();break}case 2:{c.mimetype=A.string();break}case 3:{c.fileSha256=A.bytes();break}case 4:{c.fileLength=A.uint64();break}case 5:{c.seconds=A.uint32();break}case 6:{c.mediaKey=A.bytes();break}case 7:{c.caption=A.string();break}case 8:{c.gifPlayback=A.bool();break}case 9:{c.height=A.uint32();break}case 10:{c.width=A.uint32();break}case 11:{c.fileEncSha256=A.bytes();break}case 12:{c.interactiveAnnotations&&c.interactiveAnnotations.length||(c.interactiveAnnotations=[]),c.interactiveAnnotations.push(p.proto.InteractiveAnnotation.decode(A,A.uint32()));break}case 13:{c.directPath=A.string();break}case 14:{c.mediaKeyTimestamp=A.int64();break}case 16:{c.jpegThumbnail=A.bytes();break}case 17:{c.contextInfo=p.proto.ContextInfo.decode(A,A.uint32());break}case 18:{c.streamingSidecar=A.bytes();break}case 19:{c.gifAttribution=A.int32();break}case 20:{c.viewOnce=A.bool();break}case 21:{c.thumbnailDirectPath=A.string();break}case 22:{c.thumbnailSha256=A.bytes();break}case 23:{c.thumbnailEncSha256=A.bytes();break}case 24:{c.staticUrl=A.string();break}case 25:{c.annotations&&c.annotations.length||(c.annotations=[]),c.annotations.push(p.proto.InteractiveAnnotation.decode(A,A.uint32()));break}case 26:{c.accessibilityLabel=A.string();break}case 27:{c.processedVideos&&c.processedVideos.length||(c.processedVideos=[]),c.processedVideos.push(p.proto.ProcessedVideo.decode(A,A.uint32()));break}case 28:{c.externalShareFullVideoDurationInSeconds=A.uint32();break}case 29:{c.motionPhotoPresentationOffsetMs=A.uint64();break}case 30:{c.metadataUrl=A.string();break}case 31:{c.videoSourceType=A.int32();break}case 32:{c.mediaKeyDomain=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.Message.VideoMessage)return A;var r=new p.proto.Message.VideoMessage;if(A.url!=null&&(r.url=String(A.url)),A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.seconds!=null&&(r.seconds=A.seconds>>>0),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.caption!=null&&(r.caption=String(A.caption)),A.gifPlayback!=null&&(r.gifPlayback=!!A.gifPlayback),A.height!=null&&(r.height=A.height>>>0),A.width!=null&&(r.width=A.width>>>0),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.interactiveAnnotations){if(!Array.isArray(A.interactiveAnnotations))throw TypeError(".proto.Message.VideoMessage.interactiveAnnotations: array expected");r.interactiveAnnotations=[];for(var s=0;s>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),A.contextInfo!=null){if(typeof A.contextInfo!="object")throw TypeError(".proto.Message.VideoMessage.contextInfo: object expected");r.contextInfo=p.proto.ContextInfo.fromObject(A.contextInfo)}switch(A.streamingSidecar!=null&&(typeof A.streamingSidecar=="string"?l.base64.decode(A.streamingSidecar,r.streamingSidecar=l.newBuffer(l.base64.length(A.streamingSidecar)),0):A.streamingSidecar.length>=0&&(r.streamingSidecar=A.streamingSidecar)),A.gifAttribution){default:if(typeof A.gifAttribution=="number"){r.gifAttribution=A.gifAttribution;break}break;case"NONE":case 0:r.gifAttribution=0;break;case"GIPHY":case 1:r.gifAttribution=1;break;case"TENOR":case 2:r.gifAttribution=2;break;case"KLIPY":case 3:r.gifAttribution=3;break}if(A.viewOnce!=null&&(r.viewOnce=!!A.viewOnce),A.thumbnailDirectPath!=null&&(r.thumbnailDirectPath=String(A.thumbnailDirectPath)),A.thumbnailSha256!=null&&(typeof A.thumbnailSha256=="string"?l.base64.decode(A.thumbnailSha256,r.thumbnailSha256=l.newBuffer(l.base64.length(A.thumbnailSha256)),0):A.thumbnailSha256.length>=0&&(r.thumbnailSha256=A.thumbnailSha256)),A.thumbnailEncSha256!=null&&(typeof A.thumbnailEncSha256=="string"?l.base64.decode(A.thumbnailEncSha256,r.thumbnailEncSha256=l.newBuffer(l.base64.length(A.thumbnailEncSha256)),0):A.thumbnailEncSha256.length>=0&&(r.thumbnailEncSha256=A.thumbnailEncSha256)),A.staticUrl!=null&&(r.staticUrl=String(A.staticUrl)),A.annotations){if(!Array.isArray(A.annotations))throw TypeError(".proto.Message.VideoMessage.annotations: array expected");r.annotations=[];for(var s=0;s>>0),A.motionPhotoPresentationOffsetMs!=null&&(l.Long?(r.motionPhotoPresentationOffsetMs=l.Long.fromValue(A.motionPhotoPresentationOffsetMs)).unsigned=!0:typeof A.motionPhotoPresentationOffsetMs=="string"?r.motionPhotoPresentationOffsetMs=parseInt(A.motionPhotoPresentationOffsetMs,10):typeof A.motionPhotoPresentationOffsetMs=="number"?r.motionPhotoPresentationOffsetMs=A.motionPhotoPresentationOffsetMs:typeof A.motionPhotoPresentationOffsetMs=="object"&&(r.motionPhotoPresentationOffsetMs=new l.LongBits(A.motionPhotoPresentationOffsetMs.low>>>0,A.motionPhotoPresentationOffsetMs.high>>>0).toNumber(!0))),A.metadataUrl!=null&&(r.metadataUrl=String(A.metadataUrl)),A.videoSourceType){default:if(typeof A.videoSourceType=="number"){r.videoSourceType=A.videoSourceType;break}break;case"USER_VIDEO":case 0:r.videoSourceType=0;break;case"AI_GENERATED":case 1:r.videoSourceType=1;break}switch(A.mediaKeyDomain){default:if(typeof A.mediaKeyDomain=="number"){r.mediaKeyDomain=A.mediaKeyDomain;break}break;case"UNSET":case 0:r.mediaKeyDomain=0;break;case"E2EE_CHAT":case 1:r.mediaKeyDomain=1;break;case"STATUS":case 2:r.mediaKeyDomain=2;break;case"CAPI":case 3:r.mediaKeyDomain=3;break;case"BOT":case 4:r.mediaKeyDomain=4;break}return r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.interactiveAnnotations=[],s.annotations=[],s.processedVideos=[]),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.seconds!=null&&A.hasOwnProperty("seconds")&&(s.seconds=A.seconds,r.oneofs&&(s._seconds="seconds")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.caption!=null&&A.hasOwnProperty("caption")&&(s.caption=A.caption,r.oneofs&&(s._caption="caption")),A.gifPlayback!=null&&A.hasOwnProperty("gifPlayback")&&(s.gifPlayback=A.gifPlayback,r.oneofs&&(s._gifPlayback="gifPlayback")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=A.height,r.oneofs&&(s._height="height")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=A.width,r.oneofs&&(s._width="width")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.interactiveAnnotations&&A.interactiveAnnotations.length){s.interactiveAnnotations=[];for(var g=0;g>>3){case 1:{s.messageAddOnType=e.int32();break}case 2:{s.messageAddOn=p.proto.Message.decode(e,e.uint32());break}case 3:{s.senderTimestampMs=e.int64();break}case 4:{s.serverTimestampMs=e.int64();break}case 5:{s.status=e.int32();break}case 6:{s.addOnContextInfo=p.proto.MessageAddOnContextInfo.decode(e,e.uint32());break}case 7:{s.messageAddOnKey=p.proto.MessageKey.decode(e,e.uint32());break}case 8:{s.legacyMessage=p.proto.LegacyMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageAddOn)return e;var a=new p.proto.MessageAddOn;switch(e.messageAddOnType){default:if(typeof e.messageAddOnType=="number"){a.messageAddOnType=e.messageAddOnType;break}break;case"UNDEFINED":case 0:a.messageAddOnType=0;break;case"REACTION":case 1:a.messageAddOnType=1;break;case"EVENT_RESPONSE":case 2:a.messageAddOnType=2;break;case"POLL_UPDATE":case 3:a.messageAddOnType=3;break;case"PIN_IN_CHAT":case 4:a.messageAddOnType=4;break}if(e.messageAddOn!=null){if(typeof e.messageAddOn!="object")throw TypeError(".proto.MessageAddOn.messageAddOn: object expected");a.messageAddOn=p.proto.Message.fromObject(e.messageAddOn)}switch(e.senderTimestampMs!=null&&(l.Long?(a.senderTimestampMs=l.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new l.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(l.Long?(a.serverTimestampMs=l.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new l.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),e.status){default:if(typeof e.status=="number"){a.status=e.status;break}break;case"ERROR":case 0:a.status=0;break;case"PENDING":case 1:a.status=1;break;case"SERVER_ACK":case 2:a.status=2;break;case"DELIVERY_ACK":case 3:a.status=3;break;case"READ":case 4:a.status=4;break;case"PLAYED":case 5:a.status=5;break}if(e.addOnContextInfo!=null){if(typeof e.addOnContextInfo!="object")throw TypeError(".proto.MessageAddOn.addOnContextInfo: object expected");a.addOnContextInfo=p.proto.MessageAddOnContextInfo.fromObject(e.addOnContextInfo)}if(e.messageAddOnKey!=null){if(typeof e.messageAddOnKey!="object")throw TypeError(".proto.MessageAddOn.messageAddOnKey: object expected");a.messageAddOnKey=p.proto.MessageKey.fromObject(e.messageAddOnKey)}if(e.legacyMessage!=null){if(typeof e.legacyMessage!="object")throw TypeError(".proto.MessageAddOn.legacyMessage: object expected");a.legacyMessage=p.proto.LegacyMessage.fromObject(e.legacyMessage)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.messageAddOnType!=null&&e.hasOwnProperty("messageAddOnType")&&(A.messageAddOnType=a.enums===String?p.proto.MessageAddOn.MessageAddOnType[e.messageAddOnType]===void 0?e.messageAddOnType:p.proto.MessageAddOn.MessageAddOnType[e.messageAddOnType]:e.messageAddOnType,a.oneofs&&(A._messageAddOnType="messageAddOnType")),e.messageAddOn!=null&&e.hasOwnProperty("messageAddOn")&&(A.messageAddOn=p.proto.Message.toObject(e.messageAddOn,a),a.oneofs&&(A._messageAddOn="messageAddOn")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?se(e.senderTimestampMs):a.longs===Number?ge(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?se(e.serverTimestampMs):a.longs===Number?ge(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),e.status!=null&&e.hasOwnProperty("status")&&(A.status=a.enums===String?p.proto.WebMessageInfo.Status[e.status]===void 0?e.status:p.proto.WebMessageInfo.Status[e.status]:e.status,a.oneofs&&(A._status="status")),e.addOnContextInfo!=null&&e.hasOwnProperty("addOnContextInfo")&&(A.addOnContextInfo=p.proto.MessageAddOnContextInfo.toObject(e.addOnContextInfo,a),a.oneofs&&(A._addOnContextInfo="addOnContextInfo")),e.messageAddOnKey!=null&&e.hasOwnProperty("messageAddOnKey")&&(A.messageAddOnKey=p.proto.MessageKey.toObject(e.messageAddOnKey,a),a.oneofs&&(A._messageAddOnKey="messageAddOnKey")),e.legacyMessage!=null&&e.hasOwnProperty("legacyMessage")&&(A.legacyMessage=p.proto.LegacyMessage.toObject(e.legacyMessage,a),a.oneofs&&(A._legacyMessage="legacyMessage")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageAddOn"},t.MessageAddOnType=(function(){let i={},e=Object.create(i);return e[i[0]="UNDEFINED"]=0,e[i[1]="REACTION"]=1,e[i[2]="EVENT_RESPONSE"]=2,e[i[3]="POLL_UPDATE"]=3,e[i[4]="PIN_IN_CHAT"]=4,e})(),t})(),n.MessageAddOnContextInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageAddOnDurationInSecs=e.uint32();break}case 2:{s.messageAddOnExpiryType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageAddOnContextInfo)return e;var a=new p.proto.MessageAddOnContextInfo;switch(e.messageAddOnDurationInSecs!=null&&(a.messageAddOnDurationInSecs=e.messageAddOnDurationInSecs>>>0),e.messageAddOnExpiryType){default:if(typeof e.messageAddOnExpiryType=="number"){a.messageAddOnExpiryType=e.messageAddOnExpiryType;break}break;case"STATIC":case 1:a.messageAddOnExpiryType=1;break;case"DEPENDENT_ON_PARENT":case 2:a.messageAddOnExpiryType=2;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.messageAddOnDurationInSecs!=null&&e.hasOwnProperty("messageAddOnDurationInSecs")&&(A.messageAddOnDurationInSecs=e.messageAddOnDurationInSecs,a.oneofs&&(A._messageAddOnDurationInSecs="messageAddOnDurationInSecs")),e.messageAddOnExpiryType!=null&&e.hasOwnProperty("messageAddOnExpiryType")&&(A.messageAddOnExpiryType=a.enums===String?p.proto.MessageContextInfo.MessageAddonExpiryType[e.messageAddOnExpiryType]===void 0?e.messageAddOnExpiryType:p.proto.MessageContextInfo.MessageAddonExpiryType[e.messageAddOnExpiryType]:e.messageAddOnExpiryType,a.oneofs&&(A._messageAddOnExpiryType="messageAddOnExpiryType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageAddOnContextInfo"},t})(),n.MessageAssociation=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.associationType=e.int32();break}case 2:{s.parentMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 3:{s.messageIndex=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageAssociation)return e;var a=new p.proto.MessageAssociation;switch(e.associationType){default:if(typeof e.associationType=="number"){a.associationType=e.associationType;break}break;case"UNKNOWN":case 0:a.associationType=0;break;case"MEDIA_ALBUM":case 1:a.associationType=1;break;case"BOT_PLUGIN":case 2:a.associationType=2;break;case"EVENT_COVER_IMAGE":case 3:a.associationType=3;break;case"STATUS_POLL":case 4:a.associationType=4;break;case"HD_VIDEO_DUAL_UPLOAD":case 5:a.associationType=5;break;case"STATUS_EXTERNAL_RESHARE":case 6:a.associationType=6;break;case"MEDIA_POLL":case 7:a.associationType=7;break;case"STATUS_ADD_YOURS":case 8:a.associationType=8;break;case"STATUS_NOTIFICATION":case 9:a.associationType=9;break;case"HD_IMAGE_DUAL_UPLOAD":case 10:a.associationType=10;break;case"STICKER_ANNOTATION":case 11:a.associationType=11;break;case"MOTION_PHOTO":case 12:a.associationType=12;break;case"STATUS_LINK_ACTION":case 13:a.associationType=13;break;case"VIEW_ALL_REPLIES":case 14:a.associationType=14;break;case"STATUS_ADD_YOURS_AI_IMAGINE":case 15:a.associationType=15;break;case"STATUS_QUESTION":case 16:a.associationType=16;break;case"STATUS_ADD_YOURS_DIWALI":case 17:a.associationType=17;break;case"STATUS_REACTION":case 18:a.associationType=18;break;case"HEVC_VIDEO_DUAL_UPLOAD":case 19:a.associationType=19;break}if(e.parentMessageKey!=null){if(typeof e.parentMessageKey!="object")throw TypeError(".proto.MessageAssociation.parentMessageKey: object expected");a.parentMessageKey=p.proto.MessageKey.fromObject(e.parentMessageKey)}return e.messageIndex!=null&&(a.messageIndex=e.messageIndex|0),a},t.toObject=function(e,a){a||(a={});var A={};return e.associationType!=null&&e.hasOwnProperty("associationType")&&(A.associationType=a.enums===String?p.proto.MessageAssociation.AssociationType[e.associationType]===void 0?e.associationType:p.proto.MessageAssociation.AssociationType[e.associationType]:e.associationType,a.oneofs&&(A._associationType="associationType")),e.parentMessageKey!=null&&e.hasOwnProperty("parentMessageKey")&&(A.parentMessageKey=p.proto.MessageKey.toObject(e.parentMessageKey,a),a.oneofs&&(A._parentMessageKey="parentMessageKey")),e.messageIndex!=null&&e.hasOwnProperty("messageIndex")&&(A.messageIndex=e.messageIndex,a.oneofs&&(A._messageIndex="messageIndex")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageAssociation"},t.AssociationType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="MEDIA_ALBUM"]=1,e[i[2]="BOT_PLUGIN"]=2,e[i[3]="EVENT_COVER_IMAGE"]=3,e[i[4]="STATUS_POLL"]=4,e[i[5]="HD_VIDEO_DUAL_UPLOAD"]=5,e[i[6]="STATUS_EXTERNAL_RESHARE"]=6,e[i[7]="MEDIA_POLL"]=7,e[i[8]="STATUS_ADD_YOURS"]=8,e[i[9]="STATUS_NOTIFICATION"]=9,e[i[10]="HD_IMAGE_DUAL_UPLOAD"]=10,e[i[11]="STICKER_ANNOTATION"]=11,e[i[12]="MOTION_PHOTO"]=12,e[i[13]="STATUS_LINK_ACTION"]=13,e[i[14]="VIEW_ALL_REPLIES"]=14,e[i[15]="STATUS_ADD_YOURS_AI_IMAGINE"]=15,e[i[16]="STATUS_QUESTION"]=16,e[i[17]="STATUS_ADD_YOURS_DIWALI"]=17,e[i[18]="STATUS_REACTION"]=18,e[i[19]="HEVC_VIDEO_DUAL_UPLOAD"]=19,e})(),t})(),n.MessageContextInfo=(function(){function t(i){if(this.threadId=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.deviceListMetadata=p.proto.DeviceListMetadata.decode(e,e.uint32());break}case 2:{s.deviceListMetadataVersion=e.int32();break}case 3:{s.messageSecret=e.bytes();break}case 4:{s.paddingBytes=e.bytes();break}case 5:{s.messageAddOnDurationInSecs=e.uint32();break}case 6:{s.botMessageSecret=e.bytes();break}case 7:{s.botMetadata=p.proto.BotMetadata.decode(e,e.uint32());break}case 8:{s.reportingTokenVersion=e.int32();break}case 9:{s.messageAddOnExpiryType=e.int32();break}case 10:{s.messageAssociation=p.proto.MessageAssociation.decode(e,e.uint32());break}case 11:{s.capiCreatedGroup=e.bool();break}case 12:{s.supportPayload=e.string();break}case 13:{s.limitSharing=p.proto.LimitSharing.decode(e,e.uint32());break}case 14:{s.limitSharingV2=p.proto.LimitSharing.decode(e,e.uint32());break}case 15:{s.threadId&&s.threadId.length||(s.threadId=[]),s.threadId.push(p.proto.ThreadID.decode(e,e.uint32()));break}case 16:{s.weblinkRenderConfig=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageContextInfo)return e;var a=new p.proto.MessageContextInfo;if(e.deviceListMetadata!=null){if(typeof e.deviceListMetadata!="object")throw TypeError(".proto.MessageContextInfo.deviceListMetadata: object expected");a.deviceListMetadata=p.proto.DeviceListMetadata.fromObject(e.deviceListMetadata)}if(e.deviceListMetadataVersion!=null&&(a.deviceListMetadataVersion=e.deviceListMetadataVersion|0),e.messageSecret!=null&&(typeof e.messageSecret=="string"?l.base64.decode(e.messageSecret,a.messageSecret=l.newBuffer(l.base64.length(e.messageSecret)),0):e.messageSecret.length>=0&&(a.messageSecret=e.messageSecret)),e.paddingBytes!=null&&(typeof e.paddingBytes=="string"?l.base64.decode(e.paddingBytes,a.paddingBytes=l.newBuffer(l.base64.length(e.paddingBytes)),0):e.paddingBytes.length>=0&&(a.paddingBytes=e.paddingBytes)),e.messageAddOnDurationInSecs!=null&&(a.messageAddOnDurationInSecs=e.messageAddOnDurationInSecs>>>0),e.botMessageSecret!=null&&(typeof e.botMessageSecret=="string"?l.base64.decode(e.botMessageSecret,a.botMessageSecret=l.newBuffer(l.base64.length(e.botMessageSecret)),0):e.botMessageSecret.length>=0&&(a.botMessageSecret=e.botMessageSecret)),e.botMetadata!=null){if(typeof e.botMetadata!="object")throw TypeError(".proto.MessageContextInfo.botMetadata: object expected");a.botMetadata=p.proto.BotMetadata.fromObject(e.botMetadata)}switch(e.reportingTokenVersion!=null&&(a.reportingTokenVersion=e.reportingTokenVersion|0),e.messageAddOnExpiryType){default:if(typeof e.messageAddOnExpiryType=="number"){a.messageAddOnExpiryType=e.messageAddOnExpiryType;break}break;case"STATIC":case 1:a.messageAddOnExpiryType=1;break;case"DEPENDENT_ON_PARENT":case 2:a.messageAddOnExpiryType=2;break}if(e.messageAssociation!=null){if(typeof e.messageAssociation!="object")throw TypeError(".proto.MessageContextInfo.messageAssociation: object expected");a.messageAssociation=p.proto.MessageAssociation.fromObject(e.messageAssociation)}if(e.capiCreatedGroup!=null&&(a.capiCreatedGroup=!!e.capiCreatedGroup),e.supportPayload!=null&&(a.supportPayload=String(e.supportPayload)),e.limitSharing!=null){if(typeof e.limitSharing!="object")throw TypeError(".proto.MessageContextInfo.limitSharing: object expected");a.limitSharing=p.proto.LimitSharing.fromObject(e.limitSharing)}if(e.limitSharingV2!=null){if(typeof e.limitSharingV2!="object")throw TypeError(".proto.MessageContextInfo.limitSharingV2: object expected");a.limitSharingV2=p.proto.LimitSharing.fromObject(e.limitSharingV2)}if(e.threadId){if(!Array.isArray(e.threadId))throw TypeError(".proto.MessageContextInfo.threadId: array expected");a.threadId=[];for(var A=0;A>>3){case 1:{s.remoteJid=e.string();break}case 2:{s.fromMe=e.bool();break}case 3:{s.id=e.string();break}case 4:{s.participant=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageKey)return e;var a=new p.proto.MessageKey;return e.remoteJid!=null&&(a.remoteJid=String(e.remoteJid)),e.fromMe!=null&&(a.fromMe=!!e.fromMe),e.id!=null&&(a.id=String(e.id)),e.participant!=null&&(a.participant=String(e.participant)),a},t.toObject=function(e,a){a||(a={});var A={};return e.remoteJid!=null&&e.hasOwnProperty("remoteJid")&&(A.remoteJid=e.remoteJid,a.oneofs&&(A._remoteJid="remoteJid")),e.fromMe!=null&&e.hasOwnProperty("fromMe")&&(A.fromMe=e.fromMe,a.oneofs&&(A._fromMe="fromMe")),e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.participant!=null&&e.hasOwnProperty("participant")&&(A.participant=e.participant,a.oneofs&&(A._participant="participant")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageKey"},t})(),n.MessageSecretMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.version=e.sfixed32();break}case 2:{s.encIv=e.bytes();break}case 3:{s.encPayload=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MessageSecretMessage)return e;var a=new p.proto.MessageSecretMessage;return e.version!=null&&(a.version=e.version|0),e.encIv!=null&&(typeof e.encIv=="string"?l.base64.decode(e.encIv,a.encIv=l.newBuffer(l.base64.length(e.encIv)),0):e.encIv.length>=0&&(a.encIv=e.encIv)),e.encPayload!=null&&(typeof e.encPayload=="string"?l.base64.decode(e.encPayload,a.encPayload=l.newBuffer(l.base64.length(e.encPayload)),0):e.encPayload.length>=0&&(a.encPayload=e.encPayload)),a},t.toObject=function(e,a){a||(a={});var A={};return e.version!=null&&e.hasOwnProperty("version")&&(A.version=e.version,a.oneofs&&(A._version="version")),e.encIv!=null&&e.hasOwnProperty("encIv")&&(A.encIv=a.bytes===String?l.base64.encode(e.encIv,0,e.encIv.length):a.bytes===Array?Array.prototype.slice.call(e.encIv):e.encIv,a.oneofs&&(A._encIv="encIv")),e.encPayload!=null&&e.hasOwnProperty("encPayload")&&(A.encPayload=a.bytes===String?l.base64.encode(e.encPayload,0,e.encPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encPayload):e.encPayload,a.oneofs&&(A._encPayload="encPayload")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MessageSecretMessage"},t})(),n.Money=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.value=e.int64();break}case 2:{s.offset=e.uint32();break}case 3:{s.currencyCode=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Money)return e;var a=new p.proto.Money;return e.value!=null&&(l.Long?(a.value=l.Long.fromValue(e.value)).unsigned=!1:typeof e.value=="string"?a.value=parseInt(e.value,10):typeof e.value=="number"?a.value=e.value:typeof e.value=="object"&&(a.value=new l.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber())),e.offset!=null&&(a.offset=e.offset>>>0),e.currencyCode!=null&&(a.currencyCode=String(e.currencyCode)),a},t.toObject=function(e,a){a||(a={});var A={};return e.value!=null&&e.hasOwnProperty("value")&&(typeof e.value=="number"?A.value=a.longs===String?String(e.value):e.value:A.value=a.longs===String?se(e.value):a.longs===Number?ge(e.value):e.value,a.oneofs&&(A._value="value")),e.offset!=null&&e.hasOwnProperty("offset")&&(A.offset=e.offset,a.oneofs&&(A._offset="offset")),e.currencyCode!=null&&e.hasOwnProperty("currencyCode")&&(A.currencyCode=e.currencyCode,a.oneofs&&(A._currencyCode="currencyCode")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Money"},t})(),n.MsgOpaqueData=(function(){function t(i){if(this.pollOptions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.body=e.string();break}case 3:{s.caption=e.string();break}case 5:{s.lng=e.double();break}case 6:{s.isLive=e.bool();break}case 7:{s.lat=e.double();break}case 8:{s.paymentAmount1000=e.int32();break}case 9:{s.paymentNoteMsgBody=e.string();break}case 11:{s.matchedText=e.string();break}case 12:{s.title=e.string();break}case 13:{s.description=e.string();break}case 14:{s.futureproofBuffer=e.bytes();break}case 15:{s.clientUrl=e.string();break}case 16:{s.loc=e.string();break}case 17:{s.pollName=e.string();break}case 18:{s.pollOptions&&s.pollOptions.length||(s.pollOptions=[]),s.pollOptions.push(p.proto.MsgOpaqueData.PollOption.decode(e,e.uint32()));break}case 20:{s.pollSelectableOptionsCount=e.uint32();break}case 21:{s.messageSecret=e.bytes();break}case 51:{s.originalSelfAuthor=e.string();break}case 22:{s.senderTimestampMs=e.int64();break}case 23:{s.pollUpdateParentKey=e.string();break}case 24:{s.encPollVote=p.proto.PollEncValue.decode(e,e.uint32());break}case 28:{s.isSentCagPollCreation=e.bool();break}case 42:{s.pollContentType=e.int32();break}case 46:{s.pollType=e.int32();break}case 47:{s.correctOptionIndex=e.int32();break}case 41:{s.pollVotesSnapshot=p.proto.MsgOpaqueData.PollVotesSnapshot.decode(e,e.uint32());break}case 25:{s.encReactionTargetMessageKey=e.string();break}case 26:{s.encReactionEncPayload=e.bytes();break}case 27:{s.encReactionEncIv=e.bytes();break}case 29:{s.botMessageSecret=e.bytes();break}case 30:{s.targetMessageKey=e.string();break}case 31:{s.encPayload=e.bytes();break}case 32:{s.encIv=e.bytes();break}case 33:{s.eventName=e.string();break}case 34:{s.isEventCanceled=e.bool();break}case 35:{s.eventDescription=e.string();break}case 36:{s.eventJoinLink=e.string();break}case 37:{s.eventStartTime=e.int64();break}case 38:{s.eventLocation=p.proto.MsgOpaqueData.EventLocation.decode(e,e.uint32());break}case 40:{s.eventEndTime=e.int64();break}case 44:{s.eventIsScheduledCall=e.bool();break}case 45:{s.eventExtraGuestsAllowed=e.bool();break}case 43:{s.plainProtobufBytes=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MsgOpaqueData)return e;var a=new p.proto.MsgOpaqueData;if(e.body!=null&&(a.body=String(e.body)),e.caption!=null&&(a.caption=String(e.caption)),e.lng!=null&&(a.lng=Number(e.lng)),e.isLive!=null&&(a.isLive=!!e.isLive),e.lat!=null&&(a.lat=Number(e.lat)),e.paymentAmount1000!=null&&(a.paymentAmount1000=e.paymentAmount1000|0),e.paymentNoteMsgBody!=null&&(a.paymentNoteMsgBody=String(e.paymentNoteMsgBody)),e.matchedText!=null&&(a.matchedText=String(e.matchedText)),e.title!=null&&(a.title=String(e.title)),e.description!=null&&(a.description=String(e.description)),e.futureproofBuffer!=null&&(typeof e.futureproofBuffer=="string"?l.base64.decode(e.futureproofBuffer,a.futureproofBuffer=l.newBuffer(l.base64.length(e.futureproofBuffer)),0):e.futureproofBuffer.length>=0&&(a.futureproofBuffer=e.futureproofBuffer)),e.clientUrl!=null&&(a.clientUrl=String(e.clientUrl)),e.loc!=null&&(a.loc=String(e.loc)),e.pollName!=null&&(a.pollName=String(e.pollName)),e.pollOptions){if(!Array.isArray(e.pollOptions))throw TypeError(".proto.MsgOpaqueData.pollOptions: array expected");a.pollOptions=[];for(var A=0;A>>0),e.messageSecret!=null&&(typeof e.messageSecret=="string"?l.base64.decode(e.messageSecret,a.messageSecret=l.newBuffer(l.base64.length(e.messageSecret)),0):e.messageSecret.length>=0&&(a.messageSecret=e.messageSecret)),e.originalSelfAuthor!=null&&(a.originalSelfAuthor=String(e.originalSelfAuthor)),e.senderTimestampMs!=null&&(l.Long?(a.senderTimestampMs=l.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new l.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.pollUpdateParentKey!=null&&(a.pollUpdateParentKey=String(e.pollUpdateParentKey)),e.encPollVote!=null){if(typeof e.encPollVote!="object")throw TypeError(".proto.MsgOpaqueData.encPollVote: object expected");a.encPollVote=p.proto.PollEncValue.fromObject(e.encPollVote)}switch(e.isSentCagPollCreation!=null&&(a.isSentCagPollCreation=!!e.isSentCagPollCreation),e.pollContentType){default:if(typeof e.pollContentType=="number"){a.pollContentType=e.pollContentType;break}break;case"UNKNOWN":case 0:a.pollContentType=0;break;case"TEXT":case 1:a.pollContentType=1;break;case"IMAGE":case 2:a.pollContentType=2;break}switch(e.pollType){default:if(typeof e.pollType=="number"){a.pollType=e.pollType;break}break;case"POLL":case 0:a.pollType=0;break;case"QUIZ":case 1:a.pollType=1;break}if(e.correctOptionIndex!=null&&(a.correctOptionIndex=e.correctOptionIndex|0),e.pollVotesSnapshot!=null){if(typeof e.pollVotesSnapshot!="object")throw TypeError(".proto.MsgOpaqueData.pollVotesSnapshot: object expected");a.pollVotesSnapshot=p.proto.MsgOpaqueData.PollVotesSnapshot.fromObject(e.pollVotesSnapshot)}if(e.encReactionTargetMessageKey!=null&&(a.encReactionTargetMessageKey=String(e.encReactionTargetMessageKey)),e.encReactionEncPayload!=null&&(typeof e.encReactionEncPayload=="string"?l.base64.decode(e.encReactionEncPayload,a.encReactionEncPayload=l.newBuffer(l.base64.length(e.encReactionEncPayload)),0):e.encReactionEncPayload.length>=0&&(a.encReactionEncPayload=e.encReactionEncPayload)),e.encReactionEncIv!=null&&(typeof e.encReactionEncIv=="string"?l.base64.decode(e.encReactionEncIv,a.encReactionEncIv=l.newBuffer(l.base64.length(e.encReactionEncIv)),0):e.encReactionEncIv.length>=0&&(a.encReactionEncIv=e.encReactionEncIv)),e.botMessageSecret!=null&&(typeof e.botMessageSecret=="string"?l.base64.decode(e.botMessageSecret,a.botMessageSecret=l.newBuffer(l.base64.length(e.botMessageSecret)),0):e.botMessageSecret.length>=0&&(a.botMessageSecret=e.botMessageSecret)),e.targetMessageKey!=null&&(a.targetMessageKey=String(e.targetMessageKey)),e.encPayload!=null&&(typeof e.encPayload=="string"?l.base64.decode(e.encPayload,a.encPayload=l.newBuffer(l.base64.length(e.encPayload)),0):e.encPayload.length>=0&&(a.encPayload=e.encPayload)),e.encIv!=null&&(typeof e.encIv=="string"?l.base64.decode(e.encIv,a.encIv=l.newBuffer(l.base64.length(e.encIv)),0):e.encIv.length>=0&&(a.encIv=e.encIv)),e.eventName!=null&&(a.eventName=String(e.eventName)),e.isEventCanceled!=null&&(a.isEventCanceled=!!e.isEventCanceled),e.eventDescription!=null&&(a.eventDescription=String(e.eventDescription)),e.eventJoinLink!=null&&(a.eventJoinLink=String(e.eventJoinLink)),e.eventStartTime!=null&&(l.Long?(a.eventStartTime=l.Long.fromValue(e.eventStartTime)).unsigned=!1:typeof e.eventStartTime=="string"?a.eventStartTime=parseInt(e.eventStartTime,10):typeof e.eventStartTime=="number"?a.eventStartTime=e.eventStartTime:typeof e.eventStartTime=="object"&&(a.eventStartTime=new l.LongBits(e.eventStartTime.low>>>0,e.eventStartTime.high>>>0).toNumber())),e.eventLocation!=null){if(typeof e.eventLocation!="object")throw TypeError(".proto.MsgOpaqueData.eventLocation: object expected");a.eventLocation=p.proto.MsgOpaqueData.EventLocation.fromObject(e.eventLocation)}return e.eventEndTime!=null&&(l.Long?(a.eventEndTime=l.Long.fromValue(e.eventEndTime)).unsigned=!1:typeof e.eventEndTime=="string"?a.eventEndTime=parseInt(e.eventEndTime,10):typeof e.eventEndTime=="number"?a.eventEndTime=e.eventEndTime:typeof e.eventEndTime=="object"&&(a.eventEndTime=new l.LongBits(e.eventEndTime.low>>>0,e.eventEndTime.high>>>0).toNumber())),e.eventIsScheduledCall!=null&&(a.eventIsScheduledCall=!!e.eventIsScheduledCall),e.eventExtraGuestsAllowed!=null&&(a.eventExtraGuestsAllowed=!!e.eventExtraGuestsAllowed),e.plainProtobufBytes!=null&&(typeof e.plainProtobufBytes=="string"?l.base64.decode(e.plainProtobufBytes,a.plainProtobufBytes=l.newBuffer(l.base64.length(e.plainProtobufBytes)),0):e.plainProtobufBytes.length>=0&&(a.plainProtobufBytes=e.plainProtobufBytes)),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.pollOptions=[]),e.body!=null&&e.hasOwnProperty("body")&&(A.body=e.body,a.oneofs&&(A._body="body")),e.caption!=null&&e.hasOwnProperty("caption")&&(A.caption=e.caption,a.oneofs&&(A._caption="caption")),e.lng!=null&&e.hasOwnProperty("lng")&&(A.lng=a.json&&!isFinite(e.lng)?String(e.lng):e.lng,a.oneofs&&(A._lng="lng")),e.isLive!=null&&e.hasOwnProperty("isLive")&&(A.isLive=e.isLive,a.oneofs&&(A._isLive="isLive")),e.lat!=null&&e.hasOwnProperty("lat")&&(A.lat=a.json&&!isFinite(e.lat)?String(e.lat):e.lat,a.oneofs&&(A._lat="lat")),e.paymentAmount1000!=null&&e.hasOwnProperty("paymentAmount1000")&&(A.paymentAmount1000=e.paymentAmount1000,a.oneofs&&(A._paymentAmount1000="paymentAmount1000")),e.paymentNoteMsgBody!=null&&e.hasOwnProperty("paymentNoteMsgBody")&&(A.paymentNoteMsgBody=e.paymentNoteMsgBody,a.oneofs&&(A._paymentNoteMsgBody="paymentNoteMsgBody")),e.matchedText!=null&&e.hasOwnProperty("matchedText")&&(A.matchedText=e.matchedText,a.oneofs&&(A._matchedText="matchedText")),e.title!=null&&e.hasOwnProperty("title")&&(A.title=e.title,a.oneofs&&(A._title="title")),e.description!=null&&e.hasOwnProperty("description")&&(A.description=e.description,a.oneofs&&(A._description="description")),e.futureproofBuffer!=null&&e.hasOwnProperty("futureproofBuffer")&&(A.futureproofBuffer=a.bytes===String?l.base64.encode(e.futureproofBuffer,0,e.futureproofBuffer.length):a.bytes===Array?Array.prototype.slice.call(e.futureproofBuffer):e.futureproofBuffer,a.oneofs&&(A._futureproofBuffer="futureproofBuffer")),e.clientUrl!=null&&e.hasOwnProperty("clientUrl")&&(A.clientUrl=e.clientUrl,a.oneofs&&(A._clientUrl="clientUrl")),e.loc!=null&&e.hasOwnProperty("loc")&&(A.loc=e.loc,a.oneofs&&(A._loc="loc")),e.pollName!=null&&e.hasOwnProperty("pollName")&&(A.pollName=e.pollName,a.oneofs&&(A._pollName="pollName")),e.pollOptions&&e.pollOptions.length){A.pollOptions=[];for(var r=0;r>>3){case 1:{c.degreesLatitude=A.double();break}case 2:{c.degreesLongitude=A.double();break}case 3:{c.name=A.string();break}case 4:{c.address=A.string();break}case 5:{c.url=A.string();break}case 6:{c.jpegThumbnail=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.MsgOpaqueData.EventLocation)return A;var r=new p.proto.MsgOpaqueData.EventLocation;return A.degreesLatitude!=null&&(r.degreesLatitude=Number(A.degreesLatitude)),A.degreesLongitude!=null&&(r.degreesLongitude=Number(A.degreesLongitude)),A.name!=null&&(r.name=String(A.name)),A.address!=null&&(r.address=String(A.address)),A.url!=null&&(r.url=String(A.url)),A.jpegThumbnail!=null&&(typeof A.jpegThumbnail=="string"?l.base64.decode(A.jpegThumbnail,r.jpegThumbnail=l.newBuffer(l.base64.length(A.jpegThumbnail)),0):A.jpegThumbnail.length>=0&&(r.jpegThumbnail=A.jpegThumbnail)),r},i.toObject=function(A,r){r||(r={});var s={};return A.degreesLatitude!=null&&A.hasOwnProperty("degreesLatitude")&&(s.degreesLatitude=r.json&&!isFinite(A.degreesLatitude)?String(A.degreesLatitude):A.degreesLatitude,r.oneofs&&(s._degreesLatitude="degreesLatitude")),A.degreesLongitude!=null&&A.hasOwnProperty("degreesLongitude")&&(s.degreesLongitude=r.json&&!isFinite(A.degreesLongitude)?String(A.degreesLongitude):A.degreesLongitude,r.oneofs&&(s._degreesLongitude="degreesLongitude")),A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.address!=null&&A.hasOwnProperty("address")&&(s.address=A.address,r.oneofs&&(s._address="address")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.jpegThumbnail!=null&&A.hasOwnProperty("jpegThumbnail")&&(s.jpegThumbnail=r.bytes===String?l.base64.encode(A.jpegThumbnail,0,A.jpegThumbnail.length):r.bytes===Array?Array.prototype.slice.call(A.jpegThumbnail):A.jpegThumbnail,r.oneofs&&(s._jpegThumbnail="jpegThumbnail")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.MsgOpaqueData.EventLocation"},i})(),t.PollContentType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="TEXT"]=1,e[i[2]="IMAGE"]=2,e})(),t.PollOption=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}case 2:{c.hash=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.MsgOpaqueData.PollOption)return A;var r=new p.proto.MsgOpaqueData.PollOption;return A.name!=null&&(r.name=String(A.name)),A.hash!=null&&(r.hash=String(A.hash)),r},i.toObject=function(A,r){r||(r={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.hash!=null&&A.hasOwnProperty("hash")&&(s.hash=A.hash,r.oneofs&&(s._hash="hash")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.MsgOpaqueData.PollOption"},i})(),t.PollType=(function(){let i={},e=Object.create(i);return e[i[0]="POLL"]=0,e[i[1]="QUIZ"]=1,e})(),t.PollVoteSnapshot=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.option=p.proto.MsgOpaqueData.PollOption.decode(A,A.uint32());break}case 2:{c.optionVoteCount=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.MsgOpaqueData.PollVoteSnapshot)return A;var r=new p.proto.MsgOpaqueData.PollVoteSnapshot;if(A.option!=null){if(typeof A.option!="object")throw TypeError(".proto.MsgOpaqueData.PollVoteSnapshot.option: object expected");r.option=p.proto.MsgOpaqueData.PollOption.fromObject(A.option)}return A.optionVoteCount!=null&&(r.optionVoteCount=A.optionVoteCount|0),r},i.toObject=function(A,r){r||(r={});var s={};return A.option!=null&&A.hasOwnProperty("option")&&(s.option=p.proto.MsgOpaqueData.PollOption.toObject(A.option,r),r.oneofs&&(s._option="option")),A.optionVoteCount!=null&&A.hasOwnProperty("optionVoteCount")&&(s.optionVoteCount=A.optionVoteCount,r.oneofs&&(s._optionVoteCount="optionVoteCount")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.MsgOpaqueData.PollVoteSnapshot"},i})(),t.PollVotesSnapshot=(function(){function i(e){if(this.pollVotes=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.pollVotes&&g.pollVotes.length||(g.pollVotes=[]),g.pollVotes.push(p.proto.MsgOpaqueData.PollVoteSnapshot.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.MsgOpaqueData.PollVotesSnapshot)return a;var A=new p.proto.MsgOpaqueData.PollVotesSnapshot;if(a.pollVotes){if(!Array.isArray(a.pollVotes))throw TypeError(".proto.MsgOpaqueData.PollVotesSnapshot.pollVotes: array expected");A.pollVotes=[];for(var r=0;r>>3){case 1:{s.currentMsg=p.proto.MsgOpaqueData.decode(e,e.uint32());break}case 2:{s.quotedMsg=p.proto.MsgOpaqueData.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.MsgRowOpaqueData)return e;var a=new p.proto.MsgRowOpaqueData;if(e.currentMsg!=null){if(typeof e.currentMsg!="object")throw TypeError(".proto.MsgRowOpaqueData.currentMsg: object expected");a.currentMsg=p.proto.MsgOpaqueData.fromObject(e.currentMsg)}if(e.quotedMsg!=null){if(typeof e.quotedMsg!="object")throw TypeError(".proto.MsgRowOpaqueData.quotedMsg: object expected");a.quotedMsg=p.proto.MsgOpaqueData.fromObject(e.quotedMsg)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.currentMsg!=null&&e.hasOwnProperty("currentMsg")&&(A.currentMsg=p.proto.MsgOpaqueData.toObject(e.currentMsg,a),a.oneofs&&(A._currentMsg="currentMsg")),e.quotedMsg!=null&&e.hasOwnProperty("quotedMsg")&&(A.quotedMsg=p.proto.MsgOpaqueData.toObject(e.quotedMsg,a),a.oneofs&&(A._quotedMsg="quotedMsg")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.MsgRowOpaqueData"},t})(),n.MutationProps=(function(){let t={},o=Object.create(t);return o[t[2]="STAR_ACTION"]=2,o[t[3]="CONTACT_ACTION"]=3,o[t[4]="MUTE_ACTION"]=4,o[t[5]="PIN_ACTION"]=5,o[t[6]="SECURITY_NOTIFICATION_SETTING"]=6,o[t[7]="PUSH_NAME_SETTING"]=7,o[t[8]="QUICK_REPLY_ACTION"]=8,o[t[11]="RECENT_EMOJI_WEIGHTS_ACTION"]=11,o[t[13]="LABEL_MESSAGE_ACTION"]=13,o[t[14]="LABEL_EDIT_ACTION"]=14,o[t[15]="LABEL_ASSOCIATION_ACTION"]=15,o[t[16]="LOCALE_SETTING"]=16,o[t[17]="ARCHIVE_CHAT_ACTION"]=17,o[t[18]="DELETE_MESSAGE_FOR_ME_ACTION"]=18,o[t[19]="KEY_EXPIRATION"]=19,o[t[20]="MARK_CHAT_AS_READ_ACTION"]=20,o[t[21]="CLEAR_CHAT_ACTION"]=21,o[t[22]="DELETE_CHAT_ACTION"]=22,o[t[23]="UNARCHIVE_CHATS_SETTING"]=23,o[t[24]="PRIMARY_FEATURE"]=24,o[t[26]="ANDROID_UNSUPPORTED_ACTIONS"]=26,o[t[27]="AGENT_ACTION"]=27,o[t[28]="SUBSCRIPTION_ACTION"]=28,o[t[29]="USER_STATUS_MUTE_ACTION"]=29,o[t[30]="TIME_FORMAT_ACTION"]=30,o[t[31]="NUX_ACTION"]=31,o[t[32]="PRIMARY_VERSION_ACTION"]=32,o[t[33]="STICKER_ACTION"]=33,o[t[34]="REMOVE_RECENT_STICKER_ACTION"]=34,o[t[35]="CHAT_ASSIGNMENT"]=35,o[t[36]="CHAT_ASSIGNMENT_OPENED_STATUS"]=36,o[t[37]="PN_FOR_LID_CHAT_ACTION"]=37,o[t[38]="MARKETING_MESSAGE_ACTION"]=38,o[t[39]="MARKETING_MESSAGE_BROADCAST_ACTION"]=39,o[t[40]="EXTERNAL_WEB_BETA_ACTION"]=40,o[t[41]="PRIVACY_SETTING_RELAY_ALL_CALLS"]=41,o[t[42]="CALL_LOG_ACTION"]=42,o[t[43]="UGC_BOT"]=43,o[t[44]="STATUS_PRIVACY"]=44,o[t[45]="BOT_WELCOME_REQUEST_ACTION"]=45,o[t[46]="DELETE_INDIVIDUAL_CALL_LOG"]=46,o[t[47]="LABEL_REORDERING_ACTION"]=47,o[t[48]="PAYMENT_INFO_ACTION"]=48,o[t[49]="CUSTOM_PAYMENT_METHODS_ACTION"]=49,o[t[50]="LOCK_CHAT_ACTION"]=50,o[t[51]="CHAT_LOCK_SETTINGS"]=51,o[t[52]="WAMO_USER_IDENTIFIER_ACTION"]=52,o[t[53]="PRIVACY_SETTING_DISABLE_LINK_PREVIEWS_ACTION"]=53,o[t[54]="DEVICE_CAPABILITIES"]=54,o[t[55]="NOTE_EDIT_ACTION"]=55,o[t[56]="FAVORITES_ACTION"]=56,o[t[57]="MERCHANT_PAYMENT_PARTNER_ACTION"]=57,o[t[58]="WAFFLE_ACCOUNT_LINK_STATE_ACTION"]=58,o[t[59]="USERNAME_CHAT_START_MODE"]=59,o[t[60]="NOTIFICATION_ACTIVITY_SETTING_ACTION"]=60,o[t[61]="LID_CONTACT_ACTION"]=61,o[t[62]="CTWA_PER_CUSTOMER_DATA_SHARING_ACTION"]=62,o[t[63]="PAYMENT_TOS_ACTION"]=63,o[t[64]="PRIVACY_SETTING_CHANNELS_PERSONALISED_RECOMMENDATION_ACTION"]=64,o[t[65]="BUSINESS_BROADCAST_ASSOCIATION_ACTION"]=65,o[t[66]="DETECTED_OUTCOMES_STATUS_ACTION"]=66,o[t[68]="MAIBA_AI_FEATURES_CONTROL_ACTION"]=68,o[t[69]="BUSINESS_BROADCAST_LIST_ACTION"]=69,o[t[70]="MUSIC_USER_ID_ACTION"]=70,o[t[71]="STATUS_POST_OPT_IN_NOTIFICATION_PREFERENCES_ACTION"]=71,o[t[72]="AVATAR_UPDATED_ACTION"]=72,o[t[73]="GALAXY_FLOW_ACTION"]=73,o[t[74]="PRIVATE_PROCESSING_SETTING_ACTION"]=74,o[t[75]="NEWSLETTER_SAVED_INTERESTS_ACTION"]=75,o[t[76]="AI_THREAD_RENAME_ACTION"]=76,o[t[77]="INTERACTIVE_MESSAGE_ACTION"]=77,o[t[10001]="SHARE_OWN_PN"]=10001,o[t[10002]="BUSINESS_BROADCAST_ACTION"]=10002,o})(),n.NoiseCertificate=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.details=e.bytes();break}case 2:{s.signature=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.NoiseCertificate)return e;var a=new p.proto.NoiseCertificate;return e.details!=null&&(typeof e.details=="string"?l.base64.decode(e.details,a.details=l.newBuffer(l.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.signature!=null&&(typeof e.signature=="string"?l.base64.decode(e.signature,a.signature=l.newBuffer(l.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),a},t.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?l.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?l.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.NoiseCertificate"},t.Details=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.serial=A.uint32();break}case 2:{c.issuer=A.string();break}case 3:{c.expires=A.uint64();break}case 4:{c.subject=A.string();break}case 5:{c.key=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.NoiseCertificate.Details)return A;var r=new p.proto.NoiseCertificate.Details;return A.serial!=null&&(r.serial=A.serial>>>0),A.issuer!=null&&(r.issuer=String(A.issuer)),A.expires!=null&&(l.Long?(r.expires=l.Long.fromValue(A.expires)).unsigned=!0:typeof A.expires=="string"?r.expires=parseInt(A.expires,10):typeof A.expires=="number"?r.expires=A.expires:typeof A.expires=="object"&&(r.expires=new l.LongBits(A.expires.low>>>0,A.expires.high>>>0).toNumber(!0))),A.subject!=null&&(r.subject=String(A.subject)),A.key!=null&&(typeof A.key=="string"?l.base64.decode(A.key,r.key=l.newBuffer(l.base64.length(A.key)),0):A.key.length>=0&&(r.key=A.key)),r},i.toObject=function(A,r){r||(r={});var s={};return A.serial!=null&&A.hasOwnProperty("serial")&&(s.serial=A.serial,r.oneofs&&(s._serial="serial")),A.issuer!=null&&A.hasOwnProperty("issuer")&&(s.issuer=A.issuer,r.oneofs&&(s._issuer="issuer")),A.expires!=null&&A.hasOwnProperty("expires")&&(typeof A.expires=="number"?s.expires=r.longs===String?String(A.expires):A.expires:s.expires=r.longs===String?se(A.expires,!0):r.longs===Number?ge(A.expires,!0):A.expires,r.oneofs&&(s._expires="expires")),A.subject!=null&&A.hasOwnProperty("subject")&&(s.subject=A.subject,r.oneofs&&(s._subject="subject")),A.key!=null&&A.hasOwnProperty("key")&&(s.key=r.bytes===String?l.base64.encode(A.key,0,A.key.length):r.bytes===Array?Array.prototype.slice.call(A.key):A.key,r.oneofs&&(s._key="key")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.NoiseCertificate.Details"},i})(),t})(),n.NotificationMessageInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.key=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.message=p.proto.Message.decode(e,e.uint32());break}case 3:{s.messageTimestamp=e.uint64();break}case 4:{s.participant=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.NotificationMessageInfo)return e;var a=new p.proto.NotificationMessageInfo;if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.NotificationMessageInfo.key: object expected");a.key=p.proto.MessageKey.fromObject(e.key)}if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.NotificationMessageInfo.message: object expected");a.message=p.proto.Message.fromObject(e.message)}return e.messageTimestamp!=null&&(l.Long?(a.messageTimestamp=l.Long.fromValue(e.messageTimestamp)).unsigned=!0:typeof e.messageTimestamp=="string"?a.messageTimestamp=parseInt(e.messageTimestamp,10):typeof e.messageTimestamp=="number"?a.messageTimestamp=e.messageTimestamp:typeof e.messageTimestamp=="object"&&(a.messageTimestamp=new l.LongBits(e.messageTimestamp.low>>>0,e.messageTimestamp.high>>>0).toNumber(!0))),e.participant!=null&&(a.participant=String(e.participant)),a},t.toObject=function(e,a){a||(a={});var A={};return e.key!=null&&e.hasOwnProperty("key")&&(A.key=p.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=p.proto.Message.toObject(e.message,a),a.oneofs&&(A._message="message")),e.messageTimestamp!=null&&e.hasOwnProperty("messageTimestamp")&&(typeof e.messageTimestamp=="number"?A.messageTimestamp=a.longs===String?String(e.messageTimestamp):e.messageTimestamp:A.messageTimestamp=a.longs===String?se(e.messageTimestamp,!0):a.longs===Number?ge(e.messageTimestamp,!0):e.messageTimestamp,a.oneofs&&(A._messageTimestamp="messageTimestamp")),e.participant!=null&&e.hasOwnProperty("participant")&&(A.participant=e.participant,a.oneofs&&(A._participant="participant")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.NotificationMessageInfo"},t})(),n.NotificationSettings=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.messageVibrate=e.string();break}case 2:{s.messagePopup=e.string();break}case 3:{s.messageLight=e.string();break}case 4:{s.lowPriorityNotifications=e.bool();break}case 5:{s.reactionsMuted=e.bool();break}case 6:{s.callVibrate=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.NotificationSettings)return e;var a=new p.proto.NotificationSettings;return e.messageVibrate!=null&&(a.messageVibrate=String(e.messageVibrate)),e.messagePopup!=null&&(a.messagePopup=String(e.messagePopup)),e.messageLight!=null&&(a.messageLight=String(e.messageLight)),e.lowPriorityNotifications!=null&&(a.lowPriorityNotifications=!!e.lowPriorityNotifications),e.reactionsMuted!=null&&(a.reactionsMuted=!!e.reactionsMuted),e.callVibrate!=null&&(a.callVibrate=String(e.callVibrate)),a},t.toObject=function(e,a){a||(a={});var A={};return e.messageVibrate!=null&&e.hasOwnProperty("messageVibrate")&&(A.messageVibrate=e.messageVibrate,a.oneofs&&(A._messageVibrate="messageVibrate")),e.messagePopup!=null&&e.hasOwnProperty("messagePopup")&&(A.messagePopup=e.messagePopup,a.oneofs&&(A._messagePopup="messagePopup")),e.messageLight!=null&&e.hasOwnProperty("messageLight")&&(A.messageLight=e.messageLight,a.oneofs&&(A._messageLight="messageLight")),e.lowPriorityNotifications!=null&&e.hasOwnProperty("lowPriorityNotifications")&&(A.lowPriorityNotifications=e.lowPriorityNotifications,a.oneofs&&(A._lowPriorityNotifications="lowPriorityNotifications")),e.reactionsMuted!=null&&e.hasOwnProperty("reactionsMuted")&&(A.reactionsMuted=e.reactionsMuted,a.oneofs&&(A._reactionsMuted="reactionsMuted")),e.callVibrate!=null&&e.hasOwnProperty("callVibrate")&&(A.callVibrate=e.callVibrate,a.oneofs&&(A._callVibrate="callVibrate")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.NotificationSettings"},t})(),n.PairingRequest=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.companionPublicKey=e.bytes();break}case 2:{s.companionIdentityKey=e.bytes();break}case 3:{s.advSecret=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PairingRequest)return e;var a=new p.proto.PairingRequest;return e.companionPublicKey!=null&&(typeof e.companionPublicKey=="string"?l.base64.decode(e.companionPublicKey,a.companionPublicKey=l.newBuffer(l.base64.length(e.companionPublicKey)),0):e.companionPublicKey.length>=0&&(a.companionPublicKey=e.companionPublicKey)),e.companionIdentityKey!=null&&(typeof e.companionIdentityKey=="string"?l.base64.decode(e.companionIdentityKey,a.companionIdentityKey=l.newBuffer(l.base64.length(e.companionIdentityKey)),0):e.companionIdentityKey.length>=0&&(a.companionIdentityKey=e.companionIdentityKey)),e.advSecret!=null&&(typeof e.advSecret=="string"?l.base64.decode(e.advSecret,a.advSecret=l.newBuffer(l.base64.length(e.advSecret)),0):e.advSecret.length>=0&&(a.advSecret=e.advSecret)),a},t.toObject=function(e,a){a||(a={});var A={};return e.companionPublicKey!=null&&e.hasOwnProperty("companionPublicKey")&&(A.companionPublicKey=a.bytes===String?l.base64.encode(e.companionPublicKey,0,e.companionPublicKey.length):a.bytes===Array?Array.prototype.slice.call(e.companionPublicKey):e.companionPublicKey,a.oneofs&&(A._companionPublicKey="companionPublicKey")),e.companionIdentityKey!=null&&e.hasOwnProperty("companionIdentityKey")&&(A.companionIdentityKey=a.bytes===String?l.base64.encode(e.companionIdentityKey,0,e.companionIdentityKey.length):a.bytes===Array?Array.prototype.slice.call(e.companionIdentityKey):e.companionIdentityKey,a.oneofs&&(A._companionIdentityKey="companionIdentityKey")),e.advSecret!=null&&e.hasOwnProperty("advSecret")&&(A.advSecret=a.bytes===String?l.base64.encode(e.advSecret,0,e.advSecret.length):a.bytes===Array?Array.prototype.slice.call(e.advSecret):e.advSecret,a.oneofs&&(A._advSecret="advSecret")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PairingRequest"},t})(),n.PastParticipant=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.userJid=e.string();break}case 2:{s.leaveReason=e.int32();break}case 3:{s.leaveTs=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PastParticipant)return e;var a=new p.proto.PastParticipant;switch(e.userJid!=null&&(a.userJid=String(e.userJid)),e.leaveReason){default:if(typeof e.leaveReason=="number"){a.leaveReason=e.leaveReason;break}break;case"LEFT":case 0:a.leaveReason=0;break;case"REMOVED":case 1:a.leaveReason=1;break}return e.leaveTs!=null&&(l.Long?(a.leaveTs=l.Long.fromValue(e.leaveTs)).unsigned=!0:typeof e.leaveTs=="string"?a.leaveTs=parseInt(e.leaveTs,10):typeof e.leaveTs=="number"?a.leaveTs=e.leaveTs:typeof e.leaveTs=="object"&&(a.leaveTs=new l.LongBits(e.leaveTs.low>>>0,e.leaveTs.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};return e.userJid!=null&&e.hasOwnProperty("userJid")&&(A.userJid=e.userJid,a.oneofs&&(A._userJid="userJid")),e.leaveReason!=null&&e.hasOwnProperty("leaveReason")&&(A.leaveReason=a.enums===String?p.proto.PastParticipant.LeaveReason[e.leaveReason]===void 0?e.leaveReason:p.proto.PastParticipant.LeaveReason[e.leaveReason]:e.leaveReason,a.oneofs&&(A._leaveReason="leaveReason")),e.leaveTs!=null&&e.hasOwnProperty("leaveTs")&&(typeof e.leaveTs=="number"?A.leaveTs=a.longs===String?String(e.leaveTs):e.leaveTs:A.leaveTs=a.longs===String?se(e.leaveTs,!0):a.longs===Number?ge(e.leaveTs,!0):e.leaveTs,a.oneofs&&(A._leaveTs="leaveTs")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PastParticipant"},t.LeaveReason=(function(){let i={},e=Object.create(i);return e[i[0]="LEFT"]=0,e[i[1]="REMOVED"]=1,e})(),t})(),n.PastParticipants=(function(){function t(i){if(this.pastParticipants=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.groupJid=e.string();break}case 2:{s.pastParticipants&&s.pastParticipants.length||(s.pastParticipants=[]),s.pastParticipants.push(p.proto.PastParticipant.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PastParticipants)return e;var a=new p.proto.PastParticipants;if(e.groupJid!=null&&(a.groupJid=String(e.groupJid)),e.pastParticipants){if(!Array.isArray(e.pastParticipants))throw TypeError(".proto.PastParticipants.pastParticipants: array expected");a.pastParticipants=[];for(var A=0;A>>3){case 1:{s.currentLthash=e.bytes();break}case 2:{s.newLthash=e.bytes();break}case 3:{s.patchVersion=e.bytes();break}case 4:{s.collectionName=e.bytes();break}case 5:{s.firstFourBytesFromAHashOfSnapshotMacKey=e.bytes();break}case 6:{s.newLthashSubtract=e.bytes();break}case 7:{s.numberAdd=e.int32();break}case 8:{s.numberRemove=e.int32();break}case 9:{s.numberOverride=e.int32();break}case 10:{s.senderPlatform=e.int32();break}case 11:{s.isSenderPrimary=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PatchDebugData)return e;var a=new p.proto.PatchDebugData;switch(e.currentLthash!=null&&(typeof e.currentLthash=="string"?l.base64.decode(e.currentLthash,a.currentLthash=l.newBuffer(l.base64.length(e.currentLthash)),0):e.currentLthash.length>=0&&(a.currentLthash=e.currentLthash)),e.newLthash!=null&&(typeof e.newLthash=="string"?l.base64.decode(e.newLthash,a.newLthash=l.newBuffer(l.base64.length(e.newLthash)),0):e.newLthash.length>=0&&(a.newLthash=e.newLthash)),e.patchVersion!=null&&(typeof e.patchVersion=="string"?l.base64.decode(e.patchVersion,a.patchVersion=l.newBuffer(l.base64.length(e.patchVersion)),0):e.patchVersion.length>=0&&(a.patchVersion=e.patchVersion)),e.collectionName!=null&&(typeof e.collectionName=="string"?l.base64.decode(e.collectionName,a.collectionName=l.newBuffer(l.base64.length(e.collectionName)),0):e.collectionName.length>=0&&(a.collectionName=e.collectionName)),e.firstFourBytesFromAHashOfSnapshotMacKey!=null&&(typeof e.firstFourBytesFromAHashOfSnapshotMacKey=="string"?l.base64.decode(e.firstFourBytesFromAHashOfSnapshotMacKey,a.firstFourBytesFromAHashOfSnapshotMacKey=l.newBuffer(l.base64.length(e.firstFourBytesFromAHashOfSnapshotMacKey)),0):e.firstFourBytesFromAHashOfSnapshotMacKey.length>=0&&(a.firstFourBytesFromAHashOfSnapshotMacKey=e.firstFourBytesFromAHashOfSnapshotMacKey)),e.newLthashSubtract!=null&&(typeof e.newLthashSubtract=="string"?l.base64.decode(e.newLthashSubtract,a.newLthashSubtract=l.newBuffer(l.base64.length(e.newLthashSubtract)),0):e.newLthashSubtract.length>=0&&(a.newLthashSubtract=e.newLthashSubtract)),e.numberAdd!=null&&(a.numberAdd=e.numberAdd|0),e.numberRemove!=null&&(a.numberRemove=e.numberRemove|0),e.numberOverride!=null&&(a.numberOverride=e.numberOverride|0),e.senderPlatform){default:if(typeof e.senderPlatform=="number"){a.senderPlatform=e.senderPlatform;break}break;case"ANDROID":case 0:a.senderPlatform=0;break;case"SMBA":case 1:a.senderPlatform=1;break;case"IPHONE":case 2:a.senderPlatform=2;break;case"SMBI":case 3:a.senderPlatform=3;break;case"WEB":case 4:a.senderPlatform=4;break;case"UWP":case 5:a.senderPlatform=5;break;case"DARWIN":case 6:a.senderPlatform=6;break;case"IPAD":case 7:a.senderPlatform=7;break;case"WEAROS":case 8:a.senderPlatform=8;break;case"WASG":case 9:a.senderPlatform=9;break;case"WEARM":case 10:a.senderPlatform=10;break;case"CAPI":case 11:a.senderPlatform=11;break}return e.isSenderPrimary!=null&&(a.isSenderPrimary=!!e.isSenderPrimary),a},t.toObject=function(e,a){a||(a={});var A={};return e.currentLthash!=null&&e.hasOwnProperty("currentLthash")&&(A.currentLthash=a.bytes===String?l.base64.encode(e.currentLthash,0,e.currentLthash.length):a.bytes===Array?Array.prototype.slice.call(e.currentLthash):e.currentLthash,a.oneofs&&(A._currentLthash="currentLthash")),e.newLthash!=null&&e.hasOwnProperty("newLthash")&&(A.newLthash=a.bytes===String?l.base64.encode(e.newLthash,0,e.newLthash.length):a.bytes===Array?Array.prototype.slice.call(e.newLthash):e.newLthash,a.oneofs&&(A._newLthash="newLthash")),e.patchVersion!=null&&e.hasOwnProperty("patchVersion")&&(A.patchVersion=a.bytes===String?l.base64.encode(e.patchVersion,0,e.patchVersion.length):a.bytes===Array?Array.prototype.slice.call(e.patchVersion):e.patchVersion,a.oneofs&&(A._patchVersion="patchVersion")),e.collectionName!=null&&e.hasOwnProperty("collectionName")&&(A.collectionName=a.bytes===String?l.base64.encode(e.collectionName,0,e.collectionName.length):a.bytes===Array?Array.prototype.slice.call(e.collectionName):e.collectionName,a.oneofs&&(A._collectionName="collectionName")),e.firstFourBytesFromAHashOfSnapshotMacKey!=null&&e.hasOwnProperty("firstFourBytesFromAHashOfSnapshotMacKey")&&(A.firstFourBytesFromAHashOfSnapshotMacKey=a.bytes===String?l.base64.encode(e.firstFourBytesFromAHashOfSnapshotMacKey,0,e.firstFourBytesFromAHashOfSnapshotMacKey.length):a.bytes===Array?Array.prototype.slice.call(e.firstFourBytesFromAHashOfSnapshotMacKey):e.firstFourBytesFromAHashOfSnapshotMacKey,a.oneofs&&(A._firstFourBytesFromAHashOfSnapshotMacKey="firstFourBytesFromAHashOfSnapshotMacKey")),e.newLthashSubtract!=null&&e.hasOwnProperty("newLthashSubtract")&&(A.newLthashSubtract=a.bytes===String?l.base64.encode(e.newLthashSubtract,0,e.newLthashSubtract.length):a.bytes===Array?Array.prototype.slice.call(e.newLthashSubtract):e.newLthashSubtract,a.oneofs&&(A._newLthashSubtract="newLthashSubtract")),e.numberAdd!=null&&e.hasOwnProperty("numberAdd")&&(A.numberAdd=e.numberAdd,a.oneofs&&(A._numberAdd="numberAdd")),e.numberRemove!=null&&e.hasOwnProperty("numberRemove")&&(A.numberRemove=e.numberRemove,a.oneofs&&(A._numberRemove="numberRemove")),e.numberOverride!=null&&e.hasOwnProperty("numberOverride")&&(A.numberOverride=e.numberOverride,a.oneofs&&(A._numberOverride="numberOverride")),e.senderPlatform!=null&&e.hasOwnProperty("senderPlatform")&&(A.senderPlatform=a.enums===String?p.proto.PatchDebugData.Platform[e.senderPlatform]===void 0?e.senderPlatform:p.proto.PatchDebugData.Platform[e.senderPlatform]:e.senderPlatform,a.oneofs&&(A._senderPlatform="senderPlatform")),e.isSenderPrimary!=null&&e.hasOwnProperty("isSenderPrimary")&&(A.isSenderPrimary=e.isSenderPrimary,a.oneofs&&(A._isSenderPrimary="isSenderPrimary")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PatchDebugData"},t.Platform=(function(){let i={},e=Object.create(i);return e[i[0]="ANDROID"]=0,e[i[1]="SMBA"]=1,e[i[2]="IPHONE"]=2,e[i[3]="SMBI"]=3,e[i[4]="WEB"]=4,e[i[5]="UWP"]=5,e[i[6]="DARWIN"]=6,e[i[7]="IPAD"]=7,e[i[8]="WEAROS"]=8,e[i[9]="WASG"]=9,e[i[10]="WEARM"]=10,e[i[11]="CAPI"]=11,e})(),t})(),n.PaymentBackground=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.string();break}case 2:{s.fileLength=e.uint64();break}case 3:{s.width=e.uint32();break}case 4:{s.height=e.uint32();break}case 5:{s.mimetype=e.string();break}case 6:{s.placeholderArgb=e.fixed32();break}case 7:{s.textArgb=e.fixed32();break}case 8:{s.subtextArgb=e.fixed32();break}case 9:{s.mediaData=p.proto.PaymentBackground.MediaData.decode(e,e.uint32());break}case 10:{s.type=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PaymentBackground)return e;var a=new p.proto.PaymentBackground;if(e.id!=null&&(a.id=String(e.id)),e.fileLength!=null&&(l.Long?(a.fileLength=l.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new l.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),e.width!=null&&(a.width=e.width>>>0),e.height!=null&&(a.height=e.height>>>0),e.mimetype!=null&&(a.mimetype=String(e.mimetype)),e.placeholderArgb!=null&&(a.placeholderArgb=e.placeholderArgb>>>0),e.textArgb!=null&&(a.textArgb=e.textArgb>>>0),e.subtextArgb!=null&&(a.subtextArgb=e.subtextArgb>>>0),e.mediaData!=null){if(typeof e.mediaData!="object")throw TypeError(".proto.PaymentBackground.mediaData: object expected");a.mediaData=p.proto.PaymentBackground.MediaData.fromObject(e.mediaData)}switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"UNKNOWN":case 0:a.type=0;break;case"DEFAULT":case 1:a.type=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.fileLength!=null&&e.hasOwnProperty("fileLength")&&(typeof e.fileLength=="number"?A.fileLength=a.longs===String?String(e.fileLength):e.fileLength:A.fileLength=a.longs===String?se(e.fileLength,!0):a.longs===Number?ge(e.fileLength,!0):e.fileLength,a.oneofs&&(A._fileLength="fileLength")),e.width!=null&&e.hasOwnProperty("width")&&(A.width=e.width,a.oneofs&&(A._width="width")),e.height!=null&&e.hasOwnProperty("height")&&(A.height=e.height,a.oneofs&&(A._height="height")),e.mimetype!=null&&e.hasOwnProperty("mimetype")&&(A.mimetype=e.mimetype,a.oneofs&&(A._mimetype="mimetype")),e.placeholderArgb!=null&&e.hasOwnProperty("placeholderArgb")&&(A.placeholderArgb=e.placeholderArgb,a.oneofs&&(A._placeholderArgb="placeholderArgb")),e.textArgb!=null&&e.hasOwnProperty("textArgb")&&(A.textArgb=e.textArgb,a.oneofs&&(A._textArgb="textArgb")),e.subtextArgb!=null&&e.hasOwnProperty("subtextArgb")&&(A.subtextArgb=e.subtextArgb,a.oneofs&&(A._subtextArgb="subtextArgb")),e.mediaData!=null&&e.hasOwnProperty("mediaData")&&(A.mediaData=p.proto.PaymentBackground.MediaData.toObject(e.mediaData,a),a.oneofs&&(A._mediaData="mediaData")),e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.PaymentBackground.Type[e.type]===void 0?e.type:p.proto.PaymentBackground.Type[e.type]:e.type,a.oneofs&&(A._type="type")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PaymentBackground"},t.MediaData=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.mediaKey=A.bytes();break}case 2:{c.mediaKeyTimestamp=A.int64();break}case 3:{c.fileSha256=A.bytes();break}case 4:{c.fileEncSha256=A.bytes();break}case 5:{c.directPath=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.PaymentBackground.MediaData)return A;var r=new p.proto.PaymentBackground.MediaData;return A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.mediaKeyTimestamp!=null&&(l.Long?(r.mediaKeyTimestamp=l.Long.fromValue(A.mediaKeyTimestamp)).unsigned=!1:typeof A.mediaKeyTimestamp=="string"?r.mediaKeyTimestamp=parseInt(A.mediaKeyTimestamp,10):typeof A.mediaKeyTimestamp=="number"?r.mediaKeyTimestamp=A.mediaKeyTimestamp:typeof A.mediaKeyTimestamp=="object"&&(r.mediaKeyTimestamp=new l.LongBits(A.mediaKeyTimestamp.low>>>0,A.mediaKeyTimestamp.high>>>0).toNumber())),A.fileSha256!=null&&(typeof A.fileSha256=="string"?l.base64.decode(A.fileSha256,r.fileSha256=l.newBuffer(l.base64.length(A.fileSha256)),0):A.fileSha256.length>=0&&(r.fileSha256=A.fileSha256)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.directPath!=null&&(r.directPath=String(A.directPath)),r},i.toObject=function(A,r){r||(r={});var s={};return A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.mediaKeyTimestamp!=null&&A.hasOwnProperty("mediaKeyTimestamp")&&(typeof A.mediaKeyTimestamp=="number"?s.mediaKeyTimestamp=r.longs===String?String(A.mediaKeyTimestamp):A.mediaKeyTimestamp:s.mediaKeyTimestamp=r.longs===String?se(A.mediaKeyTimestamp):r.longs===Number?ge(A.mediaKeyTimestamp):A.mediaKeyTimestamp,r.oneofs&&(s._mediaKeyTimestamp="mediaKeyTimestamp")),A.fileSha256!=null&&A.hasOwnProperty("fileSha256")&&(s.fileSha256=r.bytes===String?l.base64.encode(A.fileSha256,0,A.fileSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileSha256):A.fileSha256,r.oneofs&&(s._fileSha256="fileSha256")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.PaymentBackground.MediaData"},i})(),t.Type=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="DEFAULT"]=1,e})(),t})(),n.PaymentInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.currencyDeprecated=e.int32();break}case 2:{s.amount1000=e.uint64();break}case 3:{s.receiverJid=e.string();break}case 4:{s.status=e.int32();break}case 5:{s.transactionTimestamp=e.uint64();break}case 6:{s.requestMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 7:{s.expiryTimestamp=e.uint64();break}case 8:{s.futureproofed=e.bool();break}case 9:{s.currency=e.string();break}case 10:{s.txnStatus=e.int32();break}case 11:{s.useNoviFiatFormat=e.bool();break}case 12:{s.primaryAmount=p.proto.Money.decode(e,e.uint32());break}case 13:{s.exchangeAmount=p.proto.Money.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PaymentInfo)return e;var a=new p.proto.PaymentInfo;switch(e.currencyDeprecated){default:if(typeof e.currencyDeprecated=="number"){a.currencyDeprecated=e.currencyDeprecated;break}break;case"UNKNOWN_CURRENCY":case 0:a.currencyDeprecated=0;break;case"INR":case 1:a.currencyDeprecated=1;break}switch(e.amount1000!=null&&(l.Long?(a.amount1000=l.Long.fromValue(e.amount1000)).unsigned=!0:typeof e.amount1000=="string"?a.amount1000=parseInt(e.amount1000,10):typeof e.amount1000=="number"?a.amount1000=e.amount1000:typeof e.amount1000=="object"&&(a.amount1000=new l.LongBits(e.amount1000.low>>>0,e.amount1000.high>>>0).toNumber(!0))),e.receiverJid!=null&&(a.receiverJid=String(e.receiverJid)),e.status){default:if(typeof e.status=="number"){a.status=e.status;break}break;case"UNKNOWN_STATUS":case 0:a.status=0;break;case"PROCESSING":case 1:a.status=1;break;case"SENT":case 2:a.status=2;break;case"NEED_TO_ACCEPT":case 3:a.status=3;break;case"COMPLETE":case 4:a.status=4;break;case"COULD_NOT_COMPLETE":case 5:a.status=5;break;case"REFUNDED":case 6:a.status=6;break;case"EXPIRED":case 7:a.status=7;break;case"REJECTED":case 8:a.status=8;break;case"CANCELLED":case 9:a.status=9;break;case"WAITING_FOR_PAYER":case 10:a.status=10;break;case"WAITING":case 11:a.status=11;break}if(e.transactionTimestamp!=null&&(l.Long?(a.transactionTimestamp=l.Long.fromValue(e.transactionTimestamp)).unsigned=!0:typeof e.transactionTimestamp=="string"?a.transactionTimestamp=parseInt(e.transactionTimestamp,10):typeof e.transactionTimestamp=="number"?a.transactionTimestamp=e.transactionTimestamp:typeof e.transactionTimestamp=="object"&&(a.transactionTimestamp=new l.LongBits(e.transactionTimestamp.low>>>0,e.transactionTimestamp.high>>>0).toNumber(!0))),e.requestMessageKey!=null){if(typeof e.requestMessageKey!="object")throw TypeError(".proto.PaymentInfo.requestMessageKey: object expected");a.requestMessageKey=p.proto.MessageKey.fromObject(e.requestMessageKey)}switch(e.expiryTimestamp!=null&&(l.Long?(a.expiryTimestamp=l.Long.fromValue(e.expiryTimestamp)).unsigned=!0:typeof e.expiryTimestamp=="string"?a.expiryTimestamp=parseInt(e.expiryTimestamp,10):typeof e.expiryTimestamp=="number"?a.expiryTimestamp=e.expiryTimestamp:typeof e.expiryTimestamp=="object"&&(a.expiryTimestamp=new l.LongBits(e.expiryTimestamp.low>>>0,e.expiryTimestamp.high>>>0).toNumber(!0))),e.futureproofed!=null&&(a.futureproofed=!!e.futureproofed),e.currency!=null&&(a.currency=String(e.currency)),e.txnStatus){default:if(typeof e.txnStatus=="number"){a.txnStatus=e.txnStatus;break}break;case"UNKNOWN":case 0:a.txnStatus=0;break;case"PENDING_SETUP":case 1:a.txnStatus=1;break;case"PENDING_RECEIVER_SETUP":case 2:a.txnStatus=2;break;case"INIT":case 3:a.txnStatus=3;break;case"SUCCESS":case 4:a.txnStatus=4;break;case"COMPLETED":case 5:a.txnStatus=5;break;case"FAILED":case 6:a.txnStatus=6;break;case"FAILED_RISK":case 7:a.txnStatus=7;break;case"FAILED_PROCESSING":case 8:a.txnStatus=8;break;case"FAILED_RECEIVER_PROCESSING":case 9:a.txnStatus=9;break;case"FAILED_DA":case 10:a.txnStatus=10;break;case"FAILED_DA_FINAL":case 11:a.txnStatus=11;break;case"REFUNDED_TXN":case 12:a.txnStatus=12;break;case"REFUND_FAILED":case 13:a.txnStatus=13;break;case"REFUND_FAILED_PROCESSING":case 14:a.txnStatus=14;break;case"REFUND_FAILED_DA":case 15:a.txnStatus=15;break;case"EXPIRED_TXN":case 16:a.txnStatus=16;break;case"AUTH_CANCELED":case 17:a.txnStatus=17;break;case"AUTH_CANCEL_FAILED_PROCESSING":case 18:a.txnStatus=18;break;case"AUTH_CANCEL_FAILED":case 19:a.txnStatus=19;break;case"COLLECT_INIT":case 20:a.txnStatus=20;break;case"COLLECT_SUCCESS":case 21:a.txnStatus=21;break;case"COLLECT_FAILED":case 22:a.txnStatus=22;break;case"COLLECT_FAILED_RISK":case 23:a.txnStatus=23;break;case"COLLECT_REJECTED":case 24:a.txnStatus=24;break;case"COLLECT_EXPIRED":case 25:a.txnStatus=25;break;case"COLLECT_CANCELED":case 26:a.txnStatus=26;break;case"COLLECT_CANCELLING":case 27:a.txnStatus=27;break;case"IN_REVIEW":case 28:a.txnStatus=28;break;case"REVERSAL_SUCCESS":case 29:a.txnStatus=29;break;case"REVERSAL_PENDING":case 30:a.txnStatus=30;break;case"REFUND_PENDING":case 31:a.txnStatus=31;break}if(e.useNoviFiatFormat!=null&&(a.useNoviFiatFormat=!!e.useNoviFiatFormat),e.primaryAmount!=null){if(typeof e.primaryAmount!="object")throw TypeError(".proto.PaymentInfo.primaryAmount: object expected");a.primaryAmount=p.proto.Money.fromObject(e.primaryAmount)}if(e.exchangeAmount!=null){if(typeof e.exchangeAmount!="object")throw TypeError(".proto.PaymentInfo.exchangeAmount: object expected");a.exchangeAmount=p.proto.Money.fromObject(e.exchangeAmount)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.currencyDeprecated!=null&&e.hasOwnProperty("currencyDeprecated")&&(A.currencyDeprecated=a.enums===String?p.proto.PaymentInfo.Currency[e.currencyDeprecated]===void 0?e.currencyDeprecated:p.proto.PaymentInfo.Currency[e.currencyDeprecated]:e.currencyDeprecated,a.oneofs&&(A._currencyDeprecated="currencyDeprecated")),e.amount1000!=null&&e.hasOwnProperty("amount1000")&&(typeof e.amount1000=="number"?A.amount1000=a.longs===String?String(e.amount1000):e.amount1000:A.amount1000=a.longs===String?se(e.amount1000,!0):a.longs===Number?ge(e.amount1000,!0):e.amount1000,a.oneofs&&(A._amount1000="amount1000")),e.receiverJid!=null&&e.hasOwnProperty("receiverJid")&&(A.receiverJid=e.receiverJid,a.oneofs&&(A._receiverJid="receiverJid")),e.status!=null&&e.hasOwnProperty("status")&&(A.status=a.enums===String?p.proto.PaymentInfo.Status[e.status]===void 0?e.status:p.proto.PaymentInfo.Status[e.status]:e.status,a.oneofs&&(A._status="status")),e.transactionTimestamp!=null&&e.hasOwnProperty("transactionTimestamp")&&(typeof e.transactionTimestamp=="number"?A.transactionTimestamp=a.longs===String?String(e.transactionTimestamp):e.transactionTimestamp:A.transactionTimestamp=a.longs===String?se(e.transactionTimestamp,!0):a.longs===Number?ge(e.transactionTimestamp,!0):e.transactionTimestamp,a.oneofs&&(A._transactionTimestamp="transactionTimestamp")),e.requestMessageKey!=null&&e.hasOwnProperty("requestMessageKey")&&(A.requestMessageKey=p.proto.MessageKey.toObject(e.requestMessageKey,a),a.oneofs&&(A._requestMessageKey="requestMessageKey")),e.expiryTimestamp!=null&&e.hasOwnProperty("expiryTimestamp")&&(typeof e.expiryTimestamp=="number"?A.expiryTimestamp=a.longs===String?String(e.expiryTimestamp):e.expiryTimestamp:A.expiryTimestamp=a.longs===String?se(e.expiryTimestamp,!0):a.longs===Number?ge(e.expiryTimestamp,!0):e.expiryTimestamp,a.oneofs&&(A._expiryTimestamp="expiryTimestamp")),e.futureproofed!=null&&e.hasOwnProperty("futureproofed")&&(A.futureproofed=e.futureproofed,a.oneofs&&(A._futureproofed="futureproofed")),e.currency!=null&&e.hasOwnProperty("currency")&&(A.currency=e.currency,a.oneofs&&(A._currency="currency")),e.txnStatus!=null&&e.hasOwnProperty("txnStatus")&&(A.txnStatus=a.enums===String?p.proto.PaymentInfo.TxnStatus[e.txnStatus]===void 0?e.txnStatus:p.proto.PaymentInfo.TxnStatus[e.txnStatus]:e.txnStatus,a.oneofs&&(A._txnStatus="txnStatus")),e.useNoviFiatFormat!=null&&e.hasOwnProperty("useNoviFiatFormat")&&(A.useNoviFiatFormat=e.useNoviFiatFormat,a.oneofs&&(A._useNoviFiatFormat="useNoviFiatFormat")),e.primaryAmount!=null&&e.hasOwnProperty("primaryAmount")&&(A.primaryAmount=p.proto.Money.toObject(e.primaryAmount,a),a.oneofs&&(A._primaryAmount="primaryAmount")),e.exchangeAmount!=null&&e.hasOwnProperty("exchangeAmount")&&(A.exchangeAmount=p.proto.Money.toObject(e.exchangeAmount,a),a.oneofs&&(A._exchangeAmount="exchangeAmount")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PaymentInfo"},t.Currency=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_CURRENCY"]=0,e[i[1]="INR"]=1,e})(),t.Status=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_STATUS"]=0,e[i[1]="PROCESSING"]=1,e[i[2]="SENT"]=2,e[i[3]="NEED_TO_ACCEPT"]=3,e[i[4]="COMPLETE"]=4,e[i[5]="COULD_NOT_COMPLETE"]=5,e[i[6]="REFUNDED"]=6,e[i[7]="EXPIRED"]=7,e[i[8]="REJECTED"]=8,e[i[9]="CANCELLED"]=9,e[i[10]="WAITING_FOR_PAYER"]=10,e[i[11]="WAITING"]=11,e})(),t.TxnStatus=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="PENDING_SETUP"]=1,e[i[2]="PENDING_RECEIVER_SETUP"]=2,e[i[3]="INIT"]=3,e[i[4]="SUCCESS"]=4,e[i[5]="COMPLETED"]=5,e[i[6]="FAILED"]=6,e[i[7]="FAILED_RISK"]=7,e[i[8]="FAILED_PROCESSING"]=8,e[i[9]="FAILED_RECEIVER_PROCESSING"]=9,e[i[10]="FAILED_DA"]=10,e[i[11]="FAILED_DA_FINAL"]=11,e[i[12]="REFUNDED_TXN"]=12,e[i[13]="REFUND_FAILED"]=13,e[i[14]="REFUND_FAILED_PROCESSING"]=14,e[i[15]="REFUND_FAILED_DA"]=15,e[i[16]="EXPIRED_TXN"]=16,e[i[17]="AUTH_CANCELED"]=17,e[i[18]="AUTH_CANCEL_FAILED_PROCESSING"]=18,e[i[19]="AUTH_CANCEL_FAILED"]=19,e[i[20]="COLLECT_INIT"]=20,e[i[21]="COLLECT_SUCCESS"]=21,e[i[22]="COLLECT_FAILED"]=22,e[i[23]="COLLECT_FAILED_RISK"]=23,e[i[24]="COLLECT_REJECTED"]=24,e[i[25]="COLLECT_EXPIRED"]=25,e[i[26]="COLLECT_CANCELED"]=26,e[i[27]="COLLECT_CANCELLING"]=27,e[i[28]="IN_REVIEW"]=28,e[i[29]="REVERSAL_SUCCESS"]=29,e[i[30]="REVERSAL_PENDING"]=30,e[i[31]="REFUND_PENDING"]=31,e})(),t})(),n.PhoneNumberToLIDMapping=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pnJid=e.string();break}case 2:{s.lidJid=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PhoneNumberToLIDMapping)return e;var a=new p.proto.PhoneNumberToLIDMapping;return e.pnJid!=null&&(a.pnJid=String(e.pnJid)),e.lidJid!=null&&(a.lidJid=String(e.lidJid)),a},t.toObject=function(e,a){a||(a={});var A={};return e.pnJid!=null&&e.hasOwnProperty("pnJid")&&(A.pnJid=e.pnJid,a.oneofs&&(A._pnJid="pnJid")),e.lidJid!=null&&e.hasOwnProperty("lidJid")&&(A.lidJid=e.lidJid,a.oneofs&&(A._lidJid="lidJid")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PhoneNumberToLIDMapping"},t})(),n.PhotoChange=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.oldPhoto=e.bytes();break}case 2:{s.newPhoto=e.bytes();break}case 3:{s.newPhotoId=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PhotoChange)return e;var a=new p.proto.PhotoChange;return e.oldPhoto!=null&&(typeof e.oldPhoto=="string"?l.base64.decode(e.oldPhoto,a.oldPhoto=l.newBuffer(l.base64.length(e.oldPhoto)),0):e.oldPhoto.length>=0&&(a.oldPhoto=e.oldPhoto)),e.newPhoto!=null&&(typeof e.newPhoto=="string"?l.base64.decode(e.newPhoto,a.newPhoto=l.newBuffer(l.base64.length(e.newPhoto)),0):e.newPhoto.length>=0&&(a.newPhoto=e.newPhoto)),e.newPhotoId!=null&&(a.newPhotoId=e.newPhotoId>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.oldPhoto!=null&&e.hasOwnProperty("oldPhoto")&&(A.oldPhoto=a.bytes===String?l.base64.encode(e.oldPhoto,0,e.oldPhoto.length):a.bytes===Array?Array.prototype.slice.call(e.oldPhoto):e.oldPhoto,a.oneofs&&(A._oldPhoto="oldPhoto")),e.newPhoto!=null&&e.hasOwnProperty("newPhoto")&&(A.newPhoto=a.bytes===String?l.base64.encode(e.newPhoto,0,e.newPhoto.length):a.bytes===Array?Array.prototype.slice.call(e.newPhoto):e.newPhoto,a.oneofs&&(A._newPhoto="newPhoto")),e.newPhotoId!=null&&e.hasOwnProperty("newPhotoId")&&(A.newPhotoId=e.newPhotoId,a.oneofs&&(A._newPhotoId="newPhotoId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PhotoChange"},t})(),n.PinInChat=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}case 2:{s.key=p.proto.MessageKey.decode(e,e.uint32());break}case 3:{s.senderTimestampMs=e.int64();break}case 4:{s.serverTimestampMs=e.int64();break}case 5:{s.messageAddOnContextInfo=p.proto.MessageAddOnContextInfo.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PinInChat)return e;var a=new p.proto.PinInChat;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"UNKNOWN_TYPE":case 0:a.type=0;break;case"PIN_FOR_ALL":case 1:a.type=1;break;case"UNPIN_FOR_ALL":case 2:a.type=2;break}if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.PinInChat.key: object expected");a.key=p.proto.MessageKey.fromObject(e.key)}if(e.senderTimestampMs!=null&&(l.Long?(a.senderTimestampMs=l.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new l.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(l.Long?(a.serverTimestampMs=l.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new l.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),e.messageAddOnContextInfo!=null){if(typeof e.messageAddOnContextInfo!="object")throw TypeError(".proto.PinInChat.messageAddOnContextInfo: object expected");a.messageAddOnContextInfo=p.proto.MessageAddOnContextInfo.fromObject(e.messageAddOnContextInfo)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.PinInChat.Type[e.type]===void 0?e.type:p.proto.PinInChat.Type[e.type]:e.type,a.oneofs&&(A._type="type")),e.key!=null&&e.hasOwnProperty("key")&&(A.key=p.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?se(e.senderTimestampMs):a.longs===Number?ge(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?se(e.serverTimestampMs):a.longs===Number?ge(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),e.messageAddOnContextInfo!=null&&e.hasOwnProperty("messageAddOnContextInfo")&&(A.messageAddOnContextInfo=p.proto.MessageAddOnContextInfo.toObject(e.messageAddOnContextInfo,a),a.oneofs&&(A._messageAddOnContextInfo="messageAddOnContextInfo")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PinInChat"},t.Type=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN_TYPE"]=0,e[i[1]="PIN_FOR_ALL"]=1,e[i[2]="UNPIN_FOR_ALL"]=2,e})(),t})(),n.Point=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.xDeprecated=e.int32();break}case 2:{s.yDeprecated=e.int32();break}case 3:{s.x=e.double();break}case 4:{s.y=e.double();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Point)return e;var a=new p.proto.Point;return e.xDeprecated!=null&&(a.xDeprecated=e.xDeprecated|0),e.yDeprecated!=null&&(a.yDeprecated=e.yDeprecated|0),e.x!=null&&(a.x=Number(e.x)),e.y!=null&&(a.y=Number(e.y)),a},t.toObject=function(e,a){a||(a={});var A={};return e.xDeprecated!=null&&e.hasOwnProperty("xDeprecated")&&(A.xDeprecated=e.xDeprecated,a.oneofs&&(A._xDeprecated="xDeprecated")),e.yDeprecated!=null&&e.hasOwnProperty("yDeprecated")&&(A.yDeprecated=e.yDeprecated,a.oneofs&&(A._yDeprecated="yDeprecated")),e.x!=null&&e.hasOwnProperty("x")&&(A.x=a.json&&!isFinite(e.x)?String(e.x):e.x,a.oneofs&&(A._x="x")),e.y!=null&&e.hasOwnProperty("y")&&(A.y=a.json&&!isFinite(e.y)?String(e.y):e.y,a.oneofs&&(A._y="y")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Point"},t})(),n.PollAdditionalMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pollInvalidated=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PollAdditionalMetadata)return e;var a=new p.proto.PollAdditionalMetadata;return e.pollInvalidated!=null&&(a.pollInvalidated=!!e.pollInvalidated),a},t.toObject=function(e,a){a||(a={});var A={};return e.pollInvalidated!=null&&e.hasOwnProperty("pollInvalidated")&&(A.pollInvalidated=e.pollInvalidated,a.oneofs&&(A._pollInvalidated="pollInvalidated")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PollAdditionalMetadata"},t})(),n.PollEncValue=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encPayload=e.bytes();break}case 2:{s.encIv=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PollEncValue)return e;var a=new p.proto.PollEncValue;return e.encPayload!=null&&(typeof e.encPayload=="string"?l.base64.decode(e.encPayload,a.encPayload=l.newBuffer(l.base64.length(e.encPayload)),0):e.encPayload.length>=0&&(a.encPayload=e.encPayload)),e.encIv!=null&&(typeof e.encIv=="string"?l.base64.decode(e.encIv,a.encIv=l.newBuffer(l.base64.length(e.encIv)),0):e.encIv.length>=0&&(a.encIv=e.encIv)),a},t.toObject=function(e,a){a||(a={});var A={};return e.encPayload!=null&&e.hasOwnProperty("encPayload")&&(A.encPayload=a.bytes===String?l.base64.encode(e.encPayload,0,e.encPayload.length):a.bytes===Array?Array.prototype.slice.call(e.encPayload):e.encPayload,a.oneofs&&(A._encPayload="encPayload")),e.encIv!=null&&e.hasOwnProperty("encIv")&&(A.encIv=a.bytes===String?l.base64.encode(e.encIv,0,e.encIv.length):a.bytes===Array?Array.prototype.slice.call(e.encIv):e.encIv,a.oneofs&&(A._encIv="encIv")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PollEncValue"},t})(),n.PollUpdate=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.pollUpdateMessageKey=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.vote=p.proto.Message.PollVoteMessage.decode(e,e.uint32());break}case 3:{s.senderTimestampMs=e.int64();break}case 4:{s.serverTimestampMs=e.int64();break}case 5:{s.unread=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PollUpdate)return e;var a=new p.proto.PollUpdate;if(e.pollUpdateMessageKey!=null){if(typeof e.pollUpdateMessageKey!="object")throw TypeError(".proto.PollUpdate.pollUpdateMessageKey: object expected");a.pollUpdateMessageKey=p.proto.MessageKey.fromObject(e.pollUpdateMessageKey)}if(e.vote!=null){if(typeof e.vote!="object")throw TypeError(".proto.PollUpdate.vote: object expected");a.vote=p.proto.Message.PollVoteMessage.fromObject(e.vote)}return e.senderTimestampMs!=null&&(l.Long?(a.senderTimestampMs=l.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new l.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.serverTimestampMs!=null&&(l.Long?(a.serverTimestampMs=l.Long.fromValue(e.serverTimestampMs)).unsigned=!1:typeof e.serverTimestampMs=="string"?a.serverTimestampMs=parseInt(e.serverTimestampMs,10):typeof e.serverTimestampMs=="number"?a.serverTimestampMs=e.serverTimestampMs:typeof e.serverTimestampMs=="object"&&(a.serverTimestampMs=new l.LongBits(e.serverTimestampMs.low>>>0,e.serverTimestampMs.high>>>0).toNumber())),e.unread!=null&&(a.unread=!!e.unread),a},t.toObject=function(e,a){a||(a={});var A={};return e.pollUpdateMessageKey!=null&&e.hasOwnProperty("pollUpdateMessageKey")&&(A.pollUpdateMessageKey=p.proto.MessageKey.toObject(e.pollUpdateMessageKey,a),a.oneofs&&(A._pollUpdateMessageKey="pollUpdateMessageKey")),e.vote!=null&&e.hasOwnProperty("vote")&&(A.vote=p.proto.Message.PollVoteMessage.toObject(e.vote,a),a.oneofs&&(A._vote="vote")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?se(e.senderTimestampMs):a.longs===Number?ge(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.serverTimestampMs!=null&&e.hasOwnProperty("serverTimestampMs")&&(typeof e.serverTimestampMs=="number"?A.serverTimestampMs=a.longs===String?String(e.serverTimestampMs):e.serverTimestampMs:A.serverTimestampMs=a.longs===String?se(e.serverTimestampMs):a.longs===Number?ge(e.serverTimestampMs):e.serverTimestampMs,a.oneofs&&(A._serverTimestampMs="serverTimestampMs")),e.unread!=null&&e.hasOwnProperty("unread")&&(A.unread=e.unread,a.oneofs&&(A._unread="unread")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PollUpdate"},t})(),n.PreKeyRecordStructure=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.publicKey=e.bytes();break}case 3:{s.privateKey=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PreKeyRecordStructure)return e;var a=new p.proto.PreKeyRecordStructure;return e.id!=null&&(a.id=e.id>>>0),e.publicKey!=null&&(typeof e.publicKey=="string"?l.base64.decode(e.publicKey,a.publicKey=l.newBuffer(l.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.privateKey!=null&&(typeof e.privateKey=="string"?l.base64.decode(e.privateKey,a.privateKey=l.newBuffer(l.base64.length(e.privateKey)),0):e.privateKey.length>=0&&(a.privateKey=e.privateKey)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?l.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.privateKey!=null&&e.hasOwnProperty("privateKey")&&(A.privateKey=a.bytes===String?l.base64.encode(e.privateKey,0,e.privateKey.length):a.bytes===Array?Array.prototype.slice.call(e.privateKey):e.privateKey,a.oneofs&&(A._privateKey="privateKey")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PreKeyRecordStructure"},t})(),n.PreKeySignalMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 5:{s.registrationId=e.uint32();break}case 1:{s.preKeyId=e.uint32();break}case 6:{s.signedPreKeyId=e.uint32();break}case 2:{s.baseKey=e.bytes();break}case 3:{s.identityKey=e.bytes();break}case 4:{s.message=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PreKeySignalMessage)return e;var a=new p.proto.PreKeySignalMessage;return e.registrationId!=null&&(a.registrationId=e.registrationId>>>0),e.preKeyId!=null&&(a.preKeyId=e.preKeyId>>>0),e.signedPreKeyId!=null&&(a.signedPreKeyId=e.signedPreKeyId>>>0),e.baseKey!=null&&(typeof e.baseKey=="string"?l.base64.decode(e.baseKey,a.baseKey=l.newBuffer(l.base64.length(e.baseKey)),0):e.baseKey.length>=0&&(a.baseKey=e.baseKey)),e.identityKey!=null&&(typeof e.identityKey=="string"?l.base64.decode(e.identityKey,a.identityKey=l.newBuffer(l.base64.length(e.identityKey)),0):e.identityKey.length>=0&&(a.identityKey=e.identityKey)),e.message!=null&&(typeof e.message=="string"?l.base64.decode(e.message,a.message=l.newBuffer(l.base64.length(e.message)),0):e.message.length>=0&&(a.message=e.message)),a},t.toObject=function(e,a){a||(a={});var A={};return e.preKeyId!=null&&e.hasOwnProperty("preKeyId")&&(A.preKeyId=e.preKeyId,a.oneofs&&(A._preKeyId="preKeyId")),e.baseKey!=null&&e.hasOwnProperty("baseKey")&&(A.baseKey=a.bytes===String?l.base64.encode(e.baseKey,0,e.baseKey.length):a.bytes===Array?Array.prototype.slice.call(e.baseKey):e.baseKey,a.oneofs&&(A._baseKey="baseKey")),e.identityKey!=null&&e.hasOwnProperty("identityKey")&&(A.identityKey=a.bytes===String?l.base64.encode(e.identityKey,0,e.identityKey.length):a.bytes===Array?Array.prototype.slice.call(e.identityKey):e.identityKey,a.oneofs&&(A._identityKey="identityKey")),e.message!=null&&e.hasOwnProperty("message")&&(A.message=a.bytes===String?l.base64.encode(e.message,0,e.message.length):a.bytes===Array?Array.prototype.slice.call(e.message):e.message,a.oneofs&&(A._message="message")),e.registrationId!=null&&e.hasOwnProperty("registrationId")&&(A.registrationId=e.registrationId,a.oneofs&&(A._registrationId="registrationId")),e.signedPreKeyId!=null&&e.hasOwnProperty("signedPreKeyId")&&(A.signedPreKeyId=e.signedPreKeyId,a.oneofs&&(A._signedPreKeyId="signedPreKeyId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PreKeySignalMessage"},t})(),n.PremiumMessageInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.serverCampaignId=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PremiumMessageInfo)return e;var a=new p.proto.PremiumMessageInfo;return e.serverCampaignId!=null&&(a.serverCampaignId=String(e.serverCampaignId)),a},t.toObject=function(e,a){a||(a={});var A={};return e.serverCampaignId!=null&&e.hasOwnProperty("serverCampaignId")&&(A.serverCampaignId=e.serverCampaignId,a.oneofs&&(A._serverCampaignId="serverCampaignId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PremiumMessageInfo"},t})(),n.PrimaryEphemeralIdentity=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.nonce=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.PrimaryEphemeralIdentity)return e;var a=new p.proto.PrimaryEphemeralIdentity;return e.publicKey!=null&&(typeof e.publicKey=="string"?l.base64.decode(e.publicKey,a.publicKey=l.newBuffer(l.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.nonce!=null&&(typeof e.nonce=="string"?l.base64.decode(e.nonce,a.nonce=l.newBuffer(l.base64.length(e.nonce)),0):e.nonce.length>=0&&(a.nonce=e.nonce)),a},t.toObject=function(e,a){a||(a={});var A={};return e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?l.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.nonce!=null&&e.hasOwnProperty("nonce")&&(A.nonce=a.bytes===String?l.base64.encode(e.nonce,0,e.nonce.length):a.bytes===Array?Array.prototype.slice.call(e.nonce):e.nonce,a.oneofs&&(A._nonce="nonce")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.PrimaryEphemeralIdentity"},t})(),n.PrivacySystemMessage=(function(){let t={},o=Object.create(t);return o[t[1]="E2EE_MSG"]=1,o[t[2]="NE2EE_SELF"]=2,o[t[3]="NE2EE_OTHER"]=3,o})(),n.ProcessedVideo=(function(){function t(i){if(this.capabilities=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.directPath=e.string();break}case 2:{s.fileSha256=e.bytes();break}case 3:{s.height=e.uint32();break}case 4:{s.width=e.uint32();break}case 5:{s.fileLength=e.uint64();break}case 6:{s.bitrate=e.uint32();break}case 7:{s.quality=e.int32();break}case 8:{s.capabilities&&s.capabilities.length||(s.capabilities=[]),s.capabilities.push(e.string());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ProcessedVideo)return e;var a=new p.proto.ProcessedVideo;switch(e.directPath!=null&&(a.directPath=String(e.directPath)),e.fileSha256!=null&&(typeof e.fileSha256=="string"?l.base64.decode(e.fileSha256,a.fileSha256=l.newBuffer(l.base64.length(e.fileSha256)),0):e.fileSha256.length>=0&&(a.fileSha256=e.fileSha256)),e.height!=null&&(a.height=e.height>>>0),e.width!=null&&(a.width=e.width>>>0),e.fileLength!=null&&(l.Long?(a.fileLength=l.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new l.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),e.bitrate!=null&&(a.bitrate=e.bitrate>>>0),e.quality){default:if(typeof e.quality=="number"){a.quality=e.quality;break}break;case"UNDEFINED":case 0:a.quality=0;break;case"LOW":case 1:a.quality=1;break;case"MID":case 2:a.quality=2;break;case"HIGH":case 3:a.quality=3;break}if(e.capabilities){if(!Array.isArray(e.capabilities))throw TypeError(".proto.ProcessedVideo.capabilities: array expected");a.capabilities=[];for(var A=0;A>>3){case 1:{s.companionEphemeralIdentity=e.bytes();break}case 2:{s.commitment=p.proto.CompanionCommitment.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ProloguePayload)return e;var a=new p.proto.ProloguePayload;if(e.companionEphemeralIdentity!=null&&(typeof e.companionEphemeralIdentity=="string"?l.base64.decode(e.companionEphemeralIdentity,a.companionEphemeralIdentity=l.newBuffer(l.base64.length(e.companionEphemeralIdentity)),0):e.companionEphemeralIdentity.length>=0&&(a.companionEphemeralIdentity=e.companionEphemeralIdentity)),e.commitment!=null){if(typeof e.commitment!="object")throw TypeError(".proto.ProloguePayload.commitment: object expected");a.commitment=p.proto.CompanionCommitment.fromObject(e.commitment)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.companionEphemeralIdentity!=null&&e.hasOwnProperty("companionEphemeralIdentity")&&(A.companionEphemeralIdentity=a.bytes===String?l.base64.encode(e.companionEphemeralIdentity,0,e.companionEphemeralIdentity.length):a.bytes===Array?Array.prototype.slice.call(e.companionEphemeralIdentity):e.companionEphemeralIdentity,a.oneofs&&(A._companionEphemeralIdentity="companionEphemeralIdentity")),e.commitment!=null&&e.hasOwnProperty("commitment")&&(A.commitment=p.proto.CompanionCommitment.toObject(e.commitment,a),a.oneofs&&(A._commitment="commitment")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ProloguePayload"},t})(),n.Pushname=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.string();break}case 2:{s.pushname=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Pushname)return e;var a=new p.proto.Pushname;return e.id!=null&&(a.id=String(e.id)),e.pushname!=null&&(a.pushname=String(e.pushname)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.pushname!=null&&e.hasOwnProperty("pushname")&&(A.pushname=e.pushname,a.oneofs&&(A._pushname="pushname")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Pushname"},t})(),n.QuarantinedMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.originalData=e.bytes();break}case 2:{s.extractedText=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.QuarantinedMessage)return e;var a=new p.proto.QuarantinedMessage;return e.originalData!=null&&(typeof e.originalData=="string"?l.base64.decode(e.originalData,a.originalData=l.newBuffer(l.base64.length(e.originalData)),0):e.originalData.length>=0&&(a.originalData=e.originalData)),e.extractedText!=null&&(a.extractedText=String(e.extractedText)),a},t.toObject=function(e,a){a||(a={});var A={};return e.originalData!=null&&e.hasOwnProperty("originalData")&&(A.originalData=a.bytes===String?l.base64.encode(e.originalData,0,e.originalData.length):a.bytes===Array?Array.prototype.slice.call(e.originalData):e.originalData,a.oneofs&&(A._originalData="originalData")),e.extractedText!=null&&e.hasOwnProperty("extractedText")&&(A.extractedText=e.extractedText,a.oneofs&&(A._extractedText="extractedText")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.QuarantinedMessage"},t})(),n.Reaction=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.key=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.text=e.string();break}case 3:{s.groupingKey=e.string();break}case 4:{s.senderTimestampMs=e.int64();break}case 5:{s.unread=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Reaction)return e;var a=new p.proto.Reaction;if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.Reaction.key: object expected");a.key=p.proto.MessageKey.fromObject(e.key)}return e.text!=null&&(a.text=String(e.text)),e.groupingKey!=null&&(a.groupingKey=String(e.groupingKey)),e.senderTimestampMs!=null&&(l.Long?(a.senderTimestampMs=l.Long.fromValue(e.senderTimestampMs)).unsigned=!1:typeof e.senderTimestampMs=="string"?a.senderTimestampMs=parseInt(e.senderTimestampMs,10):typeof e.senderTimestampMs=="number"?a.senderTimestampMs=e.senderTimestampMs:typeof e.senderTimestampMs=="object"&&(a.senderTimestampMs=new l.LongBits(e.senderTimestampMs.low>>>0,e.senderTimestampMs.high>>>0).toNumber())),e.unread!=null&&(a.unread=!!e.unread),a},t.toObject=function(e,a){a||(a={});var A={};return e.key!=null&&e.hasOwnProperty("key")&&(A.key=p.proto.MessageKey.toObject(e.key,a),a.oneofs&&(A._key="key")),e.text!=null&&e.hasOwnProperty("text")&&(A.text=e.text,a.oneofs&&(A._text="text")),e.groupingKey!=null&&e.hasOwnProperty("groupingKey")&&(A.groupingKey=e.groupingKey,a.oneofs&&(A._groupingKey="groupingKey")),e.senderTimestampMs!=null&&e.hasOwnProperty("senderTimestampMs")&&(typeof e.senderTimestampMs=="number"?A.senderTimestampMs=a.longs===String?String(e.senderTimestampMs):e.senderTimestampMs:A.senderTimestampMs=a.longs===String?se(e.senderTimestampMs):a.longs===Number?ge(e.senderTimestampMs):e.senderTimestampMs,a.oneofs&&(A._senderTimestampMs="senderTimestampMs")),e.unread!=null&&e.hasOwnProperty("unread")&&(A.unread=e.unread,a.oneofs&&(A._unread="unread")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Reaction"},t})(),n.RecentEmojiWeight=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.emoji=e.string();break}case 2:{s.weight=e.float();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.RecentEmojiWeight)return e;var a=new p.proto.RecentEmojiWeight;return e.emoji!=null&&(a.emoji=String(e.emoji)),e.weight!=null&&(a.weight=Number(e.weight)),a},t.toObject=function(e,a){a||(a={});var A={};return e.emoji!=null&&e.hasOwnProperty("emoji")&&(A.emoji=e.emoji,a.oneofs&&(A._emoji="emoji")),e.weight!=null&&e.hasOwnProperty("weight")&&(A.weight=a.json&&!isFinite(e.weight)?String(e.weight):e.weight,a.oneofs&&(A._weight="weight")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.RecentEmojiWeight"},t})(),n.RecordStructure=(function(){function t(i){if(this.previousSessions=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.currentSession=p.proto.SessionStructure.decode(e,e.uint32());break}case 2:{s.previousSessions&&s.previousSessions.length||(s.previousSessions=[]),s.previousSessions.push(p.proto.SessionStructure.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.RecordStructure)return e;var a=new p.proto.RecordStructure;if(e.currentSession!=null){if(typeof e.currentSession!="object")throw TypeError(".proto.RecordStructure.currentSession: object expected");a.currentSession=p.proto.SessionStructure.fromObject(e.currentSession)}if(e.previousSessions){if(!Array.isArray(e.previousSessions))throw TypeError(".proto.RecordStructure.previousSessions: array expected");a.previousSessions=[];for(var A=0;A>>3){case 1:{s.minVersion=e.uint32();break}case 2:{s.maxVersion=e.uint32();break}case 3:{s.notReportableMinVersion=e.uint32();break}case 4:{s.never=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.Reportable)return e;var a=new p.proto.Reportable;return e.minVersion!=null&&(a.minVersion=e.minVersion>>>0),e.maxVersion!=null&&(a.maxVersion=e.maxVersion>>>0),e.notReportableMinVersion!=null&&(a.notReportableMinVersion=e.notReportableMinVersion>>>0),e.never!=null&&(a.never=!!e.never),a},t.toObject=function(e,a){a||(a={});var A={};return e.minVersion!=null&&e.hasOwnProperty("minVersion")&&(A.minVersion=e.minVersion,a.oneofs&&(A._minVersion="minVersion")),e.maxVersion!=null&&e.hasOwnProperty("maxVersion")&&(A.maxVersion=e.maxVersion,a.oneofs&&(A._maxVersion="maxVersion")),e.notReportableMinVersion!=null&&e.hasOwnProperty("notReportableMinVersion")&&(A.notReportableMinVersion=e.notReportableMinVersion,a.oneofs&&(A._notReportableMinVersion="notReportableMinVersion")),e.never!=null&&e.hasOwnProperty("never")&&(A.never=e.never,a.oneofs&&(A._never="never")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.Reportable"},t})(),n.ReportingTokenInfo=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.reportingTag=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ReportingTokenInfo)return e;var a=new p.proto.ReportingTokenInfo;return e.reportingTag!=null&&(typeof e.reportingTag=="string"?l.base64.decode(e.reportingTag,a.reportingTag=l.newBuffer(l.base64.length(e.reportingTag)),0):e.reportingTag.length>=0&&(a.reportingTag=e.reportingTag)),a},t.toObject=function(e,a){a||(a={});var A={};return e.reportingTag!=null&&e.hasOwnProperty("reportingTag")&&(A.reportingTag=a.bytes===String?l.base64.encode(e.reportingTag,0,e.reportingTag.length):a.bytes===Array?Array.prototype.slice.call(e.reportingTag):e.reportingTag,a.oneofs&&(A._reportingTag="reportingTag")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ReportingTokenInfo"},t})(),n.SenderKeyDistributionMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.iteration=e.uint32();break}case 3:{s.chainKey=e.bytes();break}case 4:{s.signingKey=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SenderKeyDistributionMessage)return e;var a=new p.proto.SenderKeyDistributionMessage;return e.id!=null&&(a.id=e.id>>>0),e.iteration!=null&&(a.iteration=e.iteration>>>0),e.chainKey!=null&&(typeof e.chainKey=="string"?l.base64.decode(e.chainKey,a.chainKey=l.newBuffer(l.base64.length(e.chainKey)),0):e.chainKey.length>=0&&(a.chainKey=e.chainKey)),e.signingKey!=null&&(typeof e.signingKey=="string"?l.base64.decode(e.signingKey,a.signingKey=l.newBuffer(l.base64.length(e.signingKey)),0):e.signingKey.length>=0&&(a.signingKey=e.signingKey)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.iteration!=null&&e.hasOwnProperty("iteration")&&(A.iteration=e.iteration,a.oneofs&&(A._iteration="iteration")),e.chainKey!=null&&e.hasOwnProperty("chainKey")&&(A.chainKey=a.bytes===String?l.base64.encode(e.chainKey,0,e.chainKey.length):a.bytes===Array?Array.prototype.slice.call(e.chainKey):e.chainKey,a.oneofs&&(A._chainKey="chainKey")),e.signingKey!=null&&e.hasOwnProperty("signingKey")&&(A.signingKey=a.bytes===String?l.base64.encode(e.signingKey,0,e.signingKey.length):a.bytes===Array?Array.prototype.slice.call(e.signingKey):e.signingKey,a.oneofs&&(A._signingKey="signingKey")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SenderKeyDistributionMessage"},t})(),n.SenderKeyMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.iteration=e.uint32();break}case 3:{s.ciphertext=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SenderKeyMessage)return e;var a=new p.proto.SenderKeyMessage;return e.id!=null&&(a.id=e.id>>>0),e.iteration!=null&&(a.iteration=e.iteration>>>0),e.ciphertext!=null&&(typeof e.ciphertext=="string"?l.base64.decode(e.ciphertext,a.ciphertext=l.newBuffer(l.base64.length(e.ciphertext)),0):e.ciphertext.length>=0&&(a.ciphertext=e.ciphertext)),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.iteration!=null&&e.hasOwnProperty("iteration")&&(A.iteration=e.iteration,a.oneofs&&(A._iteration="iteration")),e.ciphertext!=null&&e.hasOwnProperty("ciphertext")&&(A.ciphertext=a.bytes===String?l.base64.encode(e.ciphertext,0,e.ciphertext.length):a.bytes===Array?Array.prototype.slice.call(e.ciphertext):e.ciphertext,a.oneofs&&(A._ciphertext="ciphertext")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SenderKeyMessage"},t})(),n.SenderKeyRecordStructure=(function(){function t(o){if(this.senderKeyStates=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.senderKeyStates&&r.senderKeyStates.length||(r.senderKeyStates=[]),r.senderKeyStates.push(p.proto.SenderKeyStateStructure.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.SenderKeyRecordStructure)return i;var e=new p.proto.SenderKeyRecordStructure;if(i.senderKeyStates){if(!Array.isArray(i.senderKeyStates))throw TypeError(".proto.SenderKeyRecordStructure.senderKeyStates: array expected");e.senderKeyStates=[];for(var a=0;a>>3){case 1:{s.senderKeyId=e.uint32();break}case 2:{s.senderChainKey=p.proto.SenderKeyStateStructure.SenderChainKey.decode(e,e.uint32());break}case 3:{s.senderSigningKey=p.proto.SenderKeyStateStructure.SenderSigningKey.decode(e,e.uint32());break}case 4:{s.senderMessageKeys&&s.senderMessageKeys.length||(s.senderMessageKeys=[]),s.senderMessageKeys.push(p.proto.SenderKeyStateStructure.SenderMessageKey.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SenderKeyStateStructure)return e;var a=new p.proto.SenderKeyStateStructure;if(e.senderKeyId!=null&&(a.senderKeyId=e.senderKeyId>>>0),e.senderChainKey!=null){if(typeof e.senderChainKey!="object")throw TypeError(".proto.SenderKeyStateStructure.senderChainKey: object expected");a.senderChainKey=p.proto.SenderKeyStateStructure.SenderChainKey.fromObject(e.senderChainKey)}if(e.senderSigningKey!=null){if(typeof e.senderSigningKey!="object")throw TypeError(".proto.SenderKeyStateStructure.senderSigningKey: object expected");a.senderSigningKey=p.proto.SenderKeyStateStructure.SenderSigningKey.fromObject(e.senderSigningKey)}if(e.senderMessageKeys){if(!Array.isArray(e.senderMessageKeys))throw TypeError(".proto.SenderKeyStateStructure.senderMessageKeys: array expected");a.senderMessageKeys=[];for(var A=0;A>>3){case 1:{c.iteration=A.uint32();break}case 2:{c.seed=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SenderKeyStateStructure.SenderChainKey)return A;var r=new p.proto.SenderKeyStateStructure.SenderChainKey;return A.iteration!=null&&(r.iteration=A.iteration>>>0),A.seed!=null&&(typeof A.seed=="string"?l.base64.decode(A.seed,r.seed=l.newBuffer(l.base64.length(A.seed)),0):A.seed.length>=0&&(r.seed=A.seed)),r},i.toObject=function(A,r){r||(r={});var s={};return A.iteration!=null&&A.hasOwnProperty("iteration")&&(s.iteration=A.iteration,r.oneofs&&(s._iteration="iteration")),A.seed!=null&&A.hasOwnProperty("seed")&&(s.seed=r.bytes===String?l.base64.encode(A.seed,0,A.seed.length):r.bytes===Array?Array.prototype.slice.call(A.seed):A.seed,r.oneofs&&(s._seed="seed")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SenderKeyStateStructure.SenderChainKey"},i})(),t.SenderMessageKey=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.iteration=A.uint32();break}case 2:{c.seed=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SenderKeyStateStructure.SenderMessageKey)return A;var r=new p.proto.SenderKeyStateStructure.SenderMessageKey;return A.iteration!=null&&(r.iteration=A.iteration>>>0),A.seed!=null&&(typeof A.seed=="string"?l.base64.decode(A.seed,r.seed=l.newBuffer(l.base64.length(A.seed)),0):A.seed.length>=0&&(r.seed=A.seed)),r},i.toObject=function(A,r){r||(r={});var s={};return A.iteration!=null&&A.hasOwnProperty("iteration")&&(s.iteration=A.iteration,r.oneofs&&(s._iteration="iteration")),A.seed!=null&&A.hasOwnProperty("seed")&&(s.seed=r.bytes===String?l.base64.encode(A.seed,0,A.seed.length):r.bytes===Array?Array.prototype.slice.call(A.seed):A.seed,r.oneofs&&(s._seed="seed")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SenderKeyStateStructure.SenderMessageKey"},i})(),t.SenderSigningKey=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.public=A.bytes();break}case 2:{c.private=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SenderKeyStateStructure.SenderSigningKey)return A;var r=new p.proto.SenderKeyStateStructure.SenderSigningKey;return A.public!=null&&(typeof A.public=="string"?l.base64.decode(A.public,r.public=l.newBuffer(l.base64.length(A.public)),0):A.public.length>=0&&(r.public=A.public)),A.private!=null&&(typeof A.private=="string"?l.base64.decode(A.private,r.private=l.newBuffer(l.base64.length(A.private)),0):A.private.length>=0&&(r.private=A.private)),r},i.toObject=function(A,r){r||(r={});var s={};return A.public!=null&&A.hasOwnProperty("public")&&(s.public=r.bytes===String?l.base64.encode(A.public,0,A.public.length):r.bytes===Array?Array.prototype.slice.call(A.public):A.public,r.oneofs&&(s._public="public")),A.private!=null&&A.hasOwnProperty("private")&&(s.private=r.bytes===String?l.base64.encode(A.private,0,A.private.length):r.bytes===Array?Array.prototype.slice.call(A.private):A.private,r.oneofs&&(s._private="private")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SenderKeyStateStructure.SenderSigningKey"},i})(),t})(),n.ServerErrorReceipt=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.stanzaId=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ServerErrorReceipt)return e;var a=new p.proto.ServerErrorReceipt;return e.stanzaId!=null&&(a.stanzaId=String(e.stanzaId)),a},t.toObject=function(e,a){a||(a={});var A={};return e.stanzaId!=null&&e.hasOwnProperty("stanzaId")&&(A.stanzaId=e.stanzaId,a.oneofs&&(A._stanzaId="stanzaId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ServerErrorReceipt"},t})(),n.SessionStructure=(function(){function t(i){if(this.receiverChains=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.sessionVersion=e.uint32();break}case 2:{s.localIdentityPublic=e.bytes();break}case 3:{s.remoteIdentityPublic=e.bytes();break}case 4:{s.rootKey=e.bytes();break}case 5:{s.previousCounter=e.uint32();break}case 6:{s.senderChain=p.proto.SessionStructure.Chain.decode(e,e.uint32());break}case 7:{s.receiverChains&&s.receiverChains.length||(s.receiverChains=[]),s.receiverChains.push(p.proto.SessionStructure.Chain.decode(e,e.uint32()));break}case 8:{s.pendingKeyExchange=p.proto.SessionStructure.PendingKeyExchange.decode(e,e.uint32());break}case 9:{s.pendingPreKey=p.proto.SessionStructure.PendingPreKey.decode(e,e.uint32());break}case 10:{s.remoteRegistrationId=e.uint32();break}case 11:{s.localRegistrationId=e.uint32();break}case 12:{s.needsRefresh=e.bool();break}case 13:{s.aliceBaseKey=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SessionStructure)return e;var a=new p.proto.SessionStructure;if(e.sessionVersion!=null&&(a.sessionVersion=e.sessionVersion>>>0),e.localIdentityPublic!=null&&(typeof e.localIdentityPublic=="string"?l.base64.decode(e.localIdentityPublic,a.localIdentityPublic=l.newBuffer(l.base64.length(e.localIdentityPublic)),0):e.localIdentityPublic.length>=0&&(a.localIdentityPublic=e.localIdentityPublic)),e.remoteIdentityPublic!=null&&(typeof e.remoteIdentityPublic=="string"?l.base64.decode(e.remoteIdentityPublic,a.remoteIdentityPublic=l.newBuffer(l.base64.length(e.remoteIdentityPublic)),0):e.remoteIdentityPublic.length>=0&&(a.remoteIdentityPublic=e.remoteIdentityPublic)),e.rootKey!=null&&(typeof e.rootKey=="string"?l.base64.decode(e.rootKey,a.rootKey=l.newBuffer(l.base64.length(e.rootKey)),0):e.rootKey.length>=0&&(a.rootKey=e.rootKey)),e.previousCounter!=null&&(a.previousCounter=e.previousCounter>>>0),e.senderChain!=null){if(typeof e.senderChain!="object")throw TypeError(".proto.SessionStructure.senderChain: object expected");a.senderChain=p.proto.SessionStructure.Chain.fromObject(e.senderChain)}if(e.receiverChains){if(!Array.isArray(e.receiverChains))throw TypeError(".proto.SessionStructure.receiverChains: array expected");a.receiverChains=[];for(var A=0;A>>0),e.localRegistrationId!=null&&(a.localRegistrationId=e.localRegistrationId>>>0),e.needsRefresh!=null&&(a.needsRefresh=!!e.needsRefresh),e.aliceBaseKey!=null&&(typeof e.aliceBaseKey=="string"?l.base64.decode(e.aliceBaseKey,a.aliceBaseKey=l.newBuffer(l.base64.length(e.aliceBaseKey)),0):e.aliceBaseKey.length>=0&&(a.aliceBaseKey=e.aliceBaseKey)),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.receiverChains=[]),e.sessionVersion!=null&&e.hasOwnProperty("sessionVersion")&&(A.sessionVersion=e.sessionVersion,a.oneofs&&(A._sessionVersion="sessionVersion")),e.localIdentityPublic!=null&&e.hasOwnProperty("localIdentityPublic")&&(A.localIdentityPublic=a.bytes===String?l.base64.encode(e.localIdentityPublic,0,e.localIdentityPublic.length):a.bytes===Array?Array.prototype.slice.call(e.localIdentityPublic):e.localIdentityPublic,a.oneofs&&(A._localIdentityPublic="localIdentityPublic")),e.remoteIdentityPublic!=null&&e.hasOwnProperty("remoteIdentityPublic")&&(A.remoteIdentityPublic=a.bytes===String?l.base64.encode(e.remoteIdentityPublic,0,e.remoteIdentityPublic.length):a.bytes===Array?Array.prototype.slice.call(e.remoteIdentityPublic):e.remoteIdentityPublic,a.oneofs&&(A._remoteIdentityPublic="remoteIdentityPublic")),e.rootKey!=null&&e.hasOwnProperty("rootKey")&&(A.rootKey=a.bytes===String?l.base64.encode(e.rootKey,0,e.rootKey.length):a.bytes===Array?Array.prototype.slice.call(e.rootKey):e.rootKey,a.oneofs&&(A._rootKey="rootKey")),e.previousCounter!=null&&e.hasOwnProperty("previousCounter")&&(A.previousCounter=e.previousCounter,a.oneofs&&(A._previousCounter="previousCounter")),e.senderChain!=null&&e.hasOwnProperty("senderChain")&&(A.senderChain=p.proto.SessionStructure.Chain.toObject(e.senderChain,a),a.oneofs&&(A._senderChain="senderChain")),e.receiverChains&&e.receiverChains.length){A.receiverChains=[];for(var r=0;r>>3){case 1:{c.senderRatchetKey=A.bytes();break}case 2:{c.senderRatchetKeyPrivate=A.bytes();break}case 3:{c.chainKey=p.proto.SessionStructure.Chain.ChainKey.decode(A,A.uint32());break}case 4:{c.messageKeys&&c.messageKeys.length||(c.messageKeys=[]),c.messageKeys.push(p.proto.SessionStructure.Chain.MessageKey.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SessionStructure.Chain)return A;var r=new p.proto.SessionStructure.Chain;if(A.senderRatchetKey!=null&&(typeof A.senderRatchetKey=="string"?l.base64.decode(A.senderRatchetKey,r.senderRatchetKey=l.newBuffer(l.base64.length(A.senderRatchetKey)),0):A.senderRatchetKey.length>=0&&(r.senderRatchetKey=A.senderRatchetKey)),A.senderRatchetKeyPrivate!=null&&(typeof A.senderRatchetKeyPrivate=="string"?l.base64.decode(A.senderRatchetKeyPrivate,r.senderRatchetKeyPrivate=l.newBuffer(l.base64.length(A.senderRatchetKeyPrivate)),0):A.senderRatchetKeyPrivate.length>=0&&(r.senderRatchetKeyPrivate=A.senderRatchetKeyPrivate)),A.chainKey!=null){if(typeof A.chainKey!="object")throw TypeError(".proto.SessionStructure.Chain.chainKey: object expected");r.chainKey=p.proto.SessionStructure.Chain.ChainKey.fromObject(A.chainKey)}if(A.messageKeys){if(!Array.isArray(A.messageKeys))throw TypeError(".proto.SessionStructure.Chain.messageKeys: array expected");r.messageKeys=[];for(var s=0;s>>3){case 1:{d.index=s.uint32();break}case 2:{d.key=s.bytes();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.SessionStructure.Chain.ChainKey)return s;var g=new p.proto.SessionStructure.Chain.ChainKey;return s.index!=null&&(g.index=s.index>>>0),s.key!=null&&(typeof s.key=="string"?l.base64.decode(s.key,g.key=l.newBuffer(l.base64.length(s.key)),0):s.key.length>=0&&(g.key=s.key)),g},a.toObject=function(s,g){g||(g={});var c={};return s.index!=null&&s.hasOwnProperty("index")&&(c.index=s.index,g.oneofs&&(c._index="index")),s.key!=null&&s.hasOwnProperty("key")&&(c.key=g.bytes===String?l.base64.encode(s.key,0,s.key.length):g.bytes===Array?Array.prototype.slice.call(s.key):s.key,g.oneofs&&(c._key="key")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.SessionStructure.Chain.ChainKey"},a})(),i.MessageKey=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.index=s.uint32();break}case 2:{d.cipherKey=s.bytes();break}case 3:{d.macKey=s.bytes();break}case 4:{d.iv=s.bytes();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.SessionStructure.Chain.MessageKey)return s;var g=new p.proto.SessionStructure.Chain.MessageKey;return s.index!=null&&(g.index=s.index>>>0),s.cipherKey!=null&&(typeof s.cipherKey=="string"?l.base64.decode(s.cipherKey,g.cipherKey=l.newBuffer(l.base64.length(s.cipherKey)),0):s.cipherKey.length>=0&&(g.cipherKey=s.cipherKey)),s.macKey!=null&&(typeof s.macKey=="string"?l.base64.decode(s.macKey,g.macKey=l.newBuffer(l.base64.length(s.macKey)),0):s.macKey.length>=0&&(g.macKey=s.macKey)),s.iv!=null&&(typeof s.iv=="string"?l.base64.decode(s.iv,g.iv=l.newBuffer(l.base64.length(s.iv)),0):s.iv.length>=0&&(g.iv=s.iv)),g},a.toObject=function(s,g){g||(g={});var c={};return s.index!=null&&s.hasOwnProperty("index")&&(c.index=s.index,g.oneofs&&(c._index="index")),s.cipherKey!=null&&s.hasOwnProperty("cipherKey")&&(c.cipherKey=g.bytes===String?l.base64.encode(s.cipherKey,0,s.cipherKey.length):g.bytes===Array?Array.prototype.slice.call(s.cipherKey):s.cipherKey,g.oneofs&&(c._cipherKey="cipherKey")),s.macKey!=null&&s.hasOwnProperty("macKey")&&(c.macKey=g.bytes===String?l.base64.encode(s.macKey,0,s.macKey.length):g.bytes===Array?Array.prototype.slice.call(s.macKey):s.macKey,g.oneofs&&(c._macKey="macKey")),s.iv!=null&&s.hasOwnProperty("iv")&&(c.iv=g.bytes===String?l.base64.encode(s.iv,0,s.iv.length):g.bytes===Array?Array.prototype.slice.call(s.iv):s.iv,g.oneofs&&(c._iv="iv")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.SessionStructure.Chain.MessageKey"},a})(),i})(),t.PendingKeyExchange=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.sequence=A.uint32();break}case 2:{c.localBaseKey=A.bytes();break}case 3:{c.localBaseKeyPrivate=A.bytes();break}case 4:{c.localRatchetKey=A.bytes();break}case 5:{c.localRatchetKeyPrivate=A.bytes();break}case 7:{c.localIdentityKey=A.bytes();break}case 8:{c.localIdentityKeyPrivate=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SessionStructure.PendingKeyExchange)return A;var r=new p.proto.SessionStructure.PendingKeyExchange;return A.sequence!=null&&(r.sequence=A.sequence>>>0),A.localBaseKey!=null&&(typeof A.localBaseKey=="string"?l.base64.decode(A.localBaseKey,r.localBaseKey=l.newBuffer(l.base64.length(A.localBaseKey)),0):A.localBaseKey.length>=0&&(r.localBaseKey=A.localBaseKey)),A.localBaseKeyPrivate!=null&&(typeof A.localBaseKeyPrivate=="string"?l.base64.decode(A.localBaseKeyPrivate,r.localBaseKeyPrivate=l.newBuffer(l.base64.length(A.localBaseKeyPrivate)),0):A.localBaseKeyPrivate.length>=0&&(r.localBaseKeyPrivate=A.localBaseKeyPrivate)),A.localRatchetKey!=null&&(typeof A.localRatchetKey=="string"?l.base64.decode(A.localRatchetKey,r.localRatchetKey=l.newBuffer(l.base64.length(A.localRatchetKey)),0):A.localRatchetKey.length>=0&&(r.localRatchetKey=A.localRatchetKey)),A.localRatchetKeyPrivate!=null&&(typeof A.localRatchetKeyPrivate=="string"?l.base64.decode(A.localRatchetKeyPrivate,r.localRatchetKeyPrivate=l.newBuffer(l.base64.length(A.localRatchetKeyPrivate)),0):A.localRatchetKeyPrivate.length>=0&&(r.localRatchetKeyPrivate=A.localRatchetKeyPrivate)),A.localIdentityKey!=null&&(typeof A.localIdentityKey=="string"?l.base64.decode(A.localIdentityKey,r.localIdentityKey=l.newBuffer(l.base64.length(A.localIdentityKey)),0):A.localIdentityKey.length>=0&&(r.localIdentityKey=A.localIdentityKey)),A.localIdentityKeyPrivate!=null&&(typeof A.localIdentityKeyPrivate=="string"?l.base64.decode(A.localIdentityKeyPrivate,r.localIdentityKeyPrivate=l.newBuffer(l.base64.length(A.localIdentityKeyPrivate)),0):A.localIdentityKeyPrivate.length>=0&&(r.localIdentityKeyPrivate=A.localIdentityKeyPrivate)),r},i.toObject=function(A,r){r||(r={});var s={};return A.sequence!=null&&A.hasOwnProperty("sequence")&&(s.sequence=A.sequence,r.oneofs&&(s._sequence="sequence")),A.localBaseKey!=null&&A.hasOwnProperty("localBaseKey")&&(s.localBaseKey=r.bytes===String?l.base64.encode(A.localBaseKey,0,A.localBaseKey.length):r.bytes===Array?Array.prototype.slice.call(A.localBaseKey):A.localBaseKey,r.oneofs&&(s._localBaseKey="localBaseKey")),A.localBaseKeyPrivate!=null&&A.hasOwnProperty("localBaseKeyPrivate")&&(s.localBaseKeyPrivate=r.bytes===String?l.base64.encode(A.localBaseKeyPrivate,0,A.localBaseKeyPrivate.length):r.bytes===Array?Array.prototype.slice.call(A.localBaseKeyPrivate):A.localBaseKeyPrivate,r.oneofs&&(s._localBaseKeyPrivate="localBaseKeyPrivate")),A.localRatchetKey!=null&&A.hasOwnProperty("localRatchetKey")&&(s.localRatchetKey=r.bytes===String?l.base64.encode(A.localRatchetKey,0,A.localRatchetKey.length):r.bytes===Array?Array.prototype.slice.call(A.localRatchetKey):A.localRatchetKey,r.oneofs&&(s._localRatchetKey="localRatchetKey")),A.localRatchetKeyPrivate!=null&&A.hasOwnProperty("localRatchetKeyPrivate")&&(s.localRatchetKeyPrivate=r.bytes===String?l.base64.encode(A.localRatchetKeyPrivate,0,A.localRatchetKeyPrivate.length):r.bytes===Array?Array.prototype.slice.call(A.localRatchetKeyPrivate):A.localRatchetKeyPrivate,r.oneofs&&(s._localRatchetKeyPrivate="localRatchetKeyPrivate")),A.localIdentityKey!=null&&A.hasOwnProperty("localIdentityKey")&&(s.localIdentityKey=r.bytes===String?l.base64.encode(A.localIdentityKey,0,A.localIdentityKey.length):r.bytes===Array?Array.prototype.slice.call(A.localIdentityKey):A.localIdentityKey,r.oneofs&&(s._localIdentityKey="localIdentityKey")),A.localIdentityKeyPrivate!=null&&A.hasOwnProperty("localIdentityKeyPrivate")&&(s.localIdentityKeyPrivate=r.bytes===String?l.base64.encode(A.localIdentityKeyPrivate,0,A.localIdentityKeyPrivate.length):r.bytes===Array?Array.prototype.slice.call(A.localIdentityKeyPrivate):A.localIdentityKeyPrivate,r.oneofs&&(s._localIdentityKeyPrivate="localIdentityKeyPrivate")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SessionStructure.PendingKeyExchange"},i})(),t.PendingPreKey=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.preKeyId=A.uint32();break}case 3:{c.signedPreKeyId=A.int32();break}case 2:{c.baseKey=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SessionStructure.PendingPreKey)return A;var r=new p.proto.SessionStructure.PendingPreKey;return A.preKeyId!=null&&(r.preKeyId=A.preKeyId>>>0),A.signedPreKeyId!=null&&(r.signedPreKeyId=A.signedPreKeyId|0),A.baseKey!=null&&(typeof A.baseKey=="string"?l.base64.decode(A.baseKey,r.baseKey=l.newBuffer(l.base64.length(A.baseKey)),0):A.baseKey.length>=0&&(r.baseKey=A.baseKey)),r},i.toObject=function(A,r){r||(r={});var s={};return A.preKeyId!=null&&A.hasOwnProperty("preKeyId")&&(s.preKeyId=A.preKeyId,r.oneofs&&(s._preKeyId="preKeyId")),A.baseKey!=null&&A.hasOwnProperty("baseKey")&&(s.baseKey=r.bytes===String?l.base64.encode(A.baseKey,0,A.baseKey.length):r.bytes===Array?Array.prototype.slice.call(A.baseKey):A.baseKey,r.oneofs&&(s._baseKey="baseKey")),A.signedPreKeyId!=null&&A.hasOwnProperty("signedPreKeyId")&&(s.signedPreKeyId=A.signedPreKeyId,r.oneofs&&(s._signedPreKeyId="signedPreKeyId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SessionStructure.PendingPreKey"},i})(),t})(),n.SessionTransparencyMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.disclaimerText=e.string();break}case 2:{s.hcaId=e.string();break}case 3:{s.sessionTransparencyType=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SessionTransparencyMetadata)return e;var a=new p.proto.SessionTransparencyMetadata;switch(e.disclaimerText!=null&&(a.disclaimerText=String(e.disclaimerText)),e.hcaId!=null&&(a.hcaId=String(e.hcaId)),e.sessionTransparencyType){default:if(typeof e.sessionTransparencyType=="number"){a.sessionTransparencyType=e.sessionTransparencyType;break}break;case"UNKNOWN_TYPE":case 0:a.sessionTransparencyType=0;break;case"NY_AI_SAFETY_DISCLAIMER":case 1:a.sessionTransparencyType=1;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.disclaimerText!=null&&e.hasOwnProperty("disclaimerText")&&(A.disclaimerText=e.disclaimerText,a.oneofs&&(A._disclaimerText="disclaimerText")),e.hcaId!=null&&e.hasOwnProperty("hcaId")&&(A.hcaId=e.hcaId,a.oneofs&&(A._hcaId="hcaId")),e.sessionTransparencyType!=null&&e.hasOwnProperty("sessionTransparencyType")&&(A.sessionTransparencyType=a.enums===String?p.proto.SessionTransparencyType[e.sessionTransparencyType]===void 0?e.sessionTransparencyType:p.proto.SessionTransparencyType[e.sessionTransparencyType]:e.sessionTransparencyType,a.oneofs&&(A._sessionTransparencyType="sessionTransparencyType")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SessionTransparencyMetadata"},t})(),n.SessionTransparencyType=(function(){let t={},o=Object.create(t);return o[t[0]="UNKNOWN_TYPE"]=0,o[t[1]="NY_AI_SAFETY_DISCLAIMER"]=1,o})(),n.SignalMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.ratchetKey=e.bytes();break}case 2:{s.counter=e.uint32();break}case 3:{s.previousCounter=e.uint32();break}case 4:{s.ciphertext=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SignalMessage)return e;var a=new p.proto.SignalMessage;return e.ratchetKey!=null&&(typeof e.ratchetKey=="string"?l.base64.decode(e.ratchetKey,a.ratchetKey=l.newBuffer(l.base64.length(e.ratchetKey)),0):e.ratchetKey.length>=0&&(a.ratchetKey=e.ratchetKey)),e.counter!=null&&(a.counter=e.counter>>>0),e.previousCounter!=null&&(a.previousCounter=e.previousCounter>>>0),e.ciphertext!=null&&(typeof e.ciphertext=="string"?l.base64.decode(e.ciphertext,a.ciphertext=l.newBuffer(l.base64.length(e.ciphertext)),0):e.ciphertext.length>=0&&(a.ciphertext=e.ciphertext)),a},t.toObject=function(e,a){a||(a={});var A={};return e.ratchetKey!=null&&e.hasOwnProperty("ratchetKey")&&(A.ratchetKey=a.bytes===String?l.base64.encode(e.ratchetKey,0,e.ratchetKey.length):a.bytes===Array?Array.prototype.slice.call(e.ratchetKey):e.ratchetKey,a.oneofs&&(A._ratchetKey="ratchetKey")),e.counter!=null&&e.hasOwnProperty("counter")&&(A.counter=e.counter,a.oneofs&&(A._counter="counter")),e.previousCounter!=null&&e.hasOwnProperty("previousCounter")&&(A.previousCounter=e.previousCounter,a.oneofs&&(A._previousCounter="previousCounter")),e.ciphertext!=null&&e.hasOwnProperty("ciphertext")&&(A.ciphertext=a.bytes===String?l.base64.encode(e.ciphertext,0,e.ciphertext.length):a.bytes===Array?Array.prototype.slice.call(e.ciphertext):e.ciphertext,a.oneofs&&(A._ciphertext="ciphertext")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SignalMessage"},t})(),n.SignedPreKeyRecordStructure=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.id=e.uint32();break}case 2:{s.publicKey=e.bytes();break}case 3:{s.privateKey=e.bytes();break}case 4:{s.signature=e.bytes();break}case 5:{s.timestamp=e.fixed64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SignedPreKeyRecordStructure)return e;var a=new p.proto.SignedPreKeyRecordStructure;return e.id!=null&&(a.id=e.id>>>0),e.publicKey!=null&&(typeof e.publicKey=="string"?l.base64.decode(e.publicKey,a.publicKey=l.newBuffer(l.base64.length(e.publicKey)),0):e.publicKey.length>=0&&(a.publicKey=e.publicKey)),e.privateKey!=null&&(typeof e.privateKey=="string"?l.base64.decode(e.privateKey,a.privateKey=l.newBuffer(l.base64.length(e.privateKey)),0):e.privateKey.length>=0&&(a.privateKey=e.privateKey)),e.signature!=null&&(typeof e.signature=="string"?l.base64.decode(e.signature,a.signature=l.newBuffer(l.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),a},t.toObject=function(e,a){a||(a={});var A={};return e.id!=null&&e.hasOwnProperty("id")&&(A.id=e.id,a.oneofs&&(A._id="id")),e.publicKey!=null&&e.hasOwnProperty("publicKey")&&(A.publicKey=a.bytes===String?l.base64.encode(e.publicKey,0,e.publicKey.length):a.bytes===Array?Array.prototype.slice.call(e.publicKey):e.publicKey,a.oneofs&&(A._publicKey="publicKey")),e.privateKey!=null&&e.hasOwnProperty("privateKey")&&(A.privateKey=a.bytes===String?l.base64.encode(e.privateKey,0,e.privateKey.length):a.bytes===Array?Array.prototype.slice.call(e.privateKey):e.privateKey,a.oneofs&&(A._privateKey="privateKey")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?l.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp):a.longs===Number?ge(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SignedPreKeyRecordStructure"},t})(),n.StatusAttribution=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.type=e.int32();break}case 2:{s.actionUrl=e.string();break}case 3:{s.statusReshare=p.proto.StatusAttribution.StatusReshare.decode(e,e.uint32());break}case 4:{s.externalShare=p.proto.StatusAttribution.ExternalShare.decode(e,e.uint32());break}case 5:{s.music=p.proto.StatusAttribution.Music.decode(e,e.uint32());break}case 6:{s.groupStatus=p.proto.StatusAttribution.GroupStatus.decode(e,e.uint32());break}case 7:{s.rlAttribution=p.proto.StatusAttribution.RLAttribution.decode(e,e.uint32());break}case 8:{s.aiCreatedAttribution=p.proto.StatusAttribution.AiCreatedAttribution.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.StatusAttribution)return e;var a=new p.proto.StatusAttribution;switch(e.type){default:if(typeof e.type=="number"){a.type=e.type;break}break;case"UNKNOWN":case 0:a.type=0;break;case"RESHARE":case 1:a.type=1;break;case"EXTERNAL_SHARE":case 2:a.type=2;break;case"MUSIC":case 3:a.type=3;break;case"STATUS_MENTION":case 4:a.type=4;break;case"GROUP_STATUS":case 5:a.type=5;break;case"RL_ATTRIBUTION":case 6:a.type=6;break;case"AI_CREATED":case 7:a.type=7;break;case"LAYOUTS":case 8:a.type=8;break}if(e.actionUrl!=null&&(a.actionUrl=String(e.actionUrl)),e.statusReshare!=null){if(typeof e.statusReshare!="object")throw TypeError(".proto.StatusAttribution.statusReshare: object expected");a.statusReshare=p.proto.StatusAttribution.StatusReshare.fromObject(e.statusReshare)}if(e.externalShare!=null){if(typeof e.externalShare!="object")throw TypeError(".proto.StatusAttribution.externalShare: object expected");a.externalShare=p.proto.StatusAttribution.ExternalShare.fromObject(e.externalShare)}if(e.music!=null){if(typeof e.music!="object")throw TypeError(".proto.StatusAttribution.music: object expected");a.music=p.proto.StatusAttribution.Music.fromObject(e.music)}if(e.groupStatus!=null){if(typeof e.groupStatus!="object")throw TypeError(".proto.StatusAttribution.groupStatus: object expected");a.groupStatus=p.proto.StatusAttribution.GroupStatus.fromObject(e.groupStatus)}if(e.rlAttribution!=null){if(typeof e.rlAttribution!="object")throw TypeError(".proto.StatusAttribution.rlAttribution: object expected");a.rlAttribution=p.proto.StatusAttribution.RLAttribution.fromObject(e.rlAttribution)}if(e.aiCreatedAttribution!=null){if(typeof e.aiCreatedAttribution!="object")throw TypeError(".proto.StatusAttribution.aiCreatedAttribution: object expected");a.aiCreatedAttribution=p.proto.StatusAttribution.AiCreatedAttribution.fromObject(e.aiCreatedAttribution)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.type!=null&&e.hasOwnProperty("type")&&(A.type=a.enums===String?p.proto.StatusAttribution.Type[e.type]===void 0?e.type:p.proto.StatusAttribution.Type[e.type]:e.type,a.oneofs&&(A._type="type")),e.actionUrl!=null&&e.hasOwnProperty("actionUrl")&&(A.actionUrl=e.actionUrl,a.oneofs&&(A._actionUrl="actionUrl")),e.statusReshare!=null&&e.hasOwnProperty("statusReshare")&&(A.statusReshare=p.proto.StatusAttribution.StatusReshare.toObject(e.statusReshare,a),a.oneofs&&(A.attributionData="statusReshare")),e.externalShare!=null&&e.hasOwnProperty("externalShare")&&(A.externalShare=p.proto.StatusAttribution.ExternalShare.toObject(e.externalShare,a),a.oneofs&&(A.attributionData="externalShare")),e.music!=null&&e.hasOwnProperty("music")&&(A.music=p.proto.StatusAttribution.Music.toObject(e.music,a),a.oneofs&&(A.attributionData="music")),e.groupStatus!=null&&e.hasOwnProperty("groupStatus")&&(A.groupStatus=p.proto.StatusAttribution.GroupStatus.toObject(e.groupStatus,a),a.oneofs&&(A.attributionData="groupStatus")),e.rlAttribution!=null&&e.hasOwnProperty("rlAttribution")&&(A.rlAttribution=p.proto.StatusAttribution.RLAttribution.toObject(e.rlAttribution,a),a.oneofs&&(A.attributionData="rlAttribution")),e.aiCreatedAttribution!=null&&e.hasOwnProperty("aiCreatedAttribution")&&(A.aiCreatedAttribution=p.proto.StatusAttribution.AiCreatedAttribution.toObject(e.aiCreatedAttribution,a),a.oneofs&&(A.attributionData="aiCreatedAttribution")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StatusAttribution"},t.AiCreatedAttribution=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.source=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.AiCreatedAttribution)return A;var r=new p.proto.StatusAttribution.AiCreatedAttribution;switch(A.source){default:if(typeof A.source=="number"){r.source=A.source;break}break;case"UNKNOWN":case 0:r.source=0;break;case"STATUS_MIMICRY":case 1:r.source=1;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.source!=null&&A.hasOwnProperty("source")&&(s.source=r.enums===String?p.proto.StatusAttribution.AiCreatedAttribution.Source[A.source]===void 0?A.source:p.proto.StatusAttribution.AiCreatedAttribution.Source[A.source]:A.source,r.oneofs&&(s._source="source")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.AiCreatedAttribution"},i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="STATUS_MIMICRY"]=1,A})(),i})(),t.ExternalShare=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.actionUrl=A.string();break}case 2:{c.source=A.int32();break}case 3:{c.duration=A.int32();break}case 4:{c.actionFallbackUrl=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.ExternalShare)return A;var r=new p.proto.StatusAttribution.ExternalShare;switch(A.actionUrl!=null&&(r.actionUrl=String(A.actionUrl)),A.source){default:if(typeof A.source=="number"){r.source=A.source;break}break;case"UNKNOWN":case 0:r.source=0;break;case"INSTAGRAM":case 1:r.source=1;break;case"FACEBOOK":case 2:r.source=2;break;case"MESSENGER":case 3:r.source=3;break;case"SPOTIFY":case 4:r.source=4;break;case"YOUTUBE":case 5:r.source=5;break;case"PINTEREST":case 6:r.source=6;break;case"THREADS":case 7:r.source=7;break;case"APPLE_MUSIC":case 8:r.source=8;break;case"SHARECHAT":case 9:r.source=9;break;case"GOOGLE_PHOTOS":case 10:r.source=10;break}return A.duration!=null&&(r.duration=A.duration|0),A.actionFallbackUrl!=null&&(r.actionFallbackUrl=String(A.actionFallbackUrl)),r},i.toObject=function(A,r){r||(r={});var s={};return A.actionUrl!=null&&A.hasOwnProperty("actionUrl")&&(s.actionUrl=A.actionUrl,r.oneofs&&(s._actionUrl="actionUrl")),A.source!=null&&A.hasOwnProperty("source")&&(s.source=r.enums===String?p.proto.StatusAttribution.ExternalShare.Source[A.source]===void 0?A.source:p.proto.StatusAttribution.ExternalShare.Source[A.source]:A.source,r.oneofs&&(s._source="source")),A.duration!=null&&A.hasOwnProperty("duration")&&(s.duration=A.duration,r.oneofs&&(s._duration="duration")),A.actionFallbackUrl!=null&&A.hasOwnProperty("actionFallbackUrl")&&(s.actionFallbackUrl=A.actionFallbackUrl,r.oneofs&&(s._actionFallbackUrl="actionFallbackUrl")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.ExternalShare"},i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="INSTAGRAM"]=1,A[a[2]="FACEBOOK"]=2,A[a[3]="MESSENGER"]=3,A[a[4]="SPOTIFY"]=4,A[a[5]="YOUTUBE"]=5,A[a[6]="PINTEREST"]=6,A[a[7]="THREADS"]=7,A[a[8]="APPLE_MUSIC"]=8,A[a[9]="SHARECHAT"]=9,A[a[10]="GOOGLE_PHOTOS"]=10,A})(),i})(),t.GroupStatus=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.authorJid=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.GroupStatus)return A;var r=new p.proto.StatusAttribution.GroupStatus;return A.authorJid!=null&&(r.authorJid=String(A.authorJid)),r},i.toObject=function(A,r){r||(r={});var s={};return A.authorJid!=null&&A.hasOwnProperty("authorJid")&&(s.authorJid=A.authorJid,r.oneofs&&(s._authorJid="authorJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.GroupStatus"},i})(),t.Music=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.authorName=A.string();break}case 2:{c.songId=A.string();break}case 3:{c.title=A.string();break}case 4:{c.author=A.string();break}case 5:{c.artistAttribution=A.string();break}case 6:{c.isExplicit=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.Music)return A;var r=new p.proto.StatusAttribution.Music;return A.authorName!=null&&(r.authorName=String(A.authorName)),A.songId!=null&&(r.songId=String(A.songId)),A.title!=null&&(r.title=String(A.title)),A.author!=null&&(r.author=String(A.author)),A.artistAttribution!=null&&(r.artistAttribution=String(A.artistAttribution)),A.isExplicit!=null&&(r.isExplicit=!!A.isExplicit),r},i.toObject=function(A,r){r||(r={});var s={};return A.authorName!=null&&A.hasOwnProperty("authorName")&&(s.authorName=A.authorName,r.oneofs&&(s._authorName="authorName")),A.songId!=null&&A.hasOwnProperty("songId")&&(s.songId=A.songId,r.oneofs&&(s._songId="songId")),A.title!=null&&A.hasOwnProperty("title")&&(s.title=A.title,r.oneofs&&(s._title="title")),A.author!=null&&A.hasOwnProperty("author")&&(s.author=A.author,r.oneofs&&(s._author="author")),A.artistAttribution!=null&&A.hasOwnProperty("artistAttribution")&&(s.artistAttribution=A.artistAttribution,r.oneofs&&(s._artistAttribution="artistAttribution")),A.isExplicit!=null&&A.hasOwnProperty("isExplicit")&&(s.isExplicit=A.isExplicit,r.oneofs&&(s._isExplicit="isExplicit")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.Music"},i})(),t.RLAttribution=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.source=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.RLAttribution)return A;var r=new p.proto.StatusAttribution.RLAttribution;switch(A.source){default:if(typeof A.source=="number"){r.source=A.source;break}break;case"UNKNOWN":case 0:r.source=0;break;case"RAY_BAN_META_GLASSES":case 1:r.source=1;break;case"OAKLEY_META_GLASSES":case 2:r.source=2;break;case"HYPERNOVA_GLASSES":case 3:r.source=3;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.source!=null&&A.hasOwnProperty("source")&&(s.source=r.enums===String?p.proto.StatusAttribution.RLAttribution.Source[A.source]===void 0?A.source:p.proto.StatusAttribution.RLAttribution.Source[A.source]:A.source,r.oneofs&&(s._source="source")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.RLAttribution"},i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="RAY_BAN_META_GLASSES"]=1,A[a[2]="OAKLEY_META_GLASSES"]=2,A[a[3]="HYPERNOVA_GLASSES"]=3,A})(),i})(),t.StatusReshare=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.source=A.int32();break}case 2:{c.metadata=p.proto.StatusAttribution.StatusReshare.Metadata.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.StatusAttribution.StatusReshare)return A;var r=new p.proto.StatusAttribution.StatusReshare;switch(A.source){default:if(typeof A.source=="number"){r.source=A.source;break}break;case"UNKNOWN":case 0:r.source=0;break;case"INTERNAL_RESHARE":case 1:r.source=1;break;case"MENTION_RESHARE":case 2:r.source=2;break;case"CHANNEL_RESHARE":case 3:r.source=3;break;case"FORWARD":case 4:r.source=4;break}if(A.metadata!=null){if(typeof A.metadata!="object")throw TypeError(".proto.StatusAttribution.StatusReshare.metadata: object expected");r.metadata=p.proto.StatusAttribution.StatusReshare.Metadata.fromObject(A.metadata)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.source!=null&&A.hasOwnProperty("source")&&(s.source=r.enums===String?p.proto.StatusAttribution.StatusReshare.Source[A.source]===void 0?A.source:p.proto.StatusAttribution.StatusReshare.Source[A.source]:A.source,r.oneofs&&(s._source="source")),A.metadata!=null&&A.hasOwnProperty("metadata")&&(s.metadata=p.proto.StatusAttribution.StatusReshare.Metadata.toObject(A.metadata,r),r.oneofs&&(s._metadata="metadata")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.StatusAttribution.StatusReshare"},i.Metadata=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.duration=s.int32();break}case 2:{d.channelJid=s.string();break}case 3:{d.channelMessageId=s.int32();break}case 4:{d.hasMultipleReshares=s.bool();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.StatusAttribution.StatusReshare.Metadata)return s;var g=new p.proto.StatusAttribution.StatusReshare.Metadata;return s.duration!=null&&(g.duration=s.duration|0),s.channelJid!=null&&(g.channelJid=String(s.channelJid)),s.channelMessageId!=null&&(g.channelMessageId=s.channelMessageId|0),s.hasMultipleReshares!=null&&(g.hasMultipleReshares=!!s.hasMultipleReshares),g},a.toObject=function(s,g){g||(g={});var c={};return s.duration!=null&&s.hasOwnProperty("duration")&&(c.duration=s.duration,g.oneofs&&(c._duration="duration")),s.channelJid!=null&&s.hasOwnProperty("channelJid")&&(c.channelJid=s.channelJid,g.oneofs&&(c._channelJid="channelJid")),s.channelMessageId!=null&&s.hasOwnProperty("channelMessageId")&&(c.channelMessageId=s.channelMessageId,g.oneofs&&(c._channelMessageId="channelMessageId")),s.hasMultipleReshares!=null&&s.hasOwnProperty("hasMultipleReshares")&&(c.hasMultipleReshares=s.hasMultipleReshares,g.oneofs&&(c._hasMultipleReshares="hasMultipleReshares")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.StatusAttribution.StatusReshare.Metadata"},a})(),i.Source=(function(){let a={},A=Object.create(a);return A[a[0]="UNKNOWN"]=0,A[a[1]="INTERNAL_RESHARE"]=1,A[a[2]="MENTION_RESHARE"]=2,A[a[3]="CHANNEL_RESHARE"]=3,A[a[4]="FORWARD"]=4,A})(),i})(),t.Type=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="RESHARE"]=1,e[i[2]="EXTERNAL_SHARE"]=2,e[i[3]="MUSIC"]=3,e[i[4]="STATUS_MENTION"]=4,e[i[5]="GROUP_STATUS"]=5,e[i[6]="RL_ATTRIBUTION"]=6,e[i[7]="AI_CREATED"]=7,e[i[8]="LAYOUTS"]=8,e})(),t})(),n.StatusMentionMessage=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.quotedStatus=p.proto.Message.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.StatusMentionMessage)return e;var a=new p.proto.StatusMentionMessage;if(e.quotedStatus!=null){if(typeof e.quotedStatus!="object")throw TypeError(".proto.StatusMentionMessage.quotedStatus: object expected");a.quotedStatus=p.proto.Message.fromObject(e.quotedStatus)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.quotedStatus!=null&&e.hasOwnProperty("quotedStatus")&&(A.quotedStatus=p.proto.Message.toObject(e.quotedStatus,a),a.oneofs&&(A._quotedStatus="quotedStatus")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StatusMentionMessage"},t})(),n.StatusPSA=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 44:{s.campaignId=e.uint64();break}case 45:{s.campaignExpirationTimestamp=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.StatusPSA)return e;var a=new p.proto.StatusPSA;return e.campaignId!=null&&(l.Long?(a.campaignId=l.Long.fromValue(e.campaignId)).unsigned=!0:typeof e.campaignId=="string"?a.campaignId=parseInt(e.campaignId,10):typeof e.campaignId=="number"?a.campaignId=e.campaignId:typeof e.campaignId=="object"&&(a.campaignId=new l.LongBits(e.campaignId.low>>>0,e.campaignId.high>>>0).toNumber(!0))),e.campaignExpirationTimestamp!=null&&(l.Long?(a.campaignExpirationTimestamp=l.Long.fromValue(e.campaignExpirationTimestamp)).unsigned=!0:typeof e.campaignExpirationTimestamp=="string"?a.campaignExpirationTimestamp=parseInt(e.campaignExpirationTimestamp,10):typeof e.campaignExpirationTimestamp=="number"?a.campaignExpirationTimestamp=e.campaignExpirationTimestamp:typeof e.campaignExpirationTimestamp=="object"&&(a.campaignExpirationTimestamp=new l.LongBits(e.campaignExpirationTimestamp.low>>>0,e.campaignExpirationTimestamp.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};if(a.defaults)if(l.Long){var r=new l.Long(0,0,!0);A.campaignId=a.longs===String?r.toString():a.longs===Number?r.toNumber():r}else A.campaignId=a.longs===String?"0":0;return e.campaignId!=null&&e.hasOwnProperty("campaignId")&&(typeof e.campaignId=="number"?A.campaignId=a.longs===String?String(e.campaignId):e.campaignId:A.campaignId=a.longs===String?se(e.campaignId,!0):a.longs===Number?ge(e.campaignId,!0):e.campaignId),e.campaignExpirationTimestamp!=null&&e.hasOwnProperty("campaignExpirationTimestamp")&&(typeof e.campaignExpirationTimestamp=="number"?A.campaignExpirationTimestamp=a.longs===String?String(e.campaignExpirationTimestamp):e.campaignExpirationTimestamp:A.campaignExpirationTimestamp=a.longs===String?se(e.campaignExpirationTimestamp,!0):a.longs===Number?ge(e.campaignExpirationTimestamp,!0):e.campaignExpirationTimestamp,a.oneofs&&(A._campaignExpirationTimestamp="campaignExpirationTimestamp")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StatusPSA"},t})(),n.StickerMetadata=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.url=e.string();break}case 2:{s.fileSha256=e.bytes();break}case 3:{s.fileEncSha256=e.bytes();break}case 4:{s.mediaKey=e.bytes();break}case 5:{s.mimetype=e.string();break}case 6:{s.height=e.uint32();break}case 7:{s.width=e.uint32();break}case 8:{s.directPath=e.string();break}case 9:{s.fileLength=e.uint64();break}case 10:{s.weight=e.float();break}case 11:{s.lastStickerSentTs=e.int64();break}case 12:{s.isLottie=e.bool();break}case 13:{s.imageHash=e.string();break}case 14:{s.isAvatarSticker=e.bool();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.StickerMetadata)return e;var a=new p.proto.StickerMetadata;return e.url!=null&&(a.url=String(e.url)),e.fileSha256!=null&&(typeof e.fileSha256=="string"?l.base64.decode(e.fileSha256,a.fileSha256=l.newBuffer(l.base64.length(e.fileSha256)),0):e.fileSha256.length>=0&&(a.fileSha256=e.fileSha256)),e.fileEncSha256!=null&&(typeof e.fileEncSha256=="string"?l.base64.decode(e.fileEncSha256,a.fileEncSha256=l.newBuffer(l.base64.length(e.fileEncSha256)),0):e.fileEncSha256.length>=0&&(a.fileEncSha256=e.fileEncSha256)),e.mediaKey!=null&&(typeof e.mediaKey=="string"?l.base64.decode(e.mediaKey,a.mediaKey=l.newBuffer(l.base64.length(e.mediaKey)),0):e.mediaKey.length>=0&&(a.mediaKey=e.mediaKey)),e.mimetype!=null&&(a.mimetype=String(e.mimetype)),e.height!=null&&(a.height=e.height>>>0),e.width!=null&&(a.width=e.width>>>0),e.directPath!=null&&(a.directPath=String(e.directPath)),e.fileLength!=null&&(l.Long?(a.fileLength=l.Long.fromValue(e.fileLength)).unsigned=!0:typeof e.fileLength=="string"?a.fileLength=parseInt(e.fileLength,10):typeof e.fileLength=="number"?a.fileLength=e.fileLength:typeof e.fileLength=="object"&&(a.fileLength=new l.LongBits(e.fileLength.low>>>0,e.fileLength.high>>>0).toNumber(!0))),e.weight!=null&&(a.weight=Number(e.weight)),e.lastStickerSentTs!=null&&(l.Long?(a.lastStickerSentTs=l.Long.fromValue(e.lastStickerSentTs)).unsigned=!1:typeof e.lastStickerSentTs=="string"?a.lastStickerSentTs=parseInt(e.lastStickerSentTs,10):typeof e.lastStickerSentTs=="number"?a.lastStickerSentTs=e.lastStickerSentTs:typeof e.lastStickerSentTs=="object"&&(a.lastStickerSentTs=new l.LongBits(e.lastStickerSentTs.low>>>0,e.lastStickerSentTs.high>>>0).toNumber())),e.isLottie!=null&&(a.isLottie=!!e.isLottie),e.imageHash!=null&&(a.imageHash=String(e.imageHash)),e.isAvatarSticker!=null&&(a.isAvatarSticker=!!e.isAvatarSticker),a},t.toObject=function(e,a){a||(a={});var A={};return e.url!=null&&e.hasOwnProperty("url")&&(A.url=e.url,a.oneofs&&(A._url="url")),e.fileSha256!=null&&e.hasOwnProperty("fileSha256")&&(A.fileSha256=a.bytes===String?l.base64.encode(e.fileSha256,0,e.fileSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileSha256):e.fileSha256,a.oneofs&&(A._fileSha256="fileSha256")),e.fileEncSha256!=null&&e.hasOwnProperty("fileEncSha256")&&(A.fileEncSha256=a.bytes===String?l.base64.encode(e.fileEncSha256,0,e.fileEncSha256.length):a.bytes===Array?Array.prototype.slice.call(e.fileEncSha256):e.fileEncSha256,a.oneofs&&(A._fileEncSha256="fileEncSha256")),e.mediaKey!=null&&e.hasOwnProperty("mediaKey")&&(A.mediaKey=a.bytes===String?l.base64.encode(e.mediaKey,0,e.mediaKey.length):a.bytes===Array?Array.prototype.slice.call(e.mediaKey):e.mediaKey,a.oneofs&&(A._mediaKey="mediaKey")),e.mimetype!=null&&e.hasOwnProperty("mimetype")&&(A.mimetype=e.mimetype,a.oneofs&&(A._mimetype="mimetype")),e.height!=null&&e.hasOwnProperty("height")&&(A.height=e.height,a.oneofs&&(A._height="height")),e.width!=null&&e.hasOwnProperty("width")&&(A.width=e.width,a.oneofs&&(A._width="width")),e.directPath!=null&&e.hasOwnProperty("directPath")&&(A.directPath=e.directPath,a.oneofs&&(A._directPath="directPath")),e.fileLength!=null&&e.hasOwnProperty("fileLength")&&(typeof e.fileLength=="number"?A.fileLength=a.longs===String?String(e.fileLength):e.fileLength:A.fileLength=a.longs===String?se(e.fileLength,!0):a.longs===Number?ge(e.fileLength,!0):e.fileLength,a.oneofs&&(A._fileLength="fileLength")),e.weight!=null&&e.hasOwnProperty("weight")&&(A.weight=a.json&&!isFinite(e.weight)?String(e.weight):e.weight,a.oneofs&&(A._weight="weight")),e.lastStickerSentTs!=null&&e.hasOwnProperty("lastStickerSentTs")&&(typeof e.lastStickerSentTs=="number"?A.lastStickerSentTs=a.longs===String?String(e.lastStickerSentTs):e.lastStickerSentTs:A.lastStickerSentTs=a.longs===String?se(e.lastStickerSentTs):a.longs===Number?ge(e.lastStickerSentTs):e.lastStickerSentTs,a.oneofs&&(A._lastStickerSentTs="lastStickerSentTs")),e.isLottie!=null&&e.hasOwnProperty("isLottie")&&(A.isLottie=e.isLottie,a.oneofs&&(A._isLottie="isLottie")),e.imageHash!=null&&e.hasOwnProperty("imageHash")&&(A.imageHash=e.imageHash,a.oneofs&&(A._imageHash="imageHash")),e.isAvatarSticker!=null&&e.hasOwnProperty("isAvatarSticker")&&(A.isAvatarSticker=e.isAvatarSticker,a.oneofs&&(A._isAvatarSticker="isAvatarSticker")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.StickerMetadata"},t})(),n.SyncActionData=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.index=e.bytes();break}case 2:{s.value=p.proto.SyncActionValue.decode(e,e.uint32());break}case 3:{s.padding=e.bytes();break}case 4:{s.version=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncActionData)return e;var a=new p.proto.SyncActionData;if(e.index!=null&&(typeof e.index=="string"?l.base64.decode(e.index,a.index=l.newBuffer(l.base64.length(e.index)),0):e.index.length>=0&&(a.index=e.index)),e.value!=null){if(typeof e.value!="object")throw TypeError(".proto.SyncActionData.value: object expected");a.value=p.proto.SyncActionValue.fromObject(e.value)}return e.padding!=null&&(typeof e.padding=="string"?l.base64.decode(e.padding,a.padding=l.newBuffer(l.base64.length(e.padding)),0):e.padding.length>=0&&(a.padding=e.padding)),e.version!=null&&(a.version=e.version|0),a},t.toObject=function(e,a){a||(a={});var A={};return e.index!=null&&e.hasOwnProperty("index")&&(A.index=a.bytes===String?l.base64.encode(e.index,0,e.index.length):a.bytes===Array?Array.prototype.slice.call(e.index):e.index,a.oneofs&&(A._index="index")),e.value!=null&&e.hasOwnProperty("value")&&(A.value=p.proto.SyncActionValue.toObject(e.value,a),a.oneofs&&(A._value="value")),e.padding!=null&&e.hasOwnProperty("padding")&&(A.padding=a.bytes===String?l.base64.encode(e.padding,0,e.padding.length):a.bytes===Array?Array.prototype.slice.call(e.padding):e.padding,a.oneofs&&(A._padding="padding")),e.version!=null&&e.hasOwnProperty("version")&&(A.version=e.version,a.oneofs&&(A._version="version")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncActionData"},t})(),n.SyncActionValue=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.timestamp=e.int64();break}case 2:{s.starAction=p.proto.SyncActionValue.StarAction.decode(e,e.uint32());break}case 3:{s.contactAction=p.proto.SyncActionValue.ContactAction.decode(e,e.uint32());break}case 4:{s.muteAction=p.proto.SyncActionValue.MuteAction.decode(e,e.uint32());break}case 5:{s.pinAction=p.proto.SyncActionValue.PinAction.decode(e,e.uint32());break}case 7:{s.pushNameSetting=p.proto.SyncActionValue.PushNameSetting.decode(e,e.uint32());break}case 8:{s.quickReplyAction=p.proto.SyncActionValue.QuickReplyAction.decode(e,e.uint32());break}case 11:{s.recentEmojiWeightsAction=p.proto.SyncActionValue.RecentEmojiWeightsAction.decode(e,e.uint32());break}case 14:{s.labelEditAction=p.proto.SyncActionValue.LabelEditAction.decode(e,e.uint32());break}case 15:{s.labelAssociationAction=p.proto.SyncActionValue.LabelAssociationAction.decode(e,e.uint32());break}case 16:{s.localeSetting=p.proto.SyncActionValue.LocaleSetting.decode(e,e.uint32());break}case 17:{s.archiveChatAction=p.proto.SyncActionValue.ArchiveChatAction.decode(e,e.uint32());break}case 18:{s.deleteMessageForMeAction=p.proto.SyncActionValue.DeleteMessageForMeAction.decode(e,e.uint32());break}case 19:{s.keyExpiration=p.proto.SyncActionValue.KeyExpiration.decode(e,e.uint32());break}case 20:{s.markChatAsReadAction=p.proto.SyncActionValue.MarkChatAsReadAction.decode(e,e.uint32());break}case 21:{s.clearChatAction=p.proto.SyncActionValue.ClearChatAction.decode(e,e.uint32());break}case 22:{s.deleteChatAction=p.proto.SyncActionValue.DeleteChatAction.decode(e,e.uint32());break}case 23:{s.unarchiveChatsSetting=p.proto.SyncActionValue.UnarchiveChatsSetting.decode(e,e.uint32());break}case 24:{s.primaryFeature=p.proto.SyncActionValue.PrimaryFeature.decode(e,e.uint32());break}case 26:{s.androidUnsupportedActions=p.proto.SyncActionValue.AndroidUnsupportedActions.decode(e,e.uint32());break}case 27:{s.agentAction=p.proto.SyncActionValue.AgentAction.decode(e,e.uint32());break}case 28:{s.subscriptionAction=p.proto.SyncActionValue.SubscriptionAction.decode(e,e.uint32());break}case 29:{s.userStatusMuteAction=p.proto.SyncActionValue.UserStatusMuteAction.decode(e,e.uint32());break}case 30:{s.timeFormatAction=p.proto.SyncActionValue.TimeFormatAction.decode(e,e.uint32());break}case 31:{s.nuxAction=p.proto.SyncActionValue.NuxAction.decode(e,e.uint32());break}case 32:{s.primaryVersionAction=p.proto.SyncActionValue.PrimaryVersionAction.decode(e,e.uint32());break}case 33:{s.stickerAction=p.proto.SyncActionValue.StickerAction.decode(e,e.uint32());break}case 34:{s.removeRecentStickerAction=p.proto.SyncActionValue.RemoveRecentStickerAction.decode(e,e.uint32());break}case 35:{s.chatAssignment=p.proto.SyncActionValue.ChatAssignmentAction.decode(e,e.uint32());break}case 36:{s.chatAssignmentOpenedStatus=p.proto.SyncActionValue.ChatAssignmentOpenedStatusAction.decode(e,e.uint32());break}case 37:{s.pnForLidChatAction=p.proto.SyncActionValue.PnForLidChatAction.decode(e,e.uint32());break}case 38:{s.marketingMessageAction=p.proto.SyncActionValue.MarketingMessageAction.decode(e,e.uint32());break}case 39:{s.marketingMessageBroadcastAction=p.proto.SyncActionValue.MarketingMessageBroadcastAction.decode(e,e.uint32());break}case 40:{s.externalWebBetaAction=p.proto.SyncActionValue.ExternalWebBetaAction.decode(e,e.uint32());break}case 41:{s.privacySettingRelayAllCalls=p.proto.SyncActionValue.PrivacySettingRelayAllCalls.decode(e,e.uint32());break}case 42:{s.callLogAction=p.proto.SyncActionValue.CallLogAction.decode(e,e.uint32());break}case 43:{s.ugcBot=p.proto.SyncActionValue.UGCBot.decode(e,e.uint32());break}case 44:{s.statusPrivacy=p.proto.SyncActionValue.StatusPrivacyAction.decode(e,e.uint32());break}case 45:{s.botWelcomeRequestAction=p.proto.SyncActionValue.BotWelcomeRequestAction.decode(e,e.uint32());break}case 46:{s.deleteIndividualCallLog=p.proto.SyncActionValue.DeleteIndividualCallLogAction.decode(e,e.uint32());break}case 47:{s.labelReorderingAction=p.proto.SyncActionValue.LabelReorderingAction.decode(e,e.uint32());break}case 48:{s.paymentInfoAction=p.proto.SyncActionValue.PaymentInfoAction.decode(e,e.uint32());break}case 49:{s.customPaymentMethodsAction=p.proto.SyncActionValue.CustomPaymentMethodsAction.decode(e,e.uint32());break}case 50:{s.lockChatAction=p.proto.SyncActionValue.LockChatAction.decode(e,e.uint32());break}case 51:{s.chatLockSettings=p.proto.ChatLockSettings.decode(e,e.uint32());break}case 52:{s.wamoUserIdentifierAction=p.proto.SyncActionValue.WamoUserIdentifierAction.decode(e,e.uint32());break}case 53:{s.privacySettingDisableLinkPreviewsAction=p.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction.decode(e,e.uint32());break}case 54:{s.deviceCapabilities=p.proto.DeviceCapabilities.decode(e,e.uint32());break}case 55:{s.noteEditAction=p.proto.SyncActionValue.NoteEditAction.decode(e,e.uint32());break}case 56:{s.favoritesAction=p.proto.SyncActionValue.FavoritesAction.decode(e,e.uint32());break}case 57:{s.merchantPaymentPartnerAction=p.proto.SyncActionValue.MerchantPaymentPartnerAction.decode(e,e.uint32());break}case 58:{s.waffleAccountLinkStateAction=p.proto.SyncActionValue.WaffleAccountLinkStateAction.decode(e,e.uint32());break}case 59:{s.usernameChatStartMode=p.proto.SyncActionValue.UsernameChatStartModeAction.decode(e,e.uint32());break}case 60:{s.notificationActivitySettingAction=p.proto.SyncActionValue.NotificationActivitySettingAction.decode(e,e.uint32());break}case 61:{s.lidContactAction=p.proto.SyncActionValue.LidContactAction.decode(e,e.uint32());break}case 62:{s.ctwaPerCustomerDataSharingAction=p.proto.SyncActionValue.CtwaPerCustomerDataSharingAction.decode(e,e.uint32());break}case 63:{s.paymentTosAction=p.proto.SyncActionValue.PaymentTosAction.decode(e,e.uint32());break}case 64:{s.privacySettingChannelsPersonalisedRecommendationAction=p.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction.decode(e,e.uint32());break}case 65:{s.businessBroadcastAssociationAction=p.proto.SyncActionValue.BusinessBroadcastAssociationAction.decode(e,e.uint32());break}case 66:{s.detectedOutcomesStatusAction=p.proto.SyncActionValue.DetectedOutcomesStatusAction.decode(e,e.uint32());break}case 68:{s.maibaAiFeaturesControlAction=p.proto.SyncActionValue.MaibaAIFeaturesControlAction.decode(e,e.uint32());break}case 69:{s.businessBroadcastListAction=p.proto.SyncActionValue.BusinessBroadcastListAction.decode(e,e.uint32());break}case 70:{s.musicUserIdAction=p.proto.SyncActionValue.MusicUserIdAction.decode(e,e.uint32());break}case 71:{s.statusPostOptInNotificationPreferencesAction=p.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction.decode(e,e.uint32());break}case 72:{s.avatarUpdatedAction=p.proto.SyncActionValue.AvatarUpdatedAction.decode(e,e.uint32());break}case 74:{s.privateProcessingSettingAction=p.proto.SyncActionValue.PrivateProcessingSettingAction.decode(e,e.uint32());break}case 75:{s.newsletterSavedInterestsAction=p.proto.SyncActionValue.NewsletterSavedInterestsAction.decode(e,e.uint32());break}case 76:{s.aiThreadRenameAction=p.proto.SyncActionValue.AiThreadRenameAction.decode(e,e.uint32());break}case 77:{s.interactiveMessageAction=p.proto.SyncActionValue.InteractiveMessageAction.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncActionValue)return e;var a=new p.proto.SyncActionValue;if(e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!1:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber())),e.starAction!=null){if(typeof e.starAction!="object")throw TypeError(".proto.SyncActionValue.starAction: object expected");a.starAction=p.proto.SyncActionValue.StarAction.fromObject(e.starAction)}if(e.contactAction!=null){if(typeof e.contactAction!="object")throw TypeError(".proto.SyncActionValue.contactAction: object expected");a.contactAction=p.proto.SyncActionValue.ContactAction.fromObject(e.contactAction)}if(e.muteAction!=null){if(typeof e.muteAction!="object")throw TypeError(".proto.SyncActionValue.muteAction: object expected");a.muteAction=p.proto.SyncActionValue.MuteAction.fromObject(e.muteAction)}if(e.pinAction!=null){if(typeof e.pinAction!="object")throw TypeError(".proto.SyncActionValue.pinAction: object expected");a.pinAction=p.proto.SyncActionValue.PinAction.fromObject(e.pinAction)}if(e.pushNameSetting!=null){if(typeof e.pushNameSetting!="object")throw TypeError(".proto.SyncActionValue.pushNameSetting: object expected");a.pushNameSetting=p.proto.SyncActionValue.PushNameSetting.fromObject(e.pushNameSetting)}if(e.quickReplyAction!=null){if(typeof e.quickReplyAction!="object")throw TypeError(".proto.SyncActionValue.quickReplyAction: object expected");a.quickReplyAction=p.proto.SyncActionValue.QuickReplyAction.fromObject(e.quickReplyAction)}if(e.recentEmojiWeightsAction!=null){if(typeof e.recentEmojiWeightsAction!="object")throw TypeError(".proto.SyncActionValue.recentEmojiWeightsAction: object expected");a.recentEmojiWeightsAction=p.proto.SyncActionValue.RecentEmojiWeightsAction.fromObject(e.recentEmojiWeightsAction)}if(e.labelEditAction!=null){if(typeof e.labelEditAction!="object")throw TypeError(".proto.SyncActionValue.labelEditAction: object expected");a.labelEditAction=p.proto.SyncActionValue.LabelEditAction.fromObject(e.labelEditAction)}if(e.labelAssociationAction!=null){if(typeof e.labelAssociationAction!="object")throw TypeError(".proto.SyncActionValue.labelAssociationAction: object expected");a.labelAssociationAction=p.proto.SyncActionValue.LabelAssociationAction.fromObject(e.labelAssociationAction)}if(e.localeSetting!=null){if(typeof e.localeSetting!="object")throw TypeError(".proto.SyncActionValue.localeSetting: object expected");a.localeSetting=p.proto.SyncActionValue.LocaleSetting.fromObject(e.localeSetting)}if(e.archiveChatAction!=null){if(typeof e.archiveChatAction!="object")throw TypeError(".proto.SyncActionValue.archiveChatAction: object expected");a.archiveChatAction=p.proto.SyncActionValue.ArchiveChatAction.fromObject(e.archiveChatAction)}if(e.deleteMessageForMeAction!=null){if(typeof e.deleteMessageForMeAction!="object")throw TypeError(".proto.SyncActionValue.deleteMessageForMeAction: object expected");a.deleteMessageForMeAction=p.proto.SyncActionValue.DeleteMessageForMeAction.fromObject(e.deleteMessageForMeAction)}if(e.keyExpiration!=null){if(typeof e.keyExpiration!="object")throw TypeError(".proto.SyncActionValue.keyExpiration: object expected");a.keyExpiration=p.proto.SyncActionValue.KeyExpiration.fromObject(e.keyExpiration)}if(e.markChatAsReadAction!=null){if(typeof e.markChatAsReadAction!="object")throw TypeError(".proto.SyncActionValue.markChatAsReadAction: object expected");a.markChatAsReadAction=p.proto.SyncActionValue.MarkChatAsReadAction.fromObject(e.markChatAsReadAction)}if(e.clearChatAction!=null){if(typeof e.clearChatAction!="object")throw TypeError(".proto.SyncActionValue.clearChatAction: object expected");a.clearChatAction=p.proto.SyncActionValue.ClearChatAction.fromObject(e.clearChatAction)}if(e.deleteChatAction!=null){if(typeof e.deleteChatAction!="object")throw TypeError(".proto.SyncActionValue.deleteChatAction: object expected");a.deleteChatAction=p.proto.SyncActionValue.DeleteChatAction.fromObject(e.deleteChatAction)}if(e.unarchiveChatsSetting!=null){if(typeof e.unarchiveChatsSetting!="object")throw TypeError(".proto.SyncActionValue.unarchiveChatsSetting: object expected");a.unarchiveChatsSetting=p.proto.SyncActionValue.UnarchiveChatsSetting.fromObject(e.unarchiveChatsSetting)}if(e.primaryFeature!=null){if(typeof e.primaryFeature!="object")throw TypeError(".proto.SyncActionValue.primaryFeature: object expected");a.primaryFeature=p.proto.SyncActionValue.PrimaryFeature.fromObject(e.primaryFeature)}if(e.androidUnsupportedActions!=null){if(typeof e.androidUnsupportedActions!="object")throw TypeError(".proto.SyncActionValue.androidUnsupportedActions: object expected");a.androidUnsupportedActions=p.proto.SyncActionValue.AndroidUnsupportedActions.fromObject(e.androidUnsupportedActions)}if(e.agentAction!=null){if(typeof e.agentAction!="object")throw TypeError(".proto.SyncActionValue.agentAction: object expected");a.agentAction=p.proto.SyncActionValue.AgentAction.fromObject(e.agentAction)}if(e.subscriptionAction!=null){if(typeof e.subscriptionAction!="object")throw TypeError(".proto.SyncActionValue.subscriptionAction: object expected");a.subscriptionAction=p.proto.SyncActionValue.SubscriptionAction.fromObject(e.subscriptionAction)}if(e.userStatusMuteAction!=null){if(typeof e.userStatusMuteAction!="object")throw TypeError(".proto.SyncActionValue.userStatusMuteAction: object expected");a.userStatusMuteAction=p.proto.SyncActionValue.UserStatusMuteAction.fromObject(e.userStatusMuteAction)}if(e.timeFormatAction!=null){if(typeof e.timeFormatAction!="object")throw TypeError(".proto.SyncActionValue.timeFormatAction: object expected");a.timeFormatAction=p.proto.SyncActionValue.TimeFormatAction.fromObject(e.timeFormatAction)}if(e.nuxAction!=null){if(typeof e.nuxAction!="object")throw TypeError(".proto.SyncActionValue.nuxAction: object expected");a.nuxAction=p.proto.SyncActionValue.NuxAction.fromObject(e.nuxAction)}if(e.primaryVersionAction!=null){if(typeof e.primaryVersionAction!="object")throw TypeError(".proto.SyncActionValue.primaryVersionAction: object expected");a.primaryVersionAction=p.proto.SyncActionValue.PrimaryVersionAction.fromObject(e.primaryVersionAction)}if(e.stickerAction!=null){if(typeof e.stickerAction!="object")throw TypeError(".proto.SyncActionValue.stickerAction: object expected");a.stickerAction=p.proto.SyncActionValue.StickerAction.fromObject(e.stickerAction)}if(e.removeRecentStickerAction!=null){if(typeof e.removeRecentStickerAction!="object")throw TypeError(".proto.SyncActionValue.removeRecentStickerAction: object expected");a.removeRecentStickerAction=p.proto.SyncActionValue.RemoveRecentStickerAction.fromObject(e.removeRecentStickerAction)}if(e.chatAssignment!=null){if(typeof e.chatAssignment!="object")throw TypeError(".proto.SyncActionValue.chatAssignment: object expected");a.chatAssignment=p.proto.SyncActionValue.ChatAssignmentAction.fromObject(e.chatAssignment)}if(e.chatAssignmentOpenedStatus!=null){if(typeof e.chatAssignmentOpenedStatus!="object")throw TypeError(".proto.SyncActionValue.chatAssignmentOpenedStatus: object expected");a.chatAssignmentOpenedStatus=p.proto.SyncActionValue.ChatAssignmentOpenedStatusAction.fromObject(e.chatAssignmentOpenedStatus)}if(e.pnForLidChatAction!=null){if(typeof e.pnForLidChatAction!="object")throw TypeError(".proto.SyncActionValue.pnForLidChatAction: object expected");a.pnForLidChatAction=p.proto.SyncActionValue.PnForLidChatAction.fromObject(e.pnForLidChatAction)}if(e.marketingMessageAction!=null){if(typeof e.marketingMessageAction!="object")throw TypeError(".proto.SyncActionValue.marketingMessageAction: object expected");a.marketingMessageAction=p.proto.SyncActionValue.MarketingMessageAction.fromObject(e.marketingMessageAction)}if(e.marketingMessageBroadcastAction!=null){if(typeof e.marketingMessageBroadcastAction!="object")throw TypeError(".proto.SyncActionValue.marketingMessageBroadcastAction: object expected");a.marketingMessageBroadcastAction=p.proto.SyncActionValue.MarketingMessageBroadcastAction.fromObject(e.marketingMessageBroadcastAction)}if(e.externalWebBetaAction!=null){if(typeof e.externalWebBetaAction!="object")throw TypeError(".proto.SyncActionValue.externalWebBetaAction: object expected");a.externalWebBetaAction=p.proto.SyncActionValue.ExternalWebBetaAction.fromObject(e.externalWebBetaAction)}if(e.privacySettingRelayAllCalls!=null){if(typeof e.privacySettingRelayAllCalls!="object")throw TypeError(".proto.SyncActionValue.privacySettingRelayAllCalls: object expected");a.privacySettingRelayAllCalls=p.proto.SyncActionValue.PrivacySettingRelayAllCalls.fromObject(e.privacySettingRelayAllCalls)}if(e.callLogAction!=null){if(typeof e.callLogAction!="object")throw TypeError(".proto.SyncActionValue.callLogAction: object expected");a.callLogAction=p.proto.SyncActionValue.CallLogAction.fromObject(e.callLogAction)}if(e.ugcBot!=null){if(typeof e.ugcBot!="object")throw TypeError(".proto.SyncActionValue.ugcBot: object expected");a.ugcBot=p.proto.SyncActionValue.UGCBot.fromObject(e.ugcBot)}if(e.statusPrivacy!=null){if(typeof e.statusPrivacy!="object")throw TypeError(".proto.SyncActionValue.statusPrivacy: object expected");a.statusPrivacy=p.proto.SyncActionValue.StatusPrivacyAction.fromObject(e.statusPrivacy)}if(e.botWelcomeRequestAction!=null){if(typeof e.botWelcomeRequestAction!="object")throw TypeError(".proto.SyncActionValue.botWelcomeRequestAction: object expected");a.botWelcomeRequestAction=p.proto.SyncActionValue.BotWelcomeRequestAction.fromObject(e.botWelcomeRequestAction)}if(e.deleteIndividualCallLog!=null){if(typeof e.deleteIndividualCallLog!="object")throw TypeError(".proto.SyncActionValue.deleteIndividualCallLog: object expected");a.deleteIndividualCallLog=p.proto.SyncActionValue.DeleteIndividualCallLogAction.fromObject(e.deleteIndividualCallLog)}if(e.labelReorderingAction!=null){if(typeof e.labelReorderingAction!="object")throw TypeError(".proto.SyncActionValue.labelReorderingAction: object expected");a.labelReorderingAction=p.proto.SyncActionValue.LabelReorderingAction.fromObject(e.labelReorderingAction)}if(e.paymentInfoAction!=null){if(typeof e.paymentInfoAction!="object")throw TypeError(".proto.SyncActionValue.paymentInfoAction: object expected");a.paymentInfoAction=p.proto.SyncActionValue.PaymentInfoAction.fromObject(e.paymentInfoAction)}if(e.customPaymentMethodsAction!=null){if(typeof e.customPaymentMethodsAction!="object")throw TypeError(".proto.SyncActionValue.customPaymentMethodsAction: object expected");a.customPaymentMethodsAction=p.proto.SyncActionValue.CustomPaymentMethodsAction.fromObject(e.customPaymentMethodsAction)}if(e.lockChatAction!=null){if(typeof e.lockChatAction!="object")throw TypeError(".proto.SyncActionValue.lockChatAction: object expected");a.lockChatAction=p.proto.SyncActionValue.LockChatAction.fromObject(e.lockChatAction)}if(e.chatLockSettings!=null){if(typeof e.chatLockSettings!="object")throw TypeError(".proto.SyncActionValue.chatLockSettings: object expected");a.chatLockSettings=p.proto.ChatLockSettings.fromObject(e.chatLockSettings)}if(e.wamoUserIdentifierAction!=null){if(typeof e.wamoUserIdentifierAction!="object")throw TypeError(".proto.SyncActionValue.wamoUserIdentifierAction: object expected");a.wamoUserIdentifierAction=p.proto.SyncActionValue.WamoUserIdentifierAction.fromObject(e.wamoUserIdentifierAction)}if(e.privacySettingDisableLinkPreviewsAction!=null){if(typeof e.privacySettingDisableLinkPreviewsAction!="object")throw TypeError(".proto.SyncActionValue.privacySettingDisableLinkPreviewsAction: object expected");a.privacySettingDisableLinkPreviewsAction=p.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction.fromObject(e.privacySettingDisableLinkPreviewsAction)}if(e.deviceCapabilities!=null){if(typeof e.deviceCapabilities!="object")throw TypeError(".proto.SyncActionValue.deviceCapabilities: object expected");a.deviceCapabilities=p.proto.DeviceCapabilities.fromObject(e.deviceCapabilities)}if(e.noteEditAction!=null){if(typeof e.noteEditAction!="object")throw TypeError(".proto.SyncActionValue.noteEditAction: object expected");a.noteEditAction=p.proto.SyncActionValue.NoteEditAction.fromObject(e.noteEditAction)}if(e.favoritesAction!=null){if(typeof e.favoritesAction!="object")throw TypeError(".proto.SyncActionValue.favoritesAction: object expected");a.favoritesAction=p.proto.SyncActionValue.FavoritesAction.fromObject(e.favoritesAction)}if(e.merchantPaymentPartnerAction!=null){if(typeof e.merchantPaymentPartnerAction!="object")throw TypeError(".proto.SyncActionValue.merchantPaymentPartnerAction: object expected");a.merchantPaymentPartnerAction=p.proto.SyncActionValue.MerchantPaymentPartnerAction.fromObject(e.merchantPaymentPartnerAction)}if(e.waffleAccountLinkStateAction!=null){if(typeof e.waffleAccountLinkStateAction!="object")throw TypeError(".proto.SyncActionValue.waffleAccountLinkStateAction: object expected");a.waffleAccountLinkStateAction=p.proto.SyncActionValue.WaffleAccountLinkStateAction.fromObject(e.waffleAccountLinkStateAction)}if(e.usernameChatStartMode!=null){if(typeof e.usernameChatStartMode!="object")throw TypeError(".proto.SyncActionValue.usernameChatStartMode: object expected");a.usernameChatStartMode=p.proto.SyncActionValue.UsernameChatStartModeAction.fromObject(e.usernameChatStartMode)}if(e.notificationActivitySettingAction!=null){if(typeof e.notificationActivitySettingAction!="object")throw TypeError(".proto.SyncActionValue.notificationActivitySettingAction: object expected");a.notificationActivitySettingAction=p.proto.SyncActionValue.NotificationActivitySettingAction.fromObject(e.notificationActivitySettingAction)}if(e.lidContactAction!=null){if(typeof e.lidContactAction!="object")throw TypeError(".proto.SyncActionValue.lidContactAction: object expected");a.lidContactAction=p.proto.SyncActionValue.LidContactAction.fromObject(e.lidContactAction)}if(e.ctwaPerCustomerDataSharingAction!=null){if(typeof e.ctwaPerCustomerDataSharingAction!="object")throw TypeError(".proto.SyncActionValue.ctwaPerCustomerDataSharingAction: object expected");a.ctwaPerCustomerDataSharingAction=p.proto.SyncActionValue.CtwaPerCustomerDataSharingAction.fromObject(e.ctwaPerCustomerDataSharingAction)}if(e.paymentTosAction!=null){if(typeof e.paymentTosAction!="object")throw TypeError(".proto.SyncActionValue.paymentTosAction: object expected");a.paymentTosAction=p.proto.SyncActionValue.PaymentTosAction.fromObject(e.paymentTosAction)}if(e.privacySettingChannelsPersonalisedRecommendationAction!=null){if(typeof e.privacySettingChannelsPersonalisedRecommendationAction!="object")throw TypeError(".proto.SyncActionValue.privacySettingChannelsPersonalisedRecommendationAction: object expected");a.privacySettingChannelsPersonalisedRecommendationAction=p.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction.fromObject(e.privacySettingChannelsPersonalisedRecommendationAction)}if(e.businessBroadcastAssociationAction!=null){if(typeof e.businessBroadcastAssociationAction!="object")throw TypeError(".proto.SyncActionValue.businessBroadcastAssociationAction: object expected");a.businessBroadcastAssociationAction=p.proto.SyncActionValue.BusinessBroadcastAssociationAction.fromObject(e.businessBroadcastAssociationAction)}if(e.detectedOutcomesStatusAction!=null){if(typeof e.detectedOutcomesStatusAction!="object")throw TypeError(".proto.SyncActionValue.detectedOutcomesStatusAction: object expected");a.detectedOutcomesStatusAction=p.proto.SyncActionValue.DetectedOutcomesStatusAction.fromObject(e.detectedOutcomesStatusAction)}if(e.maibaAiFeaturesControlAction!=null){if(typeof e.maibaAiFeaturesControlAction!="object")throw TypeError(".proto.SyncActionValue.maibaAiFeaturesControlAction: object expected");a.maibaAiFeaturesControlAction=p.proto.SyncActionValue.MaibaAIFeaturesControlAction.fromObject(e.maibaAiFeaturesControlAction)}if(e.businessBroadcastListAction!=null){if(typeof e.businessBroadcastListAction!="object")throw TypeError(".proto.SyncActionValue.businessBroadcastListAction: object expected");a.businessBroadcastListAction=p.proto.SyncActionValue.BusinessBroadcastListAction.fromObject(e.businessBroadcastListAction)}if(e.musicUserIdAction!=null){if(typeof e.musicUserIdAction!="object")throw TypeError(".proto.SyncActionValue.musicUserIdAction: object expected");a.musicUserIdAction=p.proto.SyncActionValue.MusicUserIdAction.fromObject(e.musicUserIdAction)}if(e.statusPostOptInNotificationPreferencesAction!=null){if(typeof e.statusPostOptInNotificationPreferencesAction!="object")throw TypeError(".proto.SyncActionValue.statusPostOptInNotificationPreferencesAction: object expected");a.statusPostOptInNotificationPreferencesAction=p.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction.fromObject(e.statusPostOptInNotificationPreferencesAction)}if(e.avatarUpdatedAction!=null){if(typeof e.avatarUpdatedAction!="object")throw TypeError(".proto.SyncActionValue.avatarUpdatedAction: object expected");a.avatarUpdatedAction=p.proto.SyncActionValue.AvatarUpdatedAction.fromObject(e.avatarUpdatedAction)}if(e.privateProcessingSettingAction!=null){if(typeof e.privateProcessingSettingAction!="object")throw TypeError(".proto.SyncActionValue.privateProcessingSettingAction: object expected");a.privateProcessingSettingAction=p.proto.SyncActionValue.PrivateProcessingSettingAction.fromObject(e.privateProcessingSettingAction)}if(e.newsletterSavedInterestsAction!=null){if(typeof e.newsletterSavedInterestsAction!="object")throw TypeError(".proto.SyncActionValue.newsletterSavedInterestsAction: object expected");a.newsletterSavedInterestsAction=p.proto.SyncActionValue.NewsletterSavedInterestsAction.fromObject(e.newsletterSavedInterestsAction)}if(e.aiThreadRenameAction!=null){if(typeof e.aiThreadRenameAction!="object")throw TypeError(".proto.SyncActionValue.aiThreadRenameAction: object expected");a.aiThreadRenameAction=p.proto.SyncActionValue.AiThreadRenameAction.fromObject(e.aiThreadRenameAction)}if(e.interactiveMessageAction!=null){if(typeof e.interactiveMessageAction!="object")throw TypeError(".proto.SyncActionValue.interactiveMessageAction: object expected");a.interactiveMessageAction=p.proto.SyncActionValue.InteractiveMessageAction.fromObject(e.interactiveMessageAction)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.timestamp!=null&&e.hasOwnProperty("timestamp")&&(typeof e.timestamp=="number"?A.timestamp=a.longs===String?String(e.timestamp):e.timestamp:A.timestamp=a.longs===String?se(e.timestamp):a.longs===Number?ge(e.timestamp):e.timestamp,a.oneofs&&(A._timestamp="timestamp")),e.starAction!=null&&e.hasOwnProperty("starAction")&&(A.starAction=p.proto.SyncActionValue.StarAction.toObject(e.starAction,a),a.oneofs&&(A._starAction="starAction")),e.contactAction!=null&&e.hasOwnProperty("contactAction")&&(A.contactAction=p.proto.SyncActionValue.ContactAction.toObject(e.contactAction,a),a.oneofs&&(A._contactAction="contactAction")),e.muteAction!=null&&e.hasOwnProperty("muteAction")&&(A.muteAction=p.proto.SyncActionValue.MuteAction.toObject(e.muteAction,a),a.oneofs&&(A._muteAction="muteAction")),e.pinAction!=null&&e.hasOwnProperty("pinAction")&&(A.pinAction=p.proto.SyncActionValue.PinAction.toObject(e.pinAction,a),a.oneofs&&(A._pinAction="pinAction")),e.pushNameSetting!=null&&e.hasOwnProperty("pushNameSetting")&&(A.pushNameSetting=p.proto.SyncActionValue.PushNameSetting.toObject(e.pushNameSetting,a),a.oneofs&&(A._pushNameSetting="pushNameSetting")),e.quickReplyAction!=null&&e.hasOwnProperty("quickReplyAction")&&(A.quickReplyAction=p.proto.SyncActionValue.QuickReplyAction.toObject(e.quickReplyAction,a),a.oneofs&&(A._quickReplyAction="quickReplyAction")),e.recentEmojiWeightsAction!=null&&e.hasOwnProperty("recentEmojiWeightsAction")&&(A.recentEmojiWeightsAction=p.proto.SyncActionValue.RecentEmojiWeightsAction.toObject(e.recentEmojiWeightsAction,a),a.oneofs&&(A._recentEmojiWeightsAction="recentEmojiWeightsAction")),e.labelEditAction!=null&&e.hasOwnProperty("labelEditAction")&&(A.labelEditAction=p.proto.SyncActionValue.LabelEditAction.toObject(e.labelEditAction,a),a.oneofs&&(A._labelEditAction="labelEditAction")),e.labelAssociationAction!=null&&e.hasOwnProperty("labelAssociationAction")&&(A.labelAssociationAction=p.proto.SyncActionValue.LabelAssociationAction.toObject(e.labelAssociationAction,a),a.oneofs&&(A._labelAssociationAction="labelAssociationAction")),e.localeSetting!=null&&e.hasOwnProperty("localeSetting")&&(A.localeSetting=p.proto.SyncActionValue.LocaleSetting.toObject(e.localeSetting,a),a.oneofs&&(A._localeSetting="localeSetting")),e.archiveChatAction!=null&&e.hasOwnProperty("archiveChatAction")&&(A.archiveChatAction=p.proto.SyncActionValue.ArchiveChatAction.toObject(e.archiveChatAction,a),a.oneofs&&(A._archiveChatAction="archiveChatAction")),e.deleteMessageForMeAction!=null&&e.hasOwnProperty("deleteMessageForMeAction")&&(A.deleteMessageForMeAction=p.proto.SyncActionValue.DeleteMessageForMeAction.toObject(e.deleteMessageForMeAction,a),a.oneofs&&(A._deleteMessageForMeAction="deleteMessageForMeAction")),e.keyExpiration!=null&&e.hasOwnProperty("keyExpiration")&&(A.keyExpiration=p.proto.SyncActionValue.KeyExpiration.toObject(e.keyExpiration,a),a.oneofs&&(A._keyExpiration="keyExpiration")),e.markChatAsReadAction!=null&&e.hasOwnProperty("markChatAsReadAction")&&(A.markChatAsReadAction=p.proto.SyncActionValue.MarkChatAsReadAction.toObject(e.markChatAsReadAction,a),a.oneofs&&(A._markChatAsReadAction="markChatAsReadAction")),e.clearChatAction!=null&&e.hasOwnProperty("clearChatAction")&&(A.clearChatAction=p.proto.SyncActionValue.ClearChatAction.toObject(e.clearChatAction,a),a.oneofs&&(A._clearChatAction="clearChatAction")),e.deleteChatAction!=null&&e.hasOwnProperty("deleteChatAction")&&(A.deleteChatAction=p.proto.SyncActionValue.DeleteChatAction.toObject(e.deleteChatAction,a),a.oneofs&&(A._deleteChatAction="deleteChatAction")),e.unarchiveChatsSetting!=null&&e.hasOwnProperty("unarchiveChatsSetting")&&(A.unarchiveChatsSetting=p.proto.SyncActionValue.UnarchiveChatsSetting.toObject(e.unarchiveChatsSetting,a),a.oneofs&&(A._unarchiveChatsSetting="unarchiveChatsSetting")),e.primaryFeature!=null&&e.hasOwnProperty("primaryFeature")&&(A.primaryFeature=p.proto.SyncActionValue.PrimaryFeature.toObject(e.primaryFeature,a),a.oneofs&&(A._primaryFeature="primaryFeature")),e.androidUnsupportedActions!=null&&e.hasOwnProperty("androidUnsupportedActions")&&(A.androidUnsupportedActions=p.proto.SyncActionValue.AndroidUnsupportedActions.toObject(e.androidUnsupportedActions,a),a.oneofs&&(A._androidUnsupportedActions="androidUnsupportedActions")),e.agentAction!=null&&e.hasOwnProperty("agentAction")&&(A.agentAction=p.proto.SyncActionValue.AgentAction.toObject(e.agentAction,a),a.oneofs&&(A._agentAction="agentAction")),e.subscriptionAction!=null&&e.hasOwnProperty("subscriptionAction")&&(A.subscriptionAction=p.proto.SyncActionValue.SubscriptionAction.toObject(e.subscriptionAction,a),a.oneofs&&(A._subscriptionAction="subscriptionAction")),e.userStatusMuteAction!=null&&e.hasOwnProperty("userStatusMuteAction")&&(A.userStatusMuteAction=p.proto.SyncActionValue.UserStatusMuteAction.toObject(e.userStatusMuteAction,a),a.oneofs&&(A._userStatusMuteAction="userStatusMuteAction")),e.timeFormatAction!=null&&e.hasOwnProperty("timeFormatAction")&&(A.timeFormatAction=p.proto.SyncActionValue.TimeFormatAction.toObject(e.timeFormatAction,a),a.oneofs&&(A._timeFormatAction="timeFormatAction")),e.nuxAction!=null&&e.hasOwnProperty("nuxAction")&&(A.nuxAction=p.proto.SyncActionValue.NuxAction.toObject(e.nuxAction,a),a.oneofs&&(A._nuxAction="nuxAction")),e.primaryVersionAction!=null&&e.hasOwnProperty("primaryVersionAction")&&(A.primaryVersionAction=p.proto.SyncActionValue.PrimaryVersionAction.toObject(e.primaryVersionAction,a),a.oneofs&&(A._primaryVersionAction="primaryVersionAction")),e.stickerAction!=null&&e.hasOwnProperty("stickerAction")&&(A.stickerAction=p.proto.SyncActionValue.StickerAction.toObject(e.stickerAction,a),a.oneofs&&(A._stickerAction="stickerAction")),e.removeRecentStickerAction!=null&&e.hasOwnProperty("removeRecentStickerAction")&&(A.removeRecentStickerAction=p.proto.SyncActionValue.RemoveRecentStickerAction.toObject(e.removeRecentStickerAction,a),a.oneofs&&(A._removeRecentStickerAction="removeRecentStickerAction")),e.chatAssignment!=null&&e.hasOwnProperty("chatAssignment")&&(A.chatAssignment=p.proto.SyncActionValue.ChatAssignmentAction.toObject(e.chatAssignment,a),a.oneofs&&(A._chatAssignment="chatAssignment")),e.chatAssignmentOpenedStatus!=null&&e.hasOwnProperty("chatAssignmentOpenedStatus")&&(A.chatAssignmentOpenedStatus=p.proto.SyncActionValue.ChatAssignmentOpenedStatusAction.toObject(e.chatAssignmentOpenedStatus,a),a.oneofs&&(A._chatAssignmentOpenedStatus="chatAssignmentOpenedStatus")),e.pnForLidChatAction!=null&&e.hasOwnProperty("pnForLidChatAction")&&(A.pnForLidChatAction=p.proto.SyncActionValue.PnForLidChatAction.toObject(e.pnForLidChatAction,a),a.oneofs&&(A._pnForLidChatAction="pnForLidChatAction")),e.marketingMessageAction!=null&&e.hasOwnProperty("marketingMessageAction")&&(A.marketingMessageAction=p.proto.SyncActionValue.MarketingMessageAction.toObject(e.marketingMessageAction,a),a.oneofs&&(A._marketingMessageAction="marketingMessageAction")),e.marketingMessageBroadcastAction!=null&&e.hasOwnProperty("marketingMessageBroadcastAction")&&(A.marketingMessageBroadcastAction=p.proto.SyncActionValue.MarketingMessageBroadcastAction.toObject(e.marketingMessageBroadcastAction,a),a.oneofs&&(A._marketingMessageBroadcastAction="marketingMessageBroadcastAction")),e.externalWebBetaAction!=null&&e.hasOwnProperty("externalWebBetaAction")&&(A.externalWebBetaAction=p.proto.SyncActionValue.ExternalWebBetaAction.toObject(e.externalWebBetaAction,a),a.oneofs&&(A._externalWebBetaAction="externalWebBetaAction")),e.privacySettingRelayAllCalls!=null&&e.hasOwnProperty("privacySettingRelayAllCalls")&&(A.privacySettingRelayAllCalls=p.proto.SyncActionValue.PrivacySettingRelayAllCalls.toObject(e.privacySettingRelayAllCalls,a),a.oneofs&&(A._privacySettingRelayAllCalls="privacySettingRelayAllCalls")),e.callLogAction!=null&&e.hasOwnProperty("callLogAction")&&(A.callLogAction=p.proto.SyncActionValue.CallLogAction.toObject(e.callLogAction,a),a.oneofs&&(A._callLogAction="callLogAction")),e.ugcBot!=null&&e.hasOwnProperty("ugcBot")&&(A.ugcBot=p.proto.SyncActionValue.UGCBot.toObject(e.ugcBot,a),a.oneofs&&(A._ugcBot="ugcBot")),e.statusPrivacy!=null&&e.hasOwnProperty("statusPrivacy")&&(A.statusPrivacy=p.proto.SyncActionValue.StatusPrivacyAction.toObject(e.statusPrivacy,a),a.oneofs&&(A._statusPrivacy="statusPrivacy")),e.botWelcomeRequestAction!=null&&e.hasOwnProperty("botWelcomeRequestAction")&&(A.botWelcomeRequestAction=p.proto.SyncActionValue.BotWelcomeRequestAction.toObject(e.botWelcomeRequestAction,a),a.oneofs&&(A._botWelcomeRequestAction="botWelcomeRequestAction")),e.deleteIndividualCallLog!=null&&e.hasOwnProperty("deleteIndividualCallLog")&&(A.deleteIndividualCallLog=p.proto.SyncActionValue.DeleteIndividualCallLogAction.toObject(e.deleteIndividualCallLog,a),a.oneofs&&(A._deleteIndividualCallLog="deleteIndividualCallLog")),e.labelReorderingAction!=null&&e.hasOwnProperty("labelReorderingAction")&&(A.labelReorderingAction=p.proto.SyncActionValue.LabelReorderingAction.toObject(e.labelReorderingAction,a),a.oneofs&&(A._labelReorderingAction="labelReorderingAction")),e.paymentInfoAction!=null&&e.hasOwnProperty("paymentInfoAction")&&(A.paymentInfoAction=p.proto.SyncActionValue.PaymentInfoAction.toObject(e.paymentInfoAction,a),a.oneofs&&(A._paymentInfoAction="paymentInfoAction")),e.customPaymentMethodsAction!=null&&e.hasOwnProperty("customPaymentMethodsAction")&&(A.customPaymentMethodsAction=p.proto.SyncActionValue.CustomPaymentMethodsAction.toObject(e.customPaymentMethodsAction,a),a.oneofs&&(A._customPaymentMethodsAction="customPaymentMethodsAction")),e.lockChatAction!=null&&e.hasOwnProperty("lockChatAction")&&(A.lockChatAction=p.proto.SyncActionValue.LockChatAction.toObject(e.lockChatAction,a),a.oneofs&&(A._lockChatAction="lockChatAction")),e.chatLockSettings!=null&&e.hasOwnProperty("chatLockSettings")&&(A.chatLockSettings=p.proto.ChatLockSettings.toObject(e.chatLockSettings,a),a.oneofs&&(A._chatLockSettings="chatLockSettings")),e.wamoUserIdentifierAction!=null&&e.hasOwnProperty("wamoUserIdentifierAction")&&(A.wamoUserIdentifierAction=p.proto.SyncActionValue.WamoUserIdentifierAction.toObject(e.wamoUserIdentifierAction,a),a.oneofs&&(A._wamoUserIdentifierAction="wamoUserIdentifierAction")),e.privacySettingDisableLinkPreviewsAction!=null&&e.hasOwnProperty("privacySettingDisableLinkPreviewsAction")&&(A.privacySettingDisableLinkPreviewsAction=p.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction.toObject(e.privacySettingDisableLinkPreviewsAction,a),a.oneofs&&(A._privacySettingDisableLinkPreviewsAction="privacySettingDisableLinkPreviewsAction")),e.deviceCapabilities!=null&&e.hasOwnProperty("deviceCapabilities")&&(A.deviceCapabilities=p.proto.DeviceCapabilities.toObject(e.deviceCapabilities,a),a.oneofs&&(A._deviceCapabilities="deviceCapabilities")),e.noteEditAction!=null&&e.hasOwnProperty("noteEditAction")&&(A.noteEditAction=p.proto.SyncActionValue.NoteEditAction.toObject(e.noteEditAction,a),a.oneofs&&(A._noteEditAction="noteEditAction")),e.favoritesAction!=null&&e.hasOwnProperty("favoritesAction")&&(A.favoritesAction=p.proto.SyncActionValue.FavoritesAction.toObject(e.favoritesAction,a),a.oneofs&&(A._favoritesAction="favoritesAction")),e.merchantPaymentPartnerAction!=null&&e.hasOwnProperty("merchantPaymentPartnerAction")&&(A.merchantPaymentPartnerAction=p.proto.SyncActionValue.MerchantPaymentPartnerAction.toObject(e.merchantPaymentPartnerAction,a),a.oneofs&&(A._merchantPaymentPartnerAction="merchantPaymentPartnerAction")),e.waffleAccountLinkStateAction!=null&&e.hasOwnProperty("waffleAccountLinkStateAction")&&(A.waffleAccountLinkStateAction=p.proto.SyncActionValue.WaffleAccountLinkStateAction.toObject(e.waffleAccountLinkStateAction,a),a.oneofs&&(A._waffleAccountLinkStateAction="waffleAccountLinkStateAction")),e.usernameChatStartMode!=null&&e.hasOwnProperty("usernameChatStartMode")&&(A.usernameChatStartMode=p.proto.SyncActionValue.UsernameChatStartModeAction.toObject(e.usernameChatStartMode,a),a.oneofs&&(A._usernameChatStartMode="usernameChatStartMode")),e.notificationActivitySettingAction!=null&&e.hasOwnProperty("notificationActivitySettingAction")&&(A.notificationActivitySettingAction=p.proto.SyncActionValue.NotificationActivitySettingAction.toObject(e.notificationActivitySettingAction,a),a.oneofs&&(A._notificationActivitySettingAction="notificationActivitySettingAction")),e.lidContactAction!=null&&e.hasOwnProperty("lidContactAction")&&(A.lidContactAction=p.proto.SyncActionValue.LidContactAction.toObject(e.lidContactAction,a),a.oneofs&&(A._lidContactAction="lidContactAction")),e.ctwaPerCustomerDataSharingAction!=null&&e.hasOwnProperty("ctwaPerCustomerDataSharingAction")&&(A.ctwaPerCustomerDataSharingAction=p.proto.SyncActionValue.CtwaPerCustomerDataSharingAction.toObject(e.ctwaPerCustomerDataSharingAction,a),a.oneofs&&(A._ctwaPerCustomerDataSharingAction="ctwaPerCustomerDataSharingAction")),e.paymentTosAction!=null&&e.hasOwnProperty("paymentTosAction")&&(A.paymentTosAction=p.proto.SyncActionValue.PaymentTosAction.toObject(e.paymentTosAction,a),a.oneofs&&(A._paymentTosAction="paymentTosAction")),e.privacySettingChannelsPersonalisedRecommendationAction!=null&&e.hasOwnProperty("privacySettingChannelsPersonalisedRecommendationAction")&&(A.privacySettingChannelsPersonalisedRecommendationAction=p.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction.toObject(e.privacySettingChannelsPersonalisedRecommendationAction,a),a.oneofs&&(A._privacySettingChannelsPersonalisedRecommendationAction="privacySettingChannelsPersonalisedRecommendationAction")),e.businessBroadcastAssociationAction!=null&&e.hasOwnProperty("businessBroadcastAssociationAction")&&(A.businessBroadcastAssociationAction=p.proto.SyncActionValue.BusinessBroadcastAssociationAction.toObject(e.businessBroadcastAssociationAction,a),a.oneofs&&(A._businessBroadcastAssociationAction="businessBroadcastAssociationAction")),e.detectedOutcomesStatusAction!=null&&e.hasOwnProperty("detectedOutcomesStatusAction")&&(A.detectedOutcomesStatusAction=p.proto.SyncActionValue.DetectedOutcomesStatusAction.toObject(e.detectedOutcomesStatusAction,a),a.oneofs&&(A._detectedOutcomesStatusAction="detectedOutcomesStatusAction")),e.maibaAiFeaturesControlAction!=null&&e.hasOwnProperty("maibaAiFeaturesControlAction")&&(A.maibaAiFeaturesControlAction=p.proto.SyncActionValue.MaibaAIFeaturesControlAction.toObject(e.maibaAiFeaturesControlAction,a),a.oneofs&&(A._maibaAiFeaturesControlAction="maibaAiFeaturesControlAction")),e.businessBroadcastListAction!=null&&e.hasOwnProperty("businessBroadcastListAction")&&(A.businessBroadcastListAction=p.proto.SyncActionValue.BusinessBroadcastListAction.toObject(e.businessBroadcastListAction,a),a.oneofs&&(A._businessBroadcastListAction="businessBroadcastListAction")),e.musicUserIdAction!=null&&e.hasOwnProperty("musicUserIdAction")&&(A.musicUserIdAction=p.proto.SyncActionValue.MusicUserIdAction.toObject(e.musicUserIdAction,a),a.oneofs&&(A._musicUserIdAction="musicUserIdAction")),e.statusPostOptInNotificationPreferencesAction!=null&&e.hasOwnProperty("statusPostOptInNotificationPreferencesAction")&&(A.statusPostOptInNotificationPreferencesAction=p.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction.toObject(e.statusPostOptInNotificationPreferencesAction,a),a.oneofs&&(A._statusPostOptInNotificationPreferencesAction="statusPostOptInNotificationPreferencesAction")),e.avatarUpdatedAction!=null&&e.hasOwnProperty("avatarUpdatedAction")&&(A.avatarUpdatedAction=p.proto.SyncActionValue.AvatarUpdatedAction.toObject(e.avatarUpdatedAction,a),a.oneofs&&(A._avatarUpdatedAction="avatarUpdatedAction")),e.privateProcessingSettingAction!=null&&e.hasOwnProperty("privateProcessingSettingAction")&&(A.privateProcessingSettingAction=p.proto.SyncActionValue.PrivateProcessingSettingAction.toObject(e.privateProcessingSettingAction,a),a.oneofs&&(A._privateProcessingSettingAction="privateProcessingSettingAction")),e.newsletterSavedInterestsAction!=null&&e.hasOwnProperty("newsletterSavedInterestsAction")&&(A.newsletterSavedInterestsAction=p.proto.SyncActionValue.NewsletterSavedInterestsAction.toObject(e.newsletterSavedInterestsAction,a),a.oneofs&&(A._newsletterSavedInterestsAction="newsletterSavedInterestsAction")),e.aiThreadRenameAction!=null&&e.hasOwnProperty("aiThreadRenameAction")&&(A.aiThreadRenameAction=p.proto.SyncActionValue.AiThreadRenameAction.toObject(e.aiThreadRenameAction,a),a.oneofs&&(A._aiThreadRenameAction="aiThreadRenameAction")),e.interactiveMessageAction!=null&&e.hasOwnProperty("interactiveMessageAction")&&(A.interactiveMessageAction=p.proto.SyncActionValue.InteractiveMessageAction.toObject(e.interactiveMessageAction,a),a.oneofs&&(A._interactiveMessageAction="interactiveMessageAction")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncActionValue"},t.AgentAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}case 2:{c.deviceID=A.int32();break}case 3:{c.isDeleted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.AgentAction)return A;var r=new p.proto.SyncActionValue.AgentAction;return A.name!=null&&(r.name=String(A.name)),A.deviceID!=null&&(r.deviceID=A.deviceID|0),A.isDeleted!=null&&(r.isDeleted=!!A.isDeleted),r},i.toObject=function(A,r){r||(r={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.deviceID!=null&&A.hasOwnProperty("deviceID")&&(s.deviceID=A.deviceID,r.oneofs&&(s._deviceID="deviceID")),A.isDeleted!=null&&A.hasOwnProperty("isDeleted")&&(s.isDeleted=A.isDeleted,r.oneofs&&(s._isDeleted="isDeleted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.AgentAction"},i})(),t.AiThreadRenameAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.newTitle=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.AiThreadRenameAction)return A;var r=new p.proto.SyncActionValue.AiThreadRenameAction;return A.newTitle!=null&&(r.newTitle=String(A.newTitle)),r},i.toObject=function(A,r){r||(r={});var s={};return A.newTitle!=null&&A.hasOwnProperty("newTitle")&&(s.newTitle=A.newTitle,r.oneofs&&(s._newTitle="newTitle")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.AiThreadRenameAction"},i})(),t.AndroidUnsupportedActions=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.allowed=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.AndroidUnsupportedActions)return A;var r=new p.proto.SyncActionValue.AndroidUnsupportedActions;return A.allowed!=null&&(r.allowed=!!A.allowed),r},i.toObject=function(A,r){r||(r={});var s={};return A.allowed!=null&&A.hasOwnProperty("allowed")&&(s.allowed=A.allowed,r.oneofs&&(s._allowed="allowed")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.AndroidUnsupportedActions"},i})(),t.ArchiveChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.archived=A.bool();break}case 2:{c.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ArchiveChatAction)return A;var r=new p.proto.SyncActionValue.ArchiveChatAction;if(A.archived!=null&&(r.archived=!!A.archived),A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.ArchiveChatAction.messageRange: object expected");r.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.archived!=null&&A.hasOwnProperty("archived")&&(s.archived=A.archived,r.oneofs&&(s._archived="archived")),A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,r),r.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ArchiveChatAction"},i})(),t.AvatarUpdatedAction=(function(){function i(a){if(this.recentAvatarStickers=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.eventType=A.int32();break}case 2:{c.recentAvatarStickers&&c.recentAvatarStickers.length||(c.recentAvatarStickers=[]),c.recentAvatarStickers.push(p.proto.SyncActionValue.StickerAction.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.AvatarUpdatedAction)return A;var r=new p.proto.SyncActionValue.AvatarUpdatedAction;switch(A.eventType){default:if(typeof A.eventType=="number"){r.eventType=A.eventType;break}break;case"UPDATED":case 0:r.eventType=0;break;case"CREATED":case 1:r.eventType=1;break;case"DELETED":case 2:r.eventType=2;break}if(A.recentAvatarStickers){if(!Array.isArray(A.recentAvatarStickers))throw TypeError(".proto.SyncActionValue.AvatarUpdatedAction.recentAvatarStickers: array expected");r.recentAvatarStickers=[];for(var s=0;s>>3){case 1:{c.isSent=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.BotWelcomeRequestAction)return A;var r=new p.proto.SyncActionValue.BotWelcomeRequestAction;return A.isSent!=null&&(r.isSent=!!A.isSent),r},i.toObject=function(A,r){r||(r={});var s={};return A.isSent!=null&&A.hasOwnProperty("isSent")&&(s.isSent=A.isSent,r.oneofs&&(s._isSent="isSent")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.BotWelcomeRequestAction"},i})(),t.BroadcastListParticipant=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.lidJid=A.string();break}case 2:{c.pnJid=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.BroadcastListParticipant)return A;var r=new p.proto.SyncActionValue.BroadcastListParticipant;return A.lidJid!=null&&(r.lidJid=String(A.lidJid)),A.pnJid!=null&&(r.pnJid=String(A.pnJid)),r},i.toObject=function(A,r){r||(r={});var s={};return r.defaults&&(s.lidJid=""),A.lidJid!=null&&A.hasOwnProperty("lidJid")&&(s.lidJid=A.lidJid),A.pnJid!=null&&A.hasOwnProperty("pnJid")&&(s.pnJid=A.pnJid,r.oneofs&&(s._pnJid="pnJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.BroadcastListParticipant"},i})(),t.BusinessBroadcastAssociationAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.deleted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.BusinessBroadcastAssociationAction)return A;var r=new p.proto.SyncActionValue.BusinessBroadcastAssociationAction;return A.deleted!=null&&(r.deleted=!!A.deleted),r},i.toObject=function(A,r){r||(r={});var s={};return A.deleted!=null&&A.hasOwnProperty("deleted")&&(s.deleted=A.deleted,r.oneofs&&(s._deleted="deleted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.BusinessBroadcastAssociationAction"},i})(),t.BusinessBroadcastListAction=(function(){function i(a){if(this.participants=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.deleted=A.bool();break}case 2:{c.participants&&c.participants.length||(c.participants=[]),c.participants.push(p.proto.SyncActionValue.BroadcastListParticipant.decode(A,A.uint32()));break}case 3:{c.listName=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.BusinessBroadcastListAction)return A;var r=new p.proto.SyncActionValue.BusinessBroadcastListAction;if(A.deleted!=null&&(r.deleted=!!A.deleted),A.participants){if(!Array.isArray(A.participants))throw TypeError(".proto.SyncActionValue.BusinessBroadcastListAction.participants: array expected");r.participants=[];for(var s=0;s>>3){case 1:{c.callLogRecord=p.proto.CallLogRecord.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.CallLogAction)return A;var r=new p.proto.SyncActionValue.CallLogAction;if(A.callLogRecord!=null){if(typeof A.callLogRecord!="object")throw TypeError(".proto.SyncActionValue.CallLogAction.callLogRecord: object expected");r.callLogRecord=p.proto.CallLogRecord.fromObject(A.callLogRecord)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.callLogRecord!=null&&A.hasOwnProperty("callLogRecord")&&(s.callLogRecord=p.proto.CallLogRecord.toObject(A.callLogRecord,r),r.oneofs&&(s._callLogRecord="callLogRecord")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.CallLogAction"},i})(),t.ChatAssignmentAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.deviceAgentID=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ChatAssignmentAction)return A;var r=new p.proto.SyncActionValue.ChatAssignmentAction;return A.deviceAgentID!=null&&(r.deviceAgentID=String(A.deviceAgentID)),r},i.toObject=function(A,r){r||(r={});var s={};return A.deviceAgentID!=null&&A.hasOwnProperty("deviceAgentID")&&(s.deviceAgentID=A.deviceAgentID,r.oneofs&&(s._deviceAgentID="deviceAgentID")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ChatAssignmentAction"},i})(),t.ChatAssignmentOpenedStatusAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.chatOpened=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ChatAssignmentOpenedStatusAction)return A;var r=new p.proto.SyncActionValue.ChatAssignmentOpenedStatusAction;return A.chatOpened!=null&&(r.chatOpened=!!A.chatOpened),r},i.toObject=function(A,r){r||(r={});var s={};return A.chatOpened!=null&&A.hasOwnProperty("chatOpened")&&(s.chatOpened=A.chatOpened,r.oneofs&&(s._chatOpened="chatOpened")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ChatAssignmentOpenedStatusAction"},i})(),t.ClearChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ClearChatAction)return A;var r=new p.proto.SyncActionValue.ClearChatAction;if(A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.ClearChatAction.messageRange: object expected");r.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,r),r.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ClearChatAction"},i})(),t.ContactAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.fullName=A.string();break}case 2:{c.firstName=A.string();break}case 3:{c.lidJid=A.string();break}case 4:{c.saveOnPrimaryAddressbook=A.bool();break}case 5:{c.pnJid=A.string();break}case 6:{c.username=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ContactAction)return A;var r=new p.proto.SyncActionValue.ContactAction;return A.fullName!=null&&(r.fullName=String(A.fullName)),A.firstName!=null&&(r.firstName=String(A.firstName)),A.lidJid!=null&&(r.lidJid=String(A.lidJid)),A.saveOnPrimaryAddressbook!=null&&(r.saveOnPrimaryAddressbook=!!A.saveOnPrimaryAddressbook),A.pnJid!=null&&(r.pnJid=String(A.pnJid)),A.username!=null&&(r.username=String(A.username)),r},i.toObject=function(A,r){r||(r={});var s={};return A.fullName!=null&&A.hasOwnProperty("fullName")&&(s.fullName=A.fullName,r.oneofs&&(s._fullName="fullName")),A.firstName!=null&&A.hasOwnProperty("firstName")&&(s.firstName=A.firstName,r.oneofs&&(s._firstName="firstName")),A.lidJid!=null&&A.hasOwnProperty("lidJid")&&(s.lidJid=A.lidJid,r.oneofs&&(s._lidJid="lidJid")),A.saveOnPrimaryAddressbook!=null&&A.hasOwnProperty("saveOnPrimaryAddressbook")&&(s.saveOnPrimaryAddressbook=A.saveOnPrimaryAddressbook,r.oneofs&&(s._saveOnPrimaryAddressbook="saveOnPrimaryAddressbook")),A.pnJid!=null&&A.hasOwnProperty("pnJid")&&(s.pnJid=A.pnJid,r.oneofs&&(s._pnJid="pnJid")),A.username!=null&&A.hasOwnProperty("username")&&(s.username=A.username,r.oneofs&&(s._username="username")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ContactAction"},i})(),t.CtwaPerCustomerDataSharingAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isCtwaPerCustomerDataSharingEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.CtwaPerCustomerDataSharingAction)return A;var r=new p.proto.SyncActionValue.CtwaPerCustomerDataSharingAction;return A.isCtwaPerCustomerDataSharingEnabled!=null&&(r.isCtwaPerCustomerDataSharingEnabled=!!A.isCtwaPerCustomerDataSharingEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.isCtwaPerCustomerDataSharingEnabled!=null&&A.hasOwnProperty("isCtwaPerCustomerDataSharingEnabled")&&(s.isCtwaPerCustomerDataSharingEnabled=A.isCtwaPerCustomerDataSharingEnabled,r.oneofs&&(s._isCtwaPerCustomerDataSharingEnabled="isCtwaPerCustomerDataSharingEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.CtwaPerCustomerDataSharingAction"},i})(),t.CustomPaymentMethod=(function(){function i(e){if(this.metadata=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.credentialId=a.string();break}case 2:{g.country=a.string();break}case 3:{g.type=a.string();break}case 4:{g.metadata&&g.metadata.length||(g.metadata=[]),g.metadata.push(p.proto.SyncActionValue.CustomPaymentMethodMetadata.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.CustomPaymentMethod)return a;var A=new p.proto.SyncActionValue.CustomPaymentMethod;if(a.credentialId!=null&&(A.credentialId=String(a.credentialId)),a.country!=null&&(A.country=String(a.country)),a.type!=null&&(A.type=String(a.type)),a.metadata){if(!Array.isArray(a.metadata))throw TypeError(".proto.SyncActionValue.CustomPaymentMethod.metadata: array expected");A.metadata=[];for(var r=0;r>>3){case 1:{g.key=a.string();break}case 2:{g.value=a.string();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.CustomPaymentMethodMetadata)return a;var A=new p.proto.SyncActionValue.CustomPaymentMethodMetadata;return a.key!=null&&(A.key=String(a.key)),a.value!=null&&(A.value=String(a.value)),A},i.toObject=function(a,A){A||(A={});var r={};return A.defaults&&(r.key="",r.value=""),a.key!=null&&a.hasOwnProperty("key")&&(r.key=a.key),a.value!=null&&a.hasOwnProperty("value")&&(r.value=a.value),r},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.SyncActionValue.CustomPaymentMethodMetadata"},i})(),t.CustomPaymentMethodsAction=(function(){function i(e){if(this.customPaymentMethods=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.customPaymentMethods&&g.customPaymentMethods.length||(g.customPaymentMethods=[]),g.customPaymentMethods.push(p.proto.SyncActionValue.CustomPaymentMethod.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.CustomPaymentMethodsAction)return a;var A=new p.proto.SyncActionValue.CustomPaymentMethodsAction;if(a.customPaymentMethods){if(!Array.isArray(a.customPaymentMethods))throw TypeError(".proto.SyncActionValue.CustomPaymentMethodsAction.customPaymentMethods: array expected");A.customPaymentMethods=[];for(var r=0;r>>3){case 1:{c.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.DeleteChatAction)return A;var r=new p.proto.SyncActionValue.DeleteChatAction;if(A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.DeleteChatAction.messageRange: object expected");r.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,r),r.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DeleteChatAction"},i})(),t.DeleteIndividualCallLogAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.peerJid=A.string();break}case 2:{c.isIncoming=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.DeleteIndividualCallLogAction)return A;var r=new p.proto.SyncActionValue.DeleteIndividualCallLogAction;return A.peerJid!=null&&(r.peerJid=String(A.peerJid)),A.isIncoming!=null&&(r.isIncoming=!!A.isIncoming),r},i.toObject=function(A,r){r||(r={});var s={};return A.peerJid!=null&&A.hasOwnProperty("peerJid")&&(s.peerJid=A.peerJid,r.oneofs&&(s._peerJid="peerJid")),A.isIncoming!=null&&A.hasOwnProperty("isIncoming")&&(s.isIncoming=A.isIncoming,r.oneofs&&(s._isIncoming="isIncoming")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DeleteIndividualCallLogAction"},i})(),t.DeleteMessageForMeAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.deleteMedia=A.bool();break}case 2:{c.messageTimestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.DeleteMessageForMeAction)return A;var r=new p.proto.SyncActionValue.DeleteMessageForMeAction;return A.deleteMedia!=null&&(r.deleteMedia=!!A.deleteMedia),A.messageTimestamp!=null&&(l.Long?(r.messageTimestamp=l.Long.fromValue(A.messageTimestamp)).unsigned=!1:typeof A.messageTimestamp=="string"?r.messageTimestamp=parseInt(A.messageTimestamp,10):typeof A.messageTimestamp=="number"?r.messageTimestamp=A.messageTimestamp:typeof A.messageTimestamp=="object"&&(r.messageTimestamp=new l.LongBits(A.messageTimestamp.low>>>0,A.messageTimestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.deleteMedia!=null&&A.hasOwnProperty("deleteMedia")&&(s.deleteMedia=A.deleteMedia,r.oneofs&&(s._deleteMedia="deleteMedia")),A.messageTimestamp!=null&&A.hasOwnProperty("messageTimestamp")&&(typeof A.messageTimestamp=="number"?s.messageTimestamp=r.longs===String?String(A.messageTimestamp):A.messageTimestamp:s.messageTimestamp=r.longs===String?se(A.messageTimestamp):r.longs===Number?ge(A.messageTimestamp):A.messageTimestamp,r.oneofs&&(s._messageTimestamp="messageTimestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DeleteMessageForMeAction"},i})(),t.DetectedOutcomesStatusAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.DetectedOutcomesStatusAction)return A;var r=new p.proto.SyncActionValue.DetectedOutcomesStatusAction;return A.isEnabled!=null&&(r.isEnabled=!!A.isEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.isEnabled!=null&&A.hasOwnProperty("isEnabled")&&(s.isEnabled=A.isEnabled,r.oneofs&&(s._isEnabled="isEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.DetectedOutcomesStatusAction"},i})(),t.ExternalWebBetaAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isOptIn=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.ExternalWebBetaAction)return A;var r=new p.proto.SyncActionValue.ExternalWebBetaAction;return A.isOptIn!=null&&(r.isOptIn=!!A.isOptIn),r},i.toObject=function(A,r){r||(r={});var s={};return A.isOptIn!=null&&A.hasOwnProperty("isOptIn")&&(s.isOptIn=A.isOptIn,r.oneofs&&(s._isOptIn="isOptIn")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.ExternalWebBetaAction"},i})(),t.FavoritesAction=(function(){function i(e){if(this.favorites=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.favorites&&g.favorites.length||(g.favorites=[]),g.favorites.push(p.proto.SyncActionValue.FavoritesAction.Favorite.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.FavoritesAction)return a;var A=new p.proto.SyncActionValue.FavoritesAction;if(a.favorites){if(!Array.isArray(a.favorites))throw TypeError(".proto.SyncActionValue.FavoritesAction.favorites: array expected");A.favorites=[];for(var r=0;r>>3){case 1:{I.id=r.string();break}default:r.skipType(d&7);break}}return I},e.fromObject=function(r){if(r instanceof p.proto.SyncActionValue.FavoritesAction.Favorite)return r;var s=new p.proto.SyncActionValue.FavoritesAction.Favorite;return r.id!=null&&(s.id=String(r.id)),s},e.toObject=function(r,s){s||(s={});var g={};return r.id!=null&&r.hasOwnProperty("id")&&(g.id=r.id,s.oneofs&&(g._id="id")),g},e.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},e.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/proto.SyncActionValue.FavoritesAction.Favorite"},e})(),i})(),t.InteractiveMessageAction=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.type=a.int32();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.InteractiveMessageAction)return a;var A=new p.proto.SyncActionValue.InteractiveMessageAction;switch(a.type){default:if(typeof a.type=="number"){A.type=a.type;break}break;case"DISABLE_CTA":case 1:A.type=1;break}return A},i.toObject=function(a,A){A||(A={});var r={};return A.defaults&&(r.type=A.enums===String?"DISABLE_CTA":1),a.type!=null&&a.hasOwnProperty("type")&&(r.type=A.enums===String?p.proto.SyncActionValue.InteractiveMessageAction.InteractiveMessageActionMode[a.type]===void 0?a.type:p.proto.SyncActionValue.InteractiveMessageAction.InteractiveMessageActionMode[a.type]:a.type),r},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.SyncActionValue.InteractiveMessageAction"},i.InteractiveMessageActionMode=(function(){let e={},a=Object.create(e);return a[e[1]="DISABLE_CTA"]=1,a})(),i})(),t.KeyExpiration=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.expiredKeyEpoch=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.KeyExpiration)return A;var r=new p.proto.SyncActionValue.KeyExpiration;return A.expiredKeyEpoch!=null&&(r.expiredKeyEpoch=A.expiredKeyEpoch|0),r},i.toObject=function(A,r){r||(r={});var s={};return A.expiredKeyEpoch!=null&&A.hasOwnProperty("expiredKeyEpoch")&&(s.expiredKeyEpoch=A.expiredKeyEpoch,r.oneofs&&(s._expiredKeyEpoch="expiredKeyEpoch")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.KeyExpiration"},i})(),t.LabelAssociationAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.labeled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.LabelAssociationAction)return A;var r=new p.proto.SyncActionValue.LabelAssociationAction;return A.labeled!=null&&(r.labeled=!!A.labeled),r},i.toObject=function(A,r){r||(r={});var s={};return A.labeled!=null&&A.hasOwnProperty("labeled")&&(s.labeled=A.labeled,r.oneofs&&(s._labeled="labeled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LabelAssociationAction"},i})(),t.LabelEditAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}case 2:{c.color=A.int32();break}case 3:{c.predefinedId=A.int32();break}case 4:{c.deleted=A.bool();break}case 5:{c.orderIndex=A.int32();break}case 6:{c.isActive=A.bool();break}case 7:{c.type=A.int32();break}case 8:{c.isImmutable=A.bool();break}case 9:{c.muteEndTimeMs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.LabelEditAction)return A;var r=new p.proto.SyncActionValue.LabelEditAction;switch(A.name!=null&&(r.name=String(A.name)),A.color!=null&&(r.color=A.color|0),A.predefinedId!=null&&(r.predefinedId=A.predefinedId|0),A.deleted!=null&&(r.deleted=!!A.deleted),A.orderIndex!=null&&(r.orderIndex=A.orderIndex|0),A.isActive!=null&&(r.isActive=!!A.isActive),A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"NONE":case 0:r.type=0;break;case"UNREAD":case 1:r.type=1;break;case"GROUPS":case 2:r.type=2;break;case"FAVORITES":case 3:r.type=3;break;case"PREDEFINED":case 4:r.type=4;break;case"CUSTOM":case 5:r.type=5;break;case"COMMUNITY":case 6:r.type=6;break;case"SERVER_ASSIGNED":case 7:r.type=7;break;case"DRAFTED":case 8:r.type=8;break;case"AI_HANDOFF":case 9:r.type=9;break}return A.isImmutable!=null&&(r.isImmutable=!!A.isImmutable),A.muteEndTimeMs!=null&&(l.Long?(r.muteEndTimeMs=l.Long.fromValue(A.muteEndTimeMs)).unsigned=!1:typeof A.muteEndTimeMs=="string"?r.muteEndTimeMs=parseInt(A.muteEndTimeMs,10):typeof A.muteEndTimeMs=="number"?r.muteEndTimeMs=A.muteEndTimeMs:typeof A.muteEndTimeMs=="object"&&(r.muteEndTimeMs=new l.LongBits(A.muteEndTimeMs.low>>>0,A.muteEndTimeMs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.color!=null&&A.hasOwnProperty("color")&&(s.color=A.color,r.oneofs&&(s._color="color")),A.predefinedId!=null&&A.hasOwnProperty("predefinedId")&&(s.predefinedId=A.predefinedId,r.oneofs&&(s._predefinedId="predefinedId")),A.deleted!=null&&A.hasOwnProperty("deleted")&&(s.deleted=A.deleted,r.oneofs&&(s._deleted="deleted")),A.orderIndex!=null&&A.hasOwnProperty("orderIndex")&&(s.orderIndex=A.orderIndex,r.oneofs&&(s._orderIndex="orderIndex")),A.isActive!=null&&A.hasOwnProperty("isActive")&&(s.isActive=A.isActive,r.oneofs&&(s._isActive="isActive")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.SyncActionValue.LabelEditAction.ListType[A.type]===void 0?A.type:p.proto.SyncActionValue.LabelEditAction.ListType[A.type]:A.type,r.oneofs&&(s._type="type")),A.isImmutable!=null&&A.hasOwnProperty("isImmutable")&&(s.isImmutable=A.isImmutable,r.oneofs&&(s._isImmutable="isImmutable")),A.muteEndTimeMs!=null&&A.hasOwnProperty("muteEndTimeMs")&&(typeof A.muteEndTimeMs=="number"?s.muteEndTimeMs=r.longs===String?String(A.muteEndTimeMs):A.muteEndTimeMs:s.muteEndTimeMs=r.longs===String?se(A.muteEndTimeMs):r.longs===Number?ge(A.muteEndTimeMs):A.muteEndTimeMs,r.oneofs&&(s._muteEndTimeMs="muteEndTimeMs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LabelEditAction"},i.ListType=(function(){let a={},A=Object.create(a);return A[a[0]="NONE"]=0,A[a[1]="UNREAD"]=1,A[a[2]="GROUPS"]=2,A[a[3]="FAVORITES"]=3,A[a[4]="PREDEFINED"]=4,A[a[5]="CUSTOM"]=5,A[a[6]="COMMUNITY"]=6,A[a[7]="SERVER_ASSIGNED"]=7,A[a[8]="DRAFTED"]=8,A[a[9]="AI_HANDOFF"]=9,A})(),i})(),t.LabelReorderingAction=(function(){function i(e){if(this.sortedLabelIds=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{if(g.sortedLabelIds&&g.sortedLabelIds.length||(g.sortedLabelIds=[]),(c&7)===2)for(var I=a.uint32()+a.pos;a.pos>>3){case 1:{c.fullName=A.string();break}case 2:{c.firstName=A.string();break}case 3:{c.username=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.LidContactAction)return A;var r=new p.proto.SyncActionValue.LidContactAction;return A.fullName!=null&&(r.fullName=String(A.fullName)),A.firstName!=null&&(r.firstName=String(A.firstName)),A.username!=null&&(r.username=String(A.username)),r},i.toObject=function(A,r){r||(r={});var s={};return A.fullName!=null&&A.hasOwnProperty("fullName")&&(s.fullName=A.fullName,r.oneofs&&(s._fullName="fullName")),A.firstName!=null&&A.hasOwnProperty("firstName")&&(s.firstName=A.firstName,r.oneofs&&(s._firstName="firstName")),A.username!=null&&A.hasOwnProperty("username")&&(s.username=A.username,r.oneofs&&(s._username="username")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LidContactAction"},i})(),t.LocaleSetting=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.locale=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.LocaleSetting)return A;var r=new p.proto.SyncActionValue.LocaleSetting;return A.locale!=null&&(r.locale=String(A.locale)),r},i.toObject=function(A,r){r||(r={});var s={};return A.locale!=null&&A.hasOwnProperty("locale")&&(s.locale=A.locale,r.oneofs&&(s._locale="locale")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LocaleSetting"},i})(),t.LockChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.locked=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.LockChatAction)return A;var r=new p.proto.SyncActionValue.LockChatAction;return A.locked!=null&&(r.locked=!!A.locked),r},i.toObject=function(A,r){r||(r={});var s={};return A.locked!=null&&A.hasOwnProperty("locked")&&(s.locked=A.locked,r.oneofs&&(s._locked="locked")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.LockChatAction"},i})(),t.MaibaAIFeaturesControlAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.aiFeatureStatus=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MaibaAIFeaturesControlAction)return A;var r=new p.proto.SyncActionValue.MaibaAIFeaturesControlAction;switch(A.aiFeatureStatus){default:if(typeof A.aiFeatureStatus=="number"){r.aiFeatureStatus=A.aiFeatureStatus;break}break;case"ENABLED":case 0:r.aiFeatureStatus=0;break;case"ENABLED_HAS_LEARNING":case 1:r.aiFeatureStatus=1;break;case"DISABLED":case 2:r.aiFeatureStatus=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.aiFeatureStatus!=null&&A.hasOwnProperty("aiFeatureStatus")&&(s.aiFeatureStatus=r.enums===String?p.proto.SyncActionValue.MaibaAIFeaturesControlAction.MaibaAIFeatureStatus[A.aiFeatureStatus]===void 0?A.aiFeatureStatus:p.proto.SyncActionValue.MaibaAIFeaturesControlAction.MaibaAIFeatureStatus[A.aiFeatureStatus]:A.aiFeatureStatus,r.oneofs&&(s._aiFeatureStatus="aiFeatureStatus")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MaibaAIFeaturesControlAction"},i.MaibaAIFeatureStatus=(function(){let a={},A=Object.create(a);return A[a[0]="ENABLED"]=0,A[a[1]="ENABLED_HAS_LEARNING"]=1,A[a[2]="DISABLED"]=2,A})(),i})(),t.MarkChatAsReadAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.read=A.bool();break}case 2:{c.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MarkChatAsReadAction)return A;var r=new p.proto.SyncActionValue.MarkChatAsReadAction;if(A.read!=null&&(r.read=!!A.read),A.messageRange!=null){if(typeof A.messageRange!="object")throw TypeError(".proto.SyncActionValue.MarkChatAsReadAction.messageRange: object expected");r.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.fromObject(A.messageRange)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.read!=null&&A.hasOwnProperty("read")&&(s.read=A.read,r.oneofs&&(s._read="read")),A.messageRange!=null&&A.hasOwnProperty("messageRange")&&(s.messageRange=p.proto.SyncActionValue.SyncActionMessageRange.toObject(A.messageRange,r),r.oneofs&&(s._messageRange="messageRange")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MarkChatAsReadAction"},i})(),t.MarketingMessageAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}case 2:{c.message=A.string();break}case 3:{c.type=A.int32();break}case 4:{c.createdAt=A.int64();break}case 5:{c.lastSentAt=A.int64();break}case 6:{c.isDeleted=A.bool();break}case 7:{c.mediaId=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MarketingMessageAction)return A;var r=new p.proto.SyncActionValue.MarketingMessageAction;switch(A.name!=null&&(r.name=String(A.name)),A.message!=null&&(r.message=String(A.message)),A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"PERSONALIZED":case 0:r.type=0;break}return A.createdAt!=null&&(l.Long?(r.createdAt=l.Long.fromValue(A.createdAt)).unsigned=!1:typeof A.createdAt=="string"?r.createdAt=parseInt(A.createdAt,10):typeof A.createdAt=="number"?r.createdAt=A.createdAt:typeof A.createdAt=="object"&&(r.createdAt=new l.LongBits(A.createdAt.low>>>0,A.createdAt.high>>>0).toNumber())),A.lastSentAt!=null&&(l.Long?(r.lastSentAt=l.Long.fromValue(A.lastSentAt)).unsigned=!1:typeof A.lastSentAt=="string"?r.lastSentAt=parseInt(A.lastSentAt,10):typeof A.lastSentAt=="number"?r.lastSentAt=A.lastSentAt:typeof A.lastSentAt=="object"&&(r.lastSentAt=new l.LongBits(A.lastSentAt.low>>>0,A.lastSentAt.high>>>0).toNumber())),A.isDeleted!=null&&(r.isDeleted=!!A.isDeleted),A.mediaId!=null&&(r.mediaId=String(A.mediaId)),r},i.toObject=function(A,r){r||(r={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),A.message!=null&&A.hasOwnProperty("message")&&(s.message=A.message,r.oneofs&&(s._message="message")),A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.SyncActionValue.MarketingMessageAction.MarketingMessagePrototypeType[A.type]===void 0?A.type:p.proto.SyncActionValue.MarketingMessageAction.MarketingMessagePrototypeType[A.type]:A.type,r.oneofs&&(s._type="type")),A.createdAt!=null&&A.hasOwnProperty("createdAt")&&(typeof A.createdAt=="number"?s.createdAt=r.longs===String?String(A.createdAt):A.createdAt:s.createdAt=r.longs===String?se(A.createdAt):r.longs===Number?ge(A.createdAt):A.createdAt,r.oneofs&&(s._createdAt="createdAt")),A.lastSentAt!=null&&A.hasOwnProperty("lastSentAt")&&(typeof A.lastSentAt=="number"?s.lastSentAt=r.longs===String?String(A.lastSentAt):A.lastSentAt:s.lastSentAt=r.longs===String?se(A.lastSentAt):r.longs===Number?ge(A.lastSentAt):A.lastSentAt,r.oneofs&&(s._lastSentAt="lastSentAt")),A.isDeleted!=null&&A.hasOwnProperty("isDeleted")&&(s.isDeleted=A.isDeleted,r.oneofs&&(s._isDeleted="isDeleted")),A.mediaId!=null&&A.hasOwnProperty("mediaId")&&(s.mediaId=A.mediaId,r.oneofs&&(s._mediaId="mediaId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MarketingMessageAction"},i.MarketingMessagePrototypeType=(function(){let a={},A=Object.create(a);return A[a[0]="PERSONALIZED"]=0,A})(),i})(),t.MarketingMessageBroadcastAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.repliedCount=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MarketingMessageBroadcastAction)return A;var r=new p.proto.SyncActionValue.MarketingMessageBroadcastAction;return A.repliedCount!=null&&(r.repliedCount=A.repliedCount|0),r},i.toObject=function(A,r){r||(r={});var s={};return A.repliedCount!=null&&A.hasOwnProperty("repliedCount")&&(s.repliedCount=A.repliedCount,r.oneofs&&(s._repliedCount="repliedCount")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MarketingMessageBroadcastAction"},i})(),t.MerchantPaymentPartnerAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.status=A.int32();break}case 2:{c.country=A.string();break}case 3:{c.gatewayName=A.string();break}case 4:{c.credentialId=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MerchantPaymentPartnerAction)return A;var r=new p.proto.SyncActionValue.MerchantPaymentPartnerAction;switch(A.status){default:if(typeof A.status=="number"){r.status=A.status;break}break;case"ACTIVE":case 0:r.status=0;break;case"INACTIVE":case 1:r.status=1;break}return A.country!=null&&(r.country=String(A.country)),A.gatewayName!=null&&(r.gatewayName=String(A.gatewayName)),A.credentialId!=null&&(r.credentialId=String(A.credentialId)),r},i.toObject=function(A,r){r||(r={});var s={};return r.defaults&&(s.status=r.enums===String?"ACTIVE":0,s.country=""),A.status!=null&&A.hasOwnProperty("status")&&(s.status=r.enums===String?p.proto.SyncActionValue.MerchantPaymentPartnerAction.Status[A.status]===void 0?A.status:p.proto.SyncActionValue.MerchantPaymentPartnerAction.Status[A.status]:A.status),A.country!=null&&A.hasOwnProperty("country")&&(s.country=A.country),A.gatewayName!=null&&A.hasOwnProperty("gatewayName")&&(s.gatewayName=A.gatewayName,r.oneofs&&(s._gatewayName="gatewayName")),A.credentialId!=null&&A.hasOwnProperty("credentialId")&&(s.credentialId=A.credentialId,r.oneofs&&(s._credentialId="credentialId")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MerchantPaymentPartnerAction"},i.Status=(function(){let a={},A=Object.create(a);return A[a[0]="ACTIVE"]=0,A[a[1]="INACTIVE"]=1,A})(),i})(),t.MusicUserIdAction=(function(){function i(a){if(this.musicUserIdMap={},a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.musicUserId=A.string();break}case 2:{c.musicUserIdMap===l.emptyObject&&(c.musicUserIdMap={});var f=A.uint32()+A.pos;for(I="",d="";A.pos>>3){case 1:I=A.string();break;case 2:d=A.string();break;default:A.skipType(Q&7);break}}c.musicUserIdMap[I]=d;break}default:A.skipType(B&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MusicUserIdAction)return A;var r=new p.proto.SyncActionValue.MusicUserIdAction;if(A.musicUserId!=null&&(r.musicUserId=String(A.musicUserId)),A.musicUserIdMap){if(typeof A.musicUserIdMap!="object")throw TypeError(".proto.SyncActionValue.MusicUserIdAction.musicUserIdMap: object expected");r.musicUserIdMap={};for(var s=Object.keys(A.musicUserIdMap),g=0;g>>3){case 1:{c.muted=A.bool();break}case 2:{c.muteEndTimestamp=A.int64();break}case 3:{c.autoMuted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.MuteAction)return A;var r=new p.proto.SyncActionValue.MuteAction;return A.muted!=null&&(r.muted=!!A.muted),A.muteEndTimestamp!=null&&(l.Long?(r.muteEndTimestamp=l.Long.fromValue(A.muteEndTimestamp)).unsigned=!1:typeof A.muteEndTimestamp=="string"?r.muteEndTimestamp=parseInt(A.muteEndTimestamp,10):typeof A.muteEndTimestamp=="number"?r.muteEndTimestamp=A.muteEndTimestamp:typeof A.muteEndTimestamp=="object"&&(r.muteEndTimestamp=new l.LongBits(A.muteEndTimestamp.low>>>0,A.muteEndTimestamp.high>>>0).toNumber())),A.autoMuted!=null&&(r.autoMuted=!!A.autoMuted),r},i.toObject=function(A,r){r||(r={});var s={};return A.muted!=null&&A.hasOwnProperty("muted")&&(s.muted=A.muted,r.oneofs&&(s._muted="muted")),A.muteEndTimestamp!=null&&A.hasOwnProperty("muteEndTimestamp")&&(typeof A.muteEndTimestamp=="number"?s.muteEndTimestamp=r.longs===String?String(A.muteEndTimestamp):A.muteEndTimestamp:s.muteEndTimestamp=r.longs===String?se(A.muteEndTimestamp):r.longs===Number?ge(A.muteEndTimestamp):A.muteEndTimestamp,r.oneofs&&(s._muteEndTimestamp="muteEndTimestamp")),A.autoMuted!=null&&A.hasOwnProperty("autoMuted")&&(s.autoMuted=A.autoMuted,r.oneofs&&(s._autoMuted="autoMuted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.MuteAction"},i})(),t.NewsletterSavedInterestsAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.newsletterSavedInterests=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.NewsletterSavedInterestsAction)return A;var r=new p.proto.SyncActionValue.NewsletterSavedInterestsAction;return A.newsletterSavedInterests!=null&&(r.newsletterSavedInterests=String(A.newsletterSavedInterests)),r},i.toObject=function(A,r){r||(r={});var s={};return A.newsletterSavedInterests!=null&&A.hasOwnProperty("newsletterSavedInterests")&&(s.newsletterSavedInterests=A.newsletterSavedInterests,r.oneofs&&(s._newsletterSavedInterests="newsletterSavedInterests")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NewsletterSavedInterestsAction"},i})(),t.NoteEditAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.type=A.int32();break}case 2:{c.chatJid=A.string();break}case 3:{c.createdAt=A.int64();break}case 4:{c.deleted=A.bool();break}case 5:{c.unstructuredContent=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.NoteEditAction)return A;var r=new p.proto.SyncActionValue.NoteEditAction;switch(A.type){default:if(typeof A.type=="number"){r.type=A.type;break}break;case"UNSTRUCTURED":case 1:r.type=1;break;case"STRUCTURED":case 2:r.type=2;break}return A.chatJid!=null&&(r.chatJid=String(A.chatJid)),A.createdAt!=null&&(l.Long?(r.createdAt=l.Long.fromValue(A.createdAt)).unsigned=!1:typeof A.createdAt=="string"?r.createdAt=parseInt(A.createdAt,10):typeof A.createdAt=="number"?r.createdAt=A.createdAt:typeof A.createdAt=="object"&&(r.createdAt=new l.LongBits(A.createdAt.low>>>0,A.createdAt.high>>>0).toNumber())),A.deleted!=null&&(r.deleted=!!A.deleted),A.unstructuredContent!=null&&(r.unstructuredContent=String(A.unstructuredContent)),r},i.toObject=function(A,r){r||(r={});var s={};return A.type!=null&&A.hasOwnProperty("type")&&(s.type=r.enums===String?p.proto.SyncActionValue.NoteEditAction.NoteType[A.type]===void 0?A.type:p.proto.SyncActionValue.NoteEditAction.NoteType[A.type]:A.type,r.oneofs&&(s._type="type")),A.chatJid!=null&&A.hasOwnProperty("chatJid")&&(s.chatJid=A.chatJid,r.oneofs&&(s._chatJid="chatJid")),A.createdAt!=null&&A.hasOwnProperty("createdAt")&&(typeof A.createdAt=="number"?s.createdAt=r.longs===String?String(A.createdAt):A.createdAt:s.createdAt=r.longs===String?se(A.createdAt):r.longs===Number?ge(A.createdAt):A.createdAt,r.oneofs&&(s._createdAt="createdAt")),A.deleted!=null&&A.hasOwnProperty("deleted")&&(s.deleted=A.deleted,r.oneofs&&(s._deleted="deleted")),A.unstructuredContent!=null&&A.hasOwnProperty("unstructuredContent")&&(s.unstructuredContent=A.unstructuredContent,r.oneofs&&(s._unstructuredContent="unstructuredContent")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NoteEditAction"},i.NoteType=(function(){let a={},A=Object.create(a);return A[a[1]="UNSTRUCTURED"]=1,A[a[2]="STRUCTURED"]=2,A})(),i})(),t.NotificationActivitySettingAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.notificationActivitySetting=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.NotificationActivitySettingAction)return A;var r=new p.proto.SyncActionValue.NotificationActivitySettingAction;switch(A.notificationActivitySetting){default:if(typeof A.notificationActivitySetting=="number"){r.notificationActivitySetting=A.notificationActivitySetting;break}break;case"DEFAULT_ALL_MESSAGES":case 0:r.notificationActivitySetting=0;break;case"ALL_MESSAGES":case 1:r.notificationActivitySetting=1;break;case"HIGHLIGHTS":case 2:r.notificationActivitySetting=2;break;case"DEFAULT_HIGHLIGHTS":case 3:r.notificationActivitySetting=3;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.notificationActivitySetting!=null&&A.hasOwnProperty("notificationActivitySetting")&&(s.notificationActivitySetting=r.enums===String?p.proto.SyncActionValue.NotificationActivitySettingAction.NotificationActivitySetting[A.notificationActivitySetting]===void 0?A.notificationActivitySetting:p.proto.SyncActionValue.NotificationActivitySettingAction.NotificationActivitySetting[A.notificationActivitySetting]:A.notificationActivitySetting,r.oneofs&&(s._notificationActivitySetting="notificationActivitySetting")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NotificationActivitySettingAction"},i.NotificationActivitySetting=(function(){let a={},A=Object.create(a);return A[a[0]="DEFAULT_ALL_MESSAGES"]=0,A[a[1]="ALL_MESSAGES"]=1,A[a[2]="HIGHLIGHTS"]=2,A[a[3]="DEFAULT_HIGHLIGHTS"]=3,A})(),i})(),t.NuxAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.acknowledged=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.NuxAction)return A;var r=new p.proto.SyncActionValue.NuxAction;return A.acknowledged!=null&&(r.acknowledged=!!A.acknowledged),r},i.toObject=function(A,r){r||(r={});var s={};return A.acknowledged!=null&&A.hasOwnProperty("acknowledged")&&(s.acknowledged=A.acknowledged,r.oneofs&&(s._acknowledged="acknowledged")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.NuxAction"},i})(),t.PaymentInfoAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.cpi=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PaymentInfoAction)return A;var r=new p.proto.SyncActionValue.PaymentInfoAction;return A.cpi!=null&&(r.cpi=String(A.cpi)),r},i.toObject=function(A,r){r||(r={});var s={};return A.cpi!=null&&A.hasOwnProperty("cpi")&&(s.cpi=A.cpi,r.oneofs&&(s._cpi="cpi")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PaymentInfoAction"},i})(),t.PaymentTosAction=(function(){function i(e){if(e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.paymentNotice=a.int32();break}case 2:{g.accepted=a.bool();break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.PaymentTosAction)return a;var A=new p.proto.SyncActionValue.PaymentTosAction;switch(a.paymentNotice){default:if(typeof a.paymentNotice=="number"){A.paymentNotice=a.paymentNotice;break}break;case"BR_PAY_PRIVACY_POLICY":case 0:A.paymentNotice=0;break}return a.accepted!=null&&(A.accepted=!!a.accepted),A},i.toObject=function(a,A){A||(A={});var r={};return A.defaults&&(r.paymentNotice=A.enums===String?"BR_PAY_PRIVACY_POLICY":0,r.accepted=!1),a.paymentNotice!=null&&a.hasOwnProperty("paymentNotice")&&(r.paymentNotice=A.enums===String?p.proto.SyncActionValue.PaymentTosAction.PaymentNotice[a.paymentNotice]===void 0?a.paymentNotice:p.proto.SyncActionValue.PaymentTosAction.PaymentNotice[a.paymentNotice]:a.paymentNotice),a.accepted!=null&&a.hasOwnProperty("accepted")&&(r.accepted=a.accepted),r},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.SyncActionValue.PaymentTosAction"},i.PaymentNotice=(function(){let e={},a=Object.create(e);return a[e[0]="BR_PAY_PRIVACY_POLICY"]=0,a})(),i})(),t.PinAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.pinned=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PinAction)return A;var r=new p.proto.SyncActionValue.PinAction;return A.pinned!=null&&(r.pinned=!!A.pinned),r},i.toObject=function(A,r){r||(r={});var s={};return A.pinned!=null&&A.hasOwnProperty("pinned")&&(s.pinned=A.pinned,r.oneofs&&(s._pinned="pinned")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PinAction"},i})(),t.PnForLidChatAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.pnJid=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PnForLidChatAction)return A;var r=new p.proto.SyncActionValue.PnForLidChatAction;return A.pnJid!=null&&(r.pnJid=String(A.pnJid)),r},i.toObject=function(A,r){r||(r={});var s={};return A.pnJid!=null&&A.hasOwnProperty("pnJid")&&(s.pnJid=A.pnJid,r.oneofs&&(s._pnJid="pnJid")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PnForLidChatAction"},i})(),t.PrimaryFeature=(function(){function i(e){if(this.flags=[],e)for(var a=Object.keys(e),A=0;A>>3){case 1:{g.flags&&g.flags.length||(g.flags=[]),g.flags.push(a.string());break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.PrimaryFeature)return a;var A=new p.proto.SyncActionValue.PrimaryFeature;if(a.flags){if(!Array.isArray(a.flags))throw TypeError(".proto.SyncActionValue.PrimaryFeature.flags: array expected");A.flags=[];for(var r=0;r>>3){case 1:{c.version=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PrimaryVersionAction)return A;var r=new p.proto.SyncActionValue.PrimaryVersionAction;return A.version!=null&&(r.version=String(A.version)),r},i.toObject=function(A,r){r||(r={});var s={};return A.version!=null&&A.hasOwnProperty("version")&&(s.version=A.version,r.oneofs&&(s._version="version")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrimaryVersionAction"},i})(),t.PrivacySettingChannelsPersonalisedRecommendationAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isUserOptedOut=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction)return A;var r=new p.proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction;return A.isUserOptedOut!=null&&(r.isUserOptedOut=!!A.isUserOptedOut),r},i.toObject=function(A,r){r||(r={});var s={};return A.isUserOptedOut!=null&&A.hasOwnProperty("isUserOptedOut")&&(s.isUserOptedOut=A.isUserOptedOut,r.oneofs&&(s._isUserOptedOut="isUserOptedOut")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivacySettingChannelsPersonalisedRecommendationAction"},i})(),t.PrivacySettingDisableLinkPreviewsAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isPreviewsDisabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction)return A;var r=new p.proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction;return A.isPreviewsDisabled!=null&&(r.isPreviewsDisabled=!!A.isPreviewsDisabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.isPreviewsDisabled!=null&&A.hasOwnProperty("isPreviewsDisabled")&&(s.isPreviewsDisabled=A.isPreviewsDisabled,r.oneofs&&(s._isPreviewsDisabled="isPreviewsDisabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivacySettingDisableLinkPreviewsAction"},i})(),t.PrivacySettingRelayAllCalls=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PrivacySettingRelayAllCalls)return A;var r=new p.proto.SyncActionValue.PrivacySettingRelayAllCalls;return A.isEnabled!=null&&(r.isEnabled=!!A.isEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.isEnabled!=null&&A.hasOwnProperty("isEnabled")&&(s.isEnabled=A.isEnabled,r.oneofs&&(s._isEnabled="isEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivacySettingRelayAllCalls"},i})(),t.PrivateProcessingSettingAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.privateProcessingStatus=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PrivateProcessingSettingAction)return A;var r=new p.proto.SyncActionValue.PrivateProcessingSettingAction;switch(A.privateProcessingStatus){default:if(typeof A.privateProcessingStatus=="number"){r.privateProcessingStatus=A.privateProcessingStatus;break}break;case"UNDEFINED":case 0:r.privateProcessingStatus=0;break;case"ENABLED":case 1:r.privateProcessingStatus=1;break;case"DISABLED":case 2:r.privateProcessingStatus=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.privateProcessingStatus!=null&&A.hasOwnProperty("privateProcessingStatus")&&(s.privateProcessingStatus=r.enums===String?p.proto.SyncActionValue.PrivateProcessingSettingAction.PrivateProcessingStatus[A.privateProcessingStatus]===void 0?A.privateProcessingStatus:p.proto.SyncActionValue.PrivateProcessingSettingAction.PrivateProcessingStatus[A.privateProcessingStatus]:A.privateProcessingStatus,r.oneofs&&(s._privateProcessingStatus="privateProcessingStatus")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PrivateProcessingSettingAction"},i.PrivateProcessingStatus=(function(){let a={},A=Object.create(a);return A[a[0]="UNDEFINED"]=0,A[a[1]="ENABLED"]=1,A[a[2]="DISABLED"]=2,A})(),i})(),t.PushNameSetting=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.name=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.PushNameSetting)return A;var r=new p.proto.SyncActionValue.PushNameSetting;return A.name!=null&&(r.name=String(A.name)),r},i.toObject=function(A,r){r||(r={});var s={};return A.name!=null&&A.hasOwnProperty("name")&&(s.name=A.name,r.oneofs&&(s._name="name")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.PushNameSetting"},i})(),t.QuickReplyAction=(function(){function i(a){if(this.keywords=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.shortcut=A.string();break}case 2:{c.message=A.string();break}case 3:{c.keywords&&c.keywords.length||(c.keywords=[]),c.keywords.push(A.string());break}case 4:{c.count=A.int32();break}case 5:{c.deleted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.QuickReplyAction)return A;var r=new p.proto.SyncActionValue.QuickReplyAction;if(A.shortcut!=null&&(r.shortcut=String(A.shortcut)),A.message!=null&&(r.message=String(A.message)),A.keywords){if(!Array.isArray(A.keywords))throw TypeError(".proto.SyncActionValue.QuickReplyAction.keywords: array expected");r.keywords=[];for(var s=0;s>>3){case 1:{g.weights&&g.weights.length||(g.weights=[]),g.weights.push(p.proto.RecentEmojiWeight.decode(a,a.uint32()));break}default:a.skipType(c&7);break}}return g},i.fromObject=function(a){if(a instanceof p.proto.SyncActionValue.RecentEmojiWeightsAction)return a;var A=new p.proto.SyncActionValue.RecentEmojiWeightsAction;if(a.weights){if(!Array.isArray(a.weights))throw TypeError(".proto.SyncActionValue.RecentEmojiWeightsAction.weights: array expected");A.weights=[];for(var r=0;r>>3){case 1:{c.lastStickerSentTs=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.RemoveRecentStickerAction)return A;var r=new p.proto.SyncActionValue.RemoveRecentStickerAction;return A.lastStickerSentTs!=null&&(l.Long?(r.lastStickerSentTs=l.Long.fromValue(A.lastStickerSentTs)).unsigned=!1:typeof A.lastStickerSentTs=="string"?r.lastStickerSentTs=parseInt(A.lastStickerSentTs,10):typeof A.lastStickerSentTs=="number"?r.lastStickerSentTs=A.lastStickerSentTs:typeof A.lastStickerSentTs=="object"&&(r.lastStickerSentTs=new l.LongBits(A.lastStickerSentTs.low>>>0,A.lastStickerSentTs.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.lastStickerSentTs!=null&&A.hasOwnProperty("lastStickerSentTs")&&(typeof A.lastStickerSentTs=="number"?s.lastStickerSentTs=r.longs===String?String(A.lastStickerSentTs):A.lastStickerSentTs:s.lastStickerSentTs=r.longs===String?se(A.lastStickerSentTs):r.longs===Number?ge(A.lastStickerSentTs):A.lastStickerSentTs,r.oneofs&&(s._lastStickerSentTs="lastStickerSentTs")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.RemoveRecentStickerAction"},i})(),t.StarAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.starred=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.StarAction)return A;var r=new p.proto.SyncActionValue.StarAction;return A.starred!=null&&(r.starred=!!A.starred),r},i.toObject=function(A,r){r||(r={});var s={};return A.starred!=null&&A.hasOwnProperty("starred")&&(s.starred=A.starred,r.oneofs&&(s._starred="starred")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.StarAction"},i})(),t.StatusPostOptInNotificationPreferencesAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.enabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction)return A;var r=new p.proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction;return A.enabled!=null&&(r.enabled=!!A.enabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.enabled!=null&&A.hasOwnProperty("enabled")&&(s.enabled=A.enabled,r.oneofs&&(s._enabled="enabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.StatusPostOptInNotificationPreferencesAction"},i})(),t.StatusPrivacyAction=(function(){function i(a){if(this.userJid=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.mode=A.int32();break}case 2:{c.userJid&&c.userJid.length||(c.userJid=[]),c.userJid.push(A.string());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.StatusPrivacyAction)return A;var r=new p.proto.SyncActionValue.StatusPrivacyAction;switch(A.mode){default:if(typeof A.mode=="number"){r.mode=A.mode;break}break;case"ALLOW_LIST":case 0:r.mode=0;break;case"DENY_LIST":case 1:r.mode=1;break;case"CONTACTS":case 2:r.mode=2;break;case"CLOSE_FRIENDS":case 3:r.mode=3;break}if(A.userJid){if(!Array.isArray(A.userJid))throw TypeError(".proto.SyncActionValue.StatusPrivacyAction.userJid: array expected");r.userJid=[];for(var s=0;s>>3){case 1:{c.url=A.string();break}case 2:{c.fileEncSha256=A.bytes();break}case 3:{c.mediaKey=A.bytes();break}case 4:{c.mimetype=A.string();break}case 5:{c.height=A.uint32();break}case 6:{c.width=A.uint32();break}case 7:{c.directPath=A.string();break}case 8:{c.fileLength=A.uint64();break}case 9:{c.isFavorite=A.bool();break}case 10:{c.deviceIdHint=A.uint32();break}case 11:{c.isLottie=A.bool();break}case 12:{c.imageHash=A.string();break}case 13:{c.isAvatarSticker=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.StickerAction)return A;var r=new p.proto.SyncActionValue.StickerAction;return A.url!=null&&(r.url=String(A.url)),A.fileEncSha256!=null&&(typeof A.fileEncSha256=="string"?l.base64.decode(A.fileEncSha256,r.fileEncSha256=l.newBuffer(l.base64.length(A.fileEncSha256)),0):A.fileEncSha256.length>=0&&(r.fileEncSha256=A.fileEncSha256)),A.mediaKey!=null&&(typeof A.mediaKey=="string"?l.base64.decode(A.mediaKey,r.mediaKey=l.newBuffer(l.base64.length(A.mediaKey)),0):A.mediaKey.length>=0&&(r.mediaKey=A.mediaKey)),A.mimetype!=null&&(r.mimetype=String(A.mimetype)),A.height!=null&&(r.height=A.height>>>0),A.width!=null&&(r.width=A.width>>>0),A.directPath!=null&&(r.directPath=String(A.directPath)),A.fileLength!=null&&(l.Long?(r.fileLength=l.Long.fromValue(A.fileLength)).unsigned=!0:typeof A.fileLength=="string"?r.fileLength=parseInt(A.fileLength,10):typeof A.fileLength=="number"?r.fileLength=A.fileLength:typeof A.fileLength=="object"&&(r.fileLength=new l.LongBits(A.fileLength.low>>>0,A.fileLength.high>>>0).toNumber(!0))),A.isFavorite!=null&&(r.isFavorite=!!A.isFavorite),A.deviceIdHint!=null&&(r.deviceIdHint=A.deviceIdHint>>>0),A.isLottie!=null&&(r.isLottie=!!A.isLottie),A.imageHash!=null&&(r.imageHash=String(A.imageHash)),A.isAvatarSticker!=null&&(r.isAvatarSticker=!!A.isAvatarSticker),r},i.toObject=function(A,r){r||(r={});var s={};return A.url!=null&&A.hasOwnProperty("url")&&(s.url=A.url,r.oneofs&&(s._url="url")),A.fileEncSha256!=null&&A.hasOwnProperty("fileEncSha256")&&(s.fileEncSha256=r.bytes===String?l.base64.encode(A.fileEncSha256,0,A.fileEncSha256.length):r.bytes===Array?Array.prototype.slice.call(A.fileEncSha256):A.fileEncSha256,r.oneofs&&(s._fileEncSha256="fileEncSha256")),A.mediaKey!=null&&A.hasOwnProperty("mediaKey")&&(s.mediaKey=r.bytes===String?l.base64.encode(A.mediaKey,0,A.mediaKey.length):r.bytes===Array?Array.prototype.slice.call(A.mediaKey):A.mediaKey,r.oneofs&&(s._mediaKey="mediaKey")),A.mimetype!=null&&A.hasOwnProperty("mimetype")&&(s.mimetype=A.mimetype,r.oneofs&&(s._mimetype="mimetype")),A.height!=null&&A.hasOwnProperty("height")&&(s.height=A.height,r.oneofs&&(s._height="height")),A.width!=null&&A.hasOwnProperty("width")&&(s.width=A.width,r.oneofs&&(s._width="width")),A.directPath!=null&&A.hasOwnProperty("directPath")&&(s.directPath=A.directPath,r.oneofs&&(s._directPath="directPath")),A.fileLength!=null&&A.hasOwnProperty("fileLength")&&(typeof A.fileLength=="number"?s.fileLength=r.longs===String?String(A.fileLength):A.fileLength:s.fileLength=r.longs===String?se(A.fileLength,!0):r.longs===Number?ge(A.fileLength,!0):A.fileLength,r.oneofs&&(s._fileLength="fileLength")),A.isFavorite!=null&&A.hasOwnProperty("isFavorite")&&(s.isFavorite=A.isFavorite,r.oneofs&&(s._isFavorite="isFavorite")),A.deviceIdHint!=null&&A.hasOwnProperty("deviceIdHint")&&(s.deviceIdHint=A.deviceIdHint,r.oneofs&&(s._deviceIdHint="deviceIdHint")),A.isLottie!=null&&A.hasOwnProperty("isLottie")&&(s.isLottie=A.isLottie,r.oneofs&&(s._isLottie="isLottie")),A.imageHash!=null&&A.hasOwnProperty("imageHash")&&(s.imageHash=A.imageHash,r.oneofs&&(s._imageHash="imageHash")),A.isAvatarSticker!=null&&A.hasOwnProperty("isAvatarSticker")&&(s.isAvatarSticker=A.isAvatarSticker,r.oneofs&&(s._isAvatarSticker="isAvatarSticker")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.StickerAction"},i})(),t.SubscriptionAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.isDeactivated=A.bool();break}case 2:{c.isAutoRenewing=A.bool();break}case 3:{c.expirationDate=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.SubscriptionAction)return A;var r=new p.proto.SyncActionValue.SubscriptionAction;return A.isDeactivated!=null&&(r.isDeactivated=!!A.isDeactivated),A.isAutoRenewing!=null&&(r.isAutoRenewing=!!A.isAutoRenewing),A.expirationDate!=null&&(l.Long?(r.expirationDate=l.Long.fromValue(A.expirationDate)).unsigned=!1:typeof A.expirationDate=="string"?r.expirationDate=parseInt(A.expirationDate,10):typeof A.expirationDate=="number"?r.expirationDate=A.expirationDate:typeof A.expirationDate=="object"&&(r.expirationDate=new l.LongBits(A.expirationDate.low>>>0,A.expirationDate.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.isDeactivated!=null&&A.hasOwnProperty("isDeactivated")&&(s.isDeactivated=A.isDeactivated,r.oneofs&&(s._isDeactivated="isDeactivated")),A.isAutoRenewing!=null&&A.hasOwnProperty("isAutoRenewing")&&(s.isAutoRenewing=A.isAutoRenewing,r.oneofs&&(s._isAutoRenewing="isAutoRenewing")),A.expirationDate!=null&&A.hasOwnProperty("expirationDate")&&(typeof A.expirationDate=="number"?s.expirationDate=r.longs===String?String(A.expirationDate):A.expirationDate:s.expirationDate=r.longs===String?se(A.expirationDate):r.longs===Number?ge(A.expirationDate):A.expirationDate,r.oneofs&&(s._expirationDate="expirationDate")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.SubscriptionAction"},i})(),t.SyncActionMessage=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.key=p.proto.MessageKey.decode(A,A.uint32());break}case 2:{c.timestamp=A.int64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.SyncActionMessage)return A;var r=new p.proto.SyncActionValue.SyncActionMessage;if(A.key!=null){if(typeof A.key!="object")throw TypeError(".proto.SyncActionValue.SyncActionMessage.key: object expected");r.key=p.proto.MessageKey.fromObject(A.key)}return A.timestamp!=null&&(l.Long?(r.timestamp=l.Long.fromValue(A.timestamp)).unsigned=!1:typeof A.timestamp=="string"?r.timestamp=parseInt(A.timestamp,10):typeof A.timestamp=="number"?r.timestamp=A.timestamp:typeof A.timestamp=="object"&&(r.timestamp=new l.LongBits(A.timestamp.low>>>0,A.timestamp.high>>>0).toNumber())),r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=p.proto.MessageKey.toObject(A.key,r),r.oneofs&&(s._key="key")),A.timestamp!=null&&A.hasOwnProperty("timestamp")&&(typeof A.timestamp=="number"?s.timestamp=r.longs===String?String(A.timestamp):A.timestamp:s.timestamp=r.longs===String?se(A.timestamp):r.longs===Number?ge(A.timestamp):A.timestamp,r.oneofs&&(s._timestamp="timestamp")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.SyncActionMessage"},i})(),t.SyncActionMessageRange=(function(){function i(a){if(this.messages=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.lastMessageTimestamp=A.int64();break}case 2:{c.lastSystemMessageTimestamp=A.int64();break}case 3:{c.messages&&c.messages.length||(c.messages=[]),c.messages.push(p.proto.SyncActionValue.SyncActionMessage.decode(A,A.uint32()));break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.SyncActionMessageRange)return A;var r=new p.proto.SyncActionValue.SyncActionMessageRange;if(A.lastMessageTimestamp!=null&&(l.Long?(r.lastMessageTimestamp=l.Long.fromValue(A.lastMessageTimestamp)).unsigned=!1:typeof A.lastMessageTimestamp=="string"?r.lastMessageTimestamp=parseInt(A.lastMessageTimestamp,10):typeof A.lastMessageTimestamp=="number"?r.lastMessageTimestamp=A.lastMessageTimestamp:typeof A.lastMessageTimestamp=="object"&&(r.lastMessageTimestamp=new l.LongBits(A.lastMessageTimestamp.low>>>0,A.lastMessageTimestamp.high>>>0).toNumber())),A.lastSystemMessageTimestamp!=null&&(l.Long?(r.lastSystemMessageTimestamp=l.Long.fromValue(A.lastSystemMessageTimestamp)).unsigned=!1:typeof A.lastSystemMessageTimestamp=="string"?r.lastSystemMessageTimestamp=parseInt(A.lastSystemMessageTimestamp,10):typeof A.lastSystemMessageTimestamp=="number"?r.lastSystemMessageTimestamp=A.lastSystemMessageTimestamp:typeof A.lastSystemMessageTimestamp=="object"&&(r.lastSystemMessageTimestamp=new l.LongBits(A.lastSystemMessageTimestamp.low>>>0,A.lastSystemMessageTimestamp.high>>>0).toNumber())),A.messages){if(!Array.isArray(A.messages))throw TypeError(".proto.SyncActionValue.SyncActionMessageRange.messages: array expected");r.messages=[];for(var s=0;s>>3){case 1:{c.isTwentyFourHourFormatEnabled=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.TimeFormatAction)return A;var r=new p.proto.SyncActionValue.TimeFormatAction;return A.isTwentyFourHourFormatEnabled!=null&&(r.isTwentyFourHourFormatEnabled=!!A.isTwentyFourHourFormatEnabled),r},i.toObject=function(A,r){r||(r={});var s={};return A.isTwentyFourHourFormatEnabled!=null&&A.hasOwnProperty("isTwentyFourHourFormatEnabled")&&(s.isTwentyFourHourFormatEnabled=A.isTwentyFourHourFormatEnabled,r.oneofs&&(s._isTwentyFourHourFormatEnabled="isTwentyFourHourFormatEnabled")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.TimeFormatAction"},i})(),t.UGCBot=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.definition=A.bytes();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.UGCBot)return A;var r=new p.proto.SyncActionValue.UGCBot;return A.definition!=null&&(typeof A.definition=="string"?l.base64.decode(A.definition,r.definition=l.newBuffer(l.base64.length(A.definition)),0):A.definition.length>=0&&(r.definition=A.definition)),r},i.toObject=function(A,r){r||(r={});var s={};return A.definition!=null&&A.hasOwnProperty("definition")&&(s.definition=r.bytes===String?l.base64.encode(A.definition,0,A.definition.length):r.bytes===Array?Array.prototype.slice.call(A.definition):A.definition,r.oneofs&&(s._definition="definition")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UGCBot"},i})(),t.UnarchiveChatsSetting=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.unarchiveChats=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.UnarchiveChatsSetting)return A;var r=new p.proto.SyncActionValue.UnarchiveChatsSetting;return A.unarchiveChats!=null&&(r.unarchiveChats=!!A.unarchiveChats),r},i.toObject=function(A,r){r||(r={});var s={};return A.unarchiveChats!=null&&A.hasOwnProperty("unarchiveChats")&&(s.unarchiveChats=A.unarchiveChats,r.oneofs&&(s._unarchiveChats="unarchiveChats")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UnarchiveChatsSetting"},i})(),t.UserStatusMuteAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.muted=A.bool();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.UserStatusMuteAction)return A;var r=new p.proto.SyncActionValue.UserStatusMuteAction;return A.muted!=null&&(r.muted=!!A.muted),r},i.toObject=function(A,r){r||(r={});var s={};return A.muted!=null&&A.hasOwnProperty("muted")&&(s.muted=A.muted,r.oneofs&&(s._muted="muted")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UserStatusMuteAction"},i})(),t.UsernameChatStartModeAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.chatStartMode=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.UsernameChatStartModeAction)return A;var r=new p.proto.SyncActionValue.UsernameChatStartModeAction;switch(A.chatStartMode){default:if(typeof A.chatStartMode=="number"){r.chatStartMode=A.chatStartMode;break}break;case"LID":case 1:r.chatStartMode=1;break;case"PN":case 2:r.chatStartMode=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.chatStartMode!=null&&A.hasOwnProperty("chatStartMode")&&(s.chatStartMode=r.enums===String?p.proto.SyncActionValue.UsernameChatStartModeAction.ChatStartMode[A.chatStartMode]===void 0?A.chatStartMode:p.proto.SyncActionValue.UsernameChatStartModeAction.ChatStartMode[A.chatStartMode]:A.chatStartMode,r.oneofs&&(s._chatStartMode="chatStartMode")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.UsernameChatStartModeAction"},i.ChatStartMode=(function(){let a={},A=Object.create(a);return A[a[1]="LID"]=1,A[a[2]="PN"]=2,A})(),i})(),t.WaffleAccountLinkStateAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 2:{c.linkState=A.int32();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.WaffleAccountLinkStateAction)return A;var r=new p.proto.SyncActionValue.WaffleAccountLinkStateAction;switch(A.linkState){default:if(typeof A.linkState=="number"){r.linkState=A.linkState;break}break;case"ACTIVE":case 0:r.linkState=0;break;case"PAUSED":case 1:r.linkState=1;break;case"UNLINKED":case 2:r.linkState=2;break}return r},i.toObject=function(A,r){r||(r={});var s={};return A.linkState!=null&&A.hasOwnProperty("linkState")&&(s.linkState=r.enums===String?p.proto.SyncActionValue.WaffleAccountLinkStateAction.AccountLinkState[A.linkState]===void 0?A.linkState:p.proto.SyncActionValue.WaffleAccountLinkStateAction.AccountLinkState[A.linkState]:A.linkState,r.oneofs&&(s._linkState="linkState")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.WaffleAccountLinkStateAction"},i.AccountLinkState=(function(){let a={},A=Object.create(a);return A[a[0]="ACTIVE"]=0,A[a[1]="PAUSED"]=1,A[a[2]="UNLINKED"]=2,A})(),i})(),t.WamoUserIdentifierAction=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.identifier=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.SyncActionValue.WamoUserIdentifierAction)return A;var r=new p.proto.SyncActionValue.WamoUserIdentifierAction;return A.identifier!=null&&(r.identifier=String(A.identifier)),r},i.toObject=function(A,r){r||(r={});var s={};return A.identifier!=null&&A.hasOwnProperty("identifier")&&(s.identifier=A.identifier,r.oneofs&&(s._identifier="identifier")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.SyncActionValue.WamoUserIdentifierAction"},i})(),t})(),n.SyncdIndex=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.blob=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdIndex)return e;var a=new p.proto.SyncdIndex;return e.blob!=null&&(typeof e.blob=="string"?l.base64.decode(e.blob,a.blob=l.newBuffer(l.base64.length(e.blob)),0):e.blob.length>=0&&(a.blob=e.blob)),a},t.toObject=function(e,a){a||(a={});var A={};return e.blob!=null&&e.hasOwnProperty("blob")&&(A.blob=a.bytes===String?l.base64.encode(e.blob,0,e.blob.length):a.bytes===Array?Array.prototype.slice.call(e.blob):e.blob,a.oneofs&&(A._blob="blob")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdIndex"},t})(),n.SyncdMutation=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.operation=e.int32();break}case 2:{s.record=p.proto.SyncdRecord.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdMutation)return e;var a=new p.proto.SyncdMutation;switch(e.operation){default:if(typeof e.operation=="number"){a.operation=e.operation;break}break;case"SET":case 0:a.operation=0;break;case"REMOVE":case 1:a.operation=1;break}if(e.record!=null){if(typeof e.record!="object")throw TypeError(".proto.SyncdMutation.record: object expected");a.record=p.proto.SyncdRecord.fromObject(e.record)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.operation!=null&&e.hasOwnProperty("operation")&&(A.operation=a.enums===String?p.proto.SyncdMutation.SyncdOperation[e.operation]===void 0?e.operation:p.proto.SyncdMutation.SyncdOperation[e.operation]:e.operation,a.oneofs&&(A._operation="operation")),e.record!=null&&e.hasOwnProperty("record")&&(A.record=p.proto.SyncdRecord.toObject(e.record,a),a.oneofs&&(A._record="record")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdMutation"},t.SyncdOperation=(function(){let i={},e=Object.create(i);return e[i[0]="SET"]=0,e[i[1]="REMOVE"]=1,e})(),t})(),n.SyncdMutations=(function(){function t(o){if(this.mutations=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.mutations&&r.mutations.length||(r.mutations=[]),r.mutations.push(p.proto.SyncdMutation.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.SyncdMutations)return i;var e=new p.proto.SyncdMutations;if(i.mutations){if(!Array.isArray(i.mutations))throw TypeError(".proto.SyncdMutations.mutations: array expected");e.mutations=[];for(var a=0;a>>3){case 1:{s.version=p.proto.SyncdVersion.decode(e,e.uint32());break}case 2:{s.mutations&&s.mutations.length||(s.mutations=[]),s.mutations.push(p.proto.SyncdMutation.decode(e,e.uint32()));break}case 3:{s.externalMutations=p.proto.ExternalBlobReference.decode(e,e.uint32());break}case 4:{s.snapshotMac=e.bytes();break}case 5:{s.patchMac=e.bytes();break}case 6:{s.keyId=p.proto.KeyId.decode(e,e.uint32());break}case 7:{s.exitCode=p.proto.ExitCode.decode(e,e.uint32());break}case 8:{s.deviceIndex=e.uint32();break}case 9:{s.clientDebugData=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdPatch)return e;var a=new p.proto.SyncdPatch;if(e.version!=null){if(typeof e.version!="object")throw TypeError(".proto.SyncdPatch.version: object expected");a.version=p.proto.SyncdVersion.fromObject(e.version)}if(e.mutations){if(!Array.isArray(e.mutations))throw TypeError(".proto.SyncdPatch.mutations: array expected");a.mutations=[];for(var A=0;A=0&&(a.snapshotMac=e.snapshotMac)),e.patchMac!=null&&(typeof e.patchMac=="string"?l.base64.decode(e.patchMac,a.patchMac=l.newBuffer(l.base64.length(e.patchMac)),0):e.patchMac.length>=0&&(a.patchMac=e.patchMac)),e.keyId!=null){if(typeof e.keyId!="object")throw TypeError(".proto.SyncdPatch.keyId: object expected");a.keyId=p.proto.KeyId.fromObject(e.keyId)}if(e.exitCode!=null){if(typeof e.exitCode!="object")throw TypeError(".proto.SyncdPatch.exitCode: object expected");a.exitCode=p.proto.ExitCode.fromObject(e.exitCode)}return e.deviceIndex!=null&&(a.deviceIndex=e.deviceIndex>>>0),e.clientDebugData!=null&&(typeof e.clientDebugData=="string"?l.base64.decode(e.clientDebugData,a.clientDebugData=l.newBuffer(l.base64.length(e.clientDebugData)),0):e.clientDebugData.length>=0&&(a.clientDebugData=e.clientDebugData)),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.mutations=[]),e.version!=null&&e.hasOwnProperty("version")&&(A.version=p.proto.SyncdVersion.toObject(e.version,a),a.oneofs&&(A._version="version")),e.mutations&&e.mutations.length){A.mutations=[];for(var r=0;r>>3){case 1:{s.index=p.proto.SyncdIndex.decode(e,e.uint32());break}case 2:{s.value=p.proto.SyncdValue.decode(e,e.uint32());break}case 3:{s.keyId=p.proto.KeyId.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdRecord)return e;var a=new p.proto.SyncdRecord;if(e.index!=null){if(typeof e.index!="object")throw TypeError(".proto.SyncdRecord.index: object expected");a.index=p.proto.SyncdIndex.fromObject(e.index)}if(e.value!=null){if(typeof e.value!="object")throw TypeError(".proto.SyncdRecord.value: object expected");a.value=p.proto.SyncdValue.fromObject(e.value)}if(e.keyId!=null){if(typeof e.keyId!="object")throw TypeError(".proto.SyncdRecord.keyId: object expected");a.keyId=p.proto.KeyId.fromObject(e.keyId)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.index!=null&&e.hasOwnProperty("index")&&(A.index=p.proto.SyncdIndex.toObject(e.index,a),a.oneofs&&(A._index="index")),e.value!=null&&e.hasOwnProperty("value")&&(A.value=p.proto.SyncdValue.toObject(e.value,a),a.oneofs&&(A._value="value")),e.keyId!=null&&e.hasOwnProperty("keyId")&&(A.keyId=p.proto.KeyId.toObject(e.keyId,a),a.oneofs&&(A._keyId="keyId")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdRecord"},t})(),n.SyncdSnapshot=(function(){function t(i){if(this.records=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.version=p.proto.SyncdVersion.decode(e,e.uint32());break}case 2:{s.records&&s.records.length||(s.records=[]),s.records.push(p.proto.SyncdRecord.decode(e,e.uint32()));break}case 3:{s.mac=e.bytes();break}case 4:{s.keyId=p.proto.KeyId.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdSnapshot)return e;var a=new p.proto.SyncdSnapshot;if(e.version!=null){if(typeof e.version!="object")throw TypeError(".proto.SyncdSnapshot.version: object expected");a.version=p.proto.SyncdVersion.fromObject(e.version)}if(e.records){if(!Array.isArray(e.records))throw TypeError(".proto.SyncdSnapshot.records: array expected");a.records=[];for(var A=0;A=0&&(a.mac=e.mac)),e.keyId!=null){if(typeof e.keyId!="object")throw TypeError(".proto.SyncdSnapshot.keyId: object expected");a.keyId=p.proto.KeyId.fromObject(e.keyId)}return a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.records=[]),e.version!=null&&e.hasOwnProperty("version")&&(A.version=p.proto.SyncdVersion.toObject(e.version,a),a.oneofs&&(A._version="version")),e.records&&e.records.length){A.records=[];for(var r=0;r>>3){case 1:{s.blob=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdValue)return e;var a=new p.proto.SyncdValue;return e.blob!=null&&(typeof e.blob=="string"?l.base64.decode(e.blob,a.blob=l.newBuffer(l.base64.length(e.blob)),0):e.blob.length>=0&&(a.blob=e.blob)),a},t.toObject=function(e,a){a||(a={});var A={};return e.blob!=null&&e.hasOwnProperty("blob")&&(A.blob=a.bytes===String?l.base64.encode(e.blob,0,e.blob.length):a.bytes===Array?Array.prototype.slice.call(e.blob):e.blob,a.oneofs&&(A._blob="blob")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdValue"},t})(),n.SyncdVersion=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.version=e.uint64();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.SyncdVersion)return e;var a=new p.proto.SyncdVersion;return e.version!=null&&(l.Long?(a.version=l.Long.fromValue(e.version)).unsigned=!0:typeof e.version=="string"?a.version=parseInt(e.version,10):typeof e.version=="number"?a.version=e.version:typeof e.version=="object"&&(a.version=new l.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber(!0))),a},t.toObject=function(e,a){a||(a={});var A={};return e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?A.version=a.longs===String?String(e.version):e.version:A.version=a.longs===String?se(e.version,!0):a.longs===Number?ge(e.version,!0):e.version,a.oneofs&&(A._version="version")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.SyncdVersion"},t})(),n.TapLinkAction=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.title=e.string();break}case 2:{s.tapUrl=e.string();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.TapLinkAction)return e;var a=new p.proto.TapLinkAction;return e.title!=null&&(a.title=String(e.title)),e.tapUrl!=null&&(a.tapUrl=String(e.tapUrl)),a},t.toObject=function(e,a){a||(a={});var A={};return e.title!=null&&e.hasOwnProperty("title")&&(A.title=e.title,a.oneofs&&(A._title="title")),e.tapUrl!=null&&e.hasOwnProperty("tapUrl")&&(A.tapUrl=e.tapUrl,a.oneofs&&(A._tapUrl="tapUrl")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.TapLinkAction"},t})(),n.TemplateButton=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 4:{s.index=e.uint32();break}case 1:{s.quickReplyButton=p.proto.TemplateButton.QuickReplyButton.decode(e,e.uint32());break}case 2:{s.urlButton=p.proto.TemplateButton.URLButton.decode(e,e.uint32());break}case 3:{s.callButton=p.proto.TemplateButton.CallButton.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.TemplateButton)return e;var a=new p.proto.TemplateButton;if(e.index!=null&&(a.index=e.index>>>0),e.quickReplyButton!=null){if(typeof e.quickReplyButton!="object")throw TypeError(".proto.TemplateButton.quickReplyButton: object expected");a.quickReplyButton=p.proto.TemplateButton.QuickReplyButton.fromObject(e.quickReplyButton)}if(e.urlButton!=null){if(typeof e.urlButton!="object")throw TypeError(".proto.TemplateButton.urlButton: object expected");a.urlButton=p.proto.TemplateButton.URLButton.fromObject(e.urlButton)}if(e.callButton!=null){if(typeof e.callButton!="object")throw TypeError(".proto.TemplateButton.callButton: object expected");a.callButton=p.proto.TemplateButton.CallButton.fromObject(e.callButton)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.quickReplyButton!=null&&e.hasOwnProperty("quickReplyButton")&&(A.quickReplyButton=p.proto.TemplateButton.QuickReplyButton.toObject(e.quickReplyButton,a),a.oneofs&&(A.button="quickReplyButton")),e.urlButton!=null&&e.hasOwnProperty("urlButton")&&(A.urlButton=p.proto.TemplateButton.URLButton.toObject(e.urlButton,a),a.oneofs&&(A.button="urlButton")),e.callButton!=null&&e.hasOwnProperty("callButton")&&(A.callButton=p.proto.TemplateButton.CallButton.toObject(e.callButton,a),a.oneofs&&(A.button="callButton")),e.index!=null&&e.hasOwnProperty("index")&&(A.index=e.index,a.oneofs&&(A._index="index")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.TemplateButton"},t.CallButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=p.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}case 2:{c.phoneNumber=p.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.TemplateButton.CallButton)return A;var r=new p.proto.TemplateButton.CallButton;if(A.displayText!=null){if(typeof A.displayText!="object")throw TypeError(".proto.TemplateButton.CallButton.displayText: object expected");r.displayText=p.proto.Message.HighlyStructuredMessage.fromObject(A.displayText)}if(A.phoneNumber!=null){if(typeof A.phoneNumber!="object")throw TypeError(".proto.TemplateButton.CallButton.phoneNumber: object expected");r.phoneNumber=p.proto.Message.HighlyStructuredMessage.fromObject(A.phoneNumber)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=p.proto.Message.HighlyStructuredMessage.toObject(A.displayText,r),r.oneofs&&(s._displayText="displayText")),A.phoneNumber!=null&&A.hasOwnProperty("phoneNumber")&&(s.phoneNumber=p.proto.Message.HighlyStructuredMessage.toObject(A.phoneNumber,r),r.oneofs&&(s._phoneNumber="phoneNumber")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.TemplateButton.CallButton"},i})(),t.QuickReplyButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=p.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}case 2:{c.id=A.string();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.TemplateButton.QuickReplyButton)return A;var r=new p.proto.TemplateButton.QuickReplyButton;if(A.displayText!=null){if(typeof A.displayText!="object")throw TypeError(".proto.TemplateButton.QuickReplyButton.displayText: object expected");r.displayText=p.proto.Message.HighlyStructuredMessage.fromObject(A.displayText)}return A.id!=null&&(r.id=String(A.id)),r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=p.proto.Message.HighlyStructuredMessage.toObject(A.displayText,r),r.oneofs&&(s._displayText="displayText")),A.id!=null&&A.hasOwnProperty("id")&&(s.id=A.id,r.oneofs&&(s._id="id")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.TemplateButton.QuickReplyButton"},i})(),t.URLButton=(function(){function i(a){if(a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.displayText=p.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}case 2:{c.url=p.proto.Message.HighlyStructuredMessage.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.TemplateButton.URLButton)return A;var r=new p.proto.TemplateButton.URLButton;if(A.displayText!=null){if(typeof A.displayText!="object")throw TypeError(".proto.TemplateButton.URLButton.displayText: object expected");r.displayText=p.proto.Message.HighlyStructuredMessage.fromObject(A.displayText)}if(A.url!=null){if(typeof A.url!="object")throw TypeError(".proto.TemplateButton.URLButton.url: object expected");r.url=p.proto.Message.HighlyStructuredMessage.fromObject(A.url)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.displayText!=null&&A.hasOwnProperty("displayText")&&(s.displayText=p.proto.Message.HighlyStructuredMessage.toObject(A.displayText,r),r.oneofs&&(s._displayText="displayText")),A.url!=null&&A.hasOwnProperty("url")&&(s.url=p.proto.Message.HighlyStructuredMessage.toObject(A.url,r),r.oneofs&&(s._url="url")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.TemplateButton.URLButton"},i})(),t})(),n.ThreadID=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.threadType=e.int32();break}case 2:{s.threadKey=p.proto.MessageKey.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.ThreadID)return e;var a=new p.proto.ThreadID;switch(e.threadType){default:if(typeof e.threadType=="number"){a.threadType=e.threadType;break}break;case"UNKNOWN":case 0:a.threadType=0;break;case"VIEW_REPLIES":case 1:a.threadType=1;break;case"AI_THREAD":case 2:a.threadType=2;break}if(e.threadKey!=null){if(typeof e.threadKey!="object")throw TypeError(".proto.ThreadID.threadKey: object expected");a.threadKey=p.proto.MessageKey.fromObject(e.threadKey)}return a},t.toObject=function(e,a){a||(a={});var A={};return e.threadType!=null&&e.hasOwnProperty("threadType")&&(A.threadType=a.enums===String?p.proto.ThreadID.ThreadType[e.threadType]===void 0?e.threadType:p.proto.ThreadID.ThreadType[e.threadType]:e.threadType,a.oneofs&&(A._threadType="threadType")),e.threadKey!=null&&e.hasOwnProperty("threadKey")&&(A.threadKey=p.proto.MessageKey.toObject(e.threadKey,a),a.oneofs&&(A._threadKey="threadKey")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.ThreadID"},t.ThreadType=(function(){let i={},e=Object.create(i);return e[i[0]="UNKNOWN"]=0,e[i[1]="VIEW_REPLIES"]=1,e[i[2]="AI_THREAD"]=2,e})(),t})(),n.UrlTrackingMap=(function(){function t(o){if(this.urlTrackingMapElements=[],o)for(var i=Object.keys(o),e=0;e>>3){case 1:{r.urlTrackingMapElements&&r.urlTrackingMapElements.length||(r.urlTrackingMapElements=[]),r.urlTrackingMapElements.push(p.proto.UrlTrackingMap.UrlTrackingMapElement.decode(i,i.uint32()));break}default:i.skipType(s&7);break}}return r},t.fromObject=function(i){if(i instanceof p.proto.UrlTrackingMap)return i;var e=new p.proto.UrlTrackingMap;if(i.urlTrackingMapElements){if(!Array.isArray(i.urlTrackingMapElements))throw TypeError(".proto.UrlTrackingMap.urlTrackingMapElements: array expected");e.urlTrackingMapElements=[];for(var a=0;a>>3){case 1:{g.originalUrl=a.string();break}case 2:{g.unconsentedUsersUrl=a.string();break}case 3:{g.consentedUsersUrl=a.string();break}case 4:{g.cardIndex=a.uint32();break}default:a.skipType(c&7);break}}return g},o.fromObject=function(a){if(a instanceof p.proto.UrlTrackingMap.UrlTrackingMapElement)return a;var A=new p.proto.UrlTrackingMap.UrlTrackingMapElement;return a.originalUrl!=null&&(A.originalUrl=String(a.originalUrl)),a.unconsentedUsersUrl!=null&&(A.unconsentedUsersUrl=String(a.unconsentedUsersUrl)),a.consentedUsersUrl!=null&&(A.consentedUsersUrl=String(a.consentedUsersUrl)),a.cardIndex!=null&&(A.cardIndex=a.cardIndex>>>0),A},o.toObject=function(a,A){A||(A={});var r={};return a.originalUrl!=null&&a.hasOwnProperty("originalUrl")&&(r.originalUrl=a.originalUrl,A.oneofs&&(r._originalUrl="originalUrl")),a.unconsentedUsersUrl!=null&&a.hasOwnProperty("unconsentedUsersUrl")&&(r.unconsentedUsersUrl=a.unconsentedUsersUrl,A.oneofs&&(r._unconsentedUsersUrl="unconsentedUsersUrl")),a.consentedUsersUrl!=null&&a.hasOwnProperty("consentedUsersUrl")&&(r.consentedUsersUrl=a.consentedUsersUrl,A.oneofs&&(r._consentedUsersUrl="consentedUsersUrl")),a.cardIndex!=null&&a.hasOwnProperty("cardIndex")&&(r.cardIndex=a.cardIndex,A.oneofs&&(r._cardIndex="cardIndex")),r},o.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.UrlTrackingMap.UrlTrackingMapElement"},o})(),t})(),n.UserPassword=(function(){function t(i){if(this.transformerArg=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.encoding=e.int32();break}case 2:{s.transformer=e.int32();break}case 3:{s.transformerArg&&s.transformerArg.length||(s.transformerArg=[]),s.transformerArg.push(p.proto.UserPassword.TransformerArg.decode(e,e.uint32()));break}case 4:{s.transformedData=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.UserPassword)return e;var a=new p.proto.UserPassword;switch(e.encoding){default:if(typeof e.encoding=="number"){a.encoding=e.encoding;break}break;case"UTF8":case 0:a.encoding=0;break;case"UTF8_BROKEN":case 1:a.encoding=1;break}switch(e.transformer){default:if(typeof e.transformer=="number"){a.transformer=e.transformer;break}break;case"NONE":case 0:a.transformer=0;break;case"PBKDF2_HMAC_SHA512":case 1:a.transformer=1;break;case"PBKDF2_HMAC_SHA384":case 2:a.transformer=2;break}if(e.transformerArg){if(!Array.isArray(e.transformerArg))throw TypeError(".proto.UserPassword.transformerArg: array expected");a.transformerArg=[];for(var A=0;A=0&&(a.transformedData=e.transformedData)),a},t.toObject=function(e,a){a||(a={});var A={};if((a.arrays||a.defaults)&&(A.transformerArg=[]),e.encoding!=null&&e.hasOwnProperty("encoding")&&(A.encoding=a.enums===String?p.proto.UserPassword.Encoding[e.encoding]===void 0?e.encoding:p.proto.UserPassword.Encoding[e.encoding]:e.encoding,a.oneofs&&(A._encoding="encoding")),e.transformer!=null&&e.hasOwnProperty("transformer")&&(A.transformer=a.enums===String?p.proto.UserPassword.Transformer[e.transformer]===void 0?e.transformer:p.proto.UserPassword.Transformer[e.transformer]:e.transformer,a.oneofs&&(A._transformer="transformer")),e.transformerArg&&e.transformerArg.length){A.transformerArg=[];for(var r=0;r>>3){case 1:{c.key=A.string();break}case 2:{c.value=p.proto.UserPassword.TransformerArg.Value.decode(A,A.uint32());break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.UserPassword.TransformerArg)return A;var r=new p.proto.UserPassword.TransformerArg;if(A.key!=null&&(r.key=String(A.key)),A.value!=null){if(typeof A.value!="object")throw TypeError(".proto.UserPassword.TransformerArg.value: object expected");r.value=p.proto.UserPassword.TransformerArg.Value.fromObject(A.value)}return r},i.toObject=function(A,r){r||(r={});var s={};return A.key!=null&&A.hasOwnProperty("key")&&(s.key=A.key,r.oneofs&&(s._key="key")),A.value!=null&&A.hasOwnProperty("value")&&(s.value=p.proto.UserPassword.TransformerArg.Value.toObject(A.value,r),r.oneofs&&(s._value="value")),s},i.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},i.getTypeUrl=function(A){return A===void 0&&(A="type.googleapis.com"),A+"/proto.UserPassword.TransformerArg"},i.Value=(function(){function a(r){if(r)for(var s=Object.keys(r),g=0;g>>3){case 1:{d.asBlob=s.bytes();break}case 2:{d.asUnsignedInteger=s.uint32();break}default:s.skipType(B&7);break}}return d},a.fromObject=function(s){if(s instanceof p.proto.UserPassword.TransformerArg.Value)return s;var g=new p.proto.UserPassword.TransformerArg.Value;return s.asBlob!=null&&(typeof s.asBlob=="string"?l.base64.decode(s.asBlob,g.asBlob=l.newBuffer(l.base64.length(s.asBlob)),0):s.asBlob.length>=0&&(g.asBlob=s.asBlob)),s.asUnsignedInteger!=null&&(g.asUnsignedInteger=s.asUnsignedInteger>>>0),g},a.toObject=function(s,g){g||(g={});var c={};return s.asBlob!=null&&s.hasOwnProperty("asBlob")&&(c.asBlob=g.bytes===String?l.base64.encode(s.asBlob,0,s.asBlob.length):g.bytes===Array?Array.prototype.slice.call(s.asBlob):s.asBlob,g.oneofs&&(c.value="asBlob")),s.asUnsignedInteger!=null&&s.hasOwnProperty("asUnsignedInteger")&&(c.asUnsignedInteger=s.asUnsignedInteger,g.oneofs&&(c.value="asUnsignedInteger")),c},a.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},a.getTypeUrl=function(s){return s===void 0&&(s="type.googleapis.com"),s+"/proto.UserPassword.TransformerArg.Value"},a})(),i})(),t})(),n.UserReceipt=(function(){function t(i){if(this.pendingDeviceJid=[],this.deliveredDeviceJid=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.userJid=e.string();break}case 2:{s.receiptTimestamp=e.int64();break}case 3:{s.readTimestamp=e.int64();break}case 4:{s.playedTimestamp=e.int64();break}case 5:{s.pendingDeviceJid&&s.pendingDeviceJid.length||(s.pendingDeviceJid=[]),s.pendingDeviceJid.push(e.string());break}case 6:{s.deliveredDeviceJid&&s.deliveredDeviceJid.length||(s.deliveredDeviceJid=[]),s.deliveredDeviceJid.push(e.string());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.UserReceipt)return e;var a=new p.proto.UserReceipt;if(e.userJid!=null&&(a.userJid=String(e.userJid)),e.receiptTimestamp!=null&&(l.Long?(a.receiptTimestamp=l.Long.fromValue(e.receiptTimestamp)).unsigned=!1:typeof e.receiptTimestamp=="string"?a.receiptTimestamp=parseInt(e.receiptTimestamp,10):typeof e.receiptTimestamp=="number"?a.receiptTimestamp=e.receiptTimestamp:typeof e.receiptTimestamp=="object"&&(a.receiptTimestamp=new l.LongBits(e.receiptTimestamp.low>>>0,e.receiptTimestamp.high>>>0).toNumber())),e.readTimestamp!=null&&(l.Long?(a.readTimestamp=l.Long.fromValue(e.readTimestamp)).unsigned=!1:typeof e.readTimestamp=="string"?a.readTimestamp=parseInt(e.readTimestamp,10):typeof e.readTimestamp=="number"?a.readTimestamp=e.readTimestamp:typeof e.readTimestamp=="object"&&(a.readTimestamp=new l.LongBits(e.readTimestamp.low>>>0,e.readTimestamp.high>>>0).toNumber())),e.playedTimestamp!=null&&(l.Long?(a.playedTimestamp=l.Long.fromValue(e.playedTimestamp)).unsigned=!1:typeof e.playedTimestamp=="string"?a.playedTimestamp=parseInt(e.playedTimestamp,10):typeof e.playedTimestamp=="number"?a.playedTimestamp=e.playedTimestamp:typeof e.playedTimestamp=="object"&&(a.playedTimestamp=new l.LongBits(e.playedTimestamp.low>>>0,e.playedTimestamp.high>>>0).toNumber())),e.pendingDeviceJid){if(!Array.isArray(e.pendingDeviceJid))throw TypeError(".proto.UserReceipt.pendingDeviceJid: array expected");a.pendingDeviceJid=[];for(var A=0;A>>3){case 1:{s.details=e.bytes();break}case 2:{s.signature=e.bytes();break}case 3:{s.serverSignature=e.bytes();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.VerifiedNameCertificate)return e;var a=new p.proto.VerifiedNameCertificate;return e.details!=null&&(typeof e.details=="string"?l.base64.decode(e.details,a.details=l.newBuffer(l.base64.length(e.details)),0):e.details.length>=0&&(a.details=e.details)),e.signature!=null&&(typeof e.signature=="string"?l.base64.decode(e.signature,a.signature=l.newBuffer(l.base64.length(e.signature)),0):e.signature.length>=0&&(a.signature=e.signature)),e.serverSignature!=null&&(typeof e.serverSignature=="string"?l.base64.decode(e.serverSignature,a.serverSignature=l.newBuffer(l.base64.length(e.serverSignature)),0):e.serverSignature.length>=0&&(a.serverSignature=e.serverSignature)),a},t.toObject=function(e,a){a||(a={});var A={};return e.details!=null&&e.hasOwnProperty("details")&&(A.details=a.bytes===String?l.base64.encode(e.details,0,e.details.length):a.bytes===Array?Array.prototype.slice.call(e.details):e.details,a.oneofs&&(A._details="details")),e.signature!=null&&e.hasOwnProperty("signature")&&(A.signature=a.bytes===String?l.base64.encode(e.signature,0,e.signature.length):a.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,a.oneofs&&(A._signature="signature")),e.serverSignature!=null&&e.hasOwnProperty("serverSignature")&&(A.serverSignature=a.bytes===String?l.base64.encode(e.serverSignature,0,e.serverSignature.length):a.bytes===Array?Array.prototype.slice.call(e.serverSignature):e.serverSignature,a.oneofs&&(A._serverSignature="serverSignature")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.VerifiedNameCertificate"},t.Details=(function(){function i(a){if(this.localizedNames=[],a)for(var A=Object.keys(a),r=0;r>>3){case 1:{c.serial=A.uint64();break}case 2:{c.issuer=A.string();break}case 4:{c.verifiedName=A.string();break}case 8:{c.localizedNames&&c.localizedNames.length||(c.localizedNames=[]),c.localizedNames.push(p.proto.LocalizedName.decode(A,A.uint32()));break}case 10:{c.issueTime=A.uint64();break}default:A.skipType(I&7);break}}return c},i.fromObject=function(A){if(A instanceof p.proto.VerifiedNameCertificate.Details)return A;var r=new p.proto.VerifiedNameCertificate.Details;if(A.serial!=null&&(l.Long?(r.serial=l.Long.fromValue(A.serial)).unsigned=!0:typeof A.serial=="string"?r.serial=parseInt(A.serial,10):typeof A.serial=="number"?r.serial=A.serial:typeof A.serial=="object"&&(r.serial=new l.LongBits(A.serial.low>>>0,A.serial.high>>>0).toNumber(!0))),A.issuer!=null&&(r.issuer=String(A.issuer)),A.verifiedName!=null&&(r.verifiedName=String(A.verifiedName)),A.localizedNames){if(!Array.isArray(A.localizedNames))throw TypeError(".proto.VerifiedNameCertificate.Details.localizedNames: array expected");r.localizedNames=[];for(var s=0;s>>0,A.issueTime.high>>>0).toNumber(!0))),r},i.toObject=function(A,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.localizedNames=[]),A.serial!=null&&A.hasOwnProperty("serial")&&(typeof A.serial=="number"?s.serial=r.longs===String?String(A.serial):A.serial:s.serial=r.longs===String?se(A.serial,!0):r.longs===Number?ge(A.serial,!0):A.serial,r.oneofs&&(s._serial="serial")),A.issuer!=null&&A.hasOwnProperty("issuer")&&(s.issuer=A.issuer,r.oneofs&&(s._issuer="issuer")),A.verifiedName!=null&&A.hasOwnProperty("verifiedName")&&(s.verifiedName=A.verifiedName,r.oneofs&&(s._verifiedName="verifiedName")),A.localizedNames&&A.localizedNames.length){s.localizedNames=[];for(var g=0;g>>3){case 1:{s.filename=e.string();break}case 2:{s.opacity=e.uint32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.WallpaperSettings)return e;var a=new p.proto.WallpaperSettings;return e.filename!=null&&(a.filename=String(e.filename)),e.opacity!=null&&(a.opacity=e.opacity>>>0),a},t.toObject=function(e,a){a||(a={});var A={};return e.filename!=null&&e.hasOwnProperty("filename")&&(A.filename=e.filename,a.oneofs&&(A._filename="filename")),e.opacity!=null&&e.hasOwnProperty("opacity")&&(A.opacity=e.opacity,a.oneofs&&(A._opacity="opacity")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.WallpaperSettings"},t})(),n.WebFeatures=(function(){function t(i){if(i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.labelsDisplay=e.int32();break}case 2:{s.voipIndividualOutgoing=e.int32();break}case 3:{s.groupsV3=e.int32();break}case 4:{s.groupsV3Create=e.int32();break}case 5:{s.changeNumberV2=e.int32();break}case 6:{s.queryStatusV3Thumbnail=e.int32();break}case 7:{s.liveLocations=e.int32();break}case 8:{s.queryVname=e.int32();break}case 9:{s.voipIndividualIncoming=e.int32();break}case 10:{s.quickRepliesQuery=e.int32();break}case 11:{s.payments=e.int32();break}case 12:{s.stickerPackQuery=e.int32();break}case 13:{s.liveLocationsFinal=e.int32();break}case 14:{s.labelsEdit=e.int32();break}case 15:{s.mediaUpload=e.int32();break}case 18:{s.mediaUploadRichQuickReplies=e.int32();break}case 19:{s.vnameV2=e.int32();break}case 20:{s.videoPlaybackUrl=e.int32();break}case 21:{s.statusRanking=e.int32();break}case 22:{s.voipIndividualVideo=e.int32();break}case 23:{s.thirdPartyStickers=e.int32();break}case 24:{s.frequentlyForwardedSetting=e.int32();break}case 25:{s.groupsV4JoinPermission=e.int32();break}case 26:{s.recentStickers=e.int32();break}case 27:{s.catalog=e.int32();break}case 28:{s.starredStickers=e.int32();break}case 29:{s.voipGroupCall=e.int32();break}case 30:{s.templateMessage=e.int32();break}case 31:{s.templateMessageInteractivity=e.int32();break}case 32:{s.ephemeralMessages=e.int32();break}case 33:{s.e2ENotificationSync=e.int32();break}case 34:{s.recentStickersV2=e.int32();break}case 36:{s.recentStickersV3=e.int32();break}case 37:{s.userNotice=e.int32();break}case 39:{s.support=e.int32();break}case 40:{s.groupUiiCleanup=e.int32();break}case 41:{s.groupDogfoodingInternalOnly=e.int32();break}case 42:{s.settingsSync=e.int32();break}case 43:{s.archiveV2=e.int32();break}case 44:{s.ephemeralAllowGroupMembers=e.int32();break}case 45:{s.ephemeral24HDuration=e.int32();break}case 46:{s.mdForceUpgrade=e.int32();break}case 47:{s.disappearingMode=e.int32();break}case 48:{s.externalMdOptInAvailable=e.int32();break}case 49:{s.noDeleteMessageTimeLimit=e.int32();break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.WebFeatures)return e;var a=new p.proto.WebFeatures;switch(e.labelsDisplay){default:if(typeof e.labelsDisplay=="number"){a.labelsDisplay=e.labelsDisplay;break}break;case"NOT_STARTED":case 0:a.labelsDisplay=0;break;case"FORCE_UPGRADE":case 1:a.labelsDisplay=1;break;case"DEVELOPMENT":case 2:a.labelsDisplay=2;break;case"PRODUCTION":case 3:a.labelsDisplay=3;break}switch(e.voipIndividualOutgoing){default:if(typeof e.voipIndividualOutgoing=="number"){a.voipIndividualOutgoing=e.voipIndividualOutgoing;break}break;case"NOT_STARTED":case 0:a.voipIndividualOutgoing=0;break;case"FORCE_UPGRADE":case 1:a.voipIndividualOutgoing=1;break;case"DEVELOPMENT":case 2:a.voipIndividualOutgoing=2;break;case"PRODUCTION":case 3:a.voipIndividualOutgoing=3;break}switch(e.groupsV3){default:if(typeof e.groupsV3=="number"){a.groupsV3=e.groupsV3;break}break;case"NOT_STARTED":case 0:a.groupsV3=0;break;case"FORCE_UPGRADE":case 1:a.groupsV3=1;break;case"DEVELOPMENT":case 2:a.groupsV3=2;break;case"PRODUCTION":case 3:a.groupsV3=3;break}switch(e.groupsV3Create){default:if(typeof e.groupsV3Create=="number"){a.groupsV3Create=e.groupsV3Create;break}break;case"NOT_STARTED":case 0:a.groupsV3Create=0;break;case"FORCE_UPGRADE":case 1:a.groupsV3Create=1;break;case"DEVELOPMENT":case 2:a.groupsV3Create=2;break;case"PRODUCTION":case 3:a.groupsV3Create=3;break}switch(e.changeNumberV2){default:if(typeof e.changeNumberV2=="number"){a.changeNumberV2=e.changeNumberV2;break}break;case"NOT_STARTED":case 0:a.changeNumberV2=0;break;case"FORCE_UPGRADE":case 1:a.changeNumberV2=1;break;case"DEVELOPMENT":case 2:a.changeNumberV2=2;break;case"PRODUCTION":case 3:a.changeNumberV2=3;break}switch(e.queryStatusV3Thumbnail){default:if(typeof e.queryStatusV3Thumbnail=="number"){a.queryStatusV3Thumbnail=e.queryStatusV3Thumbnail;break}break;case"NOT_STARTED":case 0:a.queryStatusV3Thumbnail=0;break;case"FORCE_UPGRADE":case 1:a.queryStatusV3Thumbnail=1;break;case"DEVELOPMENT":case 2:a.queryStatusV3Thumbnail=2;break;case"PRODUCTION":case 3:a.queryStatusV3Thumbnail=3;break}switch(e.liveLocations){default:if(typeof e.liveLocations=="number"){a.liveLocations=e.liveLocations;break}break;case"NOT_STARTED":case 0:a.liveLocations=0;break;case"FORCE_UPGRADE":case 1:a.liveLocations=1;break;case"DEVELOPMENT":case 2:a.liveLocations=2;break;case"PRODUCTION":case 3:a.liveLocations=3;break}switch(e.queryVname){default:if(typeof e.queryVname=="number"){a.queryVname=e.queryVname;break}break;case"NOT_STARTED":case 0:a.queryVname=0;break;case"FORCE_UPGRADE":case 1:a.queryVname=1;break;case"DEVELOPMENT":case 2:a.queryVname=2;break;case"PRODUCTION":case 3:a.queryVname=3;break}switch(e.voipIndividualIncoming){default:if(typeof e.voipIndividualIncoming=="number"){a.voipIndividualIncoming=e.voipIndividualIncoming;break}break;case"NOT_STARTED":case 0:a.voipIndividualIncoming=0;break;case"FORCE_UPGRADE":case 1:a.voipIndividualIncoming=1;break;case"DEVELOPMENT":case 2:a.voipIndividualIncoming=2;break;case"PRODUCTION":case 3:a.voipIndividualIncoming=3;break}switch(e.quickRepliesQuery){default:if(typeof e.quickRepliesQuery=="number"){a.quickRepliesQuery=e.quickRepliesQuery;break}break;case"NOT_STARTED":case 0:a.quickRepliesQuery=0;break;case"FORCE_UPGRADE":case 1:a.quickRepliesQuery=1;break;case"DEVELOPMENT":case 2:a.quickRepliesQuery=2;break;case"PRODUCTION":case 3:a.quickRepliesQuery=3;break}switch(e.payments){default:if(typeof e.payments=="number"){a.payments=e.payments;break}break;case"NOT_STARTED":case 0:a.payments=0;break;case"FORCE_UPGRADE":case 1:a.payments=1;break;case"DEVELOPMENT":case 2:a.payments=2;break;case"PRODUCTION":case 3:a.payments=3;break}switch(e.stickerPackQuery){default:if(typeof e.stickerPackQuery=="number"){a.stickerPackQuery=e.stickerPackQuery;break}break;case"NOT_STARTED":case 0:a.stickerPackQuery=0;break;case"FORCE_UPGRADE":case 1:a.stickerPackQuery=1;break;case"DEVELOPMENT":case 2:a.stickerPackQuery=2;break;case"PRODUCTION":case 3:a.stickerPackQuery=3;break}switch(e.liveLocationsFinal){default:if(typeof e.liveLocationsFinal=="number"){a.liveLocationsFinal=e.liveLocationsFinal;break}break;case"NOT_STARTED":case 0:a.liveLocationsFinal=0;break;case"FORCE_UPGRADE":case 1:a.liveLocationsFinal=1;break;case"DEVELOPMENT":case 2:a.liveLocationsFinal=2;break;case"PRODUCTION":case 3:a.liveLocationsFinal=3;break}switch(e.labelsEdit){default:if(typeof e.labelsEdit=="number"){a.labelsEdit=e.labelsEdit;break}break;case"NOT_STARTED":case 0:a.labelsEdit=0;break;case"FORCE_UPGRADE":case 1:a.labelsEdit=1;break;case"DEVELOPMENT":case 2:a.labelsEdit=2;break;case"PRODUCTION":case 3:a.labelsEdit=3;break}switch(e.mediaUpload){default:if(typeof e.mediaUpload=="number"){a.mediaUpload=e.mediaUpload;break}break;case"NOT_STARTED":case 0:a.mediaUpload=0;break;case"FORCE_UPGRADE":case 1:a.mediaUpload=1;break;case"DEVELOPMENT":case 2:a.mediaUpload=2;break;case"PRODUCTION":case 3:a.mediaUpload=3;break}switch(e.mediaUploadRichQuickReplies){default:if(typeof e.mediaUploadRichQuickReplies=="number"){a.mediaUploadRichQuickReplies=e.mediaUploadRichQuickReplies;break}break;case"NOT_STARTED":case 0:a.mediaUploadRichQuickReplies=0;break;case"FORCE_UPGRADE":case 1:a.mediaUploadRichQuickReplies=1;break;case"DEVELOPMENT":case 2:a.mediaUploadRichQuickReplies=2;break;case"PRODUCTION":case 3:a.mediaUploadRichQuickReplies=3;break}switch(e.vnameV2){default:if(typeof e.vnameV2=="number"){a.vnameV2=e.vnameV2;break}break;case"NOT_STARTED":case 0:a.vnameV2=0;break;case"FORCE_UPGRADE":case 1:a.vnameV2=1;break;case"DEVELOPMENT":case 2:a.vnameV2=2;break;case"PRODUCTION":case 3:a.vnameV2=3;break}switch(e.videoPlaybackUrl){default:if(typeof e.videoPlaybackUrl=="number"){a.videoPlaybackUrl=e.videoPlaybackUrl;break}break;case"NOT_STARTED":case 0:a.videoPlaybackUrl=0;break;case"FORCE_UPGRADE":case 1:a.videoPlaybackUrl=1;break;case"DEVELOPMENT":case 2:a.videoPlaybackUrl=2;break;case"PRODUCTION":case 3:a.videoPlaybackUrl=3;break}switch(e.statusRanking){default:if(typeof e.statusRanking=="number"){a.statusRanking=e.statusRanking;break}break;case"NOT_STARTED":case 0:a.statusRanking=0;break;case"FORCE_UPGRADE":case 1:a.statusRanking=1;break;case"DEVELOPMENT":case 2:a.statusRanking=2;break;case"PRODUCTION":case 3:a.statusRanking=3;break}switch(e.voipIndividualVideo){default:if(typeof e.voipIndividualVideo=="number"){a.voipIndividualVideo=e.voipIndividualVideo;break}break;case"NOT_STARTED":case 0:a.voipIndividualVideo=0;break;case"FORCE_UPGRADE":case 1:a.voipIndividualVideo=1;break;case"DEVELOPMENT":case 2:a.voipIndividualVideo=2;break;case"PRODUCTION":case 3:a.voipIndividualVideo=3;break}switch(e.thirdPartyStickers){default:if(typeof e.thirdPartyStickers=="number"){a.thirdPartyStickers=e.thirdPartyStickers;break}break;case"NOT_STARTED":case 0:a.thirdPartyStickers=0;break;case"FORCE_UPGRADE":case 1:a.thirdPartyStickers=1;break;case"DEVELOPMENT":case 2:a.thirdPartyStickers=2;break;case"PRODUCTION":case 3:a.thirdPartyStickers=3;break}switch(e.frequentlyForwardedSetting){default:if(typeof e.frequentlyForwardedSetting=="number"){a.frequentlyForwardedSetting=e.frequentlyForwardedSetting;break}break;case"NOT_STARTED":case 0:a.frequentlyForwardedSetting=0;break;case"FORCE_UPGRADE":case 1:a.frequentlyForwardedSetting=1;break;case"DEVELOPMENT":case 2:a.frequentlyForwardedSetting=2;break;case"PRODUCTION":case 3:a.frequentlyForwardedSetting=3;break}switch(e.groupsV4JoinPermission){default:if(typeof e.groupsV4JoinPermission=="number"){a.groupsV4JoinPermission=e.groupsV4JoinPermission;break}break;case"NOT_STARTED":case 0:a.groupsV4JoinPermission=0;break;case"FORCE_UPGRADE":case 1:a.groupsV4JoinPermission=1;break;case"DEVELOPMENT":case 2:a.groupsV4JoinPermission=2;break;case"PRODUCTION":case 3:a.groupsV4JoinPermission=3;break}switch(e.recentStickers){default:if(typeof e.recentStickers=="number"){a.recentStickers=e.recentStickers;break}break;case"NOT_STARTED":case 0:a.recentStickers=0;break;case"FORCE_UPGRADE":case 1:a.recentStickers=1;break;case"DEVELOPMENT":case 2:a.recentStickers=2;break;case"PRODUCTION":case 3:a.recentStickers=3;break}switch(e.catalog){default:if(typeof e.catalog=="number"){a.catalog=e.catalog;break}break;case"NOT_STARTED":case 0:a.catalog=0;break;case"FORCE_UPGRADE":case 1:a.catalog=1;break;case"DEVELOPMENT":case 2:a.catalog=2;break;case"PRODUCTION":case 3:a.catalog=3;break}switch(e.starredStickers){default:if(typeof e.starredStickers=="number"){a.starredStickers=e.starredStickers;break}break;case"NOT_STARTED":case 0:a.starredStickers=0;break;case"FORCE_UPGRADE":case 1:a.starredStickers=1;break;case"DEVELOPMENT":case 2:a.starredStickers=2;break;case"PRODUCTION":case 3:a.starredStickers=3;break}switch(e.voipGroupCall){default:if(typeof e.voipGroupCall=="number"){a.voipGroupCall=e.voipGroupCall;break}break;case"NOT_STARTED":case 0:a.voipGroupCall=0;break;case"FORCE_UPGRADE":case 1:a.voipGroupCall=1;break;case"DEVELOPMENT":case 2:a.voipGroupCall=2;break;case"PRODUCTION":case 3:a.voipGroupCall=3;break}switch(e.templateMessage){default:if(typeof e.templateMessage=="number"){a.templateMessage=e.templateMessage;break}break;case"NOT_STARTED":case 0:a.templateMessage=0;break;case"FORCE_UPGRADE":case 1:a.templateMessage=1;break;case"DEVELOPMENT":case 2:a.templateMessage=2;break;case"PRODUCTION":case 3:a.templateMessage=3;break}switch(e.templateMessageInteractivity){default:if(typeof e.templateMessageInteractivity=="number"){a.templateMessageInteractivity=e.templateMessageInteractivity;break}break;case"NOT_STARTED":case 0:a.templateMessageInteractivity=0;break;case"FORCE_UPGRADE":case 1:a.templateMessageInteractivity=1;break;case"DEVELOPMENT":case 2:a.templateMessageInteractivity=2;break;case"PRODUCTION":case 3:a.templateMessageInteractivity=3;break}switch(e.ephemeralMessages){default:if(typeof e.ephemeralMessages=="number"){a.ephemeralMessages=e.ephemeralMessages;break}break;case"NOT_STARTED":case 0:a.ephemeralMessages=0;break;case"FORCE_UPGRADE":case 1:a.ephemeralMessages=1;break;case"DEVELOPMENT":case 2:a.ephemeralMessages=2;break;case"PRODUCTION":case 3:a.ephemeralMessages=3;break}switch(e.e2ENotificationSync){default:if(typeof e.e2ENotificationSync=="number"){a.e2ENotificationSync=e.e2ENotificationSync;break}break;case"NOT_STARTED":case 0:a.e2ENotificationSync=0;break;case"FORCE_UPGRADE":case 1:a.e2ENotificationSync=1;break;case"DEVELOPMENT":case 2:a.e2ENotificationSync=2;break;case"PRODUCTION":case 3:a.e2ENotificationSync=3;break}switch(e.recentStickersV2){default:if(typeof e.recentStickersV2=="number"){a.recentStickersV2=e.recentStickersV2;break}break;case"NOT_STARTED":case 0:a.recentStickersV2=0;break;case"FORCE_UPGRADE":case 1:a.recentStickersV2=1;break;case"DEVELOPMENT":case 2:a.recentStickersV2=2;break;case"PRODUCTION":case 3:a.recentStickersV2=3;break}switch(e.recentStickersV3){default:if(typeof e.recentStickersV3=="number"){a.recentStickersV3=e.recentStickersV3;break}break;case"NOT_STARTED":case 0:a.recentStickersV3=0;break;case"FORCE_UPGRADE":case 1:a.recentStickersV3=1;break;case"DEVELOPMENT":case 2:a.recentStickersV3=2;break;case"PRODUCTION":case 3:a.recentStickersV3=3;break}switch(e.userNotice){default:if(typeof e.userNotice=="number"){a.userNotice=e.userNotice;break}break;case"NOT_STARTED":case 0:a.userNotice=0;break;case"FORCE_UPGRADE":case 1:a.userNotice=1;break;case"DEVELOPMENT":case 2:a.userNotice=2;break;case"PRODUCTION":case 3:a.userNotice=3;break}switch(e.support){default:if(typeof e.support=="number"){a.support=e.support;break}break;case"NOT_STARTED":case 0:a.support=0;break;case"FORCE_UPGRADE":case 1:a.support=1;break;case"DEVELOPMENT":case 2:a.support=2;break;case"PRODUCTION":case 3:a.support=3;break}switch(e.groupUiiCleanup){default:if(typeof e.groupUiiCleanup=="number"){a.groupUiiCleanup=e.groupUiiCleanup;break}break;case"NOT_STARTED":case 0:a.groupUiiCleanup=0;break;case"FORCE_UPGRADE":case 1:a.groupUiiCleanup=1;break;case"DEVELOPMENT":case 2:a.groupUiiCleanup=2;break;case"PRODUCTION":case 3:a.groupUiiCleanup=3;break}switch(e.groupDogfoodingInternalOnly){default:if(typeof e.groupDogfoodingInternalOnly=="number"){a.groupDogfoodingInternalOnly=e.groupDogfoodingInternalOnly;break}break;case"NOT_STARTED":case 0:a.groupDogfoodingInternalOnly=0;break;case"FORCE_UPGRADE":case 1:a.groupDogfoodingInternalOnly=1;break;case"DEVELOPMENT":case 2:a.groupDogfoodingInternalOnly=2;break;case"PRODUCTION":case 3:a.groupDogfoodingInternalOnly=3;break}switch(e.settingsSync){default:if(typeof e.settingsSync=="number"){a.settingsSync=e.settingsSync;break}break;case"NOT_STARTED":case 0:a.settingsSync=0;break;case"FORCE_UPGRADE":case 1:a.settingsSync=1;break;case"DEVELOPMENT":case 2:a.settingsSync=2;break;case"PRODUCTION":case 3:a.settingsSync=3;break}switch(e.archiveV2){default:if(typeof e.archiveV2=="number"){a.archiveV2=e.archiveV2;break}break;case"NOT_STARTED":case 0:a.archiveV2=0;break;case"FORCE_UPGRADE":case 1:a.archiveV2=1;break;case"DEVELOPMENT":case 2:a.archiveV2=2;break;case"PRODUCTION":case 3:a.archiveV2=3;break}switch(e.ephemeralAllowGroupMembers){default:if(typeof e.ephemeralAllowGroupMembers=="number"){a.ephemeralAllowGroupMembers=e.ephemeralAllowGroupMembers;break}break;case"NOT_STARTED":case 0:a.ephemeralAllowGroupMembers=0;break;case"FORCE_UPGRADE":case 1:a.ephemeralAllowGroupMembers=1;break;case"DEVELOPMENT":case 2:a.ephemeralAllowGroupMembers=2;break;case"PRODUCTION":case 3:a.ephemeralAllowGroupMembers=3;break}switch(e.ephemeral24HDuration){default:if(typeof e.ephemeral24HDuration=="number"){a.ephemeral24HDuration=e.ephemeral24HDuration;break}break;case"NOT_STARTED":case 0:a.ephemeral24HDuration=0;break;case"FORCE_UPGRADE":case 1:a.ephemeral24HDuration=1;break;case"DEVELOPMENT":case 2:a.ephemeral24HDuration=2;break;case"PRODUCTION":case 3:a.ephemeral24HDuration=3;break}switch(e.mdForceUpgrade){default:if(typeof e.mdForceUpgrade=="number"){a.mdForceUpgrade=e.mdForceUpgrade;break}break;case"NOT_STARTED":case 0:a.mdForceUpgrade=0;break;case"FORCE_UPGRADE":case 1:a.mdForceUpgrade=1;break;case"DEVELOPMENT":case 2:a.mdForceUpgrade=2;break;case"PRODUCTION":case 3:a.mdForceUpgrade=3;break}switch(e.disappearingMode){default:if(typeof e.disappearingMode=="number"){a.disappearingMode=e.disappearingMode;break}break;case"NOT_STARTED":case 0:a.disappearingMode=0;break;case"FORCE_UPGRADE":case 1:a.disappearingMode=1;break;case"DEVELOPMENT":case 2:a.disappearingMode=2;break;case"PRODUCTION":case 3:a.disappearingMode=3;break}switch(e.externalMdOptInAvailable){default:if(typeof e.externalMdOptInAvailable=="number"){a.externalMdOptInAvailable=e.externalMdOptInAvailable;break}break;case"NOT_STARTED":case 0:a.externalMdOptInAvailable=0;break;case"FORCE_UPGRADE":case 1:a.externalMdOptInAvailable=1;break;case"DEVELOPMENT":case 2:a.externalMdOptInAvailable=2;break;case"PRODUCTION":case 3:a.externalMdOptInAvailable=3;break}switch(e.noDeleteMessageTimeLimit){default:if(typeof e.noDeleteMessageTimeLimit=="number"){a.noDeleteMessageTimeLimit=e.noDeleteMessageTimeLimit;break}break;case"NOT_STARTED":case 0:a.noDeleteMessageTimeLimit=0;break;case"FORCE_UPGRADE":case 1:a.noDeleteMessageTimeLimit=1;break;case"DEVELOPMENT":case 2:a.noDeleteMessageTimeLimit=2;break;case"PRODUCTION":case 3:a.noDeleteMessageTimeLimit=3;break}return a},t.toObject=function(e,a){a||(a={});var A={};return e.labelsDisplay!=null&&e.hasOwnProperty("labelsDisplay")&&(A.labelsDisplay=a.enums===String?p.proto.WebFeatures.Flag[e.labelsDisplay]===void 0?e.labelsDisplay:p.proto.WebFeatures.Flag[e.labelsDisplay]:e.labelsDisplay,a.oneofs&&(A._labelsDisplay="labelsDisplay")),e.voipIndividualOutgoing!=null&&e.hasOwnProperty("voipIndividualOutgoing")&&(A.voipIndividualOutgoing=a.enums===String?p.proto.WebFeatures.Flag[e.voipIndividualOutgoing]===void 0?e.voipIndividualOutgoing:p.proto.WebFeatures.Flag[e.voipIndividualOutgoing]:e.voipIndividualOutgoing,a.oneofs&&(A._voipIndividualOutgoing="voipIndividualOutgoing")),e.groupsV3!=null&&e.hasOwnProperty("groupsV3")&&(A.groupsV3=a.enums===String?p.proto.WebFeatures.Flag[e.groupsV3]===void 0?e.groupsV3:p.proto.WebFeatures.Flag[e.groupsV3]:e.groupsV3,a.oneofs&&(A._groupsV3="groupsV3")),e.groupsV3Create!=null&&e.hasOwnProperty("groupsV3Create")&&(A.groupsV3Create=a.enums===String?p.proto.WebFeatures.Flag[e.groupsV3Create]===void 0?e.groupsV3Create:p.proto.WebFeatures.Flag[e.groupsV3Create]:e.groupsV3Create,a.oneofs&&(A._groupsV3Create="groupsV3Create")),e.changeNumberV2!=null&&e.hasOwnProperty("changeNumberV2")&&(A.changeNumberV2=a.enums===String?p.proto.WebFeatures.Flag[e.changeNumberV2]===void 0?e.changeNumberV2:p.proto.WebFeatures.Flag[e.changeNumberV2]:e.changeNumberV2,a.oneofs&&(A._changeNumberV2="changeNumberV2")),e.queryStatusV3Thumbnail!=null&&e.hasOwnProperty("queryStatusV3Thumbnail")&&(A.queryStatusV3Thumbnail=a.enums===String?p.proto.WebFeatures.Flag[e.queryStatusV3Thumbnail]===void 0?e.queryStatusV3Thumbnail:p.proto.WebFeatures.Flag[e.queryStatusV3Thumbnail]:e.queryStatusV3Thumbnail,a.oneofs&&(A._queryStatusV3Thumbnail="queryStatusV3Thumbnail")),e.liveLocations!=null&&e.hasOwnProperty("liveLocations")&&(A.liveLocations=a.enums===String?p.proto.WebFeatures.Flag[e.liveLocations]===void 0?e.liveLocations:p.proto.WebFeatures.Flag[e.liveLocations]:e.liveLocations,a.oneofs&&(A._liveLocations="liveLocations")),e.queryVname!=null&&e.hasOwnProperty("queryVname")&&(A.queryVname=a.enums===String?p.proto.WebFeatures.Flag[e.queryVname]===void 0?e.queryVname:p.proto.WebFeatures.Flag[e.queryVname]:e.queryVname,a.oneofs&&(A._queryVname="queryVname")),e.voipIndividualIncoming!=null&&e.hasOwnProperty("voipIndividualIncoming")&&(A.voipIndividualIncoming=a.enums===String?p.proto.WebFeatures.Flag[e.voipIndividualIncoming]===void 0?e.voipIndividualIncoming:p.proto.WebFeatures.Flag[e.voipIndividualIncoming]:e.voipIndividualIncoming,a.oneofs&&(A._voipIndividualIncoming="voipIndividualIncoming")),e.quickRepliesQuery!=null&&e.hasOwnProperty("quickRepliesQuery")&&(A.quickRepliesQuery=a.enums===String?p.proto.WebFeatures.Flag[e.quickRepliesQuery]===void 0?e.quickRepliesQuery:p.proto.WebFeatures.Flag[e.quickRepliesQuery]:e.quickRepliesQuery,a.oneofs&&(A._quickRepliesQuery="quickRepliesQuery")),e.payments!=null&&e.hasOwnProperty("payments")&&(A.payments=a.enums===String?p.proto.WebFeatures.Flag[e.payments]===void 0?e.payments:p.proto.WebFeatures.Flag[e.payments]:e.payments,a.oneofs&&(A._payments="payments")),e.stickerPackQuery!=null&&e.hasOwnProperty("stickerPackQuery")&&(A.stickerPackQuery=a.enums===String?p.proto.WebFeatures.Flag[e.stickerPackQuery]===void 0?e.stickerPackQuery:p.proto.WebFeatures.Flag[e.stickerPackQuery]:e.stickerPackQuery,a.oneofs&&(A._stickerPackQuery="stickerPackQuery")),e.liveLocationsFinal!=null&&e.hasOwnProperty("liveLocationsFinal")&&(A.liveLocationsFinal=a.enums===String?p.proto.WebFeatures.Flag[e.liveLocationsFinal]===void 0?e.liveLocationsFinal:p.proto.WebFeatures.Flag[e.liveLocationsFinal]:e.liveLocationsFinal,a.oneofs&&(A._liveLocationsFinal="liveLocationsFinal")),e.labelsEdit!=null&&e.hasOwnProperty("labelsEdit")&&(A.labelsEdit=a.enums===String?p.proto.WebFeatures.Flag[e.labelsEdit]===void 0?e.labelsEdit:p.proto.WebFeatures.Flag[e.labelsEdit]:e.labelsEdit,a.oneofs&&(A._labelsEdit="labelsEdit")),e.mediaUpload!=null&&e.hasOwnProperty("mediaUpload")&&(A.mediaUpload=a.enums===String?p.proto.WebFeatures.Flag[e.mediaUpload]===void 0?e.mediaUpload:p.proto.WebFeatures.Flag[e.mediaUpload]:e.mediaUpload,a.oneofs&&(A._mediaUpload="mediaUpload")),e.mediaUploadRichQuickReplies!=null&&e.hasOwnProperty("mediaUploadRichQuickReplies")&&(A.mediaUploadRichQuickReplies=a.enums===String?p.proto.WebFeatures.Flag[e.mediaUploadRichQuickReplies]===void 0?e.mediaUploadRichQuickReplies:p.proto.WebFeatures.Flag[e.mediaUploadRichQuickReplies]:e.mediaUploadRichQuickReplies,a.oneofs&&(A._mediaUploadRichQuickReplies="mediaUploadRichQuickReplies")),e.vnameV2!=null&&e.hasOwnProperty("vnameV2")&&(A.vnameV2=a.enums===String?p.proto.WebFeatures.Flag[e.vnameV2]===void 0?e.vnameV2:p.proto.WebFeatures.Flag[e.vnameV2]:e.vnameV2,a.oneofs&&(A._vnameV2="vnameV2")),e.videoPlaybackUrl!=null&&e.hasOwnProperty("videoPlaybackUrl")&&(A.videoPlaybackUrl=a.enums===String?p.proto.WebFeatures.Flag[e.videoPlaybackUrl]===void 0?e.videoPlaybackUrl:p.proto.WebFeatures.Flag[e.videoPlaybackUrl]:e.videoPlaybackUrl,a.oneofs&&(A._videoPlaybackUrl="videoPlaybackUrl")),e.statusRanking!=null&&e.hasOwnProperty("statusRanking")&&(A.statusRanking=a.enums===String?p.proto.WebFeatures.Flag[e.statusRanking]===void 0?e.statusRanking:p.proto.WebFeatures.Flag[e.statusRanking]:e.statusRanking,a.oneofs&&(A._statusRanking="statusRanking")),e.voipIndividualVideo!=null&&e.hasOwnProperty("voipIndividualVideo")&&(A.voipIndividualVideo=a.enums===String?p.proto.WebFeatures.Flag[e.voipIndividualVideo]===void 0?e.voipIndividualVideo:p.proto.WebFeatures.Flag[e.voipIndividualVideo]:e.voipIndividualVideo,a.oneofs&&(A._voipIndividualVideo="voipIndividualVideo")),e.thirdPartyStickers!=null&&e.hasOwnProperty("thirdPartyStickers")&&(A.thirdPartyStickers=a.enums===String?p.proto.WebFeatures.Flag[e.thirdPartyStickers]===void 0?e.thirdPartyStickers:p.proto.WebFeatures.Flag[e.thirdPartyStickers]:e.thirdPartyStickers,a.oneofs&&(A._thirdPartyStickers="thirdPartyStickers")),e.frequentlyForwardedSetting!=null&&e.hasOwnProperty("frequentlyForwardedSetting")&&(A.frequentlyForwardedSetting=a.enums===String?p.proto.WebFeatures.Flag[e.frequentlyForwardedSetting]===void 0?e.frequentlyForwardedSetting:p.proto.WebFeatures.Flag[e.frequentlyForwardedSetting]:e.frequentlyForwardedSetting,a.oneofs&&(A._frequentlyForwardedSetting="frequentlyForwardedSetting")),e.groupsV4JoinPermission!=null&&e.hasOwnProperty("groupsV4JoinPermission")&&(A.groupsV4JoinPermission=a.enums===String?p.proto.WebFeatures.Flag[e.groupsV4JoinPermission]===void 0?e.groupsV4JoinPermission:p.proto.WebFeatures.Flag[e.groupsV4JoinPermission]:e.groupsV4JoinPermission,a.oneofs&&(A._groupsV4JoinPermission="groupsV4JoinPermission")),e.recentStickers!=null&&e.hasOwnProperty("recentStickers")&&(A.recentStickers=a.enums===String?p.proto.WebFeatures.Flag[e.recentStickers]===void 0?e.recentStickers:p.proto.WebFeatures.Flag[e.recentStickers]:e.recentStickers,a.oneofs&&(A._recentStickers="recentStickers")),e.catalog!=null&&e.hasOwnProperty("catalog")&&(A.catalog=a.enums===String?p.proto.WebFeatures.Flag[e.catalog]===void 0?e.catalog:p.proto.WebFeatures.Flag[e.catalog]:e.catalog,a.oneofs&&(A._catalog="catalog")),e.starredStickers!=null&&e.hasOwnProperty("starredStickers")&&(A.starredStickers=a.enums===String?p.proto.WebFeatures.Flag[e.starredStickers]===void 0?e.starredStickers:p.proto.WebFeatures.Flag[e.starredStickers]:e.starredStickers,a.oneofs&&(A._starredStickers="starredStickers")),e.voipGroupCall!=null&&e.hasOwnProperty("voipGroupCall")&&(A.voipGroupCall=a.enums===String?p.proto.WebFeatures.Flag[e.voipGroupCall]===void 0?e.voipGroupCall:p.proto.WebFeatures.Flag[e.voipGroupCall]:e.voipGroupCall,a.oneofs&&(A._voipGroupCall="voipGroupCall")),e.templateMessage!=null&&e.hasOwnProperty("templateMessage")&&(A.templateMessage=a.enums===String?p.proto.WebFeatures.Flag[e.templateMessage]===void 0?e.templateMessage:p.proto.WebFeatures.Flag[e.templateMessage]:e.templateMessage,a.oneofs&&(A._templateMessage="templateMessage")),e.templateMessageInteractivity!=null&&e.hasOwnProperty("templateMessageInteractivity")&&(A.templateMessageInteractivity=a.enums===String?p.proto.WebFeatures.Flag[e.templateMessageInteractivity]===void 0?e.templateMessageInteractivity:p.proto.WebFeatures.Flag[e.templateMessageInteractivity]:e.templateMessageInteractivity,a.oneofs&&(A._templateMessageInteractivity="templateMessageInteractivity")),e.ephemeralMessages!=null&&e.hasOwnProperty("ephemeralMessages")&&(A.ephemeralMessages=a.enums===String?p.proto.WebFeatures.Flag[e.ephemeralMessages]===void 0?e.ephemeralMessages:p.proto.WebFeatures.Flag[e.ephemeralMessages]:e.ephemeralMessages,a.oneofs&&(A._ephemeralMessages="ephemeralMessages")),e.e2ENotificationSync!=null&&e.hasOwnProperty("e2ENotificationSync")&&(A.e2ENotificationSync=a.enums===String?p.proto.WebFeatures.Flag[e.e2ENotificationSync]===void 0?e.e2ENotificationSync:p.proto.WebFeatures.Flag[e.e2ENotificationSync]:e.e2ENotificationSync,a.oneofs&&(A._e2ENotificationSync="e2ENotificationSync")),e.recentStickersV2!=null&&e.hasOwnProperty("recentStickersV2")&&(A.recentStickersV2=a.enums===String?p.proto.WebFeatures.Flag[e.recentStickersV2]===void 0?e.recentStickersV2:p.proto.WebFeatures.Flag[e.recentStickersV2]:e.recentStickersV2,a.oneofs&&(A._recentStickersV2="recentStickersV2")),e.recentStickersV3!=null&&e.hasOwnProperty("recentStickersV3")&&(A.recentStickersV3=a.enums===String?p.proto.WebFeatures.Flag[e.recentStickersV3]===void 0?e.recentStickersV3:p.proto.WebFeatures.Flag[e.recentStickersV3]:e.recentStickersV3,a.oneofs&&(A._recentStickersV3="recentStickersV3")),e.userNotice!=null&&e.hasOwnProperty("userNotice")&&(A.userNotice=a.enums===String?p.proto.WebFeatures.Flag[e.userNotice]===void 0?e.userNotice:p.proto.WebFeatures.Flag[e.userNotice]:e.userNotice,a.oneofs&&(A._userNotice="userNotice")),e.support!=null&&e.hasOwnProperty("support")&&(A.support=a.enums===String?p.proto.WebFeatures.Flag[e.support]===void 0?e.support:p.proto.WebFeatures.Flag[e.support]:e.support,a.oneofs&&(A._support="support")),e.groupUiiCleanup!=null&&e.hasOwnProperty("groupUiiCleanup")&&(A.groupUiiCleanup=a.enums===String?p.proto.WebFeatures.Flag[e.groupUiiCleanup]===void 0?e.groupUiiCleanup:p.proto.WebFeatures.Flag[e.groupUiiCleanup]:e.groupUiiCleanup,a.oneofs&&(A._groupUiiCleanup="groupUiiCleanup")),e.groupDogfoodingInternalOnly!=null&&e.hasOwnProperty("groupDogfoodingInternalOnly")&&(A.groupDogfoodingInternalOnly=a.enums===String?p.proto.WebFeatures.Flag[e.groupDogfoodingInternalOnly]===void 0?e.groupDogfoodingInternalOnly:p.proto.WebFeatures.Flag[e.groupDogfoodingInternalOnly]:e.groupDogfoodingInternalOnly,a.oneofs&&(A._groupDogfoodingInternalOnly="groupDogfoodingInternalOnly")),e.settingsSync!=null&&e.hasOwnProperty("settingsSync")&&(A.settingsSync=a.enums===String?p.proto.WebFeatures.Flag[e.settingsSync]===void 0?e.settingsSync:p.proto.WebFeatures.Flag[e.settingsSync]:e.settingsSync,a.oneofs&&(A._settingsSync="settingsSync")),e.archiveV2!=null&&e.hasOwnProperty("archiveV2")&&(A.archiveV2=a.enums===String?p.proto.WebFeatures.Flag[e.archiveV2]===void 0?e.archiveV2:p.proto.WebFeatures.Flag[e.archiveV2]:e.archiveV2,a.oneofs&&(A._archiveV2="archiveV2")),e.ephemeralAllowGroupMembers!=null&&e.hasOwnProperty("ephemeralAllowGroupMembers")&&(A.ephemeralAllowGroupMembers=a.enums===String?p.proto.WebFeatures.Flag[e.ephemeralAllowGroupMembers]===void 0?e.ephemeralAllowGroupMembers:p.proto.WebFeatures.Flag[e.ephemeralAllowGroupMembers]:e.ephemeralAllowGroupMembers,a.oneofs&&(A._ephemeralAllowGroupMembers="ephemeralAllowGroupMembers")),e.ephemeral24HDuration!=null&&e.hasOwnProperty("ephemeral24HDuration")&&(A.ephemeral24HDuration=a.enums===String?p.proto.WebFeatures.Flag[e.ephemeral24HDuration]===void 0?e.ephemeral24HDuration:p.proto.WebFeatures.Flag[e.ephemeral24HDuration]:e.ephemeral24HDuration,a.oneofs&&(A._ephemeral24HDuration="ephemeral24HDuration")),e.mdForceUpgrade!=null&&e.hasOwnProperty("mdForceUpgrade")&&(A.mdForceUpgrade=a.enums===String?p.proto.WebFeatures.Flag[e.mdForceUpgrade]===void 0?e.mdForceUpgrade:p.proto.WebFeatures.Flag[e.mdForceUpgrade]:e.mdForceUpgrade,a.oneofs&&(A._mdForceUpgrade="mdForceUpgrade")),e.disappearingMode!=null&&e.hasOwnProperty("disappearingMode")&&(A.disappearingMode=a.enums===String?p.proto.WebFeatures.Flag[e.disappearingMode]===void 0?e.disappearingMode:p.proto.WebFeatures.Flag[e.disappearingMode]:e.disappearingMode,a.oneofs&&(A._disappearingMode="disappearingMode")),e.externalMdOptInAvailable!=null&&e.hasOwnProperty("externalMdOptInAvailable")&&(A.externalMdOptInAvailable=a.enums===String?p.proto.WebFeatures.Flag[e.externalMdOptInAvailable]===void 0?e.externalMdOptInAvailable:p.proto.WebFeatures.Flag[e.externalMdOptInAvailable]:e.externalMdOptInAvailable,a.oneofs&&(A._externalMdOptInAvailable="externalMdOptInAvailable")),e.noDeleteMessageTimeLimit!=null&&e.hasOwnProperty("noDeleteMessageTimeLimit")&&(A.noDeleteMessageTimeLimit=a.enums===String?p.proto.WebFeatures.Flag[e.noDeleteMessageTimeLimit]===void 0?e.noDeleteMessageTimeLimit:p.proto.WebFeatures.Flag[e.noDeleteMessageTimeLimit]:e.noDeleteMessageTimeLimit,a.oneofs&&(A._noDeleteMessageTimeLimit="noDeleteMessageTimeLimit")),A},t.prototype.toJSON=function(){return this.constructor.toObject(this,v.default.util.toJSONOptions)},t.getTypeUrl=function(e){return e===void 0&&(e="type.googleapis.com"),e+"/proto.WebFeatures"},t.Flag=(function(){let i={},e=Object.create(i);return e[i[0]="NOT_STARTED"]=0,e[i[1]="FORCE_UPGRADE"]=1,e[i[2]="DEVELOPMENT"]=2,e[i[3]="PRODUCTION"]=3,e})(),t})(),n.WebLinkRenderConfig=(function(){let t={},o=Object.create(t);return o[t[0]="WEBVIEW"]=0,o[t[1]="SYSTEM"]=1,o})(),n.WebMessageInfo=(function(){function t(i){if(this.messageStubParameters=[],this.labels=[],this.userReceipt=[],this.reactions=[],this.pollUpdates=[],this.eventResponses=[],this.statusMentions=[],this.messageAddOns=[],this.statusMentionSources=[],this.supportAiCitations=[],i)for(var e=Object.keys(i),a=0;a>>3){case 1:{s.key=p.proto.MessageKey.decode(e,e.uint32());break}case 2:{s.message=p.proto.Message.decode(e,e.uint32());break}case 3:{s.messageTimestamp=e.uint64();break}case 4:{s.status=e.int32();break}case 5:{s.participant=e.string();break}case 6:{s.messageC2STimestamp=e.uint64();break}case 16:{s.ignore=e.bool();break}case 17:{s.starred=e.bool();break}case 18:{s.broadcast=e.bool();break}case 19:{s.pushName=e.string();break}case 20:{s.mediaCiphertextSha256=e.bytes();break}case 21:{s.multicast=e.bool();break}case 22:{s.urlText=e.bool();break}case 23:{s.urlNumber=e.bool();break}case 24:{s.messageStubType=e.int32();break}case 25:{s.clearMedia=e.bool();break}case 26:{s.messageStubParameters&&s.messageStubParameters.length||(s.messageStubParameters=[]),s.messageStubParameters.push(e.string());break}case 27:{s.duration=e.uint32();break}case 28:{s.labels&&s.labels.length||(s.labels=[]),s.labels.push(e.string());break}case 29:{s.paymentInfo=p.proto.PaymentInfo.decode(e,e.uint32());break}case 30:{s.finalLiveLocation=p.proto.Message.LiveLocationMessage.decode(e,e.uint32());break}case 31:{s.quotedPaymentInfo=p.proto.PaymentInfo.decode(e,e.uint32());break}case 32:{s.ephemeralStartTimestamp=e.uint64();break}case 33:{s.ephemeralDuration=e.uint32();break}case 34:{s.ephemeralOffToOn=e.bool();break}case 35:{s.ephemeralOutOfSync=e.bool();break}case 36:{s.bizPrivacyStatus=e.int32();break}case 37:{s.verifiedBizName=e.string();break}case 38:{s.mediaData=p.proto.MediaData.decode(e,e.uint32());break}case 39:{s.photoChange=p.proto.PhotoChange.decode(e,e.uint32());break}case 40:{s.userReceipt&&s.userReceipt.length||(s.userReceipt=[]),s.userReceipt.push(p.proto.UserReceipt.decode(e,e.uint32()));break}case 41:{s.reactions&&s.reactions.length||(s.reactions=[]),s.reactions.push(p.proto.Reaction.decode(e,e.uint32()));break}case 42:{s.quotedStickerData=p.proto.MediaData.decode(e,e.uint32());break}case 43:{s.futureproofData=e.bytes();break}case 44:{s.statusPsa=p.proto.StatusPSA.decode(e,e.uint32());break}case 45:{s.pollUpdates&&s.pollUpdates.length||(s.pollUpdates=[]),s.pollUpdates.push(p.proto.PollUpdate.decode(e,e.uint32()));break}case 46:{s.pollAdditionalMetadata=p.proto.PollAdditionalMetadata.decode(e,e.uint32());break}case 47:{s.agentId=e.string();break}case 48:{s.statusAlreadyViewed=e.bool();break}case 49:{s.messageSecret=e.bytes();break}case 50:{s.keepInChat=p.proto.KeepInChat.decode(e,e.uint32());break}case 51:{s.originalSelfAuthorUserJidString=e.string();break}case 52:{s.revokeMessageTimestamp=e.uint64();break}case 54:{s.pinInChat=p.proto.PinInChat.decode(e,e.uint32());break}case 55:{s.premiumMessageInfo=p.proto.PremiumMessageInfo.decode(e,e.uint32());break}case 56:{s.is1PBizBotMessage=e.bool();break}case 57:{s.isGroupHistoryMessage=e.bool();break}case 58:{s.botMessageInvokerJid=e.string();break}case 59:{s.commentMetadata=p.proto.CommentMetadata.decode(e,e.uint32());break}case 61:{s.eventResponses&&s.eventResponses.length||(s.eventResponses=[]),s.eventResponses.push(p.proto.EventResponse.decode(e,e.uint32()));break}case 62:{s.reportingTokenInfo=p.proto.ReportingTokenInfo.decode(e,e.uint32());break}case 63:{s.newsletterServerId=e.uint64();break}case 64:{s.eventAdditionalMetadata=p.proto.EventAdditionalMetadata.decode(e,e.uint32());break}case 65:{s.isMentionedInStatus=e.bool();break}case 66:{s.statusMentions&&s.statusMentions.length||(s.statusMentions=[]),s.statusMentions.push(e.string());break}case 67:{s.targetMessageId=p.proto.MessageKey.decode(e,e.uint32());break}case 68:{s.messageAddOns&&s.messageAddOns.length||(s.messageAddOns=[]),s.messageAddOns.push(p.proto.MessageAddOn.decode(e,e.uint32()));break}case 69:{s.statusMentionMessageInfo=p.proto.StatusMentionMessage.decode(e,e.uint32());break}case 70:{s.isSupportAiMessage=e.bool();break}case 71:{s.statusMentionSources&&s.statusMentionSources.length||(s.statusMentionSources=[]),s.statusMentionSources.push(e.string());break}case 72:{s.supportAiCitations&&s.supportAiCitations.length||(s.supportAiCitations=[]),s.supportAiCitations.push(p.proto.Citation.decode(e,e.uint32()));break}case 73:{s.botTargetId=e.string();break}case 74:{s.groupHistoryIndividualMessageInfo=p.proto.GroupHistoryIndividualMessageInfo.decode(e,e.uint32());break}case 75:{s.groupHistoryBundleInfo=p.proto.GroupHistoryBundleInfo.decode(e,e.uint32());break}case 76:{s.interactiveMessageAdditionalMetadata=p.proto.InteractiveMessageAdditionalMetadata.decode(e,e.uint32());break}case 77:{s.quarantinedMessage=p.proto.QuarantinedMessage.decode(e,e.uint32());break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.WebMessageInfo)return e;var a=new p.proto.WebMessageInfo;if(e.key!=null){if(typeof e.key!="object")throw TypeError(".proto.WebMessageInfo.key: object expected");a.key=p.proto.MessageKey.fromObject(e.key)}if(e.message!=null){if(typeof e.message!="object")throw TypeError(".proto.WebMessageInfo.message: object expected");a.message=p.proto.Message.fromObject(e.message)}switch(e.messageTimestamp!=null&&(l.Long?(a.messageTimestamp=l.Long.fromValue(e.messageTimestamp)).unsigned=!0:typeof e.messageTimestamp=="string"?a.messageTimestamp=parseInt(e.messageTimestamp,10):typeof e.messageTimestamp=="number"?a.messageTimestamp=e.messageTimestamp:typeof e.messageTimestamp=="object"&&(a.messageTimestamp=new l.LongBits(e.messageTimestamp.low>>>0,e.messageTimestamp.high>>>0).toNumber(!0))),e.status){default:if(typeof e.status=="number"){a.status=e.status;break}break;case"ERROR":case 0:a.status=0;break;case"PENDING":case 1:a.status=1;break;case"SERVER_ACK":case 2:a.status=2;break;case"DELIVERY_ACK":case 3:a.status=3;break;case"READ":case 4:a.status=4;break;case"PLAYED":case 5:a.status=5;break}switch(e.participant!=null&&(a.participant=String(e.participant)),e.messageC2STimestamp!=null&&(l.Long?(a.messageC2STimestamp=l.Long.fromValue(e.messageC2STimestamp)).unsigned=!0:typeof e.messageC2STimestamp=="string"?a.messageC2STimestamp=parseInt(e.messageC2STimestamp,10):typeof e.messageC2STimestamp=="number"?a.messageC2STimestamp=e.messageC2STimestamp:typeof e.messageC2STimestamp=="object"&&(a.messageC2STimestamp=new l.LongBits(e.messageC2STimestamp.low>>>0,e.messageC2STimestamp.high>>>0).toNumber(!0))),e.ignore!=null&&(a.ignore=!!e.ignore),e.starred!=null&&(a.starred=!!e.starred),e.broadcast!=null&&(a.broadcast=!!e.broadcast),e.pushName!=null&&(a.pushName=String(e.pushName)),e.mediaCiphertextSha256!=null&&(typeof e.mediaCiphertextSha256=="string"?l.base64.decode(e.mediaCiphertextSha256,a.mediaCiphertextSha256=l.newBuffer(l.base64.length(e.mediaCiphertextSha256)),0):e.mediaCiphertextSha256.length>=0&&(a.mediaCiphertextSha256=e.mediaCiphertextSha256)),e.multicast!=null&&(a.multicast=!!e.multicast),e.urlText!=null&&(a.urlText=!!e.urlText),e.urlNumber!=null&&(a.urlNumber=!!e.urlNumber),e.messageStubType){default:if(typeof e.messageStubType=="number"){a.messageStubType=e.messageStubType;break}break;case"UNKNOWN":case 0:a.messageStubType=0;break;case"REVOKE":case 1:a.messageStubType=1;break;case"CIPHERTEXT":case 2:a.messageStubType=2;break;case"FUTUREPROOF":case 3:a.messageStubType=3;break;case"NON_VERIFIED_TRANSITION":case 4:a.messageStubType=4;break;case"UNVERIFIED_TRANSITION":case 5:a.messageStubType=5;break;case"VERIFIED_TRANSITION":case 6:a.messageStubType=6;break;case"VERIFIED_LOW_UNKNOWN":case 7:a.messageStubType=7;break;case"VERIFIED_HIGH":case 8:a.messageStubType=8;break;case"VERIFIED_INITIAL_UNKNOWN":case 9:a.messageStubType=9;break;case"VERIFIED_INITIAL_LOW":case 10:a.messageStubType=10;break;case"VERIFIED_INITIAL_HIGH":case 11:a.messageStubType=11;break;case"VERIFIED_TRANSITION_ANY_TO_NONE":case 12:a.messageStubType=12;break;case"VERIFIED_TRANSITION_ANY_TO_HIGH":case 13:a.messageStubType=13;break;case"VERIFIED_TRANSITION_HIGH_TO_LOW":case 14:a.messageStubType=14;break;case"VERIFIED_TRANSITION_HIGH_TO_UNKNOWN":case 15:a.messageStubType=15;break;case"VERIFIED_TRANSITION_UNKNOWN_TO_LOW":case 16:a.messageStubType=16;break;case"VERIFIED_TRANSITION_LOW_TO_UNKNOWN":case 17:a.messageStubType=17;break;case"VERIFIED_TRANSITION_NONE_TO_LOW":case 18:a.messageStubType=18;break;case"VERIFIED_TRANSITION_NONE_TO_UNKNOWN":case 19:a.messageStubType=19;break;case"GROUP_CREATE":case 20:a.messageStubType=20;break;case"GROUP_CHANGE_SUBJECT":case 21:a.messageStubType=21;break;case"GROUP_CHANGE_ICON":case 22:a.messageStubType=22;break;case"GROUP_CHANGE_INVITE_LINK":case 23:a.messageStubType=23;break;case"GROUP_CHANGE_DESCRIPTION":case 24:a.messageStubType=24;break;case"GROUP_CHANGE_RESTRICT":case 25:a.messageStubType=25;break;case"GROUP_CHANGE_ANNOUNCE":case 26:a.messageStubType=26;break;case"GROUP_PARTICIPANT_ADD":case 27:a.messageStubType=27;break;case"GROUP_PARTICIPANT_REMOVE":case 28:a.messageStubType=28;break;case"GROUP_PARTICIPANT_PROMOTE":case 29:a.messageStubType=29;break;case"GROUP_PARTICIPANT_DEMOTE":case 30:a.messageStubType=30;break;case"GROUP_PARTICIPANT_INVITE":case 31:a.messageStubType=31;break;case"GROUP_PARTICIPANT_LEAVE":case 32:a.messageStubType=32;break;case"GROUP_PARTICIPANT_CHANGE_NUMBER":case 33:a.messageStubType=33;break;case"BROADCAST_CREATE":case 34:a.messageStubType=34;break;case"BROADCAST_ADD":case 35:a.messageStubType=35;break;case"BROADCAST_REMOVE":case 36:a.messageStubType=36;break;case"GENERIC_NOTIFICATION":case 37:a.messageStubType=37;break;case"E2E_IDENTITY_CHANGED":case 38:a.messageStubType=38;break;case"E2E_ENCRYPTED":case 39:a.messageStubType=39;break;case"CALL_MISSED_VOICE":case 40:a.messageStubType=40;break;case"CALL_MISSED_VIDEO":case 41:a.messageStubType=41;break;case"INDIVIDUAL_CHANGE_NUMBER":case 42:a.messageStubType=42;break;case"GROUP_DELETE":case 43:a.messageStubType=43;break;case"GROUP_ANNOUNCE_MODE_MESSAGE_BOUNCE":case 44:a.messageStubType=44;break;case"CALL_MISSED_GROUP_VOICE":case 45:a.messageStubType=45;break;case"CALL_MISSED_GROUP_VIDEO":case 46:a.messageStubType=46;break;case"PAYMENT_CIPHERTEXT":case 47:a.messageStubType=47;break;case"PAYMENT_FUTUREPROOF":case 48:a.messageStubType=48;break;case"PAYMENT_TRANSACTION_STATUS_UPDATE_FAILED":case 49:a.messageStubType=49;break;case"PAYMENT_TRANSACTION_STATUS_UPDATE_REFUNDED":case 50:a.messageStubType=50;break;case"PAYMENT_TRANSACTION_STATUS_UPDATE_REFUND_FAILED":case 51:a.messageStubType=51;break;case"PAYMENT_TRANSACTION_STATUS_RECEIVER_PENDING_SETUP":case 52:a.messageStubType=52;break;case"PAYMENT_TRANSACTION_STATUS_RECEIVER_SUCCESS_AFTER_HICCUP":case 53:a.messageStubType=53;break;case"PAYMENT_ACTION_ACCOUNT_SETUP_REMINDER":case 54:a.messageStubType=54;break;case"PAYMENT_ACTION_SEND_PAYMENT_REMINDER":case 55:a.messageStubType=55;break;case"PAYMENT_ACTION_SEND_PAYMENT_INVITATION":case 56:a.messageStubType=56;break;case"PAYMENT_ACTION_REQUEST_DECLINED":case 57:a.messageStubType=57;break;case"PAYMENT_ACTION_REQUEST_EXPIRED":case 58:a.messageStubType=58;break;case"PAYMENT_ACTION_REQUEST_CANCELLED":case 59:a.messageStubType=59;break;case"BIZ_VERIFIED_TRANSITION_TOP_TO_BOTTOM":case 60:a.messageStubType=60;break;case"BIZ_VERIFIED_TRANSITION_BOTTOM_TO_TOP":case 61:a.messageStubType=61;break;case"BIZ_INTRO_TOP":case 62:a.messageStubType=62;break;case"BIZ_INTRO_BOTTOM":case 63:a.messageStubType=63;break;case"BIZ_NAME_CHANGE":case 64:a.messageStubType=64;break;case"BIZ_MOVE_TO_CONSUMER_APP":case 65:a.messageStubType=65;break;case"BIZ_TWO_TIER_MIGRATION_TOP":case 66:a.messageStubType=66;break;case"BIZ_TWO_TIER_MIGRATION_BOTTOM":case 67:a.messageStubType=67;break;case"OVERSIZED":case 68:a.messageStubType=68;break;case"GROUP_CHANGE_NO_FREQUENTLY_FORWARDED":case 69:a.messageStubType=69;break;case"GROUP_V4_ADD_INVITE_SENT":case 70:a.messageStubType=70;break;case"GROUP_PARTICIPANT_ADD_REQUEST_JOIN":case 71:a.messageStubType=71;break;case"CHANGE_EPHEMERAL_SETTING":case 72:a.messageStubType=72;break;case"E2E_DEVICE_CHANGED":case 73:a.messageStubType=73;break;case"VIEWED_ONCE":case 74:a.messageStubType=74;break;case"E2E_ENCRYPTED_NOW":case 75:a.messageStubType=75;break;case"BLUE_MSG_BSP_FB_TO_BSP_PREMISE":case 76:a.messageStubType=76;break;case"BLUE_MSG_BSP_FB_TO_SELF_FB":case 77:a.messageStubType=77;break;case"BLUE_MSG_BSP_FB_TO_SELF_PREMISE":case 78:a.messageStubType=78;break;case"BLUE_MSG_BSP_FB_UNVERIFIED":case 79:a.messageStubType=79;break;case"BLUE_MSG_BSP_FB_UNVERIFIED_TO_SELF_PREMISE_VERIFIED":case 80:a.messageStubType=80;break;case"BLUE_MSG_BSP_FB_VERIFIED":case 81:a.messageStubType=81;break;case"BLUE_MSG_BSP_FB_VERIFIED_TO_SELF_PREMISE_UNVERIFIED":case 82:a.messageStubType=82;break;case"BLUE_MSG_BSP_PREMISE_TO_SELF_PREMISE":case 83:a.messageStubType=83;break;case"BLUE_MSG_BSP_PREMISE_UNVERIFIED":case 84:a.messageStubType=84;break;case"BLUE_MSG_BSP_PREMISE_UNVERIFIED_TO_SELF_PREMISE_VERIFIED":case 85:a.messageStubType=85;break;case"BLUE_MSG_BSP_PREMISE_VERIFIED":case 86:a.messageStubType=86;break;case"BLUE_MSG_BSP_PREMISE_VERIFIED_TO_SELF_PREMISE_UNVERIFIED":case 87:a.messageStubType=87;break;case"BLUE_MSG_CONSUMER_TO_BSP_FB_UNVERIFIED":case 88:a.messageStubType=88;break;case"BLUE_MSG_CONSUMER_TO_BSP_PREMISE_UNVERIFIED":case 89:a.messageStubType=89;break;case"BLUE_MSG_CONSUMER_TO_SELF_FB_UNVERIFIED":case 90:a.messageStubType=90;break;case"BLUE_MSG_CONSUMER_TO_SELF_PREMISE_UNVERIFIED":case 91:a.messageStubType=91;break;case"BLUE_MSG_SELF_FB_TO_BSP_PREMISE":case 92:a.messageStubType=92;break;case"BLUE_MSG_SELF_FB_TO_SELF_PREMISE":case 93:a.messageStubType=93;break;case"BLUE_MSG_SELF_FB_UNVERIFIED":case 94:a.messageStubType=94;break;case"BLUE_MSG_SELF_FB_UNVERIFIED_TO_SELF_PREMISE_VERIFIED":case 95:a.messageStubType=95;break;case"BLUE_MSG_SELF_FB_VERIFIED":case 96:a.messageStubType=96;break;case"BLUE_MSG_SELF_FB_VERIFIED_TO_SELF_PREMISE_UNVERIFIED":case 97:a.messageStubType=97;break;case"BLUE_MSG_SELF_PREMISE_TO_BSP_PREMISE":case 98:a.messageStubType=98;break;case"BLUE_MSG_SELF_PREMISE_UNVERIFIED":case 99:a.messageStubType=99;break;case"BLUE_MSG_SELF_PREMISE_VERIFIED":case 100:a.messageStubType=100;break;case"BLUE_MSG_TO_BSP_FB":case 101:a.messageStubType=101;break;case"BLUE_MSG_TO_CONSUMER":case 102:a.messageStubType=102;break;case"BLUE_MSG_TO_SELF_FB":case 103:a.messageStubType=103;break;case"BLUE_MSG_UNVERIFIED_TO_BSP_FB_VERIFIED":case 104:a.messageStubType=104;break;case"BLUE_MSG_UNVERIFIED_TO_BSP_PREMISE_VERIFIED":case 105:a.messageStubType=105;break;case"BLUE_MSG_UNVERIFIED_TO_SELF_FB_VERIFIED":case 106:a.messageStubType=106;break;case"BLUE_MSG_UNVERIFIED_TO_VERIFIED":case 107:a.messageStubType=107;break;case"BLUE_MSG_VERIFIED_TO_BSP_FB_UNVERIFIED":case 108:a.messageStubType=108;break;case"BLUE_MSG_VERIFIED_TO_BSP_PREMISE_UNVERIFIED":case 109:a.messageStubType=109;break;case"BLUE_MSG_VERIFIED_TO_SELF_FB_UNVERIFIED":case 110:a.messageStubType=110;break;case"BLUE_MSG_VERIFIED_TO_UNVERIFIED":case 111:a.messageStubType=111;break;case"BLUE_MSG_BSP_FB_UNVERIFIED_TO_BSP_PREMISE_VERIFIED":case 112:a.messageStubType=112;break;case"BLUE_MSG_BSP_FB_UNVERIFIED_TO_SELF_FB_VERIFIED":case 113:a.messageStubType=113;break;case"BLUE_MSG_BSP_FB_VERIFIED_TO_BSP_PREMISE_UNVERIFIED":case 114:a.messageStubType=114;break;case"BLUE_MSG_BSP_FB_VERIFIED_TO_SELF_FB_UNVERIFIED":case 115:a.messageStubType=115;break;case"BLUE_MSG_SELF_FB_UNVERIFIED_TO_BSP_PREMISE_VERIFIED":case 116:a.messageStubType=116;break;case"BLUE_MSG_SELF_FB_VERIFIED_TO_BSP_PREMISE_UNVERIFIED":case 117:a.messageStubType=117;break;case"E2E_IDENTITY_UNAVAILABLE":case 118:a.messageStubType=118;break;case"GROUP_CREATING":case 119:a.messageStubType=119;break;case"GROUP_CREATE_FAILED":case 120:a.messageStubType=120;break;case"GROUP_BOUNCED":case 121:a.messageStubType=121;break;case"BLOCK_CONTACT":case 122:a.messageStubType=122;break;case"EPHEMERAL_SETTING_NOT_APPLIED":case 123:a.messageStubType=123;break;case"SYNC_FAILED":case 124:a.messageStubType=124;break;case"SYNCING":case 125:a.messageStubType=125;break;case"BIZ_PRIVACY_MODE_INIT_FB":case 126:a.messageStubType=126;break;case"BIZ_PRIVACY_MODE_INIT_BSP":case 127:a.messageStubType=127;break;case"BIZ_PRIVACY_MODE_TO_FB":case 128:a.messageStubType=128;break;case"BIZ_PRIVACY_MODE_TO_BSP":case 129:a.messageStubType=129;break;case"DISAPPEARING_MODE":case 130:a.messageStubType=130;break;case"E2E_DEVICE_FETCH_FAILED":case 131:a.messageStubType=131;break;case"ADMIN_REVOKE":case 132:a.messageStubType=132;break;case"GROUP_INVITE_LINK_GROWTH_LOCKED":case 133:a.messageStubType=133;break;case"COMMUNITY_LINK_PARENT_GROUP":case 134:a.messageStubType=134;break;case"COMMUNITY_LINK_SIBLING_GROUP":case 135:a.messageStubType=135;break;case"COMMUNITY_LINK_SUB_GROUP":case 136:a.messageStubType=136;break;case"COMMUNITY_UNLINK_PARENT_GROUP":case 137:a.messageStubType=137;break;case"COMMUNITY_UNLINK_SIBLING_GROUP":case 138:a.messageStubType=138;break;case"COMMUNITY_UNLINK_SUB_GROUP":case 139:a.messageStubType=139;break;case"GROUP_PARTICIPANT_ACCEPT":case 140:a.messageStubType=140;break;case"GROUP_PARTICIPANT_LINKED_GROUP_JOIN":case 141:a.messageStubType=141;break;case"COMMUNITY_CREATE":case 142:a.messageStubType=142;break;case"EPHEMERAL_KEEP_IN_CHAT":case 143:a.messageStubType=143;break;case"GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST":case 144:a.messageStubType=144;break;case"GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE":case 145:a.messageStubType=145;break;case"INTEGRITY_UNLINK_PARENT_GROUP":case 146:a.messageStubType=146;break;case"COMMUNITY_PARTICIPANT_PROMOTE":case 147:a.messageStubType=147;break;case"COMMUNITY_PARTICIPANT_DEMOTE":case 148:a.messageStubType=148;break;case"COMMUNITY_PARENT_GROUP_DELETED":case 149:a.messageStubType=149;break;case"COMMUNITY_LINK_PARENT_GROUP_MEMBERSHIP_APPROVAL":case 150:a.messageStubType=150;break;case"GROUP_PARTICIPANT_JOINED_GROUP_AND_PARENT_GROUP":case 151:a.messageStubType=151;break;case"MASKED_THREAD_CREATED":case 152:a.messageStubType=152;break;case"MASKED_THREAD_UNMASKED":case 153:a.messageStubType=153;break;case"BIZ_CHAT_ASSIGNMENT":case 154:a.messageStubType=154;break;case"CHAT_PSA":case 155:a.messageStubType=155;break;case"CHAT_POLL_CREATION_MESSAGE":case 156:a.messageStubType=156;break;case"CAG_MASKED_THREAD_CREATED":case 157:a.messageStubType=157;break;case"COMMUNITY_PARENT_GROUP_SUBJECT_CHANGED":case 158:a.messageStubType=158;break;case"CAG_INVITE_AUTO_ADD":case 159:a.messageStubType=159;break;case"BIZ_CHAT_ASSIGNMENT_UNASSIGN":case 160:a.messageStubType=160;break;case"CAG_INVITE_AUTO_JOINED":case 161:a.messageStubType=161;break;case"SCHEDULED_CALL_START_MESSAGE":case 162:a.messageStubType=162;break;case"COMMUNITY_INVITE_RICH":case 163:a.messageStubType=163;break;case"COMMUNITY_INVITE_AUTO_ADD_RICH":case 164:a.messageStubType=164;break;case"SUB_GROUP_INVITE_RICH":case 165:a.messageStubType=165;break;case"SUB_GROUP_PARTICIPANT_ADD_RICH":case 166:a.messageStubType=166;break;case"COMMUNITY_LINK_PARENT_GROUP_RICH":case 167:a.messageStubType=167;break;case"COMMUNITY_PARTICIPANT_ADD_RICH":case 168:a.messageStubType=168;break;case"SILENCED_UNKNOWN_CALLER_AUDIO":case 169:a.messageStubType=169;break;case"SILENCED_UNKNOWN_CALLER_VIDEO":case 170:a.messageStubType=170;break;case"GROUP_MEMBER_ADD_MODE":case 171:a.messageStubType=171;break;case"GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD":case 172:a.messageStubType=172;break;case"COMMUNITY_CHANGE_DESCRIPTION":case 173:a.messageStubType=173;break;case"SENDER_INVITE":case 174:a.messageStubType=174;break;case"RECEIVER_INVITE":case 175:a.messageStubType=175;break;case"COMMUNITY_ALLOW_MEMBER_ADDED_GROUPS":case 176:a.messageStubType=176;break;case"PINNED_MESSAGE_IN_CHAT":case 177:a.messageStubType=177;break;case"PAYMENT_INVITE_SETUP_INVITER":case 178:a.messageStubType=178;break;case"PAYMENT_INVITE_SETUP_INVITEE_RECEIVE_ONLY":case 179:a.messageStubType=179;break;case"PAYMENT_INVITE_SETUP_INVITEE_SEND_AND_RECEIVE":case 180:a.messageStubType=180;break;case"LINKED_GROUP_CALL_START":case 181:a.messageStubType=181;break;case"REPORT_TO_ADMIN_ENABLED_STATUS":case 182:a.messageStubType=182;break;case"EMPTY_SUBGROUP_CREATE":case 183:a.messageStubType=183;break;case"SCHEDULED_CALL_CANCEL":case 184:a.messageStubType=184;break;case"SUBGROUP_ADMIN_TRIGGERED_AUTO_ADD_RICH":case 185:a.messageStubType=185;break;case"GROUP_CHANGE_RECENT_HISTORY_SHARING":case 186:a.messageStubType=186;break;case"PAID_MESSAGE_SERVER_CAMPAIGN_ID":case 187:a.messageStubType=187;break;case"GENERAL_CHAT_CREATE":case 188:a.messageStubType=188;break;case"GENERAL_CHAT_ADD":case 189:a.messageStubType=189;break;case"GENERAL_CHAT_AUTO_ADD_DISABLED":case 190:a.messageStubType=190;break;case"SUGGESTED_SUBGROUP_ANNOUNCE":case 191:a.messageStubType=191;break;case"BIZ_BOT_1P_MESSAGING_ENABLED":case 192:a.messageStubType=192;break;case"CHANGE_USERNAME":case 193:a.messageStubType=193;break;case"BIZ_COEX_PRIVACY_INIT_SELF":case 194:a.messageStubType=194;break;case"BIZ_COEX_PRIVACY_TRANSITION_SELF":case 195:a.messageStubType=195;break;case"SUPPORT_AI_EDUCATION":case 196:a.messageStubType=196;break;case"BIZ_BOT_3P_MESSAGING_ENABLED":case 197:a.messageStubType=197;break;case"REMINDER_SETUP_MESSAGE":case 198:a.messageStubType=198;break;case"REMINDER_SENT_MESSAGE":case 199:a.messageStubType=199;break;case"REMINDER_CANCEL_MESSAGE":case 200:a.messageStubType=200;break;case"BIZ_COEX_PRIVACY_INIT":case 201:a.messageStubType=201;break;case"BIZ_COEX_PRIVACY_TRANSITION":case 202:a.messageStubType=202;break;case"GROUP_DEACTIVATED":case 203:a.messageStubType=203;break;case"COMMUNITY_DEACTIVATE_SIBLING_GROUP":case 204:a.messageStubType=204;break;case"EVENT_UPDATED":case 205:a.messageStubType=205;break;case"EVENT_CANCELED":case 206:a.messageStubType=206;break;case"COMMUNITY_OWNER_UPDATED":case 207:a.messageStubType=207;break;case"COMMUNITY_SUB_GROUP_VISIBILITY_HIDDEN":case 208:a.messageStubType=208;break;case"CAPI_GROUP_NE2EE_SYSTEM_MESSAGE":case 209:a.messageStubType=209;break;case"STATUS_MENTION":case 210:a.messageStubType=210;break;case"USER_CONTROLS_SYSTEM_MESSAGE":case 211:a.messageStubType=211;break;case"SUPPORT_SYSTEM_MESSAGE":case 212:a.messageStubType=212;break;case"CHANGE_LID":case 213:a.messageStubType=213;break;case"BIZ_CUSTOMER_3PD_DATA_SHARING_OPT_IN_MESSAGE":case 214:a.messageStubType=214;break;case"BIZ_CUSTOMER_3PD_DATA_SHARING_OPT_OUT_MESSAGE":case 215:a.messageStubType=215;break;case"CHANGE_LIMIT_SHARING":case 216:a.messageStubType=216;break;case"GROUP_MEMBER_LINK_MODE":case 217:a.messageStubType=217;break;case"BIZ_AUTOMATICALLY_LABELED_CHAT_SYSTEM_MESSAGE":case 218:a.messageStubType=218;break;case"PHONE_NUMBER_HIDING_CHAT_DEPRECATED_MESSAGE":case 219:a.messageStubType=219;break;case"QUARANTINED_MESSAGE":case 220:a.messageStubType=220;break;case"GROUP_MEMBER_SHARE_GROUP_HISTORY_MODE":case 221:a.messageStubType=221;break}if(e.clearMedia!=null&&(a.clearMedia=!!e.clearMedia),e.messageStubParameters){if(!Array.isArray(e.messageStubParameters))throw TypeError(".proto.WebMessageInfo.messageStubParameters: array expected");a.messageStubParameters=[];for(var A=0;A>>0),e.labels){if(!Array.isArray(e.labels))throw TypeError(".proto.WebMessageInfo.labels: array expected");a.labels=[];for(var A=0;A>>0,e.ephemeralStartTimestamp.high>>>0).toNumber(!0))),e.ephemeralDuration!=null&&(a.ephemeralDuration=e.ephemeralDuration>>>0),e.ephemeralOffToOn!=null&&(a.ephemeralOffToOn=!!e.ephemeralOffToOn),e.ephemeralOutOfSync!=null&&(a.ephemeralOutOfSync=!!e.ephemeralOutOfSync),e.bizPrivacyStatus){default:if(typeof e.bizPrivacyStatus=="number"){a.bizPrivacyStatus=e.bizPrivacyStatus;break}break;case"E2EE":case 0:a.bizPrivacyStatus=0;break;case"FB":case 2:a.bizPrivacyStatus=2;break;case"BSP":case 1:a.bizPrivacyStatus=1;break;case"BSP_AND_FB":case 3:a.bizPrivacyStatus=3;break}if(e.verifiedBizName!=null&&(a.verifiedBizName=String(e.verifiedBizName)),e.mediaData!=null){if(typeof e.mediaData!="object")throw TypeError(".proto.WebMessageInfo.mediaData: object expected");a.mediaData=p.proto.MediaData.fromObject(e.mediaData)}if(e.photoChange!=null){if(typeof e.photoChange!="object")throw TypeError(".proto.WebMessageInfo.photoChange: object expected");a.photoChange=p.proto.PhotoChange.fromObject(e.photoChange)}if(e.userReceipt){if(!Array.isArray(e.userReceipt))throw TypeError(".proto.WebMessageInfo.userReceipt: array expected");a.userReceipt=[];for(var A=0;A=0&&(a.futureproofData=e.futureproofData)),e.statusPsa!=null){if(typeof e.statusPsa!="object")throw TypeError(".proto.WebMessageInfo.statusPsa: object expected");a.statusPsa=p.proto.StatusPSA.fromObject(e.statusPsa)}if(e.pollUpdates){if(!Array.isArray(e.pollUpdates))throw TypeError(".proto.WebMessageInfo.pollUpdates: array expected");a.pollUpdates=[];for(var A=0;A=0&&(a.messageSecret=e.messageSecret)),e.keepInChat!=null){if(typeof e.keepInChat!="object")throw TypeError(".proto.WebMessageInfo.keepInChat: object expected");a.keepInChat=p.proto.KeepInChat.fromObject(e.keepInChat)}if(e.originalSelfAuthorUserJidString!=null&&(a.originalSelfAuthorUserJidString=String(e.originalSelfAuthorUserJidString)),e.revokeMessageTimestamp!=null&&(l.Long?(a.revokeMessageTimestamp=l.Long.fromValue(e.revokeMessageTimestamp)).unsigned=!0:typeof e.revokeMessageTimestamp=="string"?a.revokeMessageTimestamp=parseInt(e.revokeMessageTimestamp,10):typeof e.revokeMessageTimestamp=="number"?a.revokeMessageTimestamp=e.revokeMessageTimestamp:typeof e.revokeMessageTimestamp=="object"&&(a.revokeMessageTimestamp=new l.LongBits(e.revokeMessageTimestamp.low>>>0,e.revokeMessageTimestamp.high>>>0).toNumber(!0))),e.pinInChat!=null){if(typeof e.pinInChat!="object")throw TypeError(".proto.WebMessageInfo.pinInChat: object expected");a.pinInChat=p.proto.PinInChat.fromObject(e.pinInChat)}if(e.premiumMessageInfo!=null){if(typeof e.premiumMessageInfo!="object")throw TypeError(".proto.WebMessageInfo.premiumMessageInfo: object expected");a.premiumMessageInfo=p.proto.PremiumMessageInfo.fromObject(e.premiumMessageInfo)}if(e.is1PBizBotMessage!=null&&(a.is1PBizBotMessage=!!e.is1PBizBotMessage),e.isGroupHistoryMessage!=null&&(a.isGroupHistoryMessage=!!e.isGroupHistoryMessage),e.botMessageInvokerJid!=null&&(a.botMessageInvokerJid=String(e.botMessageInvokerJid)),e.commentMetadata!=null){if(typeof e.commentMetadata!="object")throw TypeError(".proto.WebMessageInfo.commentMetadata: object expected");a.commentMetadata=p.proto.CommentMetadata.fromObject(e.commentMetadata)}if(e.eventResponses){if(!Array.isArray(e.eventResponses))throw TypeError(".proto.WebMessageInfo.eventResponses: array expected");a.eventResponses=[];for(var A=0;A>>0,e.newsletterServerId.high>>>0).toNumber(!0))),e.eventAdditionalMetadata!=null){if(typeof e.eventAdditionalMetadata!="object")throw TypeError(".proto.WebMessageInfo.eventAdditionalMetadata: object expected");a.eventAdditionalMetadata=p.proto.EventAdditionalMetadata.fromObject(e.eventAdditionalMetadata)}if(e.isMentionedInStatus!=null&&(a.isMentionedInStatus=!!e.isMentionedInStatus),e.statusMentions){if(!Array.isArray(e.statusMentions))throw TypeError(".proto.WebMessageInfo.statusMentions: array expected");a.statusMentions=[];for(var A=0;A>>3){case 2:{s.timestamp=e.uint64();break}case 3:{s.unreadChats=e.uint32();break}case 4:{s.notifyMessageCount=e.uint32();break}case 5:{s.notifyMessages&&s.notifyMessages.length||(s.notifyMessages=[]),s.notifyMessages.push(p.proto.WebMessageInfo.decode(e,e.uint32()));break}default:e.skipType(g&7);break}}return s},t.fromObject=function(e){if(e instanceof p.proto.WebNotificationsInfo)return e;var a=new p.proto.WebNotificationsInfo;if(e.timestamp!=null&&(l.Long?(a.timestamp=l.Long.fromValue(e.timestamp)).unsigned=!0:typeof e.timestamp=="string"?a.timestamp=parseInt(e.timestamp,10):typeof e.timestamp=="number"?a.timestamp=e.timestamp:typeof e.timestamp=="object"&&(a.timestamp=new l.LongBits(e.timestamp.low>>>0,e.timestamp.high>>>0).toNumber(!0))),e.unreadChats!=null&&(a.unreadChats=e.unreadChats>>>0),e.notifyMessageCount!=null&&(a.notifyMessageCount=e.notifyMessageCount>>>0),e.notifyMessages){if(!Array.isArray(e.notifyMessages))throw TypeError(".proto.WebNotificationsInfo.notifyMessages: array expected");a.notifyMessages=[];for(var A=0;ABa.hasSubscribers||IB.hasSubscribers,k9=new Set,R9=typeof process=="object"&&process?process:{},V2e=(n,t,o,i)=>{typeof R9.emitWarning=="function"?R9.emitWarning(n,t,o,i):console.error(`[${o}] ${t}: ${n}`)},W2e=n=>!k9.has(n),Lc=n=>!!n&&n===Math.floor(n)&&n>0&&isFinite(n),v9=n=>Lc(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?xw:null:null,xw=class extends Array{constructor(n){super(n),this.fill(0)}},Z2e=class lB{heap;length;static#e=!1;static create(t){let o=v9(t);if(!o)return[];lB.#e=!0;let i=new lB(t,o);return lB.#e=!1,i}constructor(t,o){if(!lB.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new o(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Mg=class P9{#e;#A;#t;#r;#g;#a;#n;#i;get perf(){return this.#i}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#I;#l;#o;#s;#c;#p;#d;#h;#E;#C;#f;#B;#y;#S;#Q;#m;#u;#b;#R;static unsafeExposeInternals(t){return{starts:t.#y,ttls:t.#S,autopurgeTimers:t.#Q,sizes:t.#B,keyMap:t.#o,keyList:t.#s,valList:t.#c,next:t.#p,prev:t.#d,get head(){return t.#h},get tail(){return t.#E},free:t.#C,isBackgroundFetch:o=>t.#G(o),backgroundFetch:(o,i,e,a)=>t.#K(o,i,e,a),moveToTail:o=>t.#x(o),indexes:o=>t.#P(o),rindexes:o=>t.#N(o),isStale:o=>t.#M(o)}}get max(){return this.#e}get maxSize(){return this.#A}get calculatedSize(){return this.#l}get size(){return this.#I}get fetchMethod(){return this.#a}get memoMethod(){return this.#n}get dispose(){return this.#t}get onInsert(){return this.#r}get disposeAfter(){return this.#g}constructor(t){let{max:o=0,ttl:i,ttlResolution:e=1,ttlAutopurge:a,updateAgeOnGet:A,updateAgeOnHas:r,allowStale:s,dispose:g,onInsert:c,disposeAfter:I,noDisposeOnSet:d,noUpdateTTL:B,maxSize:f=0,maxEntrySize:Q=0,sizeCalculation:y,fetchMethod:m,memoMethod:_,noDeleteOnFetchRejection:T,noDeleteOnStaleGet:R,allowStaleOnFetchRejection:L,allowStaleOnFetchAbort:U,ignoreFetchAbort:F,backgroundFetchSize:q=1,perf:z}=t;if(this.backgroundFetchSize=q,z!==void 0&&typeof z?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#i=z??z2e,o!==0&&!Lc(o))throw new TypeError("max option must be a nonnegative integer");let j=o?v9(o):Array;if(!j)throw new Error("invalid max value: "+o);if(this.#e=o,this.#A=f,this.maxEntrySize=Q||this.#A,this.sizeCalculation=y,this.sizeCalculation){if(!this.#A&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(_!==void 0&&typeof _!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#n=_,m!==void 0&&typeof m!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#a=m,this.#u=!!m,this.#o=new Map,this.#s=Array.from({length:o}).fill(void 0),this.#c=Array.from({length:o}).fill(void 0),this.#p=new j(o),this.#d=new j(o),this.#h=0,this.#E=0,this.#C=Z2e.create(o),this.#I=0,this.#l=0,typeof g=="function"&&(this.#t=g),typeof c=="function"&&(this.#r=c),typeof I=="function"?(this.#g=I,this.#f=[]):(this.#g=void 0,this.#f=void 0),this.#m=!!this.#t,this.#R=!!this.#r,this.#b=!!this.#g,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!B,this.noDeleteOnFetchRejection=!!T,this.allowStaleOnFetchRejection=!!L,this.allowStaleOnFetchAbort=!!U,this.ignoreFetchAbort=!!F,this.maxEntrySize!==0){if(this.#A!==0&&!Lc(this.#A))throw new TypeError("maxSize must be a positive integer if specified");if(!Lc(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!s,this.noDeleteOnStaleGet=!!R,this.updateAgeOnGet=!!A,this.updateAgeOnHas=!!r,this.ttlResolution=Lc(e)||e===0?e:1,this.ttlAutopurge=!!a,this.ttl=i||0,this.ttl){if(!Lc(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#e===0&&this.ttl===0&&this.#A===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#A){let P="LRU_CACHE_UNBOUNDED";W2e(P)&&(k9.add(P),V2e("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",P,P9))}}getRemainingTTL(t){return this.#o.has(t)?1/0:0}#D(){let t=new xw(this.#e),o=new xw(this.#e);this.#S=t,this.#y=o;let i=this.ttlAutopurge?Array.from({length:this.#e}):void 0;this.#Q=i,this.#k=(s,g,c=this.#i.now())=>{o[s]=g!==0?c:0,t[s]=g,e(s,g)},this.#w=s=>{o[s]=t[s]!==0?this.#i.now():0,e(s,t[s])};let e=this.ttlAutopurge?(s,g)=>{if(i?.[s]&&(clearTimeout(i[s]),i[s]=void 0),g&&g!==0&&i){let c=setTimeout(()=>{this.#M(s)?(this.#J(this.#s[s],"expire"),i[s]=void 0):e(s,r(s))},g+1);c.unref&&c.unref(),i[s]=c}}:()=>{};this.#T=(s,g)=>{if(t[g]){let c=t[g],I=o[g];if(!c||!I)return;s.ttl=c,s.start=I,s.now=a||A();let d=s.now-I;s.remainingTTL=c-d}};let a=0,A=()=>{let s=this.#i.now();if(this.ttlResolution>0){a=s;let g=setTimeout(()=>a=0,this.ttlResolution);g.unref&&g.unref()}return s};this.getRemainingTTL=s=>{let g=this.#o.get(s);return g===void 0?0:r(g)};let r=s=>{let g=t[s],c=o[s];if(!g||!c)return 1/0;let I=(a||A())-c;return g-I};this.#M=s=>{let g=o[s],c=t[s];return!!c&&!!g&&(a||A())-g>c}}#w=()=>{};#T=()=>{};#k=()=>{};#M=()=>!1;#L(){let t=new xw(this.#e);this.#l=0,this.#B=t,this.#_=o=>{this.#l-=t[o],t[o]=0},this.#v=(o,i,e,a)=>{if(!Lc(e)){if(this.#G(i))return this.backgroundFetchSize;if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(e=a(i,o),!Lc(e))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.")}return e},this.#U=(o,i,e)=>{if(t[o]=i,this.#A){let a=this.#A-t[o];for(;this.#l>a;)this.#q(!0)}this.#l+=t[o],e&&(e.entrySize=i,e.totalCalculatedSize=this.#l)}}#_=t=>{};#U=(t,o,i)=>{};#v=(t,o,i,e)=>{if(i||e)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#P({allowStale:t=this.allowStale}={}){if(this.#I)for(let o=this.#E;this.#Y(o)&&((t||!this.#M(o))&&(yield o),o!==this.#h);)o=this.#d[o]}*#N({allowStale:t=this.allowStale}={}){if(this.#I)for(let o=this.#h;this.#Y(o)&&((t||!this.#M(o))&&(yield o),o!==this.#E);)o=this.#p[o]}#Y(t){return t!==void 0&&this.#o.get(this.#s[t])===t}*entries(){for(let t of this.#P())this.#c[t]!==void 0&&this.#s[t]!==void 0&&!this.#G(this.#c[t])&&(yield[this.#s[t],this.#c[t]])}*rentries(){for(let t of this.#N())this.#c[t]!==void 0&&this.#s[t]!==void 0&&!this.#G(this.#c[t])&&(yield[this.#s[t],this.#c[t]])}*keys(){for(let t of this.#P()){let o=this.#s[t];o!==void 0&&!this.#G(this.#c[t])&&(yield o)}}*rkeys(){for(let t of this.#N()){let o=this.#s[t];o!==void 0&&!this.#G(this.#c[t])&&(yield o)}}*values(){for(let t of this.#P())this.#c[t]!==void 0&&!this.#G(this.#c[t])&&(yield this.#c[t])}*rvalues(){for(let t of this.#N())this.#c[t]!==void 0&&!this.#G(this.#c[t])&&(yield this.#c[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,o={}){for(let i of this.#P()){let e=this.#c[i],a=this.#G(e)?e.__staleWhileFetching:e;if(a!==void 0&&t(a,this.#s[i],this))return this.#j(this.#s[i],o)}}forEach(t,o=this){for(let i of this.#P()){let e=this.#c[i],a=this.#G(e)?e.__staleWhileFetching:e;a!==void 0&&t.call(o,a,this.#s[i],this)}}rforEach(t,o=this){for(let i of this.#N()){let e=this.#c[i],a=this.#G(e)?e.__staleWhileFetching:e;a!==void 0&&t.call(o,a,this.#s[i],this)}}purgeStale(){let t=!1;for(let o of this.#N({allowStale:!0}))this.#M(o)&&(this.#J(this.#s[o],"expire"),t=!0);return t}info(t){let o=this.#o.get(t);if(o===void 0)return;let i=this.#c[o],e=this.#G(i)?i.__staleWhileFetching:i;if(e===void 0)return;let a={value:e};if(this.#S&&this.#y){let A=this.#S[o],r=this.#y[o];if(A&&r){let s=A-(this.#i.now()-r);a.ttl=s,a.start=Date.now()}}return this.#B&&(a.size=this.#B[o]),a}dump(){let t=[];for(let o of this.#P({allowStale:!0})){let i=this.#s[o],e=this.#c[o],a=this.#G(e)?e.__staleWhileFetching:e;if(a===void 0||i===void 0)continue;let A={value:a};if(this.#S&&this.#y){A.ttl=this.#S[o];let r=this.#i.now()-this.#y[o];A.start=Math.floor(Date.now()-r)}this.#B&&(A.size=this.#B[o]),t.unshift([i,A])}return t}load(t){this.clear();for(let[o,i]of t){if(i.start){let e=Date.now()-i.start;i.start=this.#i.now()-e}this.#H(o,i.value,i)}}set(t,o,i={}){let{status:e=Ba.hasSubscribers?{}:void 0}=i;i.status=e,e&&(e.op="set",e.key=t,o!==void 0&&(e.value=o),e.cache=this);let a=this.#H(t,o,i);return e&&Ba.hasSubscribers&&Ba.publish(e),a}#H(t,o,i,e){let{ttl:a=this.ttl,start:A,noDisposeOnSet:r=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:g}=i,c=this.#G(o);if(o===void 0)return g&&(g.set="deleted"),this.delete(t),this;let{noUpdateTTL:I=this.noUpdateTTL}=i;g&&!c&&(g.value=o);let d=this.#v(t,o,i.size||0,s,g);if(this.maxEntrySize&&d>this.maxEntrySize)return this.#J(t,"set"),g&&(g.set="miss",g.maxEntrySizeExceeded=!0),this;let B=this.#I===0?void 0:this.#o.get(t);if(B===void 0)B=this.#I===0?this.#E:this.#C.length!==0?this.#C.pop():this.#I===this.#e?this.#q(!1):this.#I,this.#s[B]=t,this.#c[B]=o,this.#o.set(t,B),this.#p[this.#E]=B,this.#d[B]=this.#E,this.#E=B,this.#I++,this.#U(B,d,g),g&&(g.set="add"),I=!1,this.#R&&!c&&this.#r?.(o,t,"add");else{this.#x(B);let f=this.#c[B];if(o!==f){if(!r)if(this.#G(f)){f!==e&&f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:Q}=f;Q!==void 0&&Q!==o&&(this.#m&&this.#t?.(Q,t,"set"),this.#b&&this.#f?.push([Q,t,"set"]))}else this.#m&&this.#t?.(f,t,"set"),this.#b&&this.#f?.push([f,t,"set"]);if(this.#_(B),this.#U(B,d,g),this.#c[B]=o,!c){let Q=f&&this.#G(f)?f.__staleWhileFetching:f,y=Q===void 0?"add":o!==Q?"replace":"update";g&&(g.set=y,Q!==void 0&&(g.oldValue=Q)),this.#R&&this.onInsert?.(o,t,y)}}else c||(g&&(g.set="update"),this.#R&&this.onInsert?.(o,t,"update"))}if(a!==0&&!this.#S&&this.#D(),this.#S&&(I||this.#k(B,a,A),g&&this.#T(g,B)),!r&&this.#b&&this.#f){let f=this.#f,Q;for(;Q=f?.shift();)this.#g?.(...Q)}return this}pop(){try{for(;this.#I;){let t=this.#c[this.#h];if(this.#q(!0),this.#G(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#b&&this.#f){let t=this.#f,o;for(;o=t?.shift();)this.#g?.(...o)}}}#q(t){let o=this.#h,i=this.#s[o],e=this.#c[o],a=this.#G(e);a&&e.__abortController.abort(new Error("evicted"));let A=a?e.__staleWhileFetching:e;return(this.#m||this.#b)&&A!==void 0&&(this.#m&&this.#t?.(A,i,"evict"),this.#b&&this.#f?.push([A,i,"evict"])),this.#_(o),this.#Q?.[o]&&(clearTimeout(this.#Q[o]),this.#Q[o]=void 0),t&&(this.#s[o]=void 0,this.#c[o]=void 0,this.#C.push(o)),this.#I===1?(this.#h=this.#E=0,this.#C.length=0):this.#h=this.#p[o],this.#o.delete(i),this.#I--,o}has(t,o={}){let{status:i=Ba.hasSubscribers?{}:void 0}=o;o.status=i,i&&(i.op="has",i.key=t,i.cache=this);let e=this.#z(t,o);return Ba.hasSubscribers&&Ba.publish(i),e}#z(t,o={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:e}=o,a=this.#o.get(t);if(a!==void 0){let A=this.#c[a];if(this.#G(A)&&A.__staleWhileFetching===void 0)return!1;if(this.#M(a))e&&(e.has="stale",this.#T(e,a));else return i&&this.#w(a),e&&(e.has="hit",this.#T(e,a)),!0}else e&&(e.has="miss");return!1}peek(t,o={}){let{status:i=sF()?{}:void 0}=o;i&&(i.op="peek",i.key=t,i.cache=this),o.status=i;let e=this.#F(t,o);return Ba.hasSubscribers&&Ba.publish(i),e}#F(t,o){let{status:i,allowStale:e=this.allowStale}=o,a=this.#o.get(t);if(a===void 0||!e&&this.#M(a)){i&&(i.peek=a===void 0?"miss":"stale");return}let A=this.#c[a],r=this.#G(A)?A.__staleWhileFetching:A;return i&&(r!==void 0?(i.peek="hit",i.value=r):i.peek="miss"),r}#K(t,o,i,e){let a=o===void 0?void 0:this.#c[o];if(this.#G(a))return a;let A=new AbortController,{signal:r}=i;r?.addEventListener("abort",()=>A.abort(r.reason),{signal:A.signal});let s={signal:A.signal,options:i,context:e},g=(Q,y=!1)=>{let{aborted:m}=A.signal,_=i.ignoreFetchAbort&&Q!==void 0,T=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&Q!==void 0);if(i.status&&(m&&!y?(i.status.fetchAborted=!0,i.status.fetchError=A.signal.reason,_&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),m&&!_&&!y)return I(A.signal.reason,T);let R=B,L=this.#c[o];return(L===B||L===void 0&&_&&y)&&(Q===void 0?R.__staleWhileFetching!==void 0?this.#c[o]=R.__staleWhileFetching:this.#J(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#H(t,Q,s.options,R))),Q},c=Q=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=Q),I(Q,!1)),I=(Q,y)=>{let{aborted:m}=A.signal,_=m&&i.allowStaleOnFetchAbort,T=_||i.allowStaleOnFetchRejection,R=T||i.noDeleteOnFetchRejection,L=B;if(this.#c[o]===B&&(!R||!y&&L.__staleWhileFetching===void 0?this.#J(t,"fetch"):_||(this.#c[o]=L.__staleWhileFetching)),T)return i.status&&L.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),L.__staleWhileFetching;if(L.__returned===L)throw Q},d=(Q,y)=>{let m=this.#a?.(t,a,s);A.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(Q(void 0),i.allowStaleOnFetchAbort&&(Q=_=>g(_,!0)))}),m&&m instanceof Promise?m.then(_=>Q(_===void 0?void 0:_),y):m!==void 0&&Q(m)};i.status&&(i.status.fetchDispatched=!0);let B=new Promise(d).then(g,c),f=Object.assign(B,{__abortController:A,__staleWhileFetching:a,__returned:void 0});return o===void 0?(this.#H(t,f,{...s.options,status:void 0}),o=this.#o.get(t)):this.#c[o]=f,f}#G(t){if(!this.#u)return!1;let o=t;return!!o&&o instanceof Promise&&o.hasOwnProperty("__staleWhileFetching")&&o.__abortController instanceof AbortController}fetch(t,o={}){let i=IB.hasSubscribers,{status:e=sF()?{}:void 0}=o;o.status=e,e&&o.context&&(e.context=o.context);let a=this.#$(t,o);return e&&i&&(e.trace=!0,IB.tracePromise(()=>a,e).catch(()=>{})),a}async#$(t,o={}){let{allowStale:i=this.allowStale,updateAgeOnGet:e=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:A=this.ttl,noDisposeOnSet:r=this.noDisposeOnSet,size:s=0,sizeCalculation:g=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:B=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:Q,forceRefresh:y=!1,status:m,signal:_}=o;if(m&&(m.op="fetch",m.key=t,y&&(m.forceRefresh=!0),m.cache=this),!this.#u)return m&&(m.fetch="get"),this.#j(t,{allowStale:i,updateAgeOnGet:e,noDeleteOnStaleGet:a,status:m});let T={allowStale:i,updateAgeOnGet:e,noDeleteOnStaleGet:a,ttl:A,noDisposeOnSet:r,size:s,sizeCalculation:g,noUpdateTTL:c,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:f,ignoreFetchAbort:B,status:m,signal:_},R=this.#o.get(t);if(R===void 0){m&&(m.fetch="miss");let L=this.#K(t,R,T,Q);return L.__returned=L}else{let L=this.#c[R];if(this.#G(L)){let z=i&&L.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",z&&(m.returnedStale=!0)),z?L.__staleWhileFetching:L.__returned=L}let U=this.#M(R);if(!y&&!U)return m&&(m.fetch="hit"),this.#x(R),e&&this.#w(R),m&&this.#T(m,R),L;let F=this.#K(t,R,T,Q),q=F.__staleWhileFetching!==void 0&&i;return m&&(m.fetch=U?"stale":"refresh",q&&U&&(m.returnedStale=!0)),q?F.__staleWhileFetching:F.__returned=F}}forceFetch(t,o={}){let i=IB.hasSubscribers,{status:e=sF()?{}:void 0}=o;o.status=e,e&&o.context&&(e.context=o.context);let a=this.#Ae(t,o);return e&&i&&(e.trace=!0,IB.tracePromise(()=>a,e).catch(()=>{})),a}async#Ae(t,o={}){let i=await this.#$(t,o);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,o={}){let{status:i=Ba.hasSubscribers?{}:void 0}=o;o.status=i,i&&(i.op="memo",i.key=t,o.context&&(i.context=o.context),i.cache=this);let e=this.#te(t,o);return i&&(i.value=e),Ba.hasSubscribers&&Ba.publish(i),e}#te(t,o={}){let i=this.#n;if(!i)throw new Error("no memoMethod provided to constructor");let{context:e,status:a,forceRefresh:A,...r}=o;a&&A&&(a.forceRefresh=!0);let s=this.#j(t,r),g=A||s===void 0;if(a&&(a.memo=g?"miss":"hit",g||(a.value=s)),!g)return s;let c=i(t,s,{options:r,context:e});return a&&(a.value=c),this.#H(t,c,r),c}get(t,o={}){let{status:i=Ba.hasSubscribers?{}:void 0}=o;o.status=i,i&&(i.op="get",i.key=t,i.cache=this);let e=this.#j(t,o);return i&&(e!==void 0&&(i.value=e),Ba.hasSubscribers&&Ba.publish(i)),e}#j(t,o={}){let{allowStale:i=this.allowStale,updateAgeOnGet:e=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:A}=o,r=this.#o.get(t);if(r===void 0){A&&(A.get="miss");return}let s=this.#c[r],g=this.#G(s);return A&&this.#T(A,r),this.#M(r)?g?(A&&(A.get="stale-fetching"),i&&s.__staleWhileFetching!==void 0?(A&&(A.returnedStale=!0),s.__staleWhileFetching):void 0):(a||this.#J(t,"expire"),A&&(A.get="stale"),i?(A&&(A.returnedStale=!0),s):void 0):(A&&(A.get=g?"fetching":"hit"),this.#x(r),e&&this.#w(r),g?s.__staleWhileFetching:s)}#X(t,o){this.#d[o]=t,this.#p[t]=o}#x(t){t!==this.#E&&(t===this.#h?this.#h=this.#p[t]:this.#X(this.#d[t],this.#p[t]),this.#X(this.#E,t),this.#E=t)}delete(t){return this.#J(t,"delete")}#J(t,o){Ba.hasSubscribers&&Ba.publish({op:"delete",delete:o,key:t,cache:this});let i=!1;if(this.#I!==0){let e=this.#o.get(t);if(e!==void 0)if(this.#Q?.[e]&&(clearTimeout(this.#Q[e]),this.#Q[e]=void 0),i=!0,this.#I===1)this.#V(o);else{this.#_(e);let a=this.#c[e];if(this.#G(a)?a.__abortController.abort(new Error("deleted")):(this.#m||this.#b)&&(this.#m&&this.#t?.(a,t,o),this.#b&&this.#f?.push([a,t,o])),this.#o.delete(t),this.#s[e]=void 0,this.#c[e]=void 0,e===this.#E)this.#E=this.#d[e];else if(e===this.#h)this.#h=this.#p[e];else{let A=this.#d[e];this.#p[A]=this.#p[e];let r=this.#p[e];this.#d[r]=this.#d[e]}this.#I--,this.#C.push(e)}}if(this.#b&&this.#f?.length){let e=this.#f,a;for(;a=e?.shift();)this.#g?.(...a)}return i}clear(){return this.#V("delete")}#V(t){for(let o of this.#N({allowStale:!0})){let i=this.#c[o];if(this.#G(i))i.__abortController.abort(new Error("deleted"));else{let e=this.#s[o];this.#m&&this.#t?.(i,e,t),this.#b&&this.#f?.push([i,e,t])}}if(this.#o.clear(),this.#c.fill(void 0),this.#s.fill(void 0),this.#S&&this.#y){this.#S.fill(0),this.#y.fill(0);for(let o of this.#Q??[])o!==void 0&&clearTimeout(o);this.#Q?.fill(void 0)}if(this.#B&&this.#B.fill(0),this.#h=0,this.#E=0,this.#C.length=0,this.#l=0,this.#I=0,this.#b&&this.#f){let o=this.#f,i;for(;i=o?.shift();)this.#g?.(...i)}}};var oD=Je(Lr(),1);import{createHash as kUe,randomBytes as SB}from"crypto";var NX=["critical_block","critical_unblock_low","regular_high","regular_low","regular"];var IfA=Je(Lr(),1),na;(function(n){n[n.Connecting=0]="Connecting",n[n.AwaitingInitialSync=1]="AwaitingInitialSync",n[n.Syncing=2]="Syncing",n[n.Online=3]="Online"})(na||(na={}));var Hc;(function(n){n.BIZ_COMMERCE_VIOLATION_ALCOHOL="BIZ_COMMERCE_VIOLATION_ALCOHOL",n.BIZ_COMMERCE_VIOLATION_ADULT="BIZ_COMMERCE_VIOLATION_ADULT",n.BIZ_COMMERCE_VIOLATION_ANIMALS="BIZ_COMMERCE_VIOLATION_ANIMALS",n.BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS="BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS",n.BIZ_COMMERCE_VIOLATION_DATING="BIZ_COMMERCE_VIOLATION_DATING",n.BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS="BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS",n.BIZ_COMMERCE_VIOLATION_DRUGS="BIZ_COMMERCE_VIOLATION_DRUGS",n.BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC="BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC",n.BIZ_COMMERCE_VIOLATION_GAMBLING="BIZ_COMMERCE_VIOLATION_GAMBLING",n.BIZ_COMMERCE_VIOLATION_HEALTHCARE="BIZ_COMMERCE_VIOLATION_HEALTHCARE",n.BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY="BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY",n.BIZ_COMMERCE_VIOLATION_SUPPLEMENTS="BIZ_COMMERCE_VIOLATION_SUPPLEMENTS",n.BIZ_COMMERCE_VIOLATION_TOBACCO="BIZ_COMMERCE_VIOLATION_TOBACCO",n.BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT="BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT",n.BIZ_COMMERCE_VIOLATION_WEAPONS="BIZ_COMMERCE_VIOLATION_WEAPONS",n.BIZ_QUALITY="BIZ_QUALITY",n.DEFAULT="DEFAULT",n.WEB_COMPANION_ONLY="WEB_COMPANION_ONLY"})(Hc||(Hc={}));var RX;(function(n){n.NONE="NONE",n.FIRST_WARNING="FIRST_WARNING",n.SECOND_WARNING="SECOND_WARNING",n.CAPPED="CAPPED"})(RX||(RX={}));var kX;(function(n){n.NOT_ELIGIBLE="NOT_ELIGIBLE",n.NOT_ACTIVE="NOT_ACTIVE",n.ACTIVE="ACTIVE",n.ACTIVE_UPGRADE_AVAILABLE="ACTIVE_UPGRADE_AVAILABLE"})(kX||(kX={}));var vX;(function(n){n.NOT_ELIGIBLE="NOT_ELIGIBLE",n.ELIGIBLE="ELIGIBLE",n.ACTIVE_IN_CURRENT_CYCLE="ACTIVE_IN_CURRENT_CYCLE",n.EXHAUSTED="EXHAUSTED"})(vX||(vX={}));var TA=oe.WebMessageInfo.StubType,th=oe.WebMessageInfo.Status,dB;(function(n){n.PN="pn",n.LID="lid"})(dB||(dB={}));var fa;(function(n){n.xwa2_newsletter_create="xwa2_newsletter_create",n.xwa2_newsletter_subscribers="xwa2_newsletter_subscribers",n.xwa2_newsletter_view="xwa2_newsletter_view",n.xwa2_newsletter_metadata="xwa2_newsletter",n.xwa2_newsletter_admin_count="xwa2_newsletter_admin",n.xwa2_newsletter_mute_v2="xwa2_newsletter_mute_v2",n.xwa2_newsletter_unmute_v2="xwa2_newsletter_unmute_v2",n.xwa2_newsletter_follow="xwa2_newsletter_follow",n.xwa2_newsletter_unfollow="xwa2_newsletter_unfollow",n.xwa2_newsletter_join_v2="xwa2_newsletter_join_v2",n.xwa2_newsletter_leave_v2="xwa2_newsletter_leave_v2",n.xwa2_newsletter_change_owner="xwa2_newsletter_change_owner",n.xwa2_newsletter_demote="xwa2_newsletter_demote",n.xwa2_newsletter_delete_v2="xwa2_newsletter_delete_v2",n.xwa2_fetch_account_reachout_timelock="xwa2_fetch_account_reachout_timelock",n.xwa2_message_capping_info="xwa2_message_capping_info"})(fa||(fa={}));var sa;(function(n){n.CREATE="8823471724422422",n.UPDATE_METADATA="24250201037901610",n.METADATA="6563316087068696",n.SUBSCRIBERS="9783111038412085",n.FOLLOW="24404358912487870",n.UNFOLLOW="9767147403369991",n.MUTE="29766401636284406",n.UNMUTE="9864994326891137",n.ADMIN_COUNT="7130823597031706",n.CHANGE_OWNER="7341777602580933",n.DEMOTE="6551828931592903",n.DELETE="30062808666639665",n.REACHOUT_TIMELOCK="23983697327930364",n.MESSAGE_CAPPING_INFO="24503548349331633"})(sa||(sa={}));var $t;(function(n){n[n.connectionClosed=428]="connectionClosed",n[n.connectionLost=408]="connectionLost",n[n.connectionReplaced=440]="connectionReplaced",n[n.timedOut=408]="timedOut",n[n.loggedOut=401]="loggedOut",n[n.badSession=500]="badSession",n[n.restartRequired=515]="restartRequired",n[n.multideviceMismatch=411]="multideviceMismatch",n[n.forbidden=403]="forbidden",n[n.unavailableService=503]="unavailableService"})($t||($t={}));var hB={};Pr(hB,{DOUBLE_BYTE_TOKENS:()=>PX,SINGLE_BYTE_TOKENS:()=>GX,TAGS:()=>gUe,TOKEN_MAP:()=>BF});var gUe={LIST_EMPTY:0,DICTIONARY_0:236,DICTIONARY_1:237,DICTIONARY_2:238,DICTIONARY_3:239,INTEROP_JID:245,FB_JID:246,AD_JID:247,LIST_8:248,LIST_16:249,JID_PAIR:250,HEX_8:251,BINARY_8:252,BINARY_20:253,BINARY_32:254,NIBBLE_8:255,PACKED_MAX:127},PX=[["read-self","active","fbns","protocol","reaction","screen_width","heartbeat","deviceid","2:47DEQpj8","uploadfieldstat","voip_settings","retry","priority","longitude","conflict","false","ig_professional","replaced","preaccept","cover_photo","uncompressed","encopt","ppic","04","passive","status-revoke-drop","keygen","540","offer","rate","opus","latitude","w:gp2","ver","4","business_profile","medium","sender","prev_v_id","email","website","invited","sign_credential","05","transport","skey","reason","peer_abtest_bucket","America/Sao_Paulo","appid","refresh","100","06","404","101","104","107","102","109","103","member_add_mode","105","transaction-id","110","106","outgoing","108","111","tokens","followers","ig_handle","self_pid","tue","dec","thu","joinable","peer_pid","mon","features","wed","peer_device_presence","pn","delete","07","fri","audio_duration","admin","connected","delta","rcat","disable","collection","08","480","sat","phash","all","invite","accept","critical_unblock_low","group_update","signed_credential","blinded_credential","eph_setting","net","09","background_location","refresh_id","Asia/Kolkata","privacy_mode_ts","account_sync","voip_payload_type","service_areas","acs_public_key","v_id","0a","fallback_class","relay","actual_actors","metadata","w:biz","5","connected-limit","notice","0b","host_storage","fb_page","subject","privatestats","invis","groupadd","010","note.m4r","uuid","0c","8000","sun","372","1020","stage","1200","720","canonical","fb","011","video_duration","0d","1140","superadmin","012","Opening.m4r","keystore_attestation","dleq_proof","013","timestamp","ab_key","w:sync:app:state","0e","vertical","600","p_v_id","6","likes","014","500","1260","creator","0f","rte","destination","group","group_info","syncd_anti_tampering_fatal_exception_enabled","015","dl_bw","Asia/Jakarta","vp8/h.264","online","1320","fb:multiway","10","timeout","016","nse_retry","urn:xmpp:whatsapp:dirty","017","a_v_id","web_shops_chat_header_button_enabled","nse_call","inactive-upgrade","none","web","groups","2250","mms_hot_content_timespan_in_seconds","contact_blacklist","nse_read","suspended_group_deletion_notification","binary_version","018","https://www.whatsapp.com/otp/copy/","reg_push","shops_hide_catalog_attachment_entrypoint","server_sync",".","ephemeral_messages_allowed_values","019","mms_vcache_aggregation_enabled","iphone","America/Argentina/Buenos_Aires","01a","mms_vcard_autodownload_size_kb","nse_ver","shops_header_dropdown_menu_item","dhash","catalog_status","communities_mvp_new_iqs_serverprop","blocklist","default","11","ephemeral_messages_enabled","01b","original_dimensions","8","mms4_media_retry_notification_encryption_enabled","mms4_server_error_receipt_encryption_enabled","original_image_url","sync","multiway","420","companion_enc_static","shops_profile_drawer_entrypoint","01c","vcard_as_document_size_kb","status_video_max_duration","request_image_url","01d","regular_high","s_t","abt","share_ext_min_preliminary_image_quality","01e","32","syncd_key_rotation_enabled","data_namespace","md_downgrade_read_receipts2","patch","polltype","ephemeral_messages_setting","userrate","15","partial_pjpeg_bw_threshold","played-self","catalog_exists","01f","mute_v2"],["reject","dirty","announcement","020","13","9","status_video_max_bitrate","fb:thrift_iq","offline_batch","022","full","ctwa_first_business_reply_logging","h.264","smax_id","group_description_length","https://www.whatsapp.com/otp/code","status_image_max_edge","smb_upsell_business_profile_enabled","021","web_upgrade_to_md_modal","14","023","s_o","smaller_video_thumbs_status_enabled","media_max_autodownload","960","blocking_status","peer_msg","joinable_group_call_client_version","group_call_video_maximization_enabled","return_snapshot","high","America/Mexico_City","entry_point_block_logging_enabled","pop","024","1050","16","1380","one_tap_calling_in_group_chat_size","regular_low","inline_joinable_education_enabled","hq_image_max_edge","locked","America/Bogota","smb_biztools_deeplink_enabled","status_image_quality","1088","025","payments_upi_intent_transaction_limit","voip","w:g2","027","md_pin_chat_enabled","026","multi_scan_pjpeg_download_enabled","shops_product_grid","transaction_id","ctwa_context_enabled","20","fna","hq_image_quality","alt_jpeg_doc_detection_quality","group_call_max_participants","pkey","America/Belem","image_max_kbytes","web_cart_v1_1_order_message_changes_enabled","ctwa_context_enterprise_enabled","urn:xmpp:whatsapp:account","840","Asia/Kuala_Lumpur","max_participants","video_remux_after_repair_enabled","stella_addressbook_restriction_type","660","900","780","context_menu_ios13_enabled","mute-state","ref","payments_request_messages","029","frskmsg","vcard_max_size_kb","sample_buffer_gif_player_enabled","match_last_seen","510","4983","video_max_bitrate","028","w:comms:chat","17","frequently_forwarded_max","groups_privacy_blacklist","Asia/Karachi","02a","web_download_document_thumb_mms_enabled","02b","hist_sync","biz_block_reasons_version","1024","18","web_is_direct_connection_for_plm_transparent","view_once_write","file_max_size","paid_convo_id","online_privacy_setting","video_max_edge","view_once_read","enhanced_storage_management","multi_scan_pjpeg_encoding_enabled","ctwa_context_forward_enabled","video_transcode_downgrade_enable","template_doc_mime_types","hq_image_bw_threshold","30","body","u_aud_limit_sil_restarts_ctrl","other","participating","w:biz:directory","1110","vp8","4018","meta","doc_detection_image_max_edge","image_quality","1170","02c","smb_upsell_chat_banner_enabled","key_expiry_time_second","pid","stella_interop_enabled","19","linked_device_max_count","md_device_sync_enabled","02d","02e","360","enhanced_block_enabled","ephemeral_icon_in_forwarding","paid_convo_status","gif_provider","project_name","server-error","canonical_url_validation_enabled","wallpapers_v2","syncd_clear_chat_delete_chat_enabled","medianotify","02f","shops_required_tos_version","vote","reset_skey_on_id_change","030","image_max_edge","multicast_limit_global","ul_bw","21","25","5000","poll","570","22","031","1280","WhatsApp","032","bloks_shops_enabled","50","upload_host_switching_enabled","web_ctwa_context_compose_enabled","ptt_forwarded_features_enabled","unblocked","partial_pjpeg_enabled","fbid:devices","height","ephemeral_group_query_ts","group_join_permissions","order","033","alt_jpeg_status_quality","migrate","popular-bank","win_uwp_deprecation_killswitch_enabled","web_download_status_thumb_mms_enabled","blocking","url_text","035","web_forwarding_limit_to_groups","1600","val","1000","syncd_msg_date_enabled","bank-ref-id","max_subject","payments_web_enabled","web_upload_document_thumb_mms_enabled","size","request","ephemeral","24","receipt_agg","ptt_remember_play_position","sampling_weight","enc_rekey","mute_always","037","034","23","036","action","click_to_chat_qr_enabled","width","disabled","038","md_blocklist_v2","played_self_enabled","web_buttons_message_enabled","flow_id","clear","450","fbid:thread","bloks_session_state","America/Lima","attachment_picker_refresh","download_host_switching_enabled","1792","u_aud_limit_sil_restarts_test2","custom_urls","device_fanout","optimistic_upload","2000","key_cipher_suite","web_smb_upsell_in_biz_profile_enabled","e","039","siri_post_status_shortcut","pair-device","lg","lc","stream_attribution_url","model","mspjpeg_phash_gen","catalog_send_all","new_multi_vcards_ui","share_biz_vcard_enabled","-","clean","200","md_blocklist_v2_server","03b","03a","web_md_migration_experience","ptt_conversation_waveform","u_aud_limit_sil_restarts_test1"],["64","ptt_playback_speed_enabled","web_product_list_message_enabled","paid_convo_ts","27","manufacturer","psp-routing","grp_uii_cleanup","ptt_draft_enabled","03c","business_initiated","web_catalog_products_onoff","web_upload_link_thumb_mms_enabled","03e","mediaretry","35","hfm_string_changes","28","America/Fortaleza","max_keys","md_mhfs_days","streaming_upload_chunk_size","5541","040","03d","2675","03f","...","512","mute","48","041","alt_jpeg_quality","60","042","md_smb_quick_reply","5183","c","1343","40","1230","043","044","mms_cat_v1_forward_hot_override_enabled","user_notice","ptt_waveform_send","047","Asia/Calcutta","250","md_privacy_v2","31","29","128","md_messaging_enabled","046","crypto","690","045","enc_iv","75","failure","ptt_oot_playback","AIzaSyDR5yfaG7OG8sMTUj8kfQEb8T9pN8BM6Lk","w","048","2201","web_large_files_ui","Asia/Makassar","812","status_collapse_muted","1334","257","2HP4dm","049","patches","1290","43cY6T","America/Caracas","web_sticker_maker","campaign","ptt_pausable_enabled","33","42","attestation","biz","04b","query_linked","s","125","04a","810","availability","1411","responsiveness_v2_m1","catalog_not_created","34","America/Santiago","1465","enc_p","04d","status_info","04f","key_version","..","04c","04e","md_group_notification","1598","1215","web_cart_enabled","37","630","1920","2394","-1","vcard","38","elapsed","36","828","peer","pricing_category","1245","invalid","stella_ios_enabled","2687","45","1528","39","u_is_redial_audio_1104_ctrl","1025","1455","58","2524","2603","054","bsp_system_message_enabled","web_pip_redesign","051","verify_apps","1974","1272","1322","1755","052","70","050","1063","1135","1361","80","1096","1828","1851","1251","1921","key_config_id","1254","1566","1252","2525","critical_block","1669","max_available","w:auth:backup:token","product","2530","870","1022","participant_uuid","web_cart_on_off","1255","1432","1867","41","1415","1440","240","1204","1608","1690","1846","1483","1687","1749","69","url_number","053","1325","1040","365","59","Asia/Riyadh","1177","test_recommended","057","1612","43","1061","1518","1635","055","1034","1375","750","1430","event_code","1682","503","55","865","78","1309","1365","44","America/Guayaquil","535","LIMITED","1377","1613","1420","1599","1822","05a","1681","password","1111","1214","1376","1478","47","1082","4282","Europe/Istanbul","1307","46","058","1124","256","rate-overlimit","retail","u_a_socket_err_fix_succ_test","1292","1370","1388","520","861","psa","regular","1181","1766","05b","1183","1213","1304","1537"],["1724","profile_picture","1071","1314","1605","407","990","1710","746","pricing_model","056","059","061","1119","6027","65","877","1607","05d","917","seen","1516","49","470","973","1037","1350","1394","1480","1796","keys","794","1536","1594","2378","1333","1524","1825","116","309","52","808","827","909","495","1660","361","957","google","1357","1565","1967","996","1775","586","736","1052","1670","bank","177","1416","2194","2222","1454","1839","1275","53","997","1629","6028","smba","1378","1410","05c","1849","727","create","1559","536","1106","1310","1944","670","1297","1316","1762","en","1148","1295","1551","1853","1890","1208","1784","7200","05f","178","1283","1332","381","643","1056","1238","2024","2387","179","981","1547","1705","05e","290","903","1069","1285","2436","062","251","560","582","719","56","1700","2321","325","448","613","777","791","51","488","902","Asia/Almaty","is_hidden","1398","1527","1893","1999","2367","2642","237","busy","065","067","233","590","993","1511","54","723","860","363","487","522","605","995","1321","1691","1865","2447","2462","NON_TRANSACTIONAL","433","871","432","1004","1207","2032","2050","2379","2446","279","636","703","904","248","370","691","700","1068","1655","2334","060","063","364","533","534","567","1191","1210","1473","1827","069","701","2531","514","prev_dhash","064","496","790","1046","1139","1505","1521","1108","207","544","637","final","1173","1293","1694","1939","1951","1993","2353","2515","504","601","857","modify","spam_request","p_121_aa_1101_test4","866","1427","1502","1638","1744","2153","068","382","725","1704","1864","1990","2003","Asia/Dubai","508","531","1387","1474","1632","2307","2386","819","2014","066","387","1468","1706","2186","2261","471","728","1147","1372","1961"]],GX=["","xmlstreamstart","xmlstreamend","s.whatsapp.net","type","participant","from","receipt","id","notification","disappearing_mode","status","jid","broadcast","user","devices","device_hash","to","offline","message","result","class","xmlns","duration","notify","iq","t","ack","g.us","enc","urn:xmpp:whatsapp:push","presence","config_value","picture","verified_name","config_code","key-index-list","contact","mediatype","routing_info","edge_routing","get","read","urn:xmpp:ping","fallback_hostname","0","chatstate","business_hours_config","unavailable","download_buckets","skmsg","verified_level","composing","handshake","device-list","media","text","fallback_ip4","media_conn","device","creation","location","config","item","fallback_ip6","count","w:profile:picture","image","business","2","hostname","call-creator","display_name","relaylatency","platform","abprops","success","msg","offline_preview","prop","key-index","v","day_of_week","pkmsg","version","1","ping","w:p","download","video","set","specific_hours","props","primary","unknown","hash","commerce_experience","last","subscribe","max_buckets","call","profile","member_since_text","close_time","call-id","sticker","mode","participants","value","query","profile_options","open_time","code","list","host","ts","contacts","upload","lid","preview","update","usync","w:stats","delivery","auth_ttl","context","fail","cart_enabled","appdata","category","atn","direct_connection","decrypt-fail","relay_id","mmg-fallback.whatsapp.net","target","available","name","last_id","mmg.whatsapp.net","categories","401","is_new","index","tctoken","ip4","token_id","latency","recipient","edit","ip6","add","thumbnail-document","26","paused","true","identity","stream:error","key","sidelist","background","audio","3","thumbnail-image","biz-cover-photo","cat","gcm","thumbnail-video","error","auth","deny","serial","in","registration","thumbnail-link","remove","00","gif","thumbnail-gif","tag","capability","multicast","item-not-found","description","business_hours","config_expo_key","md-app-state","expiration","fallback","ttl","300","md-msg-hist","device_orientation","out","w:m","open_24h","side_list","token","inactive","01","document","te2","played","encrypt","msgr","hide","direct_path","12","state","not-authorized","url","terminate","signature","status-revoke-delay","02","te","linked_accounts","trusted_contact","timezone","ptt","kyc-id","privacy_token","readreceipts","appointment_only","address","expected_ts","privacy","7","android","interactive","device-identity","enabled","attribute_padding","1080","03","screen_height"],BF={};for(let[n,t]of GX.entries())BF[t]={index:n};for(let[n,t]of PX.entries())for(let[o,i]of t.entries())BF[i]={dict:n,index:o};var OA="@s.whatsapp.net";var FX="0@c.us";var jt;(function(n){n[n.WHATSAPP=0]="WHATSAPP",n[n.LID=1]="LID",n[n.HOSTED=128]="HOSTED",n[n.HOSTED_LID=129]="HOSTED_LID"})(jt||(jt={}));var LX=(n,t)=>{switch(t){case jt.LID:return"lid";case jt.HOSTED:return"hosted";case jt.HOSTED_LID:return"hosted.lid";case jt.WHATSAPP:default:return n}},Cr=(n,t,o,i)=>`${n||""}${i?`_${i}`:""}${o?`:${o}`:""}@${t}`,yA=n=>{let t=typeof n=="string"?n.indexOf("@"):-1;if(t<0)return;let o=n.slice(t+1),i=n.slice(0,t),[e,a]=i.split(":"),[A,r]=e.split("_"),s=jt.WHATSAPP;return o==="lid"?s=jt.LID:o==="hosted"?s=jt.HOSTED:o==="hosted.lid"?s=jt.HOSTED_LID:r&&(s=parseInt(r)),{server:o,user:A,domainType:s,device:a?+a:void 0}},Tt=(n,t)=>yA(n)?.user===yA(t)?.user,rh=n=>n?.endsWith("@bot"),_t=n=>n?.endsWith("@s.whatsapp.net"),qA=n=>n?.endsWith("@lid"),EB=n=>n?.endsWith("@broadcast"),Ur=n=>n?.endsWith("@g.us"),Tg=n=>n==="status@broadcast",Kc=n=>n?.endsWith("@newsletter"),ur=n=>n?.endsWith("@hosted"),ga=n=>n?.endsWith("@hosted.lid"),cUe=/^1313555\d{4}$|^131655500\d{2}$/,UX=n=>n&&cUe.test(n.split("@")[0])&&n.endsWith("@c.us"),uA=n=>{let t=yA(n);if(!t)return"";let{user:o,server:i}=t;return Cr(o,i==="c.us"?"s.whatsapp.net":i)},HX=(n,t)=>{let i=yA(n)?.device||0,{server:e,user:a}=yA(t);return Cr(a,e,i)};var KX=(n,t=hB,o=[0])=>{let i=xX(n,t,o);return Buffer.from(i)},xX=({tag:n,attrs:t,content:o},i,e)=>{let{TAGS:a,TOKEN_MAP:A}=i,r=F=>e.push(F&255),s=(F,q,z=!1)=>{for(let j=0;j>P*8&255)}},g=F=>{for(let q of F)e.push(q)},c=F=>{g([F>>8&255,F&255])},I=F=>g([F>>16&15,F>>8&255,F&255]),d=F=>{if(F>=4294967296)throw new Error("string too large to encode: "+F);F>=1<<20?(r(a.BINARY_32),s(F,4)):F>=256?(r(a.BINARY_20),I(F)):(r(a.BINARY_8),r(F))},B=F=>{let q=Buffer.from(F,"utf-8");d(q.length),g(q)},f=({domainType:F,device:q,user:z,server:j})=>{typeof q<"u"?(r(a.AD_JID),r(F||0),r(q||0),R(z)):(r(a.JID_PAIR),z.length?R(z):r(a.LIST_EMPTY),R(j))},Q=F=>{switch(F){case"-":return 10;case".":return 11;case"\0":return 15;default:if(F>="0"&&F<="9")return F.charCodeAt(0)-48;throw new Error(`invalid byte for nibble "${F}"`)}},y=F=>{if(F>="0"&&F<="9")return F.charCodeAt(0)-48;if(F>="A"&&F<="F")return 10+F.charCodeAt(0)-65;if(F>="a"&&F<="f")return 10+F.charCodeAt(0)-97;if(F==="\0")return 15;throw new Error(`Invalid hex char "${F}"`)},m=(F,q)=>{if(F.length>a.PACKED_MAX)throw new Error("Too many bytes to pack");r(q==="nibble"?a.NIBBLE_8:a.HEX_8);let z=Math.ceil(F.length/2);F.length%2!==0&&(z|=128),r(z);let j=q==="nibble"?Q:y,P=(H,N)=>j(H)<<4|j(N),J=Math.floor(F.length/2);for(let H=0;H{if(!F||F.length>a.PACKED_MAX)return!1;for(let q of F)if(!(q>="0"&&q<="9")&&q!=="-"&&q!==".")return!1;return!0},T=F=>{if(!F||F.length>a.PACKED_MAX)return!1;for(let q of F)if(!(q>="0"&&q<="9")&&!(q>="A"&&q<="F"))return!1;return!0},R=F=>{if(F==null){r(a.LIST_EMPTY);return}if(F===""){B(F);return}let q=A[F];if(q)typeof q.dict=="number"&&r(a.DICTIONARY_0+q.dict),r(q.index);else if(_(F))m(F,"nibble");else if(T(F))m(F,"hex");else{let z=yA(F);z?f(z):B(F)}},L=F=>{F===0?r(a.LIST_EMPTY):F<256?g([a.LIST_8,F]):(r(a.LIST_16),c(F))};if(!n)throw new Error("Invalid node: tag cannot be undefined");let U=Object.keys(t||{}).filter(F=>typeof t[F]<"u"&&t[F]!==null);L(2*U.length+1+(typeof o<"u"?1:0)),R(n);for(let F of U)typeof t[F]=="string"&&(R(F),R(t[F]));if(typeof o=="string")R(o);else if(Buffer.isBuffer(o)||o instanceof Uint8Array)d(o.length),g(o);else if(Array.isArray(o)){let F=o.filter(q=>q&&(q.tag||Buffer.isBuffer(q)||q instanceof Uint8Array||typeof q=="string"));L(F.length);for(let q of F)xX(q,i,e)}else if(!(typeof o>"u"))throw new Error(`invalid children for header "${n}": ${o} (${typeof o})`);return e};import{promisify as IUe}from"util";import{inflate as lUe}from"zlib";var pUe=IUe(lUe),dUe=async n=>(2&n.readUInt8()?n=await pUe(n.slice(1)):n=n.slice(1),n),YX=(n,t,o={index:0})=>{let{DOUBLE_BYTE_TOKENS:i,SINGLE_BYTE_TOKENS:e,TAGS:a}=t,A=k=>{if(o.index+k>n.length)throw new Error("end of stream")},r=()=>{let k=n[o.index];return o.index+=1,k},s=()=>(A(1),r()),g=k=>{A(k);let V=n.slice(o.index,o.index+k);return o.index+=k,V},c=k=>g(k).toString("utf-8"),I=(k,V=!1)=>{A(k);let Ae=0;for(let ie=0;ie(A(3),((r()&15)<<16)+(r()<<8)+r()),B=k=>{if(k>=0&&k<16)return k<10?48+k:65+k-10;throw new Error("invalid hex: "+k)},f=k=>{if(k>=0&&k<=9)return 48+k;switch(k){case 10:return 45;case 11:return 46;case 15:return 0;default:throw new Error("invalid nibble: "+k)}},Q=(k,V)=>{if(k===a.NIBBLE_8)return f(V);if(k===a.HEX_8)return B(V);throw new Error("unknown tag: "+k)},y=k=>{let V=s(),Ae="";for(let ie=0;ie<(V&127);ie++){let De=s();Ae+=String.fromCharCode(Q(k,(De&240)>>4)),Ae+=String.fromCharCode(Q(k,De&15))}return V>>7!==0&&(Ae=Ae.slice(0,-1)),Ae},m=k=>k===a.LIST_EMPTY||k===a.LIST_8||k===a.LIST_16,_=k=>{switch(k){case a.LIST_EMPTY:return 0;case a.LIST_8:return s();case a.LIST_16:return I(2);default:throw new Error("invalid tag for list size: "+k)}},T=()=>{let k=F(s()),V=F(s());if(V)return(k||"")+"@"+V;throw new Error("invalid jid pair: "+k+", "+V)},R=()=>{let k=s(),V=Number(k),Ae=s(),ie=F(s()),De="s.whatsapp.net";return V===jt.LID?De="lid":V===jt.HOSTED?De="hosted":V===jt.HOSTED_LID&&(De="hosted.lid"),Cr(ie,De,Ae)},L=()=>{let k=F(s()),V=I(2),Ae=F(s());return`${k}:${V}@${Ae}`},U=()=>{let k=F(s()),V=I(2),Ae=I(2),ie="interop",De=o.index;try{ie=F(s())}catch{o.index=De}return`${Ae}-${k}:${V}@${ie}`},F=k=>{if(k>=1&&k{let V=[],Ae=_(k);for(let ie=0;ie{let Ae=i[k];if(!Ae)throw new Error(`Invalid double token dict (${k})`);let ie=Ae[V];if(typeof ie>"u")throw new Error(`Invalid double token (${V})`);return ie},j=_(s()),P=F(s());if(!j||!P.length)throw new Error("invalid node");let J={},H;if(j===0||!P)throw new Error("invalid node");let N=j-1>>1;for(let k=0;k{let t=await dUe(n);return YX(t,hB)};var qX=Je(Lr(),1);var JX=new WeakMap,kA=(n,t)=>{if(!n||!Array.isArray(n.content))return[];let o=JX.get(n);if(!o){o=new Map;for(let i of n.content){let e=o.get(i.tag);e||o.set(i.tag,e=[]),e.push(i)}JX.set(n,o)}return o.get(t)||[]},le=(n,t)=>kA(n,t)[0],ys=({content:n})=>Array.isArray(n)?n:[],Qa=(n,t)=>{let o=le(n,t)?.content;if(Buffer.isBuffer(o)||o instanceof Uint8Array)return o},YA=(n,t)=>{let o=le(n,t)?.content;if(Buffer.isBuffer(o)||o instanceof Uint8Array)return Buffer.from(o).toString("utf-8");if(typeof o=="string")return o},xc=(n,t,o)=>{let i=Qa(n,t);if(i)return hUe(i,o)},Li=n=>{let t=le(n,"error");if(t)throw new qX.Boom(t.attrs.text||"Unknown error",{data:+t.attrs.code})},fF=(n,t)=>kA(n,t).reduce((e,{attrs:a})=>(typeof a.name=="string"?e[a.name]=a.value||a.config_value:e[a.config_code]=a.value||a.config_value,e),{});function hUe(n,t){let o=0;for(let i=0;i" ".repeat(n);function _n(n,t=0){if(!n)return n;if(typeof n=="string")return Vw(t)+n;if(n instanceof Uint8Array)return Vw(t)+Buffer.from(n).toString("hex");if(Array.isArray(n))return n.map(a=>Vw(t+1)+_n(a,t+1)).join(` `);let o=_n(n.content,t+1),i=`<${n.tag} ${Object.entries(n.attrs||{}).filter(([,a])=>a!==void 0).map(([a,A])=>`${a}='${A}'`).join(" ")}`,e=o?`> ${o} ${Vw(t)}`:"/>";return i+e}var Jc=Je(vc(),1);import{createCipheriv as DF,createDecipheriv as OF,createHash as _Ue,createHmac as TUe,randomBytes as NUe}from"crypto";var QB=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,zX.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,zX.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_expandedappstatekeys_free(t,0)}get indexKey(){let t=ae.expandedappstatekeys_indexKey(this.__wbg_ptr);return mA(t)}get patchMacKey(){let t=ae.expandedappstatekeys_patchMacKey(this.__wbg_ptr);return mA(t)}get snapshotMacKey(){let t=ae.expandedappstatekeys_snapshotMacKey(this.__wbg_ptr);return mA(t)}get valueEncryptionKey(){let t=ae.expandedappstatekeys_valueEncryptionKey(this.__wbg_ptr);return mA(t)}get valueMacKey(){let t=ae.expandedappstatekeys_valueMacKey(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(QB.prototype[Symbol.dispose]=QB.prototype.free);var Zw=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,VX.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_groupcipher_free(t,0)}decrypt(t){let o=Nt(t,ae.__wbindgen_export),i=HA,e=ae.groupcipher_decrypt(this.__wbg_ptr,o,i);return mA(e)}encrypt(t){let o=Nt(t,ae.__wbindgen_export),i=HA,e=ae.groupcipher_encrypt(this.__wbg_ptr,o,i);return mA(e)}constructor(t,o,i){let e=Nn(o,ae.__wbindgen_export,ae.__wbindgen_export2),a=HA;Yc(i,jc);let A=ae.groupcipher_new(rA(t),e,a,i.__wbg_ptr);return this.__wbg_ptr=A>>>0,VX.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(Zw.prototype[Symbol.dispose]=Zw.prototype.free);var Xw=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,WX.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_groupsessionbuilder_free(t,0)}create(t){Yc(t,nh);let o=ae.groupsessionbuilder_create(this.__wbg_ptr,t.__wbg_ptr);return mA(o)}constructor(t){let o=ae.groupsessionbuilder_new(rA(t));return this.__wbg_ptr=o>>>0,WX.register(this,this.__wbg_ptr,this),this}process(t,o){Yc(t,nh),Yc(o,oh);let i=ae.groupsessionbuilder_process(this.__wbg_ptr,t.__wbg_ptr,o.__wbg_ptr);return mA(i)}};Symbol.dispose&&(Xw.prototype[Symbol.dispose]=Xw.prototype.free);var yB=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,ZX.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,ZX.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_internalbinarynode_free(t,0)}get attrs(){let t=ae.internalbinarynode_attrs(this.__wbg_ptr);return mA(t)}get content(){let t=ae.internalbinarynode_content(this.__wbg_ptr);return mA(t)}set attrs(t){ae.internalbinarynode_set_attrs(this.__wbg_ptr,rA(t))}set content(t){ae.internalbinarynode_set_content(this.__wbg_ptr,rA(t))}get tag(){let t,o;try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.internalbinarynode_tag(a,this.__wbg_ptr);var i=Xe().getInt32(a+0,!0),e=Xe().getInt32(a+4,!0);return t=i,o=e,Nr(i,e)}finally{ae.__wbindgen_add_to_stack_pointer(16),ae.__wbindgen_export4(t,o,1)}}toJSON(){let t=ae.internalbinarynode_toJSON(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(yB.prototype[Symbol.dispose]=yB.prototype.free);var ih=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,XX.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_lthashantitampering_free(t,0)}constructor(){let t=ae.lthashantitampering_new();return this.__wbg_ptr=t>>>0,XX.register(this,this.__wbg_ptr,this),this}subtractThenAdd(t,o,i){try{let r=ae.__wbindgen_add_to_stack_pointer(-16),s=Nt(t,ae.__wbindgen_export),g=HA,c=o7(o,ae.__wbindgen_export),I=HA,d=o7(i,ae.__wbindgen_export),B=HA;ae.lthashantitampering_subtractThenAdd(r,this.__wbg_ptr,s,g,c,I,d,B);var e=Xe().getInt32(r+0,!0),a=Xe().getInt32(r+4,!0),A=Xe().getInt32(r+8,!0);if(A)throw mA(a);return mA(e)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(ih.prototype[Symbol.dispose]=ih.prototype.free);var $w=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,QF.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,QF.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_lthashstate_free(t,0)}clone(){let t=ae.lthashstate_clone(this.__wbg_ptr);return n.__wrap(t)}deleteValueMac(t){let o=Nn(t,ae.__wbindgen_export,ae.__wbindgen_export2),i=HA;return ae.lthashstate_deleteValueMac(this.__wbg_ptr,o,i)!==0}getValueMac(t){let o=Nn(t,ae.__wbindgen_export,ae.__wbindgen_export2),i=HA,e=ae.lthashstate_getValueMac(this.__wbg_ptr,o,i);return mA(e)}hasValueMac(t){let o=Nn(t,ae.__wbindgen_export,ae.__wbindgen_export2),i=HA;return ae.lthashstate_hasValueMac(this.__wbg_ptr,o,i)!==0}get hash(){let t=ae.lthashstate_hash(this.__wbg_ptr);return mA(t)}constructor(){let t=ae.lthashstate_new();return this.__wbg_ptr=t>>>0,QF.register(this,this.__wbg_ptr,this),this}setValueMac(t,o){let i=Nn(t,ae.__wbindgen_export,ae.__wbindgen_export2),e=HA,a=Nt(o,ae.__wbindgen_export),A=HA;ae.lthashstate_setValueMac(this.__wbg_ptr,i,e,a,A)}set hash(t){let o=Nt(t,ae.__wbindgen_export),i=HA;ae.lthashstate_set_hash(this.__wbg_ptr,o,i)}set version(t){ae.lthashstate_set_version(this.__wbg_ptr,t)}get version(){let t=ae.lthashstate_version(this.__wbg_ptr);return BigInt.asUintN(64,t)}};Symbol.dispose&&($w.prototype[Symbol.dispose]=$w.prototype.free);var eD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,$X.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_noisesession_free(t,0)}authenticate(t){let o=Nt(t,ae.__wbindgen_export),i=HA;ae.noisesession_authenticate(this.__wbg_ptr,o,i)}get bufferedBytes(){return ae.noisesession_bufferedBytes(this.__wbg_ptr)>>>0}clearBuffer(){ae.noisesession_clearBuffer(this.__wbg_ptr)}decodeFrame(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=Nt(t,ae.__wbindgen_export),r=HA;ae.noisesession_decodeFrame(a,this.__wbg_ptr,A,r);var o=Xe().getInt32(a+0,!0),i=Xe().getInt32(a+4,!0),e=Xe().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}decrypt(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=Nt(t,ae.__wbindgen_export),r=HA;ae.noisesession_decrypt(a,this.__wbg_ptr,A,r);var o=Xe().getInt32(a+0,!0),i=Xe().getInt32(a+4,!0),e=Xe().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}encodeFrame(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.noisesession_encodeFrame(a,this.__wbg_ptr,rA(t));var o=Xe().getInt32(a+0,!0),i=Xe().getInt32(a+4,!0),e=Xe().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}encodeFrameRaw(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=Nt(t,ae.__wbindgen_export),r=HA;ae.noisesession_encodeFrameRaw(a,this.__wbg_ptr,A,r);var o=Xe().getInt32(a+0,!0),i=Xe().getInt32(a+4,!0),e=Xe().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}encrypt(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=Nt(t,ae.__wbindgen_export),r=HA;ae.noisesession_encrypt(a,this.__wbg_ptr,A,r);var o=Xe().getInt32(a+0,!0),i=Xe().getInt32(a+4,!0),e=Xe().getInt32(a+8,!0);if(e)throw mA(i);return mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}finishInit(){try{let i=ae.__wbindgen_add_to_stack_pointer(-16);ae.noisesession_finishInit(i,this.__wbg_ptr);var t=Xe().getInt32(i+0,!0),o=Xe().getInt32(i+4,!0);if(o)throw mA(t)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}getHash(){let t=ae.noisesession_getHash(this.__wbg_ptr);return mA(t)}get isFinished(){return ae.noisesession_isFinished(this.__wbg_ptr)!==0}mixIntoKey(t){try{let e=ae.__wbindgen_add_to_stack_pointer(-16),a=Nt(t,ae.__wbindgen_export),A=HA;ae.noisesession_mixIntoKey(e,this.__wbg_ptr,a,A);var o=Xe().getInt32(e+0,!0),i=Xe().getInt32(e+4,!0);if(i)throw mA(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}constructor(t,o,i){try{let g=ae.__wbindgen_add_to_stack_pointer(-16),c=Nt(t,ae.__wbindgen_export),I=HA,d=Nt(o,ae.__wbindgen_export),B=HA;var e=Tn(i)?0:Nt(i,ae.__wbindgen_export),a=HA;ae.noisesession_new(g,c,I,d,B,e,a);var A=Xe().getInt32(g+0,!0),r=Xe().getInt32(g+4,!0),s=Xe().getInt32(g+8,!0);if(s)throw mA(r);return this.__wbg_ptr=A>>>0,$X.register(this,this.__wbg_ptr,this),this}finally{ae.__wbindgen_add_to_stack_pointer(16)}}processHandshakeFinish(t,o,i){try{let r=ae.__wbindgen_add_to_stack_pointer(-16),s=Nt(t,ae.__wbindgen_export),g=HA,c=Nt(o,ae.__wbindgen_export),I=HA,d=Nt(i,ae.__wbindgen_export),B=HA;ae.noisesession_processHandshakeFinish(r,this.__wbg_ptr,s,g,c,I,d,B);var e=Xe().getInt32(r+0,!0),a=Xe().getInt32(r+4,!0),A=Xe().getInt32(r+8,!0);if(A)throw mA(a);return mA(e)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}processHandshakeInit(t,o,i,e){try{let s=ae.__wbindgen_add_to_stack_pointer(-16),g=Nt(t,ae.__wbindgen_export),c=HA,I=Nt(o,ae.__wbindgen_export),d=HA,B=Nt(i,ae.__wbindgen_export),f=HA,Q=Nt(e,ae.__wbindgen_export),y=HA;ae.noisesession_processHandshakeInit(s,this.__wbg_ptr,g,c,I,d,B,f,Q,y);var a=Xe().getInt32(s+0,!0),A=Xe().getInt32(s+4,!0),r=Xe().getInt32(s+8,!0);if(r)throw mA(A);return mA(a)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(eD.prototype[Symbol.dispose]=eD.prototype.free);var jc=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,yF.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,yF.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_protocoladdress_free(t,0)}get deviceId(){return ae.protocoladdress_deviceId(this.__wbg_ptr)>>>0}static from(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.protocoladdress_from(a,rA(t));var o=Xe().getInt32(a+0,!0),i=Xe().getInt32(a+4,!0),e=Xe().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}get id(){let t,o;try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.protocoladdress_id(a,this.__wbg_ptr);var i=Xe().getInt32(a+0,!0),e=Xe().getInt32(a+4,!0);return t=i,o=e,Nr(i,e)}finally{ae.__wbindgen_add_to_stack_pointer(16),ae.__wbindgen_export4(t,o,1)}}is(t){return Yc(t,n),ae.protocoladdress_is(this.__wbg_ptr,t.__wbg_ptr)!==0}constructor(t,o){try{let A=ae.__wbindgen_add_to_stack_pointer(-16);ae.protocoladdress_new(A,rA(t),rA(o));var i=Xe().getInt32(A+0,!0),e=Xe().getInt32(A+4,!0),a=Xe().getInt32(A+8,!0);if(a)throw mA(e);return this.__wbg_ptr=i>>>0,yF.register(this,this.__wbg_ptr,this),this}finally{ae.__wbindgen_add_to_stack_pointer(16)}}toString(){let t,o;try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.protocoladdress_toString(a,this.__wbg_ptr);var i=Xe().getInt32(a+0,!0),e=Xe().getInt32(a+4,!0);return t=i,o=e,Nr(i,e)}finally{ae.__wbindgen_add_to_stack_pointer(16),ae.__wbindgen_export4(t,o,1)}}};Symbol.dispose&&(jc.prototype[Symbol.dispose]=jc.prototype.free);var oh=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,e7.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,e7.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_senderkeydistributionmessage_free(t,0)}static deserialize(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=Nt(t,ae.__wbindgen_export),r=HA;ae.senderkeydistributionmessage_deserialize(a,A,r);var o=Xe().getInt32(a+0,!0),i=Xe().getInt32(a+4,!0),e=Xe().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}serialize(){let t=ae.senderkeydistributionmessage_serialize(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(oh.prototype[Symbol.dispose]=oh.prototype.free);var nh=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,A7.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_senderkeyname_free(t,0)}constructor(t,o){let i=Nn(t,ae.__wbindgen_export,ae.__wbindgen_export2),e=HA;Yc(o,jc);let a=ae.senderkeyname_new(i,e,o.__wbg_ptr);return this.__wbg_ptr=a>>>0,A7.register(this,this.__wbg_ptr,this),this}toString(){let t,o;try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.senderkeyname_toString(a,this.__wbg_ptr);var i=Xe().getInt32(a+0,!0),e=Xe().getInt32(a+4,!0);return t=i,o=e,Nr(i,e)}finally{ae.__wbindgen_add_to_stack_pointer(16),ae.__wbindgen_export4(t,o,1)}}};Symbol.dispose&&(nh.prototype[Symbol.dispose]=nh.prototype.free);var AD=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,mF.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,mF.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_senderkeyrecord_free(t,0)}static deserialize(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16),A=Nt(t,ae.__wbindgen_export),r=HA;ae.senderkeyrecord_deserialize(a,A,r);var o=Xe().getInt32(a+0,!0),i=Xe().getInt32(a+4,!0),e=Xe().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}isEmpty(){return ae.senderkeyrecord_isEmpty(this.__wbg_ptr)!==0}constructor(){let t=ae.senderkeyrecord_new();return this.__wbg_ptr=t>>>0,mF.register(this,this.__wbg_ptr,this),this}serialize(){try{let e=ae.__wbindgen_add_to_stack_pointer(-16);ae.senderkeyrecord_serialize(e,this.__wbg_ptr);var t=Xe().getInt32(e+0,!0),o=Xe().getInt32(e+4,!0),i=Xe().getInt32(e+8,!0);if(i)throw mA(o);return mA(t)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(AD.prototype[Symbol.dispose]=AD.prototype.free);var tD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,t7.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_sessionbuilder_free(t,0)}initOutgoing(t){let o=ae.sessionbuilder_initOutgoing(this.__wbg_ptr,rA(t));return mA(o)}constructor(t,o){Yc(o,jc);let i=ae.sessionbuilder_new(rA(t),o.__wbg_ptr);return this.__wbg_ptr=i>>>0,t7.register(this,this.__wbg_ptr,this),this}processPreKeyBundle(t){let o=ae.sessionbuilder_processPreKeyBundle(this.__wbg_ptr,rA(t));return mA(o)}};Symbol.dispose&&(tD.prototype[Symbol.dispose]=tD.prototype.free);var rD=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,r7.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_sessioncipher_free(t,0)}decryptPreKeyWhisperMessage(t){let o=Nt(t,ae.__wbindgen_export),i=HA,e=ae.sessioncipher_decryptPreKeyWhisperMessage(this.__wbg_ptr,o,i);return mA(e)}decryptWhisperMessage(t){let o=Nt(t,ae.__wbindgen_export),i=HA,e=ae.sessioncipher_decryptWhisperMessage(this.__wbg_ptr,o,i);return mA(e)}encrypt(t){let o=Nt(t,ae.__wbindgen_export),i=HA,e=ae.sessioncipher_encrypt(this.__wbg_ptr,o,i);return mA(e)}hasOpenSession(){let t=ae.sessioncipher_hasOpenSession(this.__wbg_ptr);return mA(t)}constructor(t,o){Yc(o,jc);let i=ae.sessioncipher_new(rA(t),o.__wbg_ptr);return this.__wbg_ptr=i>>>0,r7.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(rD.prototype[Symbol.dispose]=rD.prototype.free);var mB=class n{static __wrap(t){t=t>>>0;let o=Object.create(n.prototype);return o.__wbg_ptr=t,a7.register(o,o.__wbg_ptr,o),o}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,a7.unregister(this),t}free(){let t=this.__destroy_into_raw();ae.__wbg_sessionrecord_free(t,0)}static deserialize(t){try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.sessionrecord_deserialize(a,rA(t));var o=Xe().getInt32(a+0,!0),i=Xe().getInt32(a+4,!0),e=Xe().getInt32(a+8,!0);if(e)throw mA(i);return n.__wrap(o)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}haveOpenSession(){return ae.sessionrecord_haveOpenSession(this.__wbg_ptr)!==0}serialize(){let t=ae.sessionrecord_serialize(this.__wbg_ptr);return mA(t)}};Symbol.dispose&&(mB.prototype[Symbol.dispose]=mB.prototype.free);function n7(n){let t=Nt(n,ae.__wbindgen_export),o=HA,i=ae.expandAppStateKeys(t,o);return QB.__wrap(i)}function Rn(n,t,o){try{let A=ae.__wbindgen_add_to_stack_pointer(-16),r=Nt(n,ae.__wbindgen_export),s=HA;ae.hkdf(A,r,s,t,rA(o));var i=Xe().getInt32(A+0,!0),e=Xe().getInt32(A+4,!0),a=Xe().getInt32(A+8,!0);if(a)throw mA(e);return mA(i)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}function EUe(){return{__proto__:null,"./whatsapp_rust_bridge_bg.js":{__proto__:null,__wbg_Error_83742b46f01ce22d:function(t,o){let i=Error(Nr(t,o));return rA(i)},__wbg_Number_a5a435bd7bbec835:function(t){return Number(Pe(t))},__wbg_String_8564e559799eccda:function(t,o){let i=String(Pe(o)),e=Nn(i,ae.__wbindgen_export,ae.__wbindgen_export2),a=HA;Xe().setInt32(t+4,a,!0),Xe().setInt32(t+0,e,!0)},__wbg___wbindgen_bigint_get_as_i64_447a76b5c6ef7bda:function(t,o){let i=Pe(o),e=typeof i=="bigint"?i:void 0;Xe().setBigInt64(t+8,Tn(e)?BigInt(0):e,!0),Xe().setInt32(t+0,!Tn(e),!0)},__wbg___wbindgen_boolean_get_c0f3f60bac5a78d1:function(t){let o=Pe(t),i=typeof o=="boolean"?o:void 0;return Tn(i)?16777215:i?1:0},__wbg___wbindgen_debug_string_5398f5bb970e0daa:function(t,o){let i=wF(Pe(o)),e=Nn(i,ae.__wbindgen_export,ae.__wbindgen_export2),a=HA;Xe().setInt32(t+4,a,!0),Xe().setInt32(t+0,e,!0)},__wbg___wbindgen_in_41dbb8413020e076:function(t,o){return Pe(t)in Pe(o)},__wbg___wbindgen_is_bigint_e2141d4f045b7eda:function(t){return typeof Pe(t)=="bigint"},__wbg___wbindgen_is_function_3c846841762788c1:function(t){return typeof Pe(t)=="function"},__wbg___wbindgen_is_null_0b605fc6b167c56f:function(t){return Pe(t)===null},__wbg___wbindgen_is_object_781bc9f159099513:function(t){let o=Pe(t);return typeof o=="object"&&o!==null},__wbg___wbindgen_is_undefined_52709e72fb9f179c:function(t){return Pe(t)===void 0},__wbg___wbindgen_jsval_eq_ee31bfad3e536463:function(t,o){return Pe(t)===Pe(o)},__wbg___wbindgen_jsval_loose_eq_5bcc3bed3c69e72b:function(t,o){return Pe(t)==Pe(o)},__wbg___wbindgen_number_get_34bb9d9dcfa21373:function(t,o){let i=Pe(o),e=typeof i=="number"?i:void 0;Xe().setFloat64(t+8,Tn(e)?0:e,!0),Xe().setInt32(t+0,!Tn(e),!0)},__wbg___wbindgen_string_get_395e606bd0ee4427:function(t,o){let i=Pe(o),e=typeof i=="string"?i:void 0;var a=Tn(e)?0:Nn(e,ae.__wbindgen_export,ae.__wbindgen_export2),A=HA;Xe().setInt32(t+4,A,!0),Xe().setInt32(t+0,a,!0)},__wbg___wbindgen_throw_6ddd609b62940d55:function(t,o){throw new Error(Nr(t,o))},__wbg__wbg_cb_unref_6b5b6b8576d35cb1:function(t){Pe(t)._wbg_cb_unref()},__wbg_attrs_eb268b5ce109b817:function(t){let o=Pe(t).attrs;return rA(o)},__wbg_call_2d781c1f4d5c0ef8:function(){return Tr(function(t,o,i){let e=Pe(t).call(Pe(o),Pe(i));return rA(e)},arguments)},__wbg_call_e133b57c9155d22c:function(){return Tr(function(t,o){let i=Pe(t).call(Pe(o));return rA(i)},arguments)},__wbg_content_54fb4ecf37d1b68a:function(t){let o=Pe(t).content;return rA(o)},__wbg_debug_10ca7029b12f8d85:function(t,o,i,e){Pe(t).debug(Pe(o),i===0?void 0:Nr(i,e))},__wbg_done_08ce71ee07e3bd17:function(t){return Pe(t).done},__wbg_entries_e8a20ff8c9757101:function(t){let o=Object.entries(Pe(t));return rA(o)},__wbg_error_9cce413345f88385:function(t,o,i,e){Pe(t).error(Pe(o),i===0?void 0:Nr(i,e))},__wbg_from_4bdf88943703fd48:function(t){let o=Array.from(Pe(t));return rA(o)},__wbg_getOurIdentity_85a51d9b5b46c006:function(){return Tr(function(t){let o=Pe(t).getOurIdentity();return rA(o)},arguments)},__wbg_getOurRegistrationId_6d41d022f3c2af8a:function(){return Tr(function(t){let o=Pe(t).getOurRegistrationId();return rA(o)},arguments)},__wbg_getRandomValues_3f44b700395062e5:function(){return Tr(function(t,o){globalThis.crypto.getRandomValues(CB(t,o))},arguments)},__wbg_get_326e41e095fb2575:function(){return Tr(function(t,o){let i=Reflect.get(Pe(t),Pe(o));return rA(i)},arguments)},__wbg_get_3ef1eba1850ade27:function(){return Tr(function(t,o){let i=Reflect.get(Pe(t),Pe(o));return rA(i)},arguments)},__wbg_get_a8ee5c45dabc1b3b:function(t,o){let i=Pe(t)[o>>>0];return rA(i)},__wbg_get_unchecked_329cfe50afab7352:function(t,o){let i=Pe(t)[o>>>0];return rA(i)},__wbg_get_with_ref_key_6412cf3094599694:function(t,o){let i=Pe(t)[Pe(o)];return rA(i)},__wbg_has_926ef2ff40b308cf:function(){return Tr(function(t,o){return Reflect.has(Pe(t),Pe(o))},arguments)},__wbg_info_b728e87a346ff6a2:function(t,o,i,e){Pe(t).info(Pe(o),i===0?void 0:Nr(i,e))},__wbg_instanceof_ArrayBuffer_101e2bf31071a9f6:function(t){let o;try{o=Pe(t)instanceof ArrayBuffer}catch{o=!1}return o},__wbg_instanceof_Map_f194b366846aca0c:function(t){let o;try{o=Pe(t)instanceof Map}catch{o=!1}return o},__wbg_instanceof_Object_be1962063fcc0c9f:function(t){let o;try{o=Pe(t)instanceof Object}catch{o=!1}return o},__wbg_instanceof_Promise_7c3bdd7805c2c6e6:function(t){let o;try{o=Pe(t)instanceof Promise}catch{o=!1}return o},__wbg_instanceof_Uint8Array_740438561a5b956d:function(t){let o;try{o=Pe(t)instanceof Uint8Array}catch{o=!1}return o},__wbg_internalbinarynode_new:function(t){let o=yB.__wrap(t);return rA(o)},__wbg_isArray_33b91feb269ff46e:function(t){return Array.isArray(Pe(t))},__wbg_isSafeInteger_ecd6a7f9c3e053cd:function(t){return Number.isSafeInteger(Pe(t))},__wbg_isTrustedIdentity_8beedd37958ed6af:function(){return Tr(function(t,o,i,e,a){let A=Pe(t).isTrustedIdentity(Nr(o,i),Pe(e),a>>>0);return rA(A)},arguments)},__wbg_iterator_d8f549ec8fb061b1:function(){return rA(Symbol.iterator)},__wbg_keys_ab0d051a1c55236d:function(t){let o=Object.keys(Pe(t));return rA(o)},__wbg_length_b3416cf66a5452c8:function(t){return Pe(t).length},__wbg_length_ea16607d7b61445b:function(t){return Pe(t).length},__wbg_level_4b50b181832c5acf:function(t,o){let i=Pe(o).level,e=Nn(i,ae.__wbindgen_export,ae.__wbindgen_export2),a=HA;Xe().setInt32(t+4,a,!0),Xe().setInt32(t+0,e,!0)},__wbg_loadPreKey_db3458e3339f7328:function(){return Tr(function(t,o){let i=Pe(t).loadPreKey(o>>>0);return rA(i)},arguments)},__wbg_loadSenderKey_fd075b57283fd71b:function(){return Tr(function(t,o,i){let e=Pe(t).loadSenderKey(Nr(o,i));return rA(e)},arguments)},__wbg_loadSession_8564b20b09724f27:function(){return Tr(function(t,o,i){let e=Pe(t).loadSession(Nr(o,i));return rA(e)},arguments)},__wbg_loadSignedPreKey_3d5c6c6819f3adf3:function(){return Tr(function(t,o){let i=Pe(t).loadSignedPreKey(o>>>0);return rA(i)},arguments)},__wbg_new_5f486cdf45a04d78:function(t){let o=new Uint8Array(Pe(t));return rA(o)},__wbg_new_7dce085c132c6f91:function(t,o){let i=new TypeError(Nr(t,o));return rA(i)},__wbg_new_a70fbab9066b301f:function(){let t=new Array;return rA(t)},__wbg_new_ab79df5bd7c26067:function(){let t=new Object;return rA(t)},__wbg_new_from_slice_22da9388ac046e50:function(t,o){let i=new Uint8Array(CB(t,o));return rA(i)},__wbg_new_typed_aaaeaf29cf802876:function(t,o){try{var i={a:t,b:o},e=(A,r)=>{let s=i.a;i.a=0;try{return uUe(s,i.b,A,r)}finally{i.a=s}};let a=new Promise(e);return rA(a)}finally{i.a=i.b=0}},__wbg_new_with_length_3259a525196bd8cc:function(t){let o=new Array(t>>>0);return rA(o)},__wbg_new_with_length_825018a1616e9e55:function(t){let o=new Uint8Array(t>>>0);return rA(o)},__wbg_next_11b99ee6237339e3:function(){return Tr(function(t){let o=Pe(t).next();return rA(o)},arguments)},__wbg_next_e01a967809d1aa68:function(t){let o=Pe(t).next;return rA(o)},__wbg_parse_e9eddd2a82c706eb:function(){return Tr(function(t,o){let i=JSON.parse(Nr(t,o));return rA(i)},arguments)},__wbg_prototypesetcall_d62e5099504357e6:function(t,o,i){Uint8Array.prototype.set.call(CB(t,o),Pe(i))},__wbg_push_e87b0e732085a946:function(t,o){return Pe(t).push(Pe(o))},__wbg_queueMicrotask_0c399741342fb10f:function(t){let o=Pe(t).queueMicrotask;return rA(o)},__wbg_queueMicrotask_a082d78ce798393e:function(t){queueMicrotask(Pe(t))},__wbg_removePreKey_c0b0a066eb6f2e1e:function(){return Tr(function(t,o){let i=Pe(t).removePreKey(o>>>0);return rA(i)},arguments)},__wbg_resolve_ae8d83246e5bcc12:function(t){let o=Promise.resolve(Pe(t));return rA(o)},__wbg_senderkeydistributionmessage_new:function(t){let o=oh.__wrap(t);return rA(o)},__wbg_sessionrecord_new:function(t){let o=mB.__wrap(t);return rA(o)},__wbg_set_282384002438957f:function(t,o,i){Pe(t)[o>>>0]=mA(i)},__wbg_set_6be42768c690e380:function(t,o,i){Pe(t)[mA(o)]=mA(i)},__wbg_set_7eaa4f96924fd6b3:function(){return Tr(function(t,o,i){return Reflect.set(Pe(t),Pe(o),Pe(i))},arguments)},__wbg_set_8c0b3ffcf05d61c2:function(t,o,i){Pe(t).set(CB(o,i))},__wbg_static_accessor_GLOBAL_8adb955bd33fac2f:function(){let t=typeof global>"u"?null:global;return Tn(t)?0:rA(t)},__wbg_static_accessor_GLOBAL_THIS_ad356e0db91c7913:function(){let t=typeof globalThis>"u"?null:globalThis;return Tn(t)?0:rA(t)},__wbg_static_accessor_SELF_f207c857566db248:function(){let t=typeof self>"u"?null:self;return Tn(t)?0:rA(t)},__wbg_static_accessor_WINDOW_bb9f1ba69d61b386:function(){let t=typeof window>"u"?null:window;return Tn(t)?0:rA(t)},__wbg_storeSenderKey_8a6c9ec5f7e1cd2e:function(){return Tr(function(t,o,i,e){let a=Pe(t).storeSenderKey(Nr(o,i),Pe(e));return rA(a)},arguments)},__wbg_storeSessionRaw_09b5cc73064d12d8:function(){return Tr(function(t,o,i,e){let a=Pe(t).storeSessionRaw(Nr(o,i),Pe(e));return rA(a)},arguments)},__wbg_storeSession_4d419555ce654965:function(){return Tr(function(t,o,i,e){let a=Pe(t).storeSession(Nr(o,i),mA(e));return rA(a)},arguments)},__wbg_tag_33cfe8e9ee66b4db:function(t,o){let i=Pe(o).tag,e=Nn(i,ae.__wbindgen_export,ae.__wbindgen_export2),a=HA;Xe().setInt32(t+4,a,!0),Xe().setInt32(t+0,e,!0)},__wbg_then_098abe61755d12f6:function(t,o){let i=Pe(t).then(Pe(o));return rA(i)},__wbg_then_9e335f6dd892bc11:function(t,o,i){let e=Pe(t).then(Pe(o),Pe(i));return rA(e)},__wbg_trace_58264fbce2ceb5e6:function(t,o,i,e){Pe(t).trace(Pe(o),i===0?void 0:Nr(i,e))},__wbg_value_21fc78aab0322612:function(t){let o=Pe(t).value;return rA(o)},__wbg_warn_db531770752932a9:function(t,o,i,e){Pe(t).warn(Pe(o),i===0?void 0:Nr(i,e))},__wbindgen_cast_0000000000000001:function(t,o){let i=fUe(t,o,ae.__wasm_bindgen_func_elem_694,CUe);return rA(i)},__wbindgen_cast_0000000000000002:function(t){return rA(t)},__wbindgen_cast_0000000000000003:function(t){return rA(t)},__wbindgen_cast_0000000000000004:function(t,o){let i=CB(t,o);return rA(i)},__wbindgen_cast_0000000000000005:function(t,o){let i=Nr(t,o);return rA(i)},__wbindgen_cast_0000000000000006:function(t){let o=BigInt.asUintN(64,t);return rA(o)},__wbindgen_object_clone_ref:function(t){let o=Pe(t);return rA(o)},__wbindgen_object_drop_ref:function(t){mA(t)}}}}function CUe(n,t,o){try{let a=ae.__wbindgen_add_to_stack_pointer(-16);ae.__wasm_bindgen_func_elem_699(a,n,t,rA(o));var i=Xe().getInt32(a+0,!0),e=Xe().getInt32(a+4,!0);if(e)throw mA(i)}finally{ae.__wbindgen_add_to_stack_pointer(16)}}function uUe(n,t,o,i){ae.__wasm_bindgen_func_elem_1248(n,t,rA(o),rA(i))}var zX=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_expandedappstatekeys_free(n>>>0,1)),VX=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_groupcipher_free(n>>>0,1)),WX=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_groupsessionbuilder_free(n>>>0,1)),ZX=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_internalbinarynode_free(n>>>0,1)),XX=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_lthashantitampering_free(n>>>0,1)),QF=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_lthashstate_free(n>>>0,1)),$X=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_noisesession_free(n>>>0,1)),yF=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_protocoladdress_free(n>>>0,1)),e7=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_senderkeydistributionmessage_free(n>>>0,1)),A7=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_senderkeyname_free(n>>>0,1)),mF=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_senderkeyrecord_free(n>>>0,1)),t7=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_sessionbuilder_free(n>>>0,1)),r7=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_sessioncipher_free(n>>>0,1)),a7=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>ae.__wbg_sessionrecord_free(n>>>0,1));function rA(n){BB===Ng.length&&Ng.push(Ng.length+1);let t=BB;return BB=Ng[t],Ng[t]=n,t}function Yc(n,t){if(!(n instanceof t))throw new Error(`expected instance of ${t.name}`)}var i7=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>n.dtor(n.a,n.b));function wF(n){let t=typeof n;if(t=="number"||t=="boolean"||n==null)return`${n}`;if(t=="string")return`"${n}"`;if(t=="symbol"){let e=n.description;return e==null?"Symbol":`Symbol(${e})`}if(t=="function"){let e=n.name;return typeof e=="string"&&e.length>0?`Function(${e})`:"Function"}if(Array.isArray(n)){let e=n.length,a="[";e>0&&(a+=wF(n[0]));for(let A=1;A1)i=o[1];else return toString.call(n);if(i=="Object")try{return"Object("+JSON.stringify(n)+")"}catch{return"Object"}return n instanceof Error?`${n.name}: ${n.message} -${n.stack}`:i}function BUe(n){n<1028||(Ng[n]=BB,BB=n)}function CB(n,t){return n=n>>>0,ah().subarray(n/1,n/1+t)}var wl=null;function Xe(){return(wl===null||wl.buffer.detached===!0||wl.buffer.detached===void 0&&wl.buffer!==ae.memory.buffer)&&(wl=new DataView(ae.memory.buffer)),wl}function Nr(n,t){return n=n>>>0,yUe(n,t)}var uB=null;function ah(){return(uB===null||uB.byteLength===0)&&(uB=new Uint8Array(ae.memory.buffer)),uB}function Pe(n){return Ng[n]}function Tr(n,t){try{return n.apply(this,t)}catch(o){ae.__wbindgen_export3(rA(o))}}var Ng=new Array(1024).fill(void 0);Ng.push(void 0,null,!0,!1);var BB=Ng.length;function Tn(n){return n==null}function fUe(n,t,o,i){let e={a:n,b:t,cnt:1,dtor:o},a=(...A)=>{e.cnt++;let r=e.a;e.a=0;try{return i(r,e.b,...A)}finally{e.a=r,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--e.cnt===0&&(e.dtor(e.a,e.b),e.a=0,i7.unregister(e))},i7.register(a,e,e),a}function Nt(n,t){let o=t(n.length*1,1)>>>0;return ah().set(n,o/1),HA=n.length,o}function o7(n,t){let o=t(n.length*4,4)>>>0,i=Xe();for(let e=0;e>>0;return ah().subarray(s,s+r.length).set(r),HA=r.length,s}let i=n.length,e=t(i,1)>>>0,a=ah(),A=0;for(;A127)break;a[e+A]=r}if(A!==i){A!==0&&(n=n.slice(A)),e=o(e,i,i=A+n.length*3,1)>>>0;let r=ah().subarray(e+A,e+i),s=fB.encodeInto(n,r);A+=s.written,e=o(e,i,A,1)>>>0}return HA=A,e}function mA(n){let t=Pe(n);return BUe(n),t}var Ww=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});Ww.decode();var QUe=2146435072,SF=0;function yUe(n,t){return SF+=t,SF>=QUe&&(Ww=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),Ww.decode(),SF=t),Ww.decode(ah().subarray(n,n+t))}var fB=new TextEncoder;"encodeInto"in fB||(fB.encodeInto=function(n,t){let o=fB.encode(n);return t.set(o),{read:n.length,written:o.length}});var HA=0,mUe,ae;function SUe(n,t){return ae=n.exports,mUe=t,wl=null,uB=null,ae}function s7(n){if(ae!==void 0)return ae;n!==void 0&&(Object.getPrototypeOf(n)===Object.prototype?{module:n}=n:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=EUe();n instanceof WebAssembly.Module||(n=new WebAssembly.Module(n));let o=new WebAssembly.Instance(n,t);return SUe(o,n)}var wUe=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function g7(n){let t=atob(n),o=new Uint8Array(t.length);for(let i=0;in.length===33?n:Buffer.concat([Rg,n]),Br={generateKeyPair:()=>{let{pubKey:n,privKey:t}=Jc.generateKeyPair();return{private:Buffer.from(t),public:Buffer.from(n.slice(1))}},sharedKey:(n,t)=>{let o=Jc.calculateAgreement(Yo(t),n);return Buffer.from(o)},sign:(n,t)=>Jc.calculateSignature(n,t),verify:(n,t,o)=>{try{return Jc.verifySignature(Yo(n),t,o),!0}catch{return!1}}},aD=(n,t)=>{let o=Br.generateKeyPair(),i=Yo(o.public),e=Br.sign(n.private,i);return{keyPair:o,signature:e,keyId:t}},I7=16;function Dl(n,t,o,i){let e=DF("aes-256-gcm",t,o);return e.setAAD(i),Buffer.concat([e.update(n),e.final(),e.getAuthTag()])}function Ol(n,t,o,i){let e=OF("aes-256-gcm",t,o),a=n.slice(0,n.length-I7),A=n.slice(n.length-I7);return e.setAAD(i),e.setAuthTag(A),Buffer.concat([e.update(a),e.final()])}function l7(n,t,o){let i=DF("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function p7(n,t,o){let i=OF("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function d7(n,t){return RUe(n.subarray(16),t,n.subarray(0,16))}function RUe(n,t,o){let i=OF("aes-256-cbc",t,o);return Buffer.concat([i.update(n),i.final()])}function h7(n,t){let o=NUe(16),i=DF("aes-256-cbc",t,o);return Buffer.concat([o,i.update(n),i.final()])}function kn(n,t,o="sha256"){return TUe(o,t).update(n).digest()}function sh(n){return _Ue("sha256").update(n).digest()}async function iD(n,t){let i=new TextEncoder().encode(n),e=new Uint8Array(t instanceof Uint8Array?t:new Uint8Array(t)),a=await c7.importKey("raw",i,{name:"PBKDF2"},!1,["deriveBits"]),A=await c7.deriveBits({name:"PBKDF2",salt:e,iterations:2<<16,hash:"SHA-256"},a,256);return Buffer.from(A)}var wB={replacer:(n,t)=>Buffer.isBuffer(t)||t instanceof Uint8Array||t?.type==="Buffer"?{type:"Buffer",data:Buffer.from(t?.data||t).toString("base64")}:t,reviver:(n,t)=>{if(typeof t=="object"&&t!==null&&t.type==="Buffer"&&typeof t.data=="string")return Buffer.from(t.data,"base64");if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=Object.keys(t);if(o.length>0&&o.every(i=>!isNaN(parseInt(i,10)))){let i=Object.values(t);if(i.every(e=>typeof e=="number"))return Buffer.from(i)}}return t}},gh=(n,t="me")=>(n?.fromMe?t:n?.participantAlt||n?.remoteJidAlt||n?.participant||n?.remoteJid)||"",u7=n=>n==null||n==="",vUe=n=>{let o=(SB(1)[0]&15)+1;return Buffer.concat([n,Buffer.alloc(o,o)])},B7=n=>{let t=new Uint8Array(n);if(t.length===0)throw new Error("unpadPkcs7 given empty bytes");var o=t[t.length-1];if(o>t.length)throw new Error(`unpad given ${t.length} bytes, but pad is ${o}`);return new Uint8Array(t.buffer,t.byteOffset,t.length-o)},f7=n=>(n.sort(),"2:"+sh(Buffer.from(n.join(""))).toString("base64").slice(0,6)),ch=n=>vUe(oe.Message.encode(n).finish()),Q7=()=>Uint16Array.from(SB(2))[0]&16383,kg=(n,t=4)=>{let o=n,i=new Uint8Array(t);for(let e=t-1;e>=0;e--)i[e]=255&o,o>>>=8;return i},Hr=n=>typeof n=="object"&&n?"toNumber"in n?n.toNumber():n.low:n||0,ya=(n=new Date)=>Math.floor(n.getTime()/1e3);var DB=n=>y7(n).delay,y7=n=>{let t=new Error().stack,o,i;return{delay:new Promise((A,r)=>{o=setTimeout(A,n),i=r}),cancel:()=>{clearTimeout(o),i(new oD.Boom("Cancelled",{statusCode:500,data:{stack:t}}))}}};async function Ih(n,t){if(!n)return new Promise(t);let o=new Error().stack,{delay:i,cancel:e}=y7(n);return new Promise((A,r)=>{i.then(()=>r(new oD.Boom("Timed Out",{statusCode:$t.timedOut,data:{stack:o}}))).catch(s=>r(s)),t(A,r)}).finally(e)}var Kr=n=>{let t=Buffer.alloc(44);if(t.writeBigUInt64BE(BigInt(Math.floor(Date.now()/1e3))),n){let e=yA(n);e?.user&&(t.write(e.user,8),t.write("@c.us",8+e.user.length))}return SB(16).copy(t,28),"3EB0"+kUe("sha256").update(t).digest().toString("hex").toUpperCase().substring(0,18)},bF=()=>"3EB0"+SB(18).toString("hex").toUpperCase();function MF(n,t){return async(o,i)=>{let e,a;await Ih(i,(A,r)=>{a=({connection:s,lastDisconnect:g})=>{s==="close"&&r(g?.error||new oD.Boom("Connection Closed",{statusCode:$t.connectionClosed}))},n.on("connection.update",a),e=async s=>{await o(s)&&A()},n.on(t,e)}).finally(()=>{n.off(t,e),n.off("connection.update",a)})}}var m7=n=>MF(n,"connection.update");var S7=()=>{let n=SB(4);return`${n.readUInt16BE()}.${n.readUInt16BE(2)}-`},PUe={sender:oe.WebMessageInfo.Status.SERVER_ACK,played:oe.WebMessageInfo.Status.PLAYED,read:oe.WebMessageInfo.Status.READ,"read-self":oe.WebMessageInfo.Status.READ},w7=n=>{let t=PUe[n];return typeof n>"u"?oe.WebMessageInfo.Status.DELIVERY_ACK:t},GUe={conflict:$t.connectionReplaced},D7=n=>{let[t]=ys(n),o=t?.tag||"unknown",i=+(n.attrs.code||GUe[o]||$t.badSession);return i===$t.restartRequired&&(o="restart required"),{reason:o,statusCode:i}},O7=({tag:n,attrs:t})=>{let o;switch(n){case"offer":case"offer_notice":o="offer";break;case"terminate":t.reason==="timeout"?o="timeout":o="terminate";break;case"preaccept":o="preaccept";break;case"transport":o="transport";break;case"relaylatency":o="relaylatency";break;case"reject":o="reject";break;case"accept":o="accept";break;default:o="ringing";break}return o},E7="Unexpected server response: ",b7=n=>{let t=500;if(n?.message?.includes(E7)){let o=+n?.message.slice(E7.length);!Number.isNaN(o)&&o>=400&&(t=o)}else(n?.code?.startsWith("E")||n?.message?.includes("timed out"))&&(t=408);return t};function nD(n){for(let t in n)typeof n[t]>"u"&&delete n[t];return n}var C7="123456789ABCDEFGHJKLMNPQRSTVWXYZ";function M7(n){let t=0,o=0,i=[];for(let e of n)for(t=t<<8|e&255,o+=8;o>=5;)i.push(C7.charAt(t>>>o-5&31)),o-=5;return o>0&&i.push(C7.charAt(t<<5-o&31)),i.join("")}function _7(n){return oe.Message.encode(n).finish()}var bl=Je(Lr(),1);var FUe=async(n,t)=>qA(n)||ga(n)?n:await t.lidMapping.getLIDForPN(n)||n,LUe=async(n,t,o,i,e)=>{let{senderAlt:a}=gD(n);if(a&&qA(a)&&_t(t)&&i===t)try{await o.lidMapping.storeLIDPNMappings([{lid:a,pn:t}]),await o.migrateSession(t,a),e.debug({sender:t,senderAlt:a},"Stored LID mapping from envelope")}catch(A){e.warn({sender:t,senderAlt:a,error:A},"Failed to store LID mapping")}},sD="Message absent from node",T7="Key used already or never filled",N7="Your account has been restricted",UUe={maxRetries:3,baseDelayMs:100,sessionRecordErrors:["No session record","SessionError: No session record"]},Ml={SenderReachoutTimelocked:463,ParsingError:487,UnrecognizedStanza:488,UnrecognizedStanzaClass:489,UnrecognizedStanzaType:490,InvalidProtobuf:491,InvalidHostedCompanionStanza:493,MissingMessageSecret:495,SignalErrorOldCounter:496,MessageDeletedOnPeer:499,UnhandledError:500,UnsupportedAdminRevoke:550,UnsupportedLIDGroup:551,DBOperationFailed:552},_F={MessageAccountRestriction:"463",SmaxInvalid:"479"},gD=n=>{let t,o,i=n.attrs.participant||n.attrs.from,e=n.attrs.addressing_mode||(i?.endsWith("lid")?"lid":"pn");return e==="lid"?(t=n.attrs.participant_pn||n.attrs.sender_pn||n.attrs.peer_recipient_pn,o=n.attrs.recipient_pn):(t=n.attrs.participant_lid||n.attrs.sender_lid||n.attrs.peer_recipient_lid,o=n.attrs.recipient_lid),{addressingMode:e,senderAlt:t,recipientAlt:o}};function TF(n,t,o){let i,e,a,A=!1,r=n.attrs.id,s=n.attrs.from,g=n.attrs.participant,c=n.attrs.recipient;if(!r)throw new bl.Boom("Invalid message stanza: missing id attribute",{data:n});if(!s)throw new bl.Boom("Invalid message stanza: missing from attribute",{data:n});let I=gD(n),d=m=>Tt(m,t),B=m=>Tt(m,o);if(_t(s)||qA(s)||ga(s)||ur(s)){if(c&&!rh(c)){if(!d(s)&&!B(s))throw new bl.Boom("receipient present, but msg not from me",{data:n});(d(s)||B(s))&&(A=!0),e=c}else(d(s)||B(s))&&(A=!0),e=s;i="chat",a=s}else if(Ur(s)){if(!g)throw new bl.Boom("No participant in group message");(d(g)||B(g))&&(A=!0),i="group",a=g,e=s}else if(EB(s)){if(!g)throw new bl.Boom("No participant in group message");let m=d(g);Tg(s)?i=m?"direct_peer_status":"other_status":i=m?"peer_broadcast":"other_broadcast",A=m,e=s,a=g}else if(Kc(s))i="newsletter",e=s,a=s,(d(s)||B(s))&&(A=!0);else throw new bl.Boom("Unknown message type",{data:n});let f=n?.attrs?.notify,Q={remoteJid:e,remoteJidAlt:Ur(e)?void 0:I.senderAlt,remoteJidUsername:Ur(e)?void 0:n.attrs.peer_recipient_username||n.attrs.recipient_username,fromMe:A,id:r,participant:g,participantAlt:Ur(e)?I.senderAlt:void 0,participantUsername:n.attrs.participant?n.attrs.participant_username:void 0,addressingMode:I.addressingMode,...i==="newsletter"&&n.attrs.server_id?{server_id:n.attrs.server_id}:{}},y={key:Q,category:n.attrs.category,messageTimestamp:+n.attrs.t,pushName:f,broadcast:EB(s)};return Q.fromMe&&(y.status=oe.WebMessageInfo.Status.SERVER_ACK),{fullMessage:y,author:a,sender:i==="chat"?a:e}}var R7=(n,t,o,i,e)=>{let{fullMessage:a,author:A,sender:r}=TF(n,t,o);return{fullMessage:a,category:n.attrs.category,author:A,async decrypt(){let s=0;if(Array.isArray(n.content))for(let{tag:g,attrs:c,content:I}of n.content){if(g==="verified_name"&&I instanceof Uint8Array){let f=oe.VerifiedNameCertificate.decode(I),Q=oe.VerifiedNameCertificate.Details.decode(f.details);a.verifiedBizName=Q.verifiedName}if(g==="unavailable"&&c.type==="view_once"&&(a.key.isViewOnce=!0),c.count&&g==="enc"&&(a.retryCount=Number(c.count)),g!=="enc"&&g!=="plaintext"||!(I instanceof Uint8Array))continue;s+=1;let d,B=await FUe(A,i);g!=="plaintext"&&await LUe(n,A,i,B,e);try{let f=g==="plaintext"?"plaintext":c.type;switch(f){case"skmsg":d=await i.decryptGroupMessage({group:r,authorJid:A,msg:I});break;case"pkmsg":case"msg":d=await i.decryptMessage({jid:B,type:f,ciphertext:I});break;case"plaintext":d=I;break;default:throw new Error(`Unknown e2e type: ${f}`)}let Q=oe.Message.decode(f!=="plaintext"?B7(d):d);if(Q=Q.deviceSentMessage?.message||Q,Q.senderKeyDistributionMessage)try{await i.processSenderKeyDistributionMessage({authorJid:A,item:Q.senderKeyDistributionMessage})}catch(y){e.error({key:a.key,err:y},"failed to process sender key distribution message")}a.message?Object.assign(a.message,Q):a.message=Q}catch(f){let Q={key:a.key,err:f,messageType:g==="plaintext"?"plaintext":c.type,sender:r,author:A,isSessionRecordError:HUe(f)};e.error(Q,"failed to decrypt message"),a.messageStubType=oe.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[f.message.toString()]}}!s&&!a.key?.isViewOnce&&(a.messageStubType=oe.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[sD])}}};function HUe(n){let t=n?.message||n?.toString()||"";return UUe.sessionRecordErrors.some(o=>t.includes(o))}var Yg=Je(Lr(),1);import{randomBytes as z2}from"crypto";import{promises as V2}from"fs";var Pn=Je(Lr(),1);import{exec as Hqe}from"child_process";import*as Io from"crypto";import{once as Zh}from"events";import{createReadStream as sb,createWriteStream as U2,promises as $h}from"fs";import{tmpdir as aoe}from"os";import{join as ob}from"path";import{Readable as hf,Transform as Kqe}from"stream";import{URL as H2}from"url";var K2=()=>aoe(),ioe=async()=>{let[n,t]=await Promise.all([import("jimp").catch(()=>{}),Promise.resolve().then(()=>(YAe(),xAe)).catch(()=>{})]);if(t)return{sharp:t};if(n)return{jimp:n};throw new Pn.Boom("No image processing library available")},xqe=n=>`WhatsApp ${Coe[n]} Keys`,gb=async(n,t,o)=>{let{stream:i}=await Ef(n);o?.debug("got stream for raw upload");let e=Io.createHash("sha256"),a=ob(aoe(),t+Kr()),A=U2(a),r=0;try{for await(let g of i)r+=g.length,e.update(g),A.write(g)||await Zh(A,"drain");A.end(),await Zh(A,"finish"),i.destroy();let s=e.digest();return o?.debug("hashed data for raw upload"),{filePath:a,fileSha256:s,fileLength:r}}catch(s){A.destroy(),i.destroy();try{await $h.unlink(a)}catch{}throw s}};async function ooe(n,t){if(!n)throw new Pn.Boom("Cannot derive from empty media key");typeof n=="string"&&(n=Buffer.from(n.replace("data:;base64,",""),"base64"));let o=Rn(n,112,{info:xqe(t)});return{iv:o.slice(0,16),cipherKey:o.slice(16,48),macKey:o.slice(48,80)}}var Yqe=async(n,t,o,i)=>new Promise((e,a)=>{let A=`ffmpeg -ss ${o} -i ${n} -y -vf scale=${i.width}:-1 -vframes 1 -f image2 ${t}`;Hqe(A,r=>{r?a(r):e()})}),x2=async(n,t=32)=>{n instanceof hf&&(n=await nb(n));let o=await ioe();if("sharp"in o&&typeof o.sharp?.default=="function"){let i=o.sharp.default(n),e=await i.metadata();return{buffer:await i.resize(t).jpeg({quality:50}).toBuffer(),original:{width:e.width,height:e.height}}}else if("jimp"in o&&typeof o.jimp?.Jimp=="object"){let i=await o.jimp.Jimp.read(n),e={width:i.width,height:i.height};return{buffer:await i.resize({w:t,mode:o.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50}),original:e}}else throw new Pn.Boom("No image processing library available")},jqe=n=>encodeURIComponent(n.replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")),cb=async(n,t)=>{let o,{width:i=640,height:e=640}=t||{};if(Buffer.isBuffer(n))o=n;else{let{stream:r}=await Ef(n);o=await nb(r)}let a=await ioe(),A;if("sharp"in a&&typeof a.sharp?.default=="function")A=a.sharp.default(o).resize(i,e).jpeg({quality:50}).toBuffer();else if("jimp"in a&&typeof a.jimp?.Jimp=="function"){let r=await a.jimp.Jimp.read(o),s=Math.min(r.width,r.height);A=r.crop({x:0,y:0,w:s,h:s}).resize({w:i,h:e,mode:a.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50})}else throw new Pn.Boom("No image processing library available");return{img:await A}};async function noe(n){let t=await Promise.resolve().then(()=>(toe(),Aoe)),o,i={duration:!0};return Buffer.isBuffer(n)?o=await t.parseBuffer(n,void 0,i):typeof n=="string"?o=await t.parseFile(n,i):o=await t.parseStream(n,void 0,i),o.format.duration}async function soe(n,t){try{let{default:o}=await import("audio-decode"),i;if(Buffer.isBuffer(n))i=n;else if(typeof n=="string"){let d=sb(n);i=await nb(d)}else i=await nb(n);let a=(await o(i)).getChannelData(0),A=64,r=Math.floor(a.length/A),s=[];for(let d=0;dd*g);return new Uint8Array(c.map(d=>Math.floor(100*d)))}catch(o){t?.debug("Failed to generate waveform: "+o)}}var roe=n=>{let t=new hf({read:()=>{}});return t.push(n),t.push(null),t},nb=async n=>{let t=[];for await(let o of n)t.push(o);return n.destroy(),Buffer.concat(t)},Ef=async(n,t)=>{if(Buffer.isBuffer(n))return{stream:roe(n),type:"buffer"};if("stream"in n)return{stream:n.stream,type:"readable"};let o=n.url.toString();if(o.startsWith("data:")){let i=Buffer.from(o.split(",")[1],"base64");return{stream:roe(i),type:"buffer"}}return o.startsWith("http://")||o.startsWith("https://")?{stream:await Ib(n.url,t),type:"remote"}:{stream:sb(n.url),type:"file"}};async function goe(n,t,o){let i,e;if(t==="image"){let{buffer:a,original:A}=await x2(n);i=a.toString("base64"),A.width&&A.height&&(e={width:A.width,height:A.height})}else if(t==="video"){let a=ob(K2(),Kr()+".jpg");try{await Yqe(n,a,"00:00:00",{width:32,height:32}),i=(await $h.readFile(a)).toString("base64"),await $h.unlink(a)}catch(A){o.logger?.debug("could not generate video thumb: "+A)}}return{thumbnail:i,originalImageDimensions:e}}var Ib=async(n,t={})=>{let o=await fetch(n.toString(),{dispatcher:t.dispatcher,method:"GET",headers:t.headers});if(!o.ok)throw new Pn.Boom(`Failed to fetch stream from ${n}`,{statusCode:o.status,data:{url:n}});return o.body instanceof hf?o.body:hf.fromWeb(o.body)},coe=async(n,t,{logger:o,saveOriginalFileIfRequired:i,opts:e}={})=>{let{stream:a,type:A}=await Ef(n,e);o?.debug("fetched media stream");let r=Io.randomBytes(32),{cipherKey:s,iv:g,macKey:c}=await ooe(r,t),I=ob(K2(),t+Kr()+"-enc"),d=U2(I),B,f;i&&(f=ob(K2(),t+Kr()+"-original"),B=U2(f));let Q=0,y=Io.createCipheriv("aes-256-cbc",s,g),m=Io.createHmac("sha256",c).update(g),_=Io.createHash("sha256"),T=Io.createHash("sha256"),R=async F=>{T.update(F),m.update(F),d.write(F)||await Zh(d,"drain")};try{for await(let j of a){if(Q+=j.length,A==="remote"&&e?.maxContentLength&&Q+j.length>e.maxContentLength)throw new Pn.Boom(`content length exceeded when encrypting "${A}"`,{data:{media:n,type:A}});B&&(B.write(j)||await Zh(B,"drain")),_.update(j),await R(y.update(j))}await R(y.final());let F=m.digest().slice(0,10);T.update(F);let K=_.digest(),L=T.digest();d.write(F);let q=Zh(d,"finish"),z=B?Zh(B,"finish"):Promise.resolve();return d.end(),B?.end?.(),a.destroy(),await q,await z,o?.debug("encrypted data successfully"),{mediaKey:r,originalFilePath:f,encFilePath:I,mac:F,fileEncSha256:L,fileSha256:K,fileLength:Q}}catch(F){d.destroy(),B?.destroy?.(),y.destroy(),m.destroy(),_.destroy(),T.destroy(),a.destroy();try{await $h.unlink(I),f&&await $h.unlink(f)}catch(K){o?.error({err:K},"failed deleting tmp files")}throw F}},Y2="mmg.whatsapp.net",Xh=16,L2=n=>Math.floor(n/Xh)*Xh,Cf=(n,t=Y2)=>`https://${t}${n}`,Jqe=n=>{if(n)try{return new H2(n).host}catch{return}},eE=async({mediaKey:n,directPath:t,url:o},i,e={})=>{let a=e.host??Jqe(o),A=t?Cf(t,a):o;if(!A)throw new Pn.Boom("No valid media URL or directPath present in message",{statusCode:400});let r=await ooe(n,i);return qqe(A,r,e)},qqe=async(n,{cipherKey:t,iv:o},{startByte:i,endByte:e,options:a}={})=>{let A=0,r=0,s=!1;if(i){let m=L2(i||0);m&&(r=m-Xh,A=m,s=!0)}let g=e?L2(e||0)+Xh:void 0,c=a?.headers?a.headers:void 0,I={...c?Array.isArray(c)?Object.fromEntries(c):c:{},Origin:uf};(r||g)&&(I.Range=`bytes=${r}-`,g&&(I.Range+=g));let d=await Ib(n,{...a||{},headers:I}),B=Buffer.from([]),f,Q=(m,_)=>{if(i||e){let T=A>=i?void 0:Math.max(i-A,0),R=A+m.lengththis.push(K)),T()}catch(K){T(K)}},final(m){try{Q(f.final(),_=>this.push(_)),m()}catch(_){m(_)}}});return d.pipe(y,{end:!0})};var zqe=()=>typeof process<"u"&&process.versions?.node!==null&&typeof process.versions.bun>"u"&&typeof globalThis.Deno>"u",Ioe=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e},a=0)=>{if(a>5)throw new Error("Too many redirects");let A=new H2(n),r=A.protocol==="https:"?await import("https"):await import("http"),g=(await $h.stat(t)).size;return new Promise((c,I)=>{let d=r.request({hostname:A.hostname,port:A.port||(A.protocol==="https:"?443:80),path:A.pathname+A.search,method:"POST",headers:{...o,"Content-Length":g},agent:e,timeout:i},f=>{if(f.statusCode&&f.statusCode>=300&&f.statusCode<400&&f.headers.location){f.resume();let y=new H2(f.headers.location,n).toString();c(Ioe({url:y,filePath:t,headers:o,timeoutMs:i,agent:e},a+1));return}let Q="";f.on("data",y=>Q+=y),f.on("end",()=>{try{c(JSON.parse(Q))}catch{c(void 0)}})});d.on("error",I),d.on("timeout",()=>{d.destroy(),I(new Error("Upload timeout"))});let B=sb(t);B.pipe(d),B.on("error",f=>{d.destroy(),I(f)})})},Vqe=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e})=>{let a=sb(t),A=hf.toWeb(a),r=typeof e?.dispatch=="function"?e:void 0,s=await fetch(n,{...r?{dispatcher:r}:{},method:"POST",body:A,headers:o,duplex:"half",signal:i?AbortSignal.timeout(i):void 0});try{return await s.json()}catch{return}},Wqe=async(n,t)=>zqe()?(t?.debug("Using Node.js https module for upload (avoids undici buffering bug)"),Ioe(n)):(t?.debug("Using web-standard Fetch API for upload"),Vqe(n)),loe=({customUploadHosts:n,fetchAgent:t,logger:o,options:i},e)=>async(a,{mediaType:A,fileEncSha256B64:r,timeoutMs:s})=>{let g=await e(!1),c,I=[...n,...g.hosts];r=jqe(r);let B={...(()=>{let f=i?.headers;return f?Array.isArray(f)?Object.fromEntries(f):f:{}})(),"Content-Type":"application/octet-stream",Origin:uf};for(let{hostname:f}of I){o.debug(`uploading to "${f}"`);let Q=encodeURIComponent(g.auth),y=`https://${f}${J2[A]}/${r}?auth=${Q}&token=${r}`,m;try{if(m=await Wqe({url:y,filePath:a,headers:B,timeoutMs:s,agent:t},o),m?.url||m?.direct_path){c={mediaUrl:m.url,directPath:m.direct_path,meta_hmac:m.meta_hmac,fbid:m.fbid,ts:m.ts};break}else throw g=await e(!0),new Error(`upload failed, reason: ${JSON.stringify(m)}`)}catch(_){let T=f===I[g.hosts.length-1]?.hostname;o.warn({trace:_?.stack,uploadResult:m},`Error in uploading to ${f} ${T?"":", retrying..."}`)}}if(!c)throw new Pn.Boom("Media upload failed on all hosts",{statusCode:500});return c},poe=n=>Rn(n,32,{info:"WhatsApp Media Retry Notification"}),doe=(n,t,o)=>{let i={stanzaId:n.id},e=oe.ServerErrorReceipt.encode(i).finish(),a=Io.randomBytes(12),A=poe(t),r=Dl(e,A,a,Buffer.from(n.id));return{tag:"receipt",attrs:{id:n.id,to:uA(o),type:"server-error"},content:[{tag:"encrypt",attrs:{},content:[{tag:"enc_p",attrs:{},content:r},{tag:"enc_iv",attrs:{},content:a}]},{tag:"rmr",attrs:{jid:n.remoteJid,from_me:(!!n.fromMe).toString(),participant:n.participant||void 0}}]}},hoe=n=>{let t=le(n,"rmr"),o={key:{id:n.attrs.id,remoteJid:t.attrs.jid,fromMe:t.attrs.from_me==="true",participant:t.attrs.participant}},i=le(n,"error");if(i){let e=+i.attrs.code;o.error=new Pn.Boom(`Failed to re-upload media (${e})`,{data:i.attrs,statusCode:j2(e)})}else{let e=le(n,"encrypt"),a=Qa(e,"enc_p"),A=Qa(e,"enc_iv");a&&A?o.media={ciphertext:a,iv:A}:o.error=new Pn.Boom("Failed to re-upload media (missing ciphertext)",{statusCode:404})}return o},Eoe=({ciphertext:n,iv:t},o,i)=>{let e=poe(o),a=Ol(n,e,t,Buffer.from(i));return oe.MediaRetryNotification.decode(a)},j2=n=>Zqe[n],Zqe={[oe.MediaRetryNotification.ResultType.SUCCESS]:200,[oe.MediaRetryNotification.ResultType.DECRYPTION_ERROR]:412,[oe.MediaRetryNotification.ResultType.NOT_FOUND]:404,[oe.MediaRetryNotification.ResultType.GENERAL_ERROR]:418};import{createHmac as Xqe}from"crypto";var $qe=[{f:1},{f:3,s:[{f:2},{f:3},{f:8},{f:11},{f:17,s:[{f:21},{f:22}]},{f:25}]},{f:4,s:[{f:1},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:5,s:[{f:3},{f:4},{f:5},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:6,s:[{f:1},{f:17,s:[{f:21},{f:22}]},{f:30}]},{f:7,s:[{f:2},{f:7},{f:10},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:8,s:[{f:2},{f:7},{f:9},{f:17,s:[{f:21},{f:22}]},{f:21}]},{f:9,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:12,s:[{f:1},{f:2},{f:14,m:!0},{f:15}]},{f:18,s:[{f:6},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:26,s:[{f:4},{f:5},{f:8},{f:13},{f:17,s:[{f:21},{f:22}]}]},{f:28,s:[{f:1},{f:2},{f:4},{f:5},{f:6},{f:7,s:[{f:21},{f:22}]}]},{f:37,s:[{f:1,m:!0}]},{f:49,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:53,s:[{f:1,m:!0}]},{f:55,s:[{f:1,m:!0}]},{f:58,s:[{f:1,m:!0}]},{f:59,s:[{f:1,m:!0}]},{f:60,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:64,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:66,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:74,s:[{f:1,m:!0}]},{f:87,s:[{f:1,m:!0}]},{f:88,s:[{f:1},{f:2,s:[{f:1}]},{f:3,s:[{f:21},{f:22}]}]},{f:92,s:[{f:1,m:!0}]},{f:93,s:[{f:1,m:!0}]},{f:94,s:[{f:1,m:!0}]}],Boe=n=>{let t=new Map;for(let o of n)t.set(o.f,{m:o.m,children:o.s?Boe(o.s):void 0});return t},e4e=Boe($qe),A4e=new Map,t4e="Report Token",lb={VARINT:0,FIXED64:1,BYTES:2,FIXED32:5},pb=n=>!n.reactionMessage&&!n.encReactionMessage&&!n.encEventResponseMessage&&!n.pollUpdateMessage,r4e=(n,t,o,i,e)=>{let a=Buffer.concat([Buffer.from(t,"utf8"),Buffer.from(o,"utf8"),Buffer.from(i,"utf8"),Buffer.from(n,"utf8")]);return Rn(e,32,{info:a.toString("latin1")})},foe=(n,t)=>{let o=[],i=0;for(;i>3,A=e.value&7,r=i;i+=e.bytes;let s=t.get(a),g=I=>I>n.length?!1:(o.push({num:a,bytes:n.subarray(r,I)}),i=I,!0),c=I=>I>n.length?!1:(i=I,!0);if(A===lb.VARINT){let I=q2(n,i);if(!I.ok)return null;let d=i+I.bytes;if(!s){if(!c(d))return null;continue}if(!g(d))return null;continue}if(A===lb.FIXED64){let I=i+8;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===lb.FIXED32){let I=i+4;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===lb.BYTES){let I=q2(n,i);if(!I.ok)return null;let d=i+I.bytes,B=d+I.value;if(B>n.length)return null;if(!s){i=B;continue}if(s.m||s.children){let f=foe(n.subarray(d,B),s.children??A4e);if(f===null)return null;if(f.length>0){let Q=uoe(e.value),y=uoe(f.length);o.push({num:a,bytes:Buffer.concat([Q,y,f])})}i=B;continue}o.push({num:a,bytes:n.subarray(r,B)}),i=B;continue}return null}return o.length===0?Buffer.alloc(0):(o.sort((e,a)=>e.num-a.num),Buffer.concat(o.map(e=>e.bytes)))},q2=(n,t)=>{let o=0,i=0,e=0;for(;t+i35)return{value:0,bytes:0,ok:!1}}return{value:0,bytes:0,ok:!1}},uoe=n=>{let t=[],o=n>>>0;for(;o>127;)t.push(o&127|128),o>>>=7;return t.push(o),Buffer.from(t)},Qoe=async(n,t,o)=>{let i=t.messageContextInfo?.messageSecret;if(!i||!o.id)return null;let e=o.fromMe?o.remoteJid:o.participant||o.remoteJid,a=o.fromMe&&o.participant||o.remoteJid,A=r4e(t4e,o.id,e,a,i),r=foe(n,e4e);if(!r||r.length===0)return null;let s=Xqe("sha256",A).update(r).digest().subarray(0,16);return{tag:"reporting",attrs:{},content:[{tag:"reporting_token",attrs:{v:"2"},content:s}]}};var a4e={image:"image/jpeg",video:"video/mp4",document:"application/pdf",audio:"audio/ogg; codecs=opus",sticker:"image/webp","product-catalog-image":"image/jpeg"},yoe={image:oe.Message.ImageMessage,video:oe.Message.VideoMessage,audio:oe.Message.AudioMessage,sticker:oe.Message.StickerMessage,document:oe.Message.DocumentMessage},i4e=n=>n.match(_oe)?.[0],o4e=async(n,t,o)=>{let i=i4e(n);if(t&&i)try{return await t(i)}catch(e){o?.warn({trace:e.stack},"url generation failed")}},moe=async n=>{let t;if(typeof n=="number")t=n>0?n:4294967295+Number(n)+1;else{let o=n.trim().replace("#","");return o.length<=6&&(o="FF"+o.padStart(6,"0")),t=parseInt(o,16),t}},Bf=async(n,t)=>{let o=t.logger,i;for(let K of Toe)K in n&&(i=K);if(!i)throw new Yg.Boom("Invalid media type",{statusCode:400});let e={...n,media:n[i]};delete e[i];let a=typeof e.media=="object"&&"url"in e.media&&!!e.media.url&&!!t.mediaCache&&i+":"+e.media.url.toString();if(i==="document"&&!e.fileName&&(e.fileName="file"),e.mimetype||(e.mimetype=a4e[i]),a){let K=await t.mediaCache.get(a);if(K){o?.debug({cacheableKey:a},"got media cache hit");let L=oe.Message.decode(K),q=`${i}Message`;return Object.assign(L[q],{...e,media:void 0}),L}}if(!!t.jid&&Kc(t.jid)){o?.info({key:a},"Preparing raw media for newsletter");let{filePath:K,fileSha256:L,fileLength:q}=await gb(e.media,t.mediaTypeOverride||i,o),z=L.toString("base64"),{mediaUrl:j,directPath:P}=await t.upload(K,{fileEncSha256B64:z,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});await V2.unlink(K);let J=oe.Message.fromObject({[`${i}Message`]:yoe[i].fromObject({url:j,directPath:P,fileSha256:L,fileLength:q,...e,media:void 0})});return e.ptv&&(J.ptvMessage=J.videoMessage,delete J.videoMessage),J.stickerMessage&&(J.stickerMessage.stickerSentTs=Date.now()),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,oe.Message.encode(J).finish())),J}let r=i==="audio"&&typeof e.seconds>"u",s=(i==="image"||i==="video")&&typeof e.jpegThumbnail>"u",g=i==="audio"&&e.ptt===!0&&typeof e.waveform>"u",c=t.backgroundColor&&i==="audio"&&e.ptt===!0,I=r||s,{mediaKey:d,encFilePath:B,originalFilePath:f,fileEncSha256:Q,fileSha256:y,fileLength:m}=await coe(e.media,t.mediaTypeOverride||i,{logger:o,saveOriginalFileIfRequired:I,opts:t.options}),_=Q.toString("base64"),[{mediaUrl:T,directPath:R}]=await Promise.all([(async()=>{let K=await t.upload(B,{fileEncSha256B64:_,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});return o?.debug({mediaType:i,cacheableKey:a},"uploaded media"),K})(),(async()=>{try{if(s){let{thumbnail:K,originalImageDimensions:L}=await goe(f,i,t);e.jpegThumbnail=K,!e.width&&L&&(e.width=L.width,e.height=L.height,o?.debug("set dimensions")),o?.debug("generated thumbnail")}r&&(e.seconds=await noe(f),o?.debug("computed audio duration")),g&&(e.waveform=await soe(f,o),o?.debug("processed waveform")),c&&(e.backgroundArgb=await moe(t.backgroundColor),o?.debug("computed backgroundColor audio status"))}catch(K){o?.warn({trace:K.stack},"failed to obtain extra info")}})()]).finally(async()=>{try{await V2.unlink(B),f&&await V2.unlink(f),o?.debug("removed tmp files")}catch{o?.warn("failed to remove tmp file")}}),F=oe.Message.fromObject({[`${i}Message`]:yoe[i].fromObject({url:T,directPath:R,mediaKey:d,fileEncSha256:Q,fileSha256:y,fileLength:m,mediaKeyTimestamp:ya(),...e,media:void 0})});return e.ptv&&(F.ptvMessage=F.videoMessage,delete F.videoMessage),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,oe.Message.encode(F).finish())),F},n4e=n=>{n=n||0;let t={ephemeralMessage:{message:{protocolMessage:{type:oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:n}}}};return oe.Message.fromObject(t)},s4e=(n,t)=>{let o=n.message;if(!o)throw new Yg.Boom("no content in message",{statusCode:400});o=Oa(o),o=oe.Message.decode(oe.Message.encode(o).finish());let i=Object.keys(o)[0],e=o?.[i]?.contextInfo?.forwardingScore||0;e+=n.key.fromMe&&!t?0:1,i==="conversation"&&(o.extendedTextMessage={text:o[i]},delete o.conversation,i="extendedTextMessage");let a=o?.[i];return e>0?a.contextInfo={forwardingScore:e,isForwarded:!0}:a.contextInfo={},o},da=(n,t)=>typeof n=="object"&&n!==null&&t in n&&n[t]!==null&&n[t]!==void 0;function Xl(n,t){return typeof n=="object"&&n!==null&&t in n&&n[t]!==null}var g4e=async(n,t)=>{var o,i;let e={};if(da(n,"text")){let a={text:n.text},A=n.linkPreview;if(typeof A>"u"&&(A=await o4e(n.text,t.getUrlInfo,t.logger)),A){a.matchedText=A["matched-text"],a.jpegThumbnail=A.jpegThumbnail,a.description=A.description,a.title=A.title,a.previewType=0;let r=A.highQualityThumbnail;r&&(a.thumbnailDirectPath=r.directPath,a.mediaKey=r.mediaKey,a.mediaKeyTimestamp=r.mediaKeyTimestamp,a.thumbnailWidth=r.width,a.thumbnailHeight=r.height,a.thumbnailSha256=r.fileSha256,a.thumbnailEncSha256=r.fileEncSha256)}t.backgroundColor&&(a.backgroundArgb=await moe(t.backgroundColor)),t.font&&(a.font=t.font),e.extendedTextMessage=a}else if(da(n,"contacts")){let a=n.contacts.contacts.length;if(!a)throw new Yg.Boom("require atleast 1 contact",{statusCode:400});a===1?e.contactMessage=oe.Message.ContactMessage.create(n.contacts.contacts[0]):e.contactsArrayMessage=oe.Message.ContactsArrayMessage.create(n.contacts)}else if(da(n,"location"))e.locationMessage=oe.Message.LocationMessage.create(n.location);else if(da(n,"react"))n.react.senderTimestampMs||(n.react.senderTimestampMs=Date.now()),e.reactionMessage=oe.Message.ReactionMessage.create(n.react);else if(da(n,"delete"))e.protocolMessage={key:n.delete,type:oe.Message.ProtocolMessage.Type.REVOKE};else if(da(n,"forward"))e=s4e(n.forward,n.force);else if(da(n,"disappearingMessagesInChat")){let a=typeof n.disappearingMessagesInChat=="boolean"?n.disappearingMessagesInChat?Qf:0:n.disappearingMessagesInChat;e=n4e(a)}else if(da(n,"groupInvite")){if(e.groupInviteMessage={},e.groupInviteMessage.inviteCode=n.groupInvite.inviteCode,e.groupInviteMessage.inviteExpiration=n.groupInvite.inviteExpiration,e.groupInviteMessage.caption=n.groupInvite.text,e.groupInviteMessage.groupJid=n.groupInvite.jid,e.groupInviteMessage.groupName=n.groupInvite.subject,t.getProfilePicUrl){let a=await t.getProfilePicUrl(n.groupInvite.jid,"preview");if(a){let A=await fetch(a,{method:"GET",dispatcher:t?.options?.dispatcher});if(A.ok){let r=Buffer.from(await A.arrayBuffer());e.groupInviteMessage.jpegThumbnail=r}}}}else if(da(n,"pin"))e.pinInChatMessage={},e.messageContextInfo={},e.pinInChatMessage.key=n.pin,e.pinInChatMessage.type=n.type,e.pinInChatMessage.senderTimestampMs=Date.now(),e.messageContextInfo.messageAddOnDurationInSecs=n.type===1?n.time||86400:0;else if(da(n,"buttonReply"))switch(n.type){case"template":e.templateButtonReplyMessage={selectedDisplayText:n.buttonReply.displayText,selectedId:n.buttonReply.id,selectedIndex:n.buttonReply.index};break;case"plain":e.buttonsResponseMessage={selectedButtonId:n.buttonReply.id,selectedDisplayText:n.buttonReply.displayText,type:oe.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT};break}else if(Xl(n,"ptv")&&n.ptv){let{videoMessage:a}=await Bf({video:n.video},t);e.ptvMessage=a}else if(da(n,"product")){let{imageMessage:a}=await Bf({image:n.product.productImage},t);e.productMessage=oe.Message.ProductMessage.create({...n,product:{...n.product,productImage:a}})}else if(da(n,"listReply"))e.listResponseMessage={...n.listReply};else if(da(n,"event")){e.eventMessage={};let a=Math.floor(n.event.startDate.getTime()/1e3);if(n.event.call&&t.getCallLink){let A=await t.getCallLink(n.event.call,{startTime:a});e.eventMessage.joinLink=(n.event.call==="audio"?Moe:boe)+A}e.messageContextInfo={messageSecret:n.event.messageSecret||z2(32)},e.eventMessage.name=n.event.name,e.eventMessage.description=n.event.description,e.eventMessage.startTime=a,e.eventMessage.endTime=n.event.endDate?n.event.endDate.getTime()/1e3:void 0,e.eventMessage.isCanceled=n.event.isCancelled??!1,e.eventMessage.extraGuestsAllowed=n.event.extraGuestsAllowed,e.eventMessage.isScheduleCall=n.event.isScheduleCall??!1,e.eventMessage.location=n.event.location}else if(da(n,"poll")){if((o=n.poll).selectableCount||(o.selectableCount=0),(i=n.poll).toAnnouncementGroup||(i.toAnnouncementGroup=!1),!Array.isArray(n.poll.values))throw new Yg.Boom("Invalid poll values",{statusCode:400});if(n.poll.selectableCount<0||n.poll.selectableCount>n.poll.values.length)throw new Yg.Boom(`poll.selectableCount in poll should be >= 0 and <= ${n.poll.values.length}`,{statusCode:400});e.messageContextInfo={messageSecret:n.poll.messageSecret||z2(32)};let a={name:n.poll.name,selectableOptionsCount:n.poll.selectableCount,options:n.poll.values.map(A=>({optionName:A}))};n.poll.toAnnouncementGroup?e.pollCreationMessageV2=a:n.poll.selectableCount===1?e.pollCreationMessageV3=a:e.pollCreationMessage=a}else da(n,"album")?e.albumMessage={expectedImageCount:n.album.expectedImageCount,expectedVideoCount:n.album.expectedVideoCount}:da(n,"sharePhoneNumber")?e.protocolMessage={type:oe.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER}:da(n,"requestPhoneNumber")?e.requestPhoneNumberMessage={}:da(n,"limitSharing")?e.protocolMessage={type:oe.Message.ProtocolMessage.Type.LIMIT_SHARING,limitSharing:{sharingLimited:n.limitSharing===!0,trigger:1,limitSharingSettingTimestamp:Date.now(),initiatedByMe:!0}}:e=await Bf(n,t);if(Xl(n,"viewOnce")&&n.viewOnce&&(e={viewOnceMessage:{message:e}}),Xl(n,"mentions")&&n.mentions?.length||Xl(n,"mentionAll")&&n.mentionAll){let a=Object.keys(e)[0],A=e[a];A&&"contextInfo"in A?(A.contextInfo=A.contextInfo||{},n.mentions?.length&&(A.contextInfo.mentionedJid=n.mentions),n.mentionAll&&(A.contextInfo.nonJidMentions=1)):A&&(A.contextInfo={mentionedJid:n.mentions,nonJidMentions:n.mentionAll?1:0})}if(Xl(n,"edit")&&(e={protocolMessage:{key:n.edit,editedMessage:e,timestampMs:Date.now(),type:oe.Message.ProtocolMessage.Type.MESSAGE_EDIT}}),Xl(n,"contextInfo")&&n.contextInfo){let a=Object.keys(e)[0],A=e[a];"contextInfo"in A&&A.contextInfo?A.contextInfo={...A.contextInfo,...n.contextInfo}:A&&(A.contextInfo=n.contextInfo)}return Xl(n,"albumParentKey")&&n.albumParentKey&&(e.messageContextInfo={...e.messageContextInfo,messageAssociation:{associationType:oe.MessageAssociation.AssociationType.MEDIA_ALBUM,parentMessageKey:n.albumParentKey}}),pb(e)&&(e.messageContextInfo=e.messageContextInfo||{},e.messageContextInfo.messageSecret||(e.messageContextInfo.messageSecret=z2(32))),oe.Message.create(e)},c4e=(n,t,o)=>{o.timestamp||(o.timestamp=new Date);let i=Oa(t),e=ff(i),a=ya(o.timestamp),{quoted:A,userJid:r}=o;if(A&&!Kc(n)){let g=A.key.fromMe?r:A.participant||A.key.participant||A.key.remoteJid,c=Oa(A.message),I=ff(c);c=oe.Message.create({[I]:c[I]});let d=c[I];typeof d=="object"&&d&&"contextInfo"in d&&delete d.contextInfo;let B="contextInfo"in i[e]&&i[e]?.contextInfo||{};B.participant=uA(g),B.stanzaId=A.key.id,B.quotedMessage=c,n!==A.key.remoteJid&&(B.remoteJid=A.key.remoteJid),B&&i[e]&&(i[e].contextInfo=B)}o?.ephemeralExpiration&&e!=="protocolMessage"&&e!=="ephemeralMessage"&&!Kc(n)&&(i[e].contextInfo={...i[e].contextInfo||{},expiration:o.ephemeralExpiration||Qf}),t=oe.Message.create(t);let s={key:{remoteJid:n,fromMe:!0,id:o?.messageId||Kr()},message:t,messageTimestamp:a,messageStubParameters:[],participant:Ur(n)||Tg(n)?r:void 0,status:th.PENDING};return oe.WebMessageInfo.fromObject(s)},Soe=async(n,t,o)=>(o.logger=o?.logger?.child({msgId:o.messageId}),c4e(n,await g4e(t,{...o,jid:n}),o)),ff=n=>{if(n)return Object.keys(n).find(i=>(i==="conversation"||i.includes("Message"))&&i!=="senderKeyDistributionMessage")},Oa=n=>{if(!n)return;for(let o=0;o<5;o++){let i=t(n);if(!i)break;n=i.message}return n;function t(o){return o?.ephemeralMessage||o?.viewOnceMessage||o?.documentWithCaptionMessage||o?.viewOnceMessageV2||o?.viewOnceMessageV2Extension||o?.editedMessage||o?.associatedChildMessage||o?.groupStatusMessage||o?.groupStatusMessageV2}},woe=n=>{let t=o=>o.imageMessage?{imageMessage:o.imageMessage}:o.documentMessage?{documentMessage:o.documentMessage}:o.videoMessage?{videoMessage:o.videoMessage}:o.locationMessage?{locationMessage:o.locationMessage}:{conversation:"contentText"in o?o.contentText:"hydratedContentText"in o?o.hydratedContentText:""};return n=Oa(n),n?.buttonsMessage?t(n.buttonsMessage):n?.templateMessage?.hydratedFourRowTemplate?t(n?.templateMessage?.hydratedFourRowTemplate):n?.templateMessage?.hydratedTemplate?t(n?.templateMessage?.hydratedTemplate):n?.templateMessage?.fourRowTemplate?t(n?.templateMessage?.fourRowTemplate):n};var W2=(n,t)=>{n.userReceipt=n.userReceipt||[];let o=n.userReceipt.find(i=>i.userJid===t.userJid);o?Object.assign(o,t):n.userReceipt.push(t)},Z2=(n,t)=>{let o=gh(t.key),i=(n.reactions||[]).filter(e=>gh(e.key)!==o);t.text=t.text||"",i.push(t),n.reactions=i};var Doe=n=>{let t={};for(let{remoteJid:o,id:i,participant:e,fromMe:a}of n)if(!a){let A=`${o}:${e||""}`;t[A]||(t[A]={jid:o,participant:e,messageIds:[]}),t[A].messageIds.push(i)}return Object.values(t)},I4e=[410,404],X2=async(n,t,o,i)=>{return await a().catch(async A=>{if(i&&typeof A?.status=="number"&&I4e.includes(A.status))return i.logger.info({key:n.key},"sending reupload media request..."),n=await i.reuploadRequest(n),await a();throw A});async function a(){let A=woe(n.message);if(!A)throw new Yg.Boom("No message present",{statusCode:400,data:n});let r=ff(A),s=r?.replace("Message",""),g=A[r];if(!g||typeof g!="object"||!("url"in g)&&!("thumbnailDirectPath"in g))throw new Yg.Boom(`"${r}" message is not a media message`);let c;"thumbnailDirectPath"in g&&!("url"in g)?(c={directPath:g.thumbnailDirectPath,mediaKey:g.mediaKey},s="thumbnail-link"):c=g;let I=await eE(c,s,o);if(t==="buffer"){let d=[];for await(let B of I)d.push(B);return Buffer.concat(d)}return I}},Ooe=n=>{n=woe(n);let t=n?.documentMessage||n?.imageMessage||n?.videoMessage||n?.audioMessage||n?.stickerMessage;if(!t)throw new Yg.Boom("given message is not a media message",{statusCode:400,data:n});return t};var db=Je(Lr(),1);import{createHash as h4e}from"crypto";function l4e(n,t){let o=[];for(let i=0;i({identifier:{name:n,deviceId:0},identifierKey:Yo(t)}),p4e=async({get:n},t,o)=>{let i=[];for(let e=t;e{let o=n.nextPreKeyId-n.firstUnuploadedPreKeyId,i=t-o,e=n.nextPreKeyId+i-1,a={};if(i>0)for(let A=n.nextPreKeyId;A<=e;A++)a[A]=Br.generateKeyPair();return{newPreKeys:a,lastPreKeyId:e,preKeysRange:[n.firstUnuploadedPreKeyId,t]}},yf=n=>({tag:"skey",attrs:{},content:[{tag:"id",attrs:{},content:kg(n.keyId,3)},{tag:"value",attrs:{},content:n.keyPair.public},{tag:"signature",attrs:{},content:n.signature}]}),eU=(n,t)=>({tag:"key",attrs:{},content:[{tag:"id",attrs:{},content:kg(t,3)},{tag:"value",attrs:{},content:n.public}]}),$2=n=>typeof n=="number"&&Number.isInteger(n),Roe=n=>{let t=le(n,"keys");if(!t)return null;let o=Qa(t,"type");if(!o||o.length!==1||o[0]!==Rg[0])return null;let i=Qa(t,"identity"),e=le(t,"skey");if(!i||i.length!==32||!e)return null;let a=xc(n,"registration",4);if(!$2(a))return null;let A=Qa(e,"value"),r=Qa(e,"signature"),s=xc(e,"id",3);if(!A||A.length!==32||!r||!$2(s))return null;let g=le(t,"key"),c;if(g){let I=Qa(g,"value"),d=xc(g,"id",3);if(!I||I.length!==32||!$2(d))return null;c={keyId:d,publicKey:Yo(I)}}return{registrationId:a,identityKey:Yo(i),signedPreKey:{keyId:s,publicKey:Yo(A),signature:r},preKey:c}},koe=async(n,t)=>{let o=A=>A?{keyId:xc(A,"id",3),publicKey:Yo(Qa(A,"value")),signature:Qa(A,"signature")}:void 0,i=kA(le(n,"list"),"user");for(let A of i)Li(A);let a=l4e(i,100);for(let A of a)for(let r of A){let s=le(r,"skey"),g=le(r,"key"),c=Qa(r,"identity"),I=r.attrs.jid,d=xc(r,"registration",4);await t.injectE2ESession({jid:I,session:{registrationId:d,identityKey:Yo(c),signedPreKey:o(s),preKey:o(g)}})}},voe=(n,t,o,i)=>{let{user:e,device:a}=yA(t),A=[];for(let r of n){let{devices:s,id:g}=r,c=yA(g),{user:I,server:d}=c,{domainType:B}=c,f=s?.deviceList;if(Array.isArray(f))for(let{id:Q,keyIndex:y,isHosted:m}of f)(!i||Q!==0)&&(e!==I&&o!==I||a!==Q)&&(Q===0||y)&&(m&&(B=B===jt.LID?jt.HOSTED_LID:jt.HOSTED),A.push({user:I,device:Q,domainType:B,server:LX(d,B)}))}return A},AU=async({creds:n,keys:t},o)=>{let{newPreKeys:i,lastPreKeyId:e,preKeysRange:a}=d4e(n,o),A={nextPreKeyId:Math.max(e+1,n.nextPreKeyId),firstUnuploadedPreKeyId:Math.max(n.firstUnuploadedPreKeyId,e+1)};await t.set({"pre-key":i});let r=await p4e(t,a[0],a[0]+a[1]);return{update:A,preKeys:r}},Poe=async(n,t)=>{let{creds:o}=n,{update:i,preKeys:e}=await AU(n,t),a={tag:"iq",attrs:{xmlns:"encrypt",type:"set",to:OA},content:[{tag:"registration",attrs:{},content:kg(o.registrationId)},{tag:"type",attrs:{},content:Rg},{tag:"identity",attrs:{},content:o.signedIdentityKey.public},{tag:"list",attrs:{},content:Object.keys(e).map(A=>eU(e[+A],+A))},yf(o.signedPreKey)]};return{update:i,node:a}};var E4e=n=>({appVersion:{primary:n.version[0],secondary:n.version[1],tertiary:n.version[2]},platform:n.browser[1].toLocaleLowerCase().includes("android")?oe.ClientPayload.UserAgent.Platform.ANDROID:oe.ClientPayload.UserAgent.Platform.WEB,releaseChannel:oe.ClientPayload.UserAgent.ReleaseChannel.RELEASE,osVersion:"0.1",device:"Desktop",osBuildNumber:"0.1",localeLanguageIso6391:"en",mnc:"000",mcc:"000",localeCountryIso31661Alpha2:n.countryCode}),Goe={"Mac OS":oe.ClientPayload.WebInfo.WebSubPlatform.DARWIN,Windows:oe.ClientPayload.WebInfo.WebSubPlatform.WIN32},C4e=n=>{let t=oe.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;return n.syncFullHistory&&Goe[n.browser[0]]&&n.browser[1]==="Desktop"&&(t=Goe[n.browser[0]]),{webSubPlatform:t}},Foe=n=>{let t={connectType:oe.ClientPayload.ConnectType.WIFI_UNKNOWN,connectReason:oe.ClientPayload.ConnectReason.USER_ACTIVATED,userAgent:E4e(n)};return n.browser[1].toLocaleLowerCase().includes("android")||(t.webInfo=C4e(n)),n.pushName&&(t.pushName=n.pushName),t},Loe=(n,t)=>{let{user:o,device:i}=yA(n),e={...Foe(t),passive:!0,pull:!0,username:+o,device:i,lidDbMigrated:!1};return oe.ClientPayload.fromObject(e)},u4e=n=>{let t=n.toUpperCase();return t==="ANDROID"?oe.DeviceProps.PlatformType.ANDROID_PHONE:oe.DeviceProps.PlatformType[t]||oe.DeviceProps.PlatformType.CHROME},Uoe=({registrationId:n,signedPreKey:t,signedIdentityKey:o},i)=>{let e=h4e("md5").update(i.version.join(".")).digest(),a={os:i.browser[0],platformType:u4e(i.browser[1]),requireFullSync:i.syncFullHistory,historySyncConfig:{storageQuotaMb:10240,inlineInitialPayloadInE2EeMsg:!0,recentSyncDaysLimit:void 0,supportCallLogHistory:!1,supportBotUserAgentChatHistory:!0,supportCagReactionsAndPolls:!0,supportBizHostedMsg:!0,supportRecentSyncChunkMessageCountTuning:!0,supportHostedGroupMsg:!0,supportFbidBotChatHistory:!0,supportAddOnHistorySyncMigration:void 0,supportMessageAssociation:!0,supportGroupHistory:!1,onDemandReady:void 0,supportGuestChat:void 0},version:{primary:10,secondary:15,tertiary:7}},A=oe.DeviceProps.encode(a).finish(),r={...Foe(i),passive:!1,pull:!1,devicePairingData:{buildHash:e,deviceProps:A,eRegid:kg(n),eKeytype:Rg,eIdent:o.public,eSkeyId:kg(t.keyId,3),eSkeyVal:t.keyPair.public,eSkeySig:t.signature}};return oe.ClientPayload.fromObject(r)},Hoe=(n,{advSecretKey:t,signedIdentityKey:o,signalIdentities:i})=>{let e=n.attrs.id,a=le(n,"pair-success"),A=le(a,"device-identity"),r=le(a,"platform"),s=le(a,"device"),g=le(a,"biz");if(!A||!s)throw new db.Boom("Missing device-identity or device in pair success node",{data:n});let c=g?.attrs.name,I=s.attrs.jid,d=s.attrs.lid,{details:B,hmac:f,accountType:Q}=oe.ADVSignedDeviceIdentityHMAC.decode(A.content),y=Buffer.from([]);Q!==void 0&&Q===oe.ADVEncryptionType.HOSTED&&(y=tU);let m=kn(Buffer.concat([y,B]),Buffer.from(t,"base64"));if(Buffer.compare(f,m)!==0)throw new db.Boom("Invalid account signature");let _=oe.ADVSignedDeviceIdentity.decode(B),{accountSignatureKey:T,accountSignature:R,details:F}=_,K=oe.ADVDeviceIdentity.decode(F),L=K.deviceType===oe.ADVEncryptionType.HOSTED?tU:Koe,q=Buffer.concat([L,F,o.public]);if(!Br.verify(T,q,R))throw new db.Boom("Failed to verify account signature");let z=Buffer.concat([xoe,F,o.public,T]);_.deviceSignature=Br.sign(o.private,z);let j=Noe(d,T),P=mf(_,!1),J={tag:"iq",attrs:{to:OA,type:"result",id:e},content:[{tag:"pair-device-sign",attrs:{},content:[{tag:"device-identity",attrs:{"key-index":K.keyIndex.toString()},content:P}]}]};return{creds:{account:_,me:{id:I,name:c,lid:d},signalIdentities:[...i||[],j],platform:r?.attrs.name},reply:J}},mf=(n,t)=>(n={...n},(!t||!n.accountSignatureKey?.length)&&(n.accountSignatureKey=null),oe.ADVSignedDeviceIdentity.encode(n).finish());var AE=Je(Lr(),1);var Joe=12,Yoe=Buffer.alloc(0),joe=n=>{let t=new ArrayBuffer(Joe);return new DataView(t).setUint32(8,n),new Uint8Array(t)},rU=class{constructor(t,o){this.encKey=t,this.decKey=o,this.readCounter=0,this.writeCounter=0,this.iv=new Uint8Array(Joe)}encrypt(t){let o=this.writeCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,Dl(t,this.encKey,this.iv,Yoe)}decrypt(t){let o=this.readCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,Ol(t,this.decKey,this.iv,Yoe)}},qoe=({keyPair:{private:n,public:t},NOISE_HEADER:o,logger:i,routingInfo:e})=>{i=i.child({class:"ns"});let a=Buffer.from(zoe),A=a.byteLength===32?a:sh(a),r=A,s=A,g=A,c=0,I=!1,d=Buffer.alloc(0),B=null,f=!1,Q=null,y;e?(y=Buffer.alloc(7+e.byteLength+o.length),y.write("ED",0,"utf8"),y.writeUint8(0,2),y.writeUint8(1,3),y.writeUint8(e.byteLength>>16,4),y.writeUint16BE(e.byteLength&65535,5),y.set(e,7),y.set(o,7+e.byteLength)):y=Buffer.from(o);let m=q=>{B||(A=sh(Buffer.concat([A,q])))},_=q=>{if(B)return B.encrypt(q);let z=Dl(q,s,joe(c++),A);return m(z),z},T=q=>{if(B)return B.decrypt(q);let z=Ol(q,g,joe(c++),A);return m(q),z},R=q=>{let z=Rn(Buffer.from(q),64,{salt:r,info:""});return[z.subarray(0,32),z.subarray(32)]},F=q=>{let[z,j]=R(q);r=z,s=j,g=j,c=0},K=async()=>{f=!0;let[q,z]=R(new Uint8Array(0));B=new rU(q,z),f=!1,i.trace("Noise handler transitioned to Transport state"),Q&&(i.trace({length:d.length},"Flushing buffered frames after transport ready"),await L(Q),Q=null)},L=async q=>{let z;for(;;){if(d.length<3||(z=d[0]<<16|d[1]<<8|d[2],d.length{m(q.ephemeral),F(Br.sharedKey(n,q.ephemeral));let j=T(q.static);F(Br.sharedKey(n,j));let P=T(q.payload),{intermediate:J,leaf:U}=oe.CertChain.decode(P);if(!U?.details||!U?.signature)throw new AE.Boom("invalid noise leaf certificate",{statusCode:400});if(!J?.details||!J?.signature)throw new AE.Boom("invalid noise intermediate certificate",{statusCode:400});let N=oe.CertChain.NoiseCertificate.Details.decode(J.details),{issuerSerial:k}=N,V=Br.verify(N.key,U.details,U.signature),Ae=Br.verify(aU.PUBLIC_KEY,J.details,J.signature);if(!V)throw new AE.Boom("noise certificate signature invalid",{statusCode:400});if(!Ae)throw new AE.Boom("noise intermediate certificate signature invalid",{statusCode:400});if(k!==aU.SERIAL)throw new AE.Boom("certification match failed",{statusCode:400});let ie=_(z.public);return F(Br.sharedKey(z.private,q.ephemeral)),ie},encodeFrame:q=>{B&&(q=B.encrypt(q));let z=q.byteLength,j=I?0:y.length,P=Buffer.allocUnsafe(j+3+z);return I||(P.set(y),I=!0),P[j]=z>>>16&255,P[j+1]=z>>>8&255,P[j+2]=z&255,P.set(q,j+3),P},decodeFrame:async(q,z)=>{if(f){d=Buffer.concat([d,q]),Q=z;return}d.length===0?d=Buffer.from(q):d=Buffer.concat([d,q]),await L(z)}}};import{pipeline as B4e}from"stream/promises";import{promisify as f4e}from"util";import{createInflate as Q4e,inflate as y4e}from"zlib";var m4e=f4e(y4e),S4e=n=>{for(let t of n){let o=t.message;if(!o?.key?.fromMe||!o.userReceipt?.length)continue;let i=o.userReceipt[0]?.userJid;if(i&&(_t(i)||ur(i)))return i}},w4e=async(n,t)=>{let o=await eE(n,"md-msg-hist",{options:t}),i=Q4e(),e=[];i.on("data",r=>e.push(r)),await B4e(o,i);let a=Buffer.concat(e);return oe.HistorySync.decode(a)},D4e=(n,t)=>{let o=[],i=[],e=[],a=[];t?.trace({progress:n.progress},"processing history of type "+n.syncType?.toString());for(let A of n.phoneNumberToLidMappings||[])A.lidJid&&A.pnJid&&a.push({lid:A.lidJid,pn:A.pnJid});switch(n.syncType){case oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:case oe.HistorySync.HistorySyncType.RECENT:case oe.HistorySync.HistorySyncType.FULL:case oe.HistorySync.HistorySyncType.ON_DEMAND:for(let A of n.conversations){i.push({id:A.id,name:A.displayName||A.name||A.username||void 0,username:A.username||void 0,lid:A.lidJid||A.accountLid||void 0,phoneNumber:A.pnJid||void 0});let r=A.id,s=qA(r)||ga(r),g=_t(r)||ur(r);if(s&&A.pnJid)a.push({lid:r,pn:A.pnJid});else if(g&&A.lidJid)a.push({lid:A.lidJid,pn:r});else if(s&&!A.pnJid){let I=S4e(A.messages||[]);I&&a.push({lid:r,pn:I})}let c=A.messages||[];delete A.messages;for(let I of c){let d=I.message;o.push(d),A.messages?.length||(A.messages=[{message:d}]),!d.key.fromMe&&!A.lastMessageRecvTimestamp&&(A.lastMessageRecvTimestamp=Hr(d.messageTimestamp)),(d.messageStubType===TA.BIZ_PRIVACY_MODE_TO_BSP||d.messageStubType===TA.BIZ_PRIVACY_MODE_TO_FB)&&d.messageStubParameters?.[0]&&i.push({id:d.key.participant||d.key.remoteJid,verifiedName:d.messageStubParameters?.[0]})}e.push(A)}break;case oe.HistorySync.HistorySyncType.PUSH_NAME:for(let A of n.pushnames)i.push({id:A.id,notify:A.pushname});break}return{chats:e,contacts:i,messages:o,lidPnMappings:a,pastParticipants:n.pastParticipants,syncType:n.syncType,progress:n.progress}},Voe=async(n,t,o)=>{let i;return n.initialHistBootstrapInlinePayload?i=oe.HistorySync.decode(await m4e(n.initialHistBootstrapInlinePayload)):i=await w4e(n,t),D4e(i,o)},hb=n=>(n?Oa(n):void 0)?.protocolMessage?.historySyncNotification;var en=Je(Lr(),1);var Ys;(function(n){n.Chat="label_jid",n.Message="label_message"})(Ys||(Ys={}));var Woe=new ih;var Zoe=(n,t,o)=>{let i=[];if(!t)return o?.warn({hasFullName:!!n.fullName,hasLidJid:!!n.lidJid,hasPnJid:!!n.pnJid},"contactAction sync: missing id in index"),i;let e=n.lidJid,a=_t(t),A=a?t:n.pnJid||void 0;return i.push({event:"contacts.upsert",data:[{id:t,name:n.fullName||n.firstName||n.username||void 0,username:n.username||void 0,lid:e||void 0,phoneNumber:A}]}),e&&qA(e)&&a&&i.push({event:"lid-mapping.update",data:{lid:e,pn:t}}),i},Xoe=(n,t)=>{for(let o of t)o.event==="contacts.upsert"?n.emit("contacts.upsert",o.data):n.emit("lid-mapping.update",o.data)};var Sf=n=>{let t=n7(n);return{indexKey:t.indexKey,valueEncryptionKey:t.valueEncryptionKey,valueMacKey:t.valueMacKey,snapshotMacKey:t.snapshotMacKey,patchMacKey:t.patchMacKey}},$oe=(n,t,o,i)=>{let e=n===oe.SyncdMutation.SyncdOperation.SET?1:2,a=typeof o=="string"?Buffer.from(o,"base64"):o,A=new Uint8Array(1+a.length);A[0]=e,A.set(a,1);let r=new Uint8Array(8);r[7]=A.length;let s=new Uint8Array(A.length+t.length+r.length);return s.set(A,0),s.set(t,A.length),s.set(r,A.length+t.length),kn(s,i,"sha512").subarray(0,32)},ene=n=>{let t=Buffer.alloc(8);return t.writeUint32BE(n,4),t},Ane=({indexValueMap:n,hash:t})=>{n={...n};let o=[],i=[];return{mix:({indexMac:e,valueMac:a,operation:A})=>{let r=Buffer.from(e).toString("base64"),s=n[r];if(A===oe.SyncdMutation.SyncdOperation.REMOVE){if(!s)return;delete n[r]}else o.push(a),n[r]={valueMac:a};s&&i.push(s.valueMac)},finish:()=>{let e=Woe.subtractThenAdd(t,i,o);return{hash:Buffer.from(e),indexValueMap:n}}}},iU=(n,t,o,i)=>{let e=Buffer.concat([n,ene(t),Buffer.from(o,"utf-8")]);return kn(e,i,"sha256")},tne=(n,t,o,i,e)=>{let a=Buffer.concat([n,...t,ene(o),Buffer.from(i,"utf-8")]);return kn(a,e)},Eb=()=>({version:0,hash:Buffer.alloc(128),indexValueMap:{}}),oU=n=>((typeof n.version!="number"||isNaN(n.version))&&(n.version=0),n),nU=2,wf=n=>n?.data?.isMissingKey===!0,rne=(n,t)=>t>=nU||n?.name==="TypeError",ane=async({type:n,index:t,syncAction:o,apiVersion:i,operation:e},a,A,r)=>{let s=a?await r(a):void 0;if(!s)throw new en.Boom(`myAppStateKey ("${a}") not present`,{data:{isMissingKey:!0}});let g=Buffer.from(a,"base64");A={...A,indexValueMap:{...A.indexValueMap}};let c=Buffer.from(JSON.stringify(t)),I=oe.SyncActionData.fromObject({index:c,value:o,padding:new Uint8Array(0),version:i}),d=oe.SyncActionData.encode(I).finish(),B=Sf(s.keyData),f=h7(d,B.valueEncryptionKey),Q=$oe(e,f,g,B.valueMacKey),y=kn(c,B.indexKey),m=Ane(A);m.mix({indexMac:y,valueMac:Q,operation:e}),Object.assign(A,m.finish()),A.version+=1;let _=iU(A.hash,A.version,n,B.snapshotMacKey),T={patchMac:tne(_,[Q],A.version,n,B.patchMacKey),snapshotMac:_,keyId:{id:g},mutations:[{operation:e,record:{index:{blob:y},value:{blob:Buffer.concat([f,Q])},keyId:{id:g}}}]},R=y.toString("base64");return A.indexValueMap[R]={valueMac:Q},{patch:T,state:A}},ine=async(n,t,o,i,e)=>{let a=Ane(t),A=new Map;for(let s of n){let g="operation"in s?s.operation:oe.SyncdMutation.SyncdOperation.SET,c="record"in s&&s.record?s.record:s,I;try{I=await r(c.keyId.id)}catch(_){if(wf(_))throw _;continue}let d=c.value.blob,B=d.subarray(0,-32),f=d.subarray(-32);if(e){let _=$oe(g,B,c.keyId.id,I.valueMacKey);if(Buffer.compare(_,f)!==0)continue}let Q;try{Q=d7(B,I.valueEncryptionKey)}catch{continue}let y=oe.SyncActionData.decode(Q);if(e){let _=kn(y.index,I.indexKey);if(Buffer.compare(_,c.index.blob)!==0)throw new en.Boom("HMAC index verification failed")}let m=Buffer.from(y.index).toString();i({syncAction:y,index:JSON.parse(m)}),a.mix({indexMac:c.index.blob,valueMac:f,operation:g})}return a.finish();async function r(s){let g=Buffer.from(s).toString("base64"),c=A.get(g);if(c)return c;let I=await o(g);if(!I)throw new en.Boom(`failed to find key "${g}" to decode mutation`,{data:{isMissingKey:!0,msgMutations:n}});let d=Sf(I.keyData);return A.set(g,d),d}},O4e=async(n,t,o,i,e,a)=>{if(a){let r=Buffer.from(n.keyId.id).toString("base64"),s=await i(r);if(!s)throw new en.Boom(`failed to find key "${r}" to decode patch`,{data:{isMissingKey:!0,msg:n}});let g=Sf(s.keyData),c=n.mutations.map(d=>d.record.value.blob.slice(-32)),I=tne(n.snapshotMac,c,Hr(n.version.version),t,g.patchMacKey);if(Buffer.compare(I,n.patchMac)!==0)throw new en.Boom("Invalid patch mac")}return await ine(n.mutations,o,i,e,a)},one=async(n,t)=>{let o=le(n,"sync"),i=kA(o,"collection"),e={};return await Promise.all(i.map(async a=>{let A=le(a,"patches"),r=kA(A||a,"patch"),s=le(a,"snapshot"),g=[],c=a.attrs.name,I=a.attrs.has_more_patches==="true",d;if(s&&s.content){Buffer.isBuffer(s)||(s.content=Buffer.from(Object.values(s.content)));let B=oe.ExternalBlobReference.decode(s.content),f=await nne(B,t);d=oe.SyncdSnapshot.decode(f)}for(let{content:B}of r)if(B){Buffer.isBuffer(B)||(B=Buffer.from(Object.values(B)));let f=oe.SyncdPatch.decode(B);f.version||(f.version={version:+a.attrs.version+1}),g.push(f)}e[c]={patches:g,hasMorePatches:I,snapshot:d}})),e},nne=async(n,t)=>{let o=await eE(n,"md-app-state",{options:t}),i=[];for await(let e of o)i.push(e);return Buffer.concat(i)},b4e=async(n,t)=>{let o=await nne(n,t);return oe.SyncdMutations.decode(o)},sne=async(n,t,o,i,e=!0,a)=>{let A=Eb();A.version=Hr(t.version.version);let r={},s=typeof i>"u"||A.version>i,{hash:g,indexValueMap:c}=await ine(t.records,A,o,s?I=>{let d=I.syncAction.index?.toString();r[d]=I}:()=>{},e);if(A.hash=g,A.indexValueMap=c,e){let I=Buffer.from(t.keyId.id).toString("base64"),d=await o(I);if(!d)throw new en.Boom(`failed to find key "${I}" to decode mutation`,{data:{isMissingKey:!0}});let B=Sf(d.keyData),f=iU(A.hash,A.version,n,B.snapshotMacKey);Buffer.compare(t.mac,f)!==0&&a?.warn({name:n,version:A.version},"LTHash verification failed on snapshot, continuing with partial state")}return{state:A,mutationMap:r}},sU=async(n,t,o,i,e,a,A,r=!0)=>{let s={...o,indexValueMap:{...o.indexValueMap}},g={};for(let c of t){let{version:I,keyId:d,snapshotMac:B}=c;if(c.externalMutations){A?.trace({name:n,version:I},"downloading external patch");let m=await b4e(c.externalMutations,e);A?.debug({name:n,version:I,mutations:m.mutations.length},"downloaded external patch"),c.mutations?.push(...m.mutations)}let f=Hr(I.version);s.version=f;let Q=typeof a>"u"||f>a,y;try{y=await O4e(c,n,s,i,Q?m=>{let _=m.syncAction.index?.toString();g[_]=m}:()=>{},r)}catch(m){if(wf(m))throw m;A?.warn({name:n,version:f,error:m.message},"failed to decode patch, skipping");continue}if(s.hash=y.hash,s.indexValueMap=y.indexValueMap,r){let m=Buffer.from(d.id).toString("base64"),_=await i(m);if(!_)throw new en.Boom(`failed to find key "${m}" to decode mutation`,{data:{isMissingKey:!0}});let T=Sf(_.keyData),R=iU(s.hash,s.version,n,T.snapshotMacKey);if(Buffer.compare(B,R)!==0){A?.warn({name:n,version:s.version},"LTHash verification failed, skipping remaining patches");break}}c.mutations=[]}return{state:s,mutationMap:g}},gne=(n,t)=>{let o=oe.SyncdMutation.SyncdOperation,i=a=>{let A;return Array.isArray(a)?A={lastMessageTimestamp:a[a.length-1]?.messageTimestamp,messages:a?.length?a.map(s=>{if(!s.key?.id||!s.key?.remoteJid)throw new en.Boom("Incomplete key",{statusCode:400,data:s});if(Ur(s.key.remoteJid)&&!s.key.fromMe&&!s.key.participant)throw new en.Boom("Expected not from me message to have participant",{statusCode:400,data:s});if(!s.messageTimestamp||!Hr(s.messageTimestamp))throw new en.Boom("Missing timestamp in last message list",{statusCode:400,data:s});return s.key.participant&&(s.key.participant=uA(s.key.participant)),s}):void 0}:A=a,A},e;if("mute"in n)e={syncAction:{muteAction:{muted:!!n.mute,muteEndTimestamp:n.mute||void 0}},index:["mute",t],type:"regular_high",apiVersion:2,operation:o.SET};else if("archive"in n)e={syncAction:{archiveChatAction:{archived:!!n.archive,messageRange:i(n.lastMessages)}},index:["archive",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("markRead"in n)e={syncAction:{markChatAsReadAction:{read:n.markRead,messageRange:i(n.lastMessages)}},index:["markChatAsRead",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("deleteForMe"in n){let{timestamp:a,key:A,deleteMedia:r}=n.deleteForMe;e={syncAction:{deleteMessageForMeAction:{deleteMedia:r,messageTimestamp:a}},index:["deleteMessageForMe",t,A.id,A.fromMe?"1":"0","0"],type:"regular_high",apiVersion:3,operation:o.SET}}else if("clear"in n)e={syncAction:{clearChatAction:{messageRange:i(n.lastMessages)}},index:["clearChat",t,"1","0"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pin"in n)e={syncAction:{pinAction:{pinned:!!n.pin}},index:["pin_v1",t],type:"regular_low",apiVersion:5,operation:o.SET};else if("contact"in n)e={syncAction:{contactAction:n.contact||{}},index:["contact",t],type:"critical_unblock_low",apiVersion:2,operation:n.contact?o.SET:o.REMOVE};else if("disableLinkPreviews"in n)e={syncAction:{privacySettingDisableLinkPreviewsAction:n.disableLinkPreviews||{}},index:["setting_disableLinkPreviews"],type:"regular",apiVersion:8,operation:o.SET};else if("star"in n){let a=n.star.messages[0];e={syncAction:{starAction:{starred:!!n.star.star}},index:["star",t,a.id,a.fromMe?"1":"0","0"],type:"regular_low",apiVersion:2,operation:o.SET}}else if("delete"in n)e={syncAction:{deleteChatAction:{messageRange:i(n.lastMessages)}},index:["deleteChat",t,"1"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pushNameSetting"in n)e={syncAction:{pushNameSetting:{name:n.pushNameSetting}},index:["setting_pushName"],type:"critical_block",apiVersion:1,operation:o.SET};else if("quickReply"in n)e={syncAction:{quickReplyAction:{count:0,deleted:n.quickReply.deleted||!1,keywords:[],message:n.quickReply.message||"",shortcut:n.quickReply.shortcut||""}},index:["quick_reply",n.quickReply.timestamp||String(Math.floor(Date.now()/1e3))],type:"regular",apiVersion:2,operation:o.SET};else if("addLabel"in n)e={syncAction:{labelEditAction:{name:n.addLabel.name,color:n.addLabel.color,predefinedId:n.addLabel.predefinedId,deleted:n.addLabel.deleted}},index:["label_edit",n.addLabel.id],type:"regular",apiVersion:3,operation:o.SET};else if("addChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[Ys.Chat,n.addChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("removeChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Ys.Chat,n.removeChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("addMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[Ys.Message,n.addMessageLabel.labelId,t,n.addMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else if("removeMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Ys.Message,n.removeMessageLabel.labelId,t,n.removeMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else throw new en.Boom("not supported");return e.syncAction.timestamp=Date.now(),e},cne=(n,t,o,i,e)=>{let a=!!i,A=i?.accountSettings;e?.trace({syncAction:n,initialSync:!!i},"processing sync action");let{syncAction:{value:r},index:[s,g,c,I]}=n;if(r?.muteAction)t.emit("chats.update",[{id:g,muteEndTime:r.muteAction?.muted?Hr(r.muteAction.muteEndTimestamp):null,conditional:d(g,void 0)}]);else if(r?.archiveChatAction||s==="archive"||s==="unarchive"){let f=r?.archiveChatAction,Q=f?f.archived:s==="archive",y=A?.unarchiveChats?f?.messageRange:void 0;t.emit("chats.update",[{id:g,archived:Q,conditional:d(g,y)}])}else if(r?.markChatAsReadAction){let f=r.markChatAsReadAction,Q=a&&f.read;t.emit("chats.update",[{id:g,unreadCount:Q?null:f?.read?0:-1,conditional:d(g,f?.messageRange)}])}else if(r?.deleteMessageForMeAction||s==="deleteMessageForMe")t.emit("messages.delete",{keys:[{remoteJid:g,id:c,fromMe:I==="1"}]});else if(r?.contactAction){let f=Zoe(r.contactAction,g,e);Xoe(t,f)}else if(r?.pushNameSetting){let f=r?.pushNameSetting?.name;f&&o?.name!==f&&t.emit("creds.update",{me:{...o,name:f}})}else if(r?.pinAction)t.emit("chats.update",[{id:g,pinned:r.pinAction?.pinned?Hr(r.timestamp):null,conditional:d(g,void 0)}]);else if(r?.unarchiveChatsSetting){let f=!!r.unarchiveChatsSetting.unarchiveChats;t.emit("creds.update",{accountSettings:{unarchiveChats:f}}),e?.info(`archive setting updated => '${r.unarchiveChatsSetting.unarchiveChats}'`),A&&(A.unarchiveChats=f)}else if(r?.starAction||s==="star"){let f=r?.starAction?.starred;typeof f!="boolean"&&(f=n.index[n.index.length-1]==="1"),t.emit("messages.update",[{key:{remoteJid:g,id:c,fromMe:I==="1"},update:{starred:f}}])}else if(r?.deleteChatAction||s==="deleteChat")a||t.emit("chats.delete",[g]);else if(r?.labelEditAction){let{name:f,color:Q,deleted:y,predefinedId:m}=r.labelEditAction;t.emit("labels.edit",{id:g,name:f,color:Q,deleted:y,predefinedId:m?String(m):void 0})}else r?.labelAssociationAction?t.emit("labels.association",{type:r.labelAssociationAction.labeled?"add":"remove",association:s===Ys.Chat?{type:Ys.Chat,chatId:n.index[2],labelId:n.index[1]}:{type:Ys.Message,chatId:n.index[2],messageId:n.index[3],labelId:n.index[1]}}):r?.localeSetting?.locale?t.emit("settings.update",{setting:"locale",value:r.localeSetting.locale}):r?.timeFormatAction?t.emit("settings.update",{setting:"timeFormat",value:r.timeFormatAction}):r?.pnForLidChatAction?r.pnForLidChatAction.pnJid&&t.emit("lid-mapping.update",{lid:g,pn:r.pnForLidChatAction.pnJid}):r?.privacySettingRelayAllCalls?t.emit("settings.update",{setting:"privacySettingRelayAllCalls",value:r.privacySettingRelayAllCalls}):r?.statusPrivacy?t.emit("settings.update",{setting:"statusPrivacy",value:r.statusPrivacy}):r?.lockChatAction?t.emit("chats.lock",{id:g,locked:!!r.lockChatAction.locked}):r?.privacySettingDisableLinkPreviewsAction?t.emit("settings.update",{setting:"disableLinkPreviews",value:r.privacySettingDisableLinkPreviewsAction}):r?.notificationActivitySettingAction?.notificationActivitySetting?t.emit("settings.update",{setting:"notificationActivitySetting",value:r.notificationActivitySettingAction.notificationActivitySetting}):r?.lidContactAction?t.emit("contacts.upsert",[{id:g,name:r.lidContactAction.fullName||r.lidContactAction.firstName||r.lidContactAction.username||void 0,username:r.lidContactAction.username||void 0,lid:g,phoneNumber:void 0}]):r?.privacySettingChannelsPersonalisedRecommendationAction?t.emit("settings.update",{setting:"channelsPersonalisedRecommendation",value:r.privacySettingChannelsPersonalisedRecommendationAction}):e?.debug({syncAction:n,id:g},"unprocessable update");function d(f,Q){return a?y=>{let m=y.historySets.chats[f]||y.chatUpserts[f];if(m)return Q?B(m,Q):!0}:void 0}function B(f,Q){let y=Number(Q?.lastMessageTimestamp||Q?.lastSystemMessageTimestamp||0),m=Number(f?.lastMessageRecvTimestamp||0);return y>=m}};var M4e=class{_eventListeners;_maxListeners;_logger;_throwOnEmitError=!1;_throwOnEmptyListeners=!1;_errorEvent="error";constructor(n){this._eventListeners=new Map,this._maxListeners=100,this._logger=n?.logger,n?.throwOnEmitError!==void 0&&(this._throwOnEmitError=n.throwOnEmitError),n?.throwOnEmptyListeners!==void 0&&(this._throwOnEmptyListeners=n.throwOnEmptyListeners)}get logger(){return this._logger}set logger(n){this._logger=n}get throwOnEmitError(){return this._throwOnEmitError}set throwOnEmitError(n){this._throwOnEmitError=n}get throwOnEmptyListeners(){return this._throwOnEmptyListeners}set throwOnEmptyListeners(n){this._throwOnEmptyListeners=n}once(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.on(n,o),this}listenerCount(n){if(n===void 0)return this.getAllListeners().length;let t=this._eventListeners.get(n);return t?t.length:0}eventNames(){return[...this._eventListeners.keys()]}rawListeners(n){return n===void 0?this.getAllListeners():this._eventListeners.get(n)??[]}prependListener(n,t){let o=this._eventListeners.get(n)??[];return o.unshift(t),this._eventListeners.set(n,o),this}prependOnceListener(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.prependListener(n,o),this}maxListeners(){return this._maxListeners}addListener(n,t){return this.on(n,t),this}on(n,t){this._eventListeners.has(n)||this._eventListeners.set(n,[]);let o=this._eventListeners.get(n);return o&&(o.length>=this._maxListeners&&console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${o.length+1} ${n} listeners added. Use setMaxListeners() to increase limit.`),o.push(t)),this}removeListener(n,t){return this.off(n,t),this}off(n,t){let o=this._eventListeners.get(n)??[],i=o.indexOf(t);return i!==-1&&o.splice(i,1),o.length===0&&this._eventListeners.delete(n),this}emit(n,...t){let o=!1,i=this._eventListeners.get(n);if(i&&i.length>0)for(let e of i)e(...t),o=!0;if(n===this._errorEvent){let e=t[0]instanceof Error?t[0]:new Error(`${t[0]}`);if(this._throwOnEmitError&&!o)throw e;if(this.listeners(this._errorEvent).length===0&&this._throwOnEmptyListeners===!0)throw e}return this.sendLog(n,t),o}listeners(n){return this._eventListeners.get(n)??[]}removeAllListeners(n){return n!==void 0?this._eventListeners.delete(n):this._eventListeners.clear(),this}setMaxListeners(n){this._maxListeners=n;for(let t of this._eventListeners.values())t.length>n&&t.splice(n)}getAllListeners(){let n=[];for(let t of this._eventListeners.values())n=[...n,...t];return n}sendLog(n,t){if(!this._logger)return;let o;switch(typeof t=="string"?o=t:Array.isArray(t)&&t.length>0&&t[0]instanceof Error?o=t[0].message:t instanceof Error?o=t.message:Array.isArray(t)&&t.length>0&&typeof t[0]?.message=="string"?o=t[0].message:o=JSON.stringify(t),n){case"error":{this._logger.error?.(o,{event:n,data:t});break}case"warn":{this._logger.warn?.(o,{event:n,data:t});break}case"trace":{this._logger.trace?.(o,{event:n,data:t});break}case"debug":{this._logger.debug?.(o,{event:n,data:t});break}case"fatal":{this._logger.fatal?.(o,{event:n,data:t});break}default:{this._logger.info?.(o,{event:n,data:t});break}}}},lI=class extends M4e{_hooks;_throwOnHookError=!1;_enforceBeforeAfter=!1;_deprecatedHooks;_allowDeprecated=!0;constructor(n){super({logger:n?.logger,throwOnEmitError:n?.throwOnEmitError,throwOnEmptyListeners:n?.throwOnEmptyListeners}),this._hooks=new Map,this._deprecatedHooks=n?.deprecatedHooks?new Map(n.deprecatedHooks):new Map,n?.throwOnHookError!==void 0?this._throwOnHookError=n.throwOnHookError:n?.throwHookErrors!==void 0&&(this._throwOnHookError=n.throwHookErrors),n?.enforceBeforeAfter!==void 0&&(this._enforceBeforeAfter=n.enforceBeforeAfter),n?.allowDeprecated!==void 0&&(this._allowDeprecated=n.allowDeprecated)}get hooks(){return this._hooks}get throwHookErrors(){return this._throwOnHookError}set throwHookErrors(n){this._throwOnHookError=n}get throwOnHookError(){return this._throwOnHookError}set throwOnHookError(n){this._throwOnHookError=n}get enforceBeforeAfter(){return this._enforceBeforeAfter}set enforceBeforeAfter(n){this._enforceBeforeAfter=n}get deprecatedHooks(){return this._deprecatedHooks}set deprecatedHooks(n){this._deprecatedHooks=n}get allowDeprecated(){return this._allowDeprecated}set allowDeprecated(n){this._allowDeprecated=n}validateHookName(n){if(this._enforceBeforeAfter){let t=n.trim().toLocaleLowerCase();if(!t.startsWith("before")&&!t.startsWith("after"))throw new Error(`Hook event "${n}" must start with "before" or "after" when enforceBeforeAfter is enabled`)}}checkDeprecatedHook(n){if(this._deprecatedHooks.has(n)){let t=this._deprecatedHooks.get(n),o=`Hook "${n}" is deprecated${t?`: ${t}`:""}`;return this.emit("warn",{hook:n,message:o}),this._allowDeprecated}return!0}onHook(n,t){this.onHookEntry({event:n,handler:t})}onHookEntry(n){if(this.validateHookName(n.event),!this.checkDeprecatedHook(n.event))return;let t=this._hooks.get(n.event);t?t.push(n.handler):this._hooks.set(n.event,[n.handler])}addHook(n,t){this.onHookEntry({event:n,handler:t})}onHooks(n){for(let t of n)this.onHook(t.event,t.handler)}prependHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);o?o.unshift(t):this._hooks.set(n,[t])}prependOnceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.prependHook(n,o)}onceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.onHook(n,o)}removeHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){let i=o.indexOf(t);i!==-1&&o.splice(i,1)}}removeHooks(n){for(let t of n)this.removeHook(t.event,t.handler)}async hook(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o)for(let i of o)try{await i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}hookSync(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){for(let i of o)if(i.constructor.name!=="AsyncFunction")try{i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}}async beforeHook(n,...t){await this.hook(`before:${n}`,...t)}async afterHook(n,...t){await this.hook(`after:${n}`,...t)}async callHook(n,...t){await this.hook(n,...t)}getHooks(n){if(this.validateHookName(n),!!this.checkDeprecatedHook(n))return this._hooks.get(n)}clearHooks(){this._hooks.clear()}};var _4e=class{_enabled=!0;_maxSize=4e3;_store=new Map;_keys=[];constructor(n){n?.enabled!==void 0&&(this._enabled=n.enabled),n?.maxSize!==void 0&&(this._maxSize=n.maxSize)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get maxSize(){return this._maxSize}set maxSize(n){this._maxSize=n}get store(){return this._store}get size(){return this._store.size}get(n){return this._store.get(n)}set(n,t){if(this._enabled){if(this._store.has(n)){this._store.set(n,t);return}if(this._store.size>=this._maxSize){let o=this._keys.shift();o&&this._store.delete(o)}this._keys.push(n),this._store.set(n,t)}}has(n){return this._store.has(n)}clear(){this._store.clear(),this._keys=[]}},T4e=class{get name(){return"crc32"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let a=n;t=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}let o=3988292384,i=4294967295;for(let a=0;a>>1^o&-(i&1)}return i=(i^4294967295)>>>0,i.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},Cb=class{_algorithm="SHA-256";constructor(n){n?.algorithm&&(this._algorithm=n?.algorithm)}get name(){return this._algorithm}async toHash(n){let t=await crypto.subtle.digest(this._algorithm,n);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}},N4e=class{get name(){return"djb2"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let e=n;t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let o=5381;for(let e=0;e>>0;return o.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},R4e=class{get name(){return"fnv1"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let A=n;t=new Uint8Array(A.buffer,A.byteOffset,A.byteLength)}let o=2166136261,i=16777619,e=o;for(let A=0;A>>0;return e.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},k4e=class{_seed;constructor(n=0){this._seed=n>>>0}get name(){return"murmur"}get seed(){return this._seed}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let c=n;t=new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let o=3432918353,i=461845907,e=t.length,a=Math.floor(e/4),A=this._seed;for(let c=0;c>>16,A=this._imul(A,2246822507),A^=A>>>13,A=this._imul(A,3266489909),A^=A>>>16,A=A>>>0,A.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}_imul(n,t){if(Math.imul)return Math.imul(n,t);let o=n>>>16&65535,i=n&65535,e=t>>>16&65535,a=t&65535;return i*a+(o*a+i*e<<16>>>0)|0}_rotl32(n,t){return n<>>32-t}},v4e=class{_providers=new Map;_getFuzzy=!0;constructor(n){n?.providers&&this.loadProviders(n?.providers),n?.getFuzzy!==void 0&&(this._getFuzzy=!!n?.getFuzzy)}loadProviders(n){for(let t of n)this._providers.set(t.name,t)}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return Array.from(this._providers.keys())}get(n,t){let o=t?.fuzzy??this._getFuzzy;n=n.trim();let i=this._providers.get(n);return i===void 0&&o===!0&&(n=n.toLowerCase(),i=this._providers.get(n)),i===void 0&&o===!0&&(n=n.replaceAll("-",""),i=this._providers.get(n)),i}add(n){this._providers.set(n.name,n)}remove(n){return this._providers.delete(n)}},gU=class extends lI{_parse=JSON.parse;_stringify=JSON.stringify;_providers=new v4e;_defaultAlgorithm="SHA-256";_defaultAlgorithmSync="djb2";_cache;constructor(n){super(n),n?.parse&&(this._parse=n.parse),n?.stringify&&(this._stringify=n.stringify),n?.defaultAlgorithm&&(this._defaultAlgorithm=n.defaultAlgorithm),n?.defaultAlgorithmSync&&(this._defaultAlgorithmSync=n.defaultAlgorithmSync),this._cache=new _4e(n?.cache),this.loadProviders(n?.providers,{includeBase:n?.includeBase??!0})}get parse(){return this._parse}set parse(n){this._parse=n}get stringify(){return this._stringify}set stringify(n){this._stringify=n}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return this._providers.names}get defaultAlgorithm(){return this._defaultAlgorithm}set defaultAlgorithm(n){this._defaultAlgorithm=n}get defaultAlgorithmSync(){return this._defaultAlgorithmSync}set defaultAlgorithmSync(n){this._defaultAlgorithmSync=n}get cache(){return this._cache}async toHash(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithm,maxLength:t?.maxLength};await this.beforeHook("toHash",o);let i=this._stringify(o.data),e=`${o.algorithm}:${i}`;if(this._cache.enabled){let c=this._cache.get(e);if(c!==void 0){let I=c;t?.maxLength&&I.length>t.maxLength&&(I=I.substring(0,t.maxLength));let d={hash:I,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",d),d.hash}}let A=new TextEncoder().encode(i),r=this._providers.get(o.algorithm);r||(this.emit("warn",`Invalid algorithm '${o.algorithm}' not found. Falling back to default algorithm '${this._defaultAlgorithm}'.`),r=new Cb({algorithm:this._defaultAlgorithm}));let s=await r.toHash(A);this._cache.enabled&&this._cache.set(e,s),t?.maxLength&&s.length>t?.maxLength&&(s=s.substring(0,t.maxLength));let g={hash:s,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",g),g.hash}async toNumber(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithm,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=await this.toHash(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}toHashSync(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithmSync,maxLength:t?.maxLength};this.hookSync("before:toHashSync",o);let i=o.algorithm,e=this._stringify(o.data),a=`${i}:${e}`;if(this._cache.enabled){let I=this._cache.get(a);if(I!==void 0){let d=I;t?.maxLength&&d.length>t.maxLength&&(d=d.substring(0,t.maxLength));let B={hash:d,data:o.data,algorithm:i};return this.hookSync("after:toHashSync",B),B.hash}}let r=new TextEncoder().encode(e),s=this._providers.get(i);if(!s&&(this.emit("warn",`Invalid algorithm '${i}' not found. Falling back to default algorithm '${this._defaultAlgorithmSync}'.`),s=this._providers.get(this._defaultAlgorithmSync),!s))throw new Error(`Hash provider '${this._defaultAlgorithmSync}' (default) not found`);if(!s.toHashSync)throw new Error(`Hash provider '${i}' does not support synchronous hashing. Use toHash() instead or choose a different algorithm (djb2, fnv1, murmur, crc32).`);let g=s.toHashSync(r);this._cache.enabled&&this._cache.set(a,g),t?.maxLength&&g.length>t?.maxLength&&(g=g.substring(0,t.maxLength));let c={hash:g,data:o.data,algorithm:o.algorithm};return this.hookSync("after:toHashSync",c),c.hash}toNumberSync(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithmSync,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=this.toHashSync(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}loadProviders(n,t={includeBase:!0}){if(n)for(let o of n)this._providers.add(o);t.includeBase&&(this.providers.add(new Cb({algorithm:"SHA-256"})),this.providers.add(new Cb({algorithm:"SHA-384"})),this.providers.add(new Cb({algorithm:"SHA-512"})),this.providers.add(new T4e),this.providers.add(new N4e),this.providers.add(new R4e),this.providers.add(new k4e))}};var lU=n=>{let t;if(n!==void 0){if(typeof n=="number")t=n;else{if(typeof n!="string")return;if(n=n.trim(),Number.isNaN(Number(n))){let o=/^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(n);if(!o)throw new Error(`Unsupported time format: "${n}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);let[,i,e]=o,a=Number.parseFloat(i);switch(e.toLowerCase()){case"ms":t=a;break;case"s":t=a*1e3;break;case"m":t=a*1e3*60;break;case"h":t=a*1e3*60*60;break;case"hr":t=a*1e3*60*60;break;case"d":t=a*1e3*60*60*24;break;default:t=Number(n)}}else t=Number(n)}return t}},$l=(n,t)=>{t??=new Date;let o=lU(n);return o===void 0?t.getTime():t.getTime()+o};var Df=(function(n){return n.SHA256="SHA-256",n.SHA384="SHA-384",n.SHA512="SHA-512",n.DJB2="djb2",n.FNV1="fnv1",n.MURMER="murmer",n.CRC32="crc32",n})({});function cU(n,t={algorithm:"djb2",serialize:JSON.stringify}){let o=t?.algorithm??"djb2",i=(t?.serialize??JSON.stringify)(n);return new gU().toHashSync(i,{algorithm:o})}function Ine(n,t={min:0,max:10,algorithm:"djb2",serialize:JSON.stringify}){let o=t?.min??0,i=t?.max??10,e=t?.algorithm??"djb2",a=t?.serialize??JSON.stringify,A=t?.hashLength??16;if(o>=i)throw new Error(`Invalid range: min (${o}) must be less than max (${i})`);let r=a(n);return new gU().toNumberSync(r,{algorithm:e,min:o,max:i,hashLength:A})}function pU(n,t){let{ttl:o,keyPrefix:i,cache:e,serialize:a}=t;return(...A)=>{let r=P4e(n,A,{keyPrefix:i,serialize:a});t.createKey&&(r=t.createKey(n,A,t));let s=e.get(r);if(s===void 0)try{s=n(...A),e.set(r,s,o)}catch(g){e.emit("error",g),t.cacheErrors&&e.set(r,g,o)}return s}}function dU(n,t,o){let i=typeof n=="function"?n(o):n,e;try{e=o.cache.get(i)}catch(a){if(o.cache.emit("error",a),o.throwErrors===!0||o.throwErrors==="store")throw a}if(e===void 0)try{try{e=t()}catch(a){throw new ub(a,"function")}try{o.cache.set(i,e,o.ttl)}catch(a){throw new ub(a,"store")}}catch(a){let A=a instanceof ub?a.context:void 0,r=a instanceof ub?a.error:a;if(o.cache.emit("error",r),o.cacheErrors&&A==="function")try{o.cache.set(i,r,o.ttl)}catch(s){o.cache.emit("error",s)}if(o.throwErrors===!0||o.throwErrors===A)throw r}return e}function P4e(n,t,o){let{keyPrefix:i,serialize:e}=o||{};return i?`${i}::${n.name}::${cU(t,{serialize:e})}`:`${n.name}::${cU(t,{serialize:e})}`}var ub=class{error;context;constructor(n,t){this.error=n,this.context=t}};var pI=class{_counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0};_vsize=0;_ksize=0;_enabled=!1;_lastUpdated;_lastReset;_subscriptions=[];_trackedKeys=new Map;_trackKeys=!1;_maxTrackedKeys;constructor(n){n?.enabled&&(this._enabled=n.enabled),n?.trackKeys&&(this._trackKeys=n.trackKeys),n?.maxTrackedKeys!==void 0&&(this._maxTrackedKeys=n.maxTrackedKeys),n?.emitter&&n?.eventMap&&this.subscribe(n.emitter,n.eventMap)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get trackKeys(){return this._trackKeys}set trackKeys(n){this._trackKeys=n}get maxTrackedKeys(){return this._maxTrackedKeys}set maxTrackedKeys(n){this._maxTrackedKeys=n}get trackedKeys(){return this._trackedKeys}get hits(){return this._counters.hits}get misses(){return this._counters.misses}get gets(){return this._counters.gets}get sets(){return this._counters.sets}get deletes(){return this._counters.deletes}get clears(){return this._counters.clears}get vsize(){return this._vsize}get ksize(){return this._ksize}get count(){return this._counters.count}get hitRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.hits/n}get missRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.misses/n}get lastUpdated(){return this._lastUpdated}get lastReset(){return this._lastReset}increment(n,t=1){this._enabled&&(this._counters[n]+=t,this.touch())}decrement(n,t=1){this._enabled&&(this._counters[n]-=t,this.touch())}incrementHits(n=1){this.increment("hits",n)}incrementMisses(n=1){this.increment("misses",n)}incrementGets(n=1){this.increment("gets",n)}incrementSets(n=1){this.increment("sets",n)}incrementDeletes(n=1){this.increment("deletes",n)}incrementClears(n=1){this.increment("clears",n)}incrementVSize(n){this._enabled&&(this._vsize+=this.roughSizeOfObject(n),this.touch())}decreaseVSize(n){this._enabled&&(this._vsize=Math.max(0,this._vsize-this.roughSizeOfObject(n)),this.touch())}incrementKSize(n){this._enabled&&(this._ksize+=this.roughSizeOfString(n),this.touch())}decreaseKSize(n){this._enabled&&(this._ksize=Math.max(0,this._ksize-this.roughSizeOfString(n)),this.touch())}incrementCount(n=1){this.increment("count",n)}decreaseCount(n=1){this._enabled&&(this._counters.count=Math.max(0,this._counters.count-n),this.touch())}setCount(n){this._enabled&&(this._counters.count=n,this.touch())}roughSizeOfString(n){return n.length*2}roughSizeOfObject(n){let t=[],o=[n],i=0;for(;o.length>0;){let e=o.pop();if(typeof e=="boolean")i+=4;else if(typeof e=="string")i+=e.length*2;else if(typeof e=="number")i+=8;else{if(e==null){i+=4;continue}if(t.includes(e))continue;t.push(e);for(let a in e)i+=a.length*2,o.push(e[a])}}return i}enable(){this._enabled=!0}disable(){this._enabled=!1}clear(){this.reset()}reset(){this._counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0},this._vsize=0,this._ksize=0,this._trackedKeys.clear(),this._lastReset=Date.now(),this._lastUpdated=void 0}resetStoreValues(){this._vsize=0,this._ksize=0,this._counters.count=0}toJSON(){return{enabled:this._enabled,hits:this._counters.hits,misses:this._counters.misses,gets:this._counters.gets,sets:this._counters.sets,deletes:this._counters.deletes,clears:this._counters.clears,vsize:this._vsize,ksize:this._ksize,count:this._counters.count,hitRate:this.hitRate,missRate:this.missRate,trackedKeys:this._trackedKeys.size,lastUpdated:this._lastUpdated,lastReset:this._lastReset}}snapshot(){return this.toJSON()}recordKey(n,t,o=1){if(!this._enabled||!this._trackKeys)return;let i=this._trackedKeys.get(n);i||(i={hits:0,misses:0,gets:0,sets:0,deletes:0},this._trackedKeys.set(n,i),this.pruneTrackedKeys(n)),i[t]+=o,this.touch()}mostUsedKeys(n=100,t){return this.sortedKeyEntries(t,"desc").slice(0,n)}leastUsedKeys(n=100,t){return this.sortedKeyEntries(t,"asc").slice(0,n)}keyStats(n){let t=this._trackedKeys.get(n);return t?this.toKeyEntry(n,t):void 0}clearKeys(){this._trackedKeys.clear()}totalOf(n){return n.hits+n.misses+n.gets+n.sets+n.deletes}toKeyEntry(n,t){let o=t.hits+t.misses;return{key:n,count:this.totalOf(t),hits:t.hits,misses:t.misses,gets:t.gets,sets:t.sets,deletes:t.deletes,hitRate:o===0?0:t.hits/o}}sortedKeyEntries(n,t){let o=[];for(let[e,a]of this._trackedKeys)o.push(this.toKeyEntry(e,a));let i=t==="asc"?1:-1;return o.sort((e,a)=>{let A=n?e[n]:e.count,r=n?a[n]:a.count;return A!==r?(A-r)*i:e.keythis.totalOf(i[1])-this.totalOf(e[1]));for(let[i]of o){if(this._trackedKeys.size<=t)break;i!==n&&this._trackedKeys.delete(i)}}subscribe(n,t){for(let[o,i]of Object.entries(t)){let e=(...a)=>{this.applyEvent(i,a)};n.on(o,e),this._subscriptions.push({emitter:n,event:o,listener:e})}}unsubscribe(n){let t=[];for(let o of this._subscriptions){if(n&&o.emitter!==n){t.push(o);continue}(o.emitter.off??o.emitter.removeListener)?.call(o.emitter,o.event,o.listener)}this._subscriptions=t}applyEvent(n,t){if(this._enabled){if(typeof n=="function"){n(this,...t);return}if(Array.isArray(n)){for(let o of n)this.increment(o);return}this.increment(n)}}touch(){this._lastUpdated=Date.now()}};var G4e=class{value;prev=void 0;next=void 0;constructor(n){this.value=n}},hU=class{head=void 0;tail=void 0;nodesMap=new Map;addToFront(n){let t=new G4e(n);this.head?(t.next=this.head,this.head.prev=t,this.head=t):this.head=this.tail=t,this.nodesMap.set(n,t)}moveToFront(n){let t=this.nodesMap.get(n);if(!t||this.head===t)return;t.prev&&(t.prev.next=t.next);t.next&&(t.next.prev=t.prev);t===this.tail&&(this.tail=t.prev),t.prev=void 0,t.next=this.head;this.head&&(this.head.prev=t),this.head=t,this.tail??=t}getOldest(){return this.tail?this.tail.value:void 0}removeOldest(){if(!this.tail)return;let n=this.tail.value;return this.tail.prev?(this.tail=this.tail.prev,this.tail.next=void 0):this.head=this.tail=void 0,this.nodesMap.delete(n),n}remove(n){let t=this.nodesMap.get(n);return t?(t.prev?t.prev.next=t.next:(this.head=t.next,this.head&&(this.head.prev=void 0)),t.next?t.next.prev=t.prev:(this.tail=t.prev,this.tail&&(this.tail.next=void 0)),this.nodesMap.delete(n),!0):!1}get size(){return this.nodesMap.size}};var lne=16777216,EU=class extends lI{_lru=new hU;_storeHashSize=16;_storeHashAlgorithm=Df.DJB2;_store=Array.from({length:this._storeHashSize},()=>new Map);_ttl;_maxTtl;_useClone=!0;_lruSize=0;_checkInterval=0;_interval=0;_stats=new pI({enabled:!1});constructor(n){super(),n?.ttl&&this.setTtl(n.ttl),n?.maxTtl!==void 0&&this.setMaxTtl(n.maxTtl),n?.useClone!==void 0&&(this._useClone=n.useClone),n?.stats&&(this._stats.enabled=n.stats),n?.storeHashSize&&n.storeHashSize>0&&(this._storeHashSize=n.storeHashSize),n?.lruSize&&(n.lruSize>16777216?this.emit("error",new Error(`LRU size cannot be larger than ${lne} due to Map limitations.`)):this._lruSize=n.lruSize),n?.checkInterval&&(this._checkInterval=n.checkInterval),n?.storeHashAlgorithm&&(this._storeHashAlgorithm=n.storeHashAlgorithm),this._store=Array.from({length:this._storeHashSize},()=>new Map),this.startIntervalCheck()}get ttl(){return this._ttl}set ttl(n){this.setTtl(n)}get maxTtl(){return this._maxTtl}set maxTtl(n){this.setMaxTtl(n)}get useClone(){return this._useClone}set useClone(n){this._useClone=n}get lruSize(){return this._lruSize}set lruSize(n){if(n>16777216){this.emit("error",new Error(`LRU size cannot be larger than ${lne} due to Map limitations.`));return}if(this._lruSize=n,this._lruSize===0){this._lru=new hU;return}this.lruResize()}get checkInterval(){return this._checkInterval}set checkInterval(n){this._checkInterval=n}get size(){let n=0;for(let t of this._store)n+=t.size;return n}get stats(){return this._stats}get storeHashSize(){return this._storeHashSize}set storeHashSize(n){n!==this._storeHashSize&&(this._storeHashSize=n,this._store=Array.from({length:this._storeHashSize},()=>new Map),this._stats.enabled&&this._stats.resetStoreValues())}get storeHashAlgorithm(){return this._storeHashAlgorithm}set storeHashAlgorithm(n){this._storeHashAlgorithm=n}get keys(){let n=[];for(let t of this._store)for(let o of t.keys()){let i=t.get(o);if(i&&this.hasExpired(i)){this.recordExpiration(i),t.delete(o),this.lruRemove(o);continue}n.push(o)}return n.values()}get items(){let n=[];for(let t of this._store)for(let o of t.values()){if(this.hasExpired(o)){this.recordExpiration(o),t.delete(o.key),this.lruRemove(o.key);continue}n.push(o)}return n.values()}get store(){return this._store}get(n){this.hookSync("BEFORE_GET",n);let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}this.lruMoveToFront(n);let i;return this._useClone?i=this.clone(o.value):i=o.value,this.recordRead(!0),this.hookSync("AFTER_GET",{key:n,result:i}),i}getMany(n){this.hookSync("BEFORE_GET_MANY",n);let t=[];for(let o of n)t.push(this.get(o));return this.hookSync("AFTER_GET_MANY",{keys:n,result:t}),t}getRaw(n){let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1);return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1);return}return this.lruMoveToFront(n),this.recordRead(!0),o}getManyRaw(n){let t=[];for(let o of n)t.push(this.getRaw(o));return t}set(n,t,o){let i={key:n,value:t,ttl:o};this.hookSync("BEFORE_SET",i);let e=this.getStore(i.key),a,A=i.ttl;if(A!==void 0||this._ttl!==void 0)if(typeof A=="object"){if(A.expire&&(a=typeof A.expire=="number"?A.expire:A.expire.getTime()),A.ttl){let s=$l(A.ttl);s!==void 0&&(a=s)}}else{let s=$l(A??this._ttl);s!==void 0&&(a=s)}if(this._maxTtl!==void 0){let s=$l(this._maxTtl);(a===void 0||a>s)&&(a=s)}if(this._lruSize>0){if(e.has(i.key))this.lruMoveToFront(i.key);else if(this.lruAddToFront(i.key),this._lru.size>this._lruSize){let s=this._lru.getOldest();s&&(this._lru.removeOldest(),this.delete(s))}}if(this._stats.enabled){let s=e.get(i.key);s?this._stats.decreaseVSize(s.value):(this._stats.incrementKSize(i.key),this._stats.incrementCount()),this._stats.incrementVSize(i.value),this._stats.incrementSets()}let r={key:i.key,value:i.value,expires:a};e.set(i.key,r),this.hookSync("AFTER_SET",i)}setMany(n){this.hookSync("BEFORE_SET_MANY",n);for(let t of n)this.set(t.key,t.value,t.ttl);this.hookSync("AFTER_SET_MANY",n)}has(n){return!!this.get(n)}hasMany(n){let t=[];for(let o of n){let i=this.get(o);t.push(!!i)}return t}take(n){let t=this.get(n);if(t)return this.delete(n),t}takeMany(n){let t=[];for(let o of n)t.push(this.take(o));return t}delete(n){this.hookSync("BEFORE_DELETE",n);let t=this.getStore(n);if(this._stats.enabled){let o=t.get(n);o&&(this._stats.decreaseKSize(n),this._stats.decreaseVSize(o.value),this._stats.decreaseCount(),this._stats.incrementDeletes())}t.delete(n),this.lruRemove(n),this.hookSync("AFTER_DELETE",n)}deleteMany(n){this.hookSync("BEFORE_DELETE_MANY",n);for(let t of n)this.delete(t);this.hookSync("AFTER_DELETE_MANY",n)}clear(){this.hookSync("BEFORE_CLEAR"),this._store=Array.from({length:this._storeHashSize},()=>new Map),this._lru=new hU,this._stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears()),this.hookSync("AFTER_CLEAR")}getStore(n){let t=this.getKeyStoreHash(n);return this._store[t]||=new Map,this._store[t]}getKeyStoreHash(n){return this._store.length===1?0:typeof this._storeHashAlgorithm=="function"?this._storeHashAlgorithm(n,this._storeHashSize):Ine(n,{min:0,max:this._storeHashSize-1,algorithm:this._storeHashAlgorithm})}clone(n){return this.isPrimitive(n)?n:structuredClone(n)}lruAddToFront(n){this._lruSize!==0&&this._lru.addToFront(n)}lruMoveToFront(n){this._lruSize!==0&&this._lru.moveToFront(n)}lruRemove(n){this._lruSize!==0&&this._lru.remove(n)}lruResize(){for(;this._lru.size>this._lruSize;){let n=this._lru.getOldest();n&&(this._lru.removeOldest(),this.delete(n))}}checkExpiration(){for(let n of this._store)for(let t of n.values())t.expires&&Date.now()>t.expires&&(this.recordExpiration(t),n.delete(t.key),this.lruRemove(t.key))}startIntervalCheck(){if(this._checkInterval>0){this._interval&&clearInterval(this._interval),this._interval=setInterval(()=>{this.checkExpiration()},this._checkInterval).unref()}}stopIntervalCheck(){this._interval&&clearInterval(this._interval),this._interval=0,this._checkInterval=0}wrap(n,t){return pU(n,{ttl:t?.ttl??this._ttl,keyPrefix:t?.keyPrefix,createKey:t?.createKey,cache:this})}getOrSet(n,t,o){return dU(n,t,{cache:this,ttl:o?.ttl??this._ttl,cacheErrors:o?.cacheErrors,throwErrors:o?.throwErrors})}recordRead(n){this._stats.enabled&&(n?this._stats.incrementHits():this._stats.incrementMisses(),this._stats.incrementGets())}recordExpiration(n){this._stats.enabled&&(this._stats.decreaseKSize(n.key),this._stats.decreaseVSize(n.value),this._stats.decreaseCount())}isPrimitive(n){return n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"}setTtl(n){typeof n=="string"||n===void 0?this._ttl=n:n>0?this._ttl=n:this._ttl=void 0}setMaxTtl(n){typeof n=="string"||n===void 0?this._maxTtl=n:n>0?this._maxTtl=n:this._maxTtl=void 0}hasExpired(n){return!!(n.expires&&Date.now()>n.expires)}};var Y4e=class extends lI{options={stdTTL:0,checkperiod:600,useClones:!0,deleteOnExpire:!0,maxKeys:-1};store=new Map;_stats=new pI({enabled:!0});_cacheable=new EU;intervalId=0;constructor(n){super(),n&&(this.options={...this.options,...n}),this.startInterval()}set(n,t,o=0){if(typeof n!="string"&&typeof n!="number")throw this.createError("The key argument has to be of type `string` or `number`. Found: `__key`",n);if(o&&typeof o!="number"&&typeof o!="string")throw this.createError("The ttl argument has to be a number or a string for shorthand ttl.",this.formatKey(n));let i=this.formatKey(n),e=0;this.options.stdTTL&&(e=this.getExpirationTimestamp(this.options.stdTTL)),o&&(e=this.getExpirationTimestamp(o));let a=0;if(e&&e>0&&(a=e),this.options.maxKeys){let{maxKeys:A}=this.options;if(A>-1&&this.store.size>=A)throw this.createError("Cache max keys amount exceeded",this.formatKey(n))}return this.store.set(i,{key:i,value:t,ttl:a}),this.emit("set",i,t,e),this._stats.incrementKSize(i),this._stats.incrementVSize(t),this._stats.setCount(this.store.size),!0}mset(n){if(!Array.isArray(n))throw this.createError("The keys argument has to be an array.");for(let t of n)this.set(t.key,t.value,t.ttl);return!0}get(n){let t=this.store.get(this.formatKey(n));if(t){if(t.ttl>0){if(t.ttl0){let n=this.options.checkperiod*1e3;this.intervalId=setInterval(()=>{this.checkData()},n).unref();return}this.intervalId=0}stopInterval(){this.intervalId!==0&&(clearInterval(this.intervalId),this.intervalId=0)}formatKey(n){return n.toString()}getExpirationTimestamp(n){if(typeof n=="string")return $l(n);let t=Date.now(),o=n*1e3;return t+o}checkData(){for(let[n,t]of this.store.entries())t.ttl>0&&t.ttl{let a={resolve:i,reject:e,weight:t,priority:o},A=dne(this._queue,r=>o<=r.priority);A===-1&&t<=this._value?this._dispatchItem(a):this._queue.splice(A+1,0,a)})}runExclusive(t){return J4e(this,arguments,void 0,function*(o,i=1,e=0){let[a,A]=yield this.acquire(i,e);try{return yield o(a)}finally{A()}})}waitForUnlock(t=1,o=0){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return this._couldLockImmediately(t,o)?Promise.resolve():new Promise(i=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),q4e(this._weightedWaiters[t-1],{resolve:i,priority:o})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatchQueue()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatchQueue()}cancel(){this._queue.forEach(t=>t.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(t){let o=this._value;this._value-=t.weight,t.resolve([o,this._newReleaser(t.weight)])}_newReleaser(t){let o=!1;return()=>{o||(o=!0,this.release(t))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let t=this._value;t>0;t--){let o=this._weightedWaiters[t-1];o&&(o.forEach(i=>i.resolve()),this._weightedWaiters[t-1]=[])}else{let t=this._queue[0].priority;for(let o=this._value;o>0;o--){let i=this._weightedWaiters[o-1];if(!i)continue;let e=i.findIndex(a=>a.priority<=t);(e===-1?i:i.splice(0,e)).forEach((a=>a.resolve()))}}}_couldLockImmediately(t,o){return(this._queue.length===0||this._queue[0].priorityt.priority<=i.priority);n.splice(o+1,0,t)}function dne(n,t){for(let o=n.length-1;o>=0;o--)if(t(n[o]))return o;return-1}var z4e=function(n,t,o,i){function e(a){return a instanceof o?a:new o(function(A){A(a)})}return new(o||(o=Promise))(function(a,A){function r(c){try{g(i.next(c))}catch(I){A(I)}}function s(c){try{g(i.throw(c))}catch(I){A(I)}}function g(c){c.done?a(c.value):e(c.value).then(r,s)}g((i=i.apply(n,t||[])).next())})},Jg=class{constructor(t){this._semaphore=new CU(1,t)}acquire(){return z4e(this,arguments,void 0,function*(t=0){let[,o]=yield this._semaphore.acquire(1,t);return o})}runExclusive(t,o=0){return this._semaphore.runExclusive(()=>t(),1,o)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(t=0){return this._semaphore.waitForUnlock(1,t)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};import{randomBytes as $4e}from"crypto";var BU=Je(Ene(),1);var fU=class n extends Error{name="TimeoutError";constructor(t,o){super(t,o),Error.captureStackTrace?.(this,n)}},Cne=n=>n.reason??new DOMException("This operation was aborted.","AbortError");function QU(n,t){let{milliseconds:o,fallback:i,message:e,customTimers:a={setTimeout,clearTimeout},signal:A}=t,r,s,c=new Promise((I,d)=>{if(typeof o!="number"||Math.sign(o)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);if(A?.aborted){d(Cne(A));return}if(A&&(s=()=>{d(Cne(A))},A.addEventListener("abort",s,{once:!0})),n.then(I,d),o===Number.POSITIVE_INFINITY)return;let B=new fU;r=a.setTimeout.call(void 0,()=>{if(i){try{I(i())}catch(f){d(f)}return}typeof n.cancel=="function"&&n.cancel(),e===!1?I():e instanceof Error?d(e):(B.message=e??`Promise timed out after ${o} milliseconds`,d(B))},o)}).finally(()=>{c.clear(),s&&A&&A.removeEventListener("abort",s)});return c.clear=()=>{a.clearTimeout.call(void 0,r),r=void 0},c}function yU(n,t,o){let i=0,e=n.length;for(;e>0;){let a=Math.trunc(e/2),A=i+a;o(n[A],t)<=0?(i=++A,e-=a+1):e=a}return i}var Z4e=100,tE=class{#e=[];#A=0;enqueue(t,o){let{priority:i=0,id:e}=o??{},{size:a}=this,A={priority:i,id:e,run:t};if(a===0){this.#e.length=0,this.#A=0,this.#e.push(A);return}if(this.#e.at(-1).priority>=i){this.#e.push(A);return}this.#t();let r=yU(this.#e,A,(s,g)=>g.priority-s.priority);this.#e.splice(r,0,A)}setPriority(t,o){let i=this.#e.findIndex((a,A)=>A>=this.#A&&a.id===t);if(i===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[e]=this.#e.splice(i,1);this.enqueue(e.run,{priority:o,id:t})}remove(t){let o=this.#e.findIndex((i,e)=>eZ4e&&this.#A>this.#e.length/2&&this.#t(),t?.run}filter(t){let o=[];for(let i=this.#A;i=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);if(t.strict&&t.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(t.strict&&t.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=t.carryoverIntervalCount??t.carryoverConcurrencyCount??!1,this.#A=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#r=t.intervalCap,this.#n=t.interval,this.#o=t.strict,this.#p=new t.queueClass,this.#d=t.queueClass,this.concurrency=t.concurrency,t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);this.timeout=t.timeout,this.#C=t.autoStart===!1,this.#Y()}#S(t){for(;this.#c=this.#n)this.#c++;else break}(this.#c>100&&this.#c>this.#s.length/2||this.#c===this.#s.length)&&(this.#s=this.#s.slice(this.#c),this.#c=0)}#Q(t){this.#o?this.#s.push(t):this.#t++}#m(){this.#o?this.#s.length>this.#c&&this.#s.pop():this.#t>0&&this.#t--}#u(){return this.#s.length-this.#c}get#b(){return this.#A?!0:this.#o?this.#u()=this.#r){let i=this.#s[this.#c],e=this.#n-(t-i);return this.#k(e),!0}return!1}if(this.#I===void 0){let o=this.#i-t;if(o<0)this.#t=this.#e?this.#h:0;else return this.#k(o),!0}return!1}#k(t){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#w()},t))}#M(){this.#I&&(clearInterval(this.#I),this.#I=void 0)}#L(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#_(){if(this.#p.size===0){if(this.#M(),this.emit("empty"),this.#h===0){if(this.#L(),this.#o&&this.#c>0){let o=Date.now();this.#S(o)}this.emit("idle")}return!1}let t=!1;if(!this.#C){let o=Date.now(),i=!this.#T(o);if(this.#b&&this.#R){let e=this.#p.dequeue();this.#A||(this.#Q(o),this.#H()),i&&this.#U(),this.emit("active"),e(),t=!0}}return t}#U(){this.#A||this.#I!==void 0||this.#o||(this.#I=setInterval(()=>{this.#v()},this.#n),this.#i=Date.now()+this.#n)}#v(){this.#o||(this.#I!==void 0&&(this.#t===0&&this.#h===0?this.#M():this.#i=Date.now()+this.#n),this.#t=this.#e?this.#h:0),this.#P(),this.#H()}#P(){for(;this.#_(););}get concurrency(){return this.#E}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#E=t,this.#P()}setPriority(t,o){if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${o}\` (${typeof o})`);this.#p.setPriority(t,o)}async add(t,o={}){if(o={timeout:this.timeout,...o,id:o.id??(this.#f++).toString()},o.timeout!==void 0&&!(Number.isFinite(o.timeout)&&o.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${o.timeout}\` (${typeof o.timeout})`);return new Promise((i,e)=>{let a=Symbol(`task-${o.id}`),A=()=>{},r=async()=>{A(),this.#h++,this.#B.set(a,{id:o.id,priority:o.priority??0,startTime:Date.now(),timeout:o.timeout});let g;try{try{o.signal?.throwIfAborted()}catch(d){throw this.#q(),this.#B.delete(a),d}let c=t({signal:o.signal});if(o.timeout!==void 0&&(c=QU(Promise.resolve(c),{milliseconds:o.timeout,message:`Task timed out after ${o.timeout}ms (queue has ${this.#h} running, ${this.#p.size} waiting)`})),o.signal){let{signal:d}=o;c=Promise.race([c,new Promise((B,f)=>{g=()=>{f(d.reason)},d.addEventListener("abort",g,{once:!0})})])}let I=await c;i(I),this.emit("completed",I)}catch(c){e(c),this.emit("error",c)}finally{g&&o.signal?.removeEventListener("abort",g),this.#B.delete(a),queueMicrotask(()=>{this.#D()})}};this.#p.enqueue(r,o);let s=()=>{if(this.#p instanceof tE){this.#p.remove(r);return}this.#p.remove?.(o.id)};if(o.signal){let{signal:g}=o,c=()=>{A(),s(),e(g.reason),this.#_(),this.emit("next")};if(A=()=>{g.removeEventListener("abort",c),this.#y.delete(A)},g.aborted){c();return}g.addEventListener("abort",c,{once:!0}),this.#y.add(A)}this.emit("add"),this.#_()})}async addAll(t,o){return Promise.all(t.map(async i=>this.add(i,o)))}start(){return this.#C?(this.#C=!1,this.#P(),this):this}pause(){this.#C=!0}clear(){for(let t of this.#y)t();this.#p=new this.#d,this.#M(),this.#z(),this.emit("empty"),this.#h===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#p.size!==0&&await this.#N("empty")}async onSizeLessThan(t){this.#p.sizethis.#p.size{let i=e=>{this.off("error",i),o(e)};this.on("error",i)})}async#N(t,o){let i=Array.isArray(t)?t:[t];return new Promise(e=>{let a=()=>{if(!(o&&!o())){for(let A of i)this.off(A,a);e()}};for(let A of i)this.on(A,a)})}get size(){return this.#p.size}sizeBy(t){return this.#p.filter(t).length}get pending(){return this.#h}get isPaused(){return this.#C}#Y(){this.#A||(this.on("add",()=>{this.#p.size>0&&this.#H()}),this.on("next",()=>{this.#H()}))}#H(){this.#A||this.#a||(this.#a=!0,queueMicrotask(()=>{this.#a=!1,this.#z()}))}#q(){this.#A||(this.#m(),this.#H())}#z(){let t=this.#g;if(this.#A||this.#p.size===0){t&&(this.#g=!1,this.emit("rateLimitCleared"));return}let o;if(this.#o){let e=Date.now();this.#S(e),o=this.#u()}else o=this.#t;let i=o>=this.#r;i!==t&&(this.#g=i,this.emit(i?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#g}get isSaturated(){return this.#h===this.#E&&this.#p.size>0||this.isRateLimited&&this.#p.size>0}get runningTasks(){return[...this.#B.values()].map(t=>({...t,timeoutRemaining:t.timeout?Math.max(0,t.startTime+t.timeout-Date.now()):void 0}))}};var fb=class{constructor(t,o){this.store=t,this.logger=o,this.queues=new Map}getQueue(t){return this.queues.has(t)||this.queues.set(t,new ep({concurrency:1})),this.queues.get(t)}async processOperations(t,o,i,e,a){let A=t[o];if(A)return this.getQueue(o).add(async()=>{i[o]=i[o]||{},e[o]=e[o]||{};let r=[],s={};for(let g in A)A[g]===null?r.push(g):s[g]=A[g];Object.keys(s).length>0&&(Object.assign(i[o],s),Object.assign(e[o],s)),r.length>0&&await this.processDeletions(o,r,i,e,a)})}async processDeletions(t,o,i,e,a){if(a)for(let A of o)i[t]?.[A]?(i[t][A]=null,e[t][A]=null):this.logger.warn(`Skipping deletion of non-existent ${t} in transaction: ${A}`);else{let A=await this.store.get(t,o);for(let r of o)A[r]?(i[t][r]=null,e[t][r]=null):this.logger.warn(`Skipping deletion of non-existent ${t}: ${r}`)}}async validateDeletions(t,o){let i=t[o];if(i)return this.getQueue(o).add(async()=>{let e=Object.keys(i).filter(A=>i[A]===null);if(e.length===0)return;let a=await this.store.get(o,e);for(let A of e)a[A]||(this.logger.warn(`Skipping deletion of non-existent ${o}: ${A}`),delete t[o][A])})}};var Bne=(n,t,{maxCommitRetries:o,delayBetweenTriesMs:i})=>{let e=new X4e,a=new Map,A=new Map,r=new Map,s=new fb(n,t);function g(Q){return a.has(Q)||a.set(Q,new ep({concurrency:1})),a.get(Q)}function c(Q){return A.has(Q)||(A.set(Q,new Jg),r.set(Q,0)),A.get(Q)}function I(Q){let y=r.get(Q)??0;r.set(Q,y+1)}function d(Q){let y=(r.get(Q)??1)-1;if(r.set(Q,y),y<=0){let m=A.get(Q);m&&!m.isLocked()&&(A.delete(Q),r.delete(Q))}}function B(){return!!e.getStore()}async function f(Q){if(Object.keys(Q).length===0){t.trace("no mutations in transaction");return}t.trace("committing transaction");for(let y=0;y{let m=e.getStore();if(!m)return n.get(Q,y);let _=m.cache[Q]||{},T=y.filter(F=>!(F in _));if(T.length>0){m.dbQueries++,t.trace({type:Q,count:T.length},"fetching missing keys in transaction");let F=await c(Q).runExclusive(()=>n.get(Q,T));m.cache[Q]=m.cache[Q]||{},Object.assign(m.cache[Q],F)}let R={};for(let F of y){let K=m.cache[Q]?.[F];K!=null&&(R[F]=K)}return R},set:async Q=>{let y=e.getStore();if(!y){let m=Object.keys(Q);for(let _ of m){let T=_;T==="pre-key"&&await s.validateDeletions(Q,T)}await Promise.all(m.map(_=>g(_).add(async()=>{let T={[_]:Q[_]};await n.set(T)})));return}t.trace({types:Object.keys(Q)},"caching in transaction");for(let m in Q){let _=m;y.cache[_]=y.cache[_]||{},y.mutations[_]=y.mutations[_]||{},_==="pre-key"?await s.processOperations(Q,_,y.cache,y.mutations,!0):(Object.assign(y.cache[_],Q[_]),Object.assign(y.mutations[_],Q[_]))}},isInTransaction:B,transaction:async(Q,y)=>{if(e.getStore())return t.trace("reusing existing transaction context"),Q();let _=c(y);I(y);try{return await _.runExclusive(async()=>{let T={cache:{},mutations:{},dbQueries:0};t.trace("entering transaction");try{let R=await e.run(T,Q);return await f(T.mutations),t.trace({dbQueries:T.dbQueries},"transaction completed"),R}catch(R){throw t.error({error:R},"transaction failed, rolling back"),R}})}finally{d(y)}}}},fne=n=>{let t=n.me?.id;if(!t)throw new une.Boom("Cannot proceed: socket is not authenticated yet (creds.me.id is missing)",{statusCode:401});return t},Qne=()=>{let n=Br.generateKeyPair();return{noiseKey:Br.generateKeyPair(),pairingEphemeralKeyPair:Br.generateKeyPair(),signedIdentityKey:n,signedPreKey:aD(n,1),registrationId:Q7(),advSecretKey:$4e(32).toString("base64"),processedHistoryMessages:[],nextPreKeyId:1,firstUnuploadedPreKeyId:1,accountSyncCounter:0,accountSettings:{unarchiveChats:!1},registered:!1,pairingCode:void 0,lastPropHash:void 0,routingInfo:void 0,additionalData:void 0}};import{mkdir as e8e,readFile as A8e,stat as t8e,unlink as r8e,writeFile as a8e}from"fs/promises";import{join as mU}from"path";var yne=new Map,SU=n=>{let t=yne.get(n);return t||(t=new Jg,yne.set(n,t)),t},mne=async n=>{let t=async(r,s)=>{let g=mU(n,a(s));return SU(g).acquire().then(async I=>{try{await a8e(g,JSON.stringify(r,wB.replacer))}finally{I()}})},o=async r=>{try{let s=mU(n,a(r));return await SU(s).acquire().then(async c=>{try{let I=await A8e(s,{encoding:"utf-8"});return JSON.parse(I,wB.reviver)}finally{c()}})}catch{return null}},i=async r=>{try{let s=mU(n,a(r));return SU(s).acquire().then(async c=>{try{await r8e(s)}catch{}finally{c()}})}catch{}},e=await t8e(n).catch(()=>{});if(e){if(!e.isDirectory())throw new Error(`found something that is not a directory at ${n}, either delete it or specify a different location`)}else await e8e(n,{recursive:!0});let a=r=>r?.replace(/\//g,"__")?.replace(/:/g,"-"),A=await o("creds.json")||Qne();return{state:{creds:A,keys:{get:async(r,s)=>{let g={};return await Promise.all(s.map(async c=>{let I=await o(`${r}-${c}.json`);r==="app-state-sync-key"&&I&&(I=oe.Message.AppStateSyncKeyData.fromObject(I)),g[c]=I})),g},set:async r=>{let s=[];for(let g in r)for(let c in r[g]){let I=r[g][c],d=`${g}-${c}.json`;s.push(I?t(I,d):i(d))}await Promise.all(s)}}},saveCreds:async()=>t(A,"creds.json")}};var i8e=192,o8e=async(n,{thumbnailWidth:t,fetchOpts:o})=>{let i=await Ib(n,o);return await x2(i,t)},Sne=async(n,t={thumbnailWidth:i8e,fetchOpts:{timeout:3e3}})=>{try{let o=0,i=5,{getLinkPreview:e}=await import("link-preview-js"),a=n;!n.startsWith("https://")&&!n.startsWith("http://")&&(a="https://"+a);let A=await e(a,{...t.fetchOpts,followRedirects:"follow",handleRedirects:(r,s)=>{let g=new URL(r),c=new URL(s);return o>=i?!1:c.hostname===g.hostname||c.hostname==="www."+g.hostname||"www."+c.hostname===g.hostname?(o+=1,!0):!1},headers:t.fetchOpts?.headers});if(A&&"title"in A&&A.title){let[r]=A.images,s={"canonical-url":A.url,"matched-text":n,title:A.title,description:A.description,originalThumbnailUrl:r};if(t.uploadImage){let{imageMessage:g}=await Bf({image:{url:r}},{upload:t.uploadImage,mediaTypeOverride:"thumbnail-link",options:t.fetchOpts});s.jpegThumbnail=g?.jpegThumbnail?Buffer.from(g.jpegThumbnail):void 0,s.highQualityThumbnail=g||void 0}else try{s.jpegThumbnail=r?(await o8e(r,t)).buffer:void 0}catch(g){t.logger?.debug({err:g.stack,url:a},"error in generating thumbnail")}return s}}catch(o){if(!o.message.includes("receive a valid"))throw o}};import E8e from"events";var DU=Je(Lr(),1);var n8e=/^1313555\d{4}$|^131655500\d{2}$/;function s8e(n){if(!n)return!1;let t=n.split("@")[0]??"";return t==="0"||n8e.test(t)||rh(n)?!1:!!(_t(n)||qA(n)||ur(n)||ga(n)||n.endsWith("@c.us"))}var Qb=604800,g8e=4,hI="__index";async function yb(n){let o=(await n.get("tctoken",[hI]))[hI];if(!o?.token?.length)return[];try{let i=JSON.parse(Buffer.from(o.token).toString());return Array.isArray(i)?i.filter(e=>typeof e=="string"&&e.length>0&&e!==hI):[]}catch{return[]}}async function rE(n,t){let o=await yb(n),i=new Set(o);for(let e of t)e&&e!==hI&&i.add(e);return{[hI]:{token:Buffer.from(JSON.stringify([...i]))}}}function Ap(n){if(n==null)return!0;let t=typeof n=="string"?parseInt(n):n;if(isNaN(t))return!0;let o=Math.floor(Date.now()/1e3),a=(Math.floor(o/Qb)-(g8e-1))*Qb;return ti}async function js(n,t){return qA(n)?n:await t(n)??n}async function bf(n,t,o,i){return t?qA(n)?n:await o(n)??n:qA(n)&&i?await i(n)??n:n}async function wU({authState:n,jid:t,baseContent:o=[],getLIDForPN:i}){try{let e=await js(t,i),A=(await n.keys.get("tctoken",[e]))?.[e],r=A?.token,s=A?.timestamp;if(!r?.length||s===void 0||Ap(s)){if(r){let g=A?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:A.senderTimestamp}:null;await n.keys.set({tctoken:{[e]:g}})}return o.length>0?o:void 0}return o.push({tag:"tctoken",attrs:{t:String(s)},content:r}),o}catch{return o.length>0?o:void 0}}async function aE({result:n,fallbackJid:t,keys:o,getLIDForPN:i,onNewJidStored:e}){let a=le(n,"tokens");if(!a)return;let A=kA(a,"token");for(let r of A){if(r.attrs.type!=="trusted_contact"||!(r.content instanceof Uint8Array))continue;let s=uA(t||r.attrs.jid);if(!s8e(s))continue;let g=await js(s,i),I=(await o.get("tctoken",[g]))[g],d=I?.timestamp?Number(I.timestamp):0,B=r.attrs.t?Number(r.attrs.t):0;B&&(d>0&&d>B||(await o.set({tctoken:{[g]:{...I,token:Buffer.from(r.content),timestamp:r.attrs.t}}}),e?.(g)))}}var c8e=new Set([TA.CALL_MISSED_GROUP_VIDEO,TA.CALL_MISSED_GROUP_VOICE,TA.CALL_MISSED_VIDEO,TA.CALL_MISSED_VOICE]),I8e=new Set([TA.GROUP_PARTICIPANT_ADD]);async function l8e(n,t,o,i){let e=t.lidMapping.getLIDForPN.bind(t.lidMapping),a=[];for(let g of n){let c=g.tcTokenTimestamp?Hr(g.tcTokenTimestamp):0;if(g.tcToken?.length&&c>0){let I=uA(g.id),d=await js(I,e);a.push({storageJid:d,token:Buffer.from(g.tcToken),ts:c,senderTs:g.tcTokenSenderTimestamp?Hr(g.tcTokenSenderTimestamp):void 0})}}if(!a.length)return;let A=a.map(g=>g.storageJid),r=await o.get("tctoken",A),s={};for(let g of a){let c=r[g.storageJid],I=c?.timestamp?Number(c.timestamp):0;I>0&&I>=g.ts||(s[g.storageJid]={...c,token:g.token,timestamp:String(g.ts),...g.senderTs!==void 0?{senderTimestamp:g.senderTs}:{}})}if(Object.keys(s).length){i?.debug({count:Object.keys(s).length},"storing tctokens from history sync");try{let g=await rE(o,Object.keys(s));await o.set({tctoken:{...s,...g}})}catch(g){i?.warn({err:g},"failed to store tctokens from history sync")}}}var Dne=(n,t,o)=>{ur(n.key.remoteJid)||ga(n.key.remoteJid)?n.key.remoteJid=Cr(yA(n.key?.remoteJid)?.user,ur(n.key.remoteJid)?"s.whatsapp.net":"lid"):n.key.remoteJid=uA(n.key.remoteJid),ur(n.key.participant)||ga(n.key.participant)?n.key.participant=Cr(yA(n.key.participant)?.user,ur(n.key.participant)?"s.whatsapp.net":"lid"):n.key.participant=uA(n.key.participant);let i=Oa(n.message);i?.reactionMessage&&e(i.reactionMessage.key),i?.pollUpdateMessage&&e(i.pollUpdateMessage.pollCreationMessageKey);function e(a){n.key.fromMe||(a.fromMe=a.fromMe?!1:Tt(a.participant||a.remoteJid,t)||Tt(a.participant||a.remoteJid,o),a.remoteJid=n.key.remoteJid,a.participant=a.participant||n.key.participant)}},OU=n=>{let t=Oa(n.message),o=!!ff(t);return(!!t||c8e.has(n.messageStubType)||I8e.has(n.messageStubType))&&o&&!t?.protocolMessage&&!t?.reactionMessage&&!t?.pollUpdateMessage},bU=n=>!n.key.fromMe&&!n.messageStubType,p8e=({remoteJid:n,participant:t,fromMe:o})=>{if(!n)throw new DU.Boom("Cannot derive chat id: message key is missing remoteJid",{data:{remoteJid:n,participant:t,fromMe:o}});if(EB(n)&&!Tg(n)&&!o){if(!t)throw new DU.Boom("Cannot derive chat id: broadcast message key is missing participant",{data:{remoteJid:n,fromMe:o}});return t}return n};function d8e({encPayload:n,encIv:t},{eventCreatorJid:o,eventMsgId:i,eventEncKey:e,responderJid:a}){let A=Buffer.concat([I(i),I(o),I(a),I("Event Response"),new Uint8Array([1])]),r=kn(e,new Uint8Array(32),"sha256"),s=kn(A,r,"sha256"),g=I(`${i}\0${a}`),c=Ol(n,s,t,g);return oe.Message.EventResponseMessage.decode(c);function I(d){return Buffer.from(d)}}var h8e=async(n,{shouldProcessHistoryMsg:t,placeholderResendCache:o,ev:i,creds:e,signalRepository:a,keyStore:A,logger:r,options:s,getMessage:g})=>{let c=e.me.id,{accountSettings:I}=e,d={id:uA(p8e(n.key))},B=OU(n);B&&(d.messages=[{message:n}],d.conversationTimestamp=Hr(n.messageTimestamp),bU(n)&&(d.unreadCount=(d.unreadCount||0)+1));let f=Oa(n.message);(B||f?.reactionMessage?.key?.fromMe)&&I?.unarchiveChats&&(d.archived=!1,d.readOnly=!1);let Q=f?.protocolMessage;if(Q){let y=new Set([oe.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,oe.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,oe.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE]);if(Q.type!==null&&Q.type!==void 0&&y.has(Q.type)&&!n.key.fromMe){r?.warn({msgId:n.key.id,type:Q.type,from:n.key.participant||n.key.remoteJid},"dropping spoofed self-only protocolMessage from non-self origin");return}switch(Q.type){case oe.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:let m=Q.historySyncNotification,_=t,T=!e.processedHistoryMessages?.length;if(r?.info({histNotification:m,process:_,id:n.key.id,isLatest:T},"got history notification"),_){m.syncType!==oe.HistorySync.HistorySyncType.ON_DEMAND&&i.emit("creds.update",{processedHistoryMessages:[...e.processedHistoryMessages||[],{key:n.key,messageTimestamp:n.messageTimestamp}]});let P=await Voe(m,s,r);P.lidPnMappings?.length&&(r?.debug({count:P.lidPnMappings.length},"processing LID-PN mappings from history sync"),await a.lidMapping.storeLIDPNMappings(P.lidPnMappings).catch(J=>r?.warn({err:J},"failed to store LID-PN mappings from history sync"))),await l8e(P.chats,a,A,r),i.emit("messaging-history.set",{...P,isLatest:m.syncType!==oe.HistorySync.HistorySyncType.ON_DEMAND?T:void 0,chunkOrder:m.chunkOrder,peerDataRequestSessionId:m.peerDataRequestSessionId})}break;case oe.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:let R=Q.appStateSyncKeyShare.keys;if(R?.length){let P="";await A.transaction(async()=>{let J=[];for(let{keyData:U,keyId:N}of R){let k=Buffer.from(N.keyId).toString("base64");J.push(k),await A.set({"app-state-sync-key":{[k]:U}}),P=k}r?.info({newAppStateSyncKeyId:P,newKeys:J},"injecting new app state sync keys")},c),i.emit("creds.update",{myAppStateKeyId:P})}else r?.info({protocolMsg:Q},"recv app state sync with 0 keys");break;case oe.Message.ProtocolMessage.Type.REVOKE:i.emit("messages.update",[{key:{...n.key,id:Q.key.id},update:{message:null,messageStubType:TA.REVOKE,key:n.key}}]);break;case oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:Object.assign(d,{ephemeralSettingTimestamp:Hr(n.messageTimestamp),ephemeralExpiration:Q.ephemeralExpiration||null});break;case oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:let F=Q.peerDataOperationRequestResponseMessage;if(F){let P=F.peerDataOperationResult||[];for(let J of P){let U=J?.placeholderMessageResendResponse;if(U?.webMessageInfoBytes)try{let N=oe.WebMessageInfo.decode(U.webMessageInfoBytes),k=N.key?.id,V=k?await o?.get(k):void 0;k&&await o?.del(k);let Ae;V&&typeof V=="object"?(V.message=N.message,N.messageTimestamp&&(V.messageTimestamp=N.messageTimestamp),Ae=V):Ae=N,r?.debug({msgId:k,requestId:F.stanzaId},"received placeholder resend"),i.emit("messages.upsert",{messages:[Ae],type:"notify",requestId:F.stanzaId})}catch(N){r?.warn({err:N,stanzaId:F.stanzaId},"failed to decode placeholder resend response")}}}break;case oe.Message.ProtocolMessage.Type.MESSAGE_EDIT:i.emit("messages.update",[{key:{...n.key,id:Q.key?.id},update:{message:{editedMessage:{message:Q.editedMessage}},messageTimestamp:Q.timestampMs?Math.floor(Hr(Q.timestampMs)/1e3):n.messageTimestamp}}]);break;case oe.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:let K=Q.memberLabel;K?.label&&i.emit("group.member-tag.update",{groupId:d.id,label:K.label,participant:n.key.participant,participantAlt:n.key.participantAlt,messageTimestamp:Number(n.messageTimestamp)});break;case oe.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:let L=Q.lidMigrationMappingSyncMessage?.encodedMappingPayload,{pnToLidMappings:q,chatDbMigrationTimestamp:z}=oe.LIDMigrationMappingSyncPayload.decode(L);r?.debug({pnToLidMappings:q,chatDbMigrationTimestamp:z},"got lid mappings and chat db migration timestamp");let j=[];for(let{pn:P,latestLid:J,assignedLid:U}of q){let N=J||U;j.push({lid:`${N}@lid`,pn:`${P}@s.whatsapp.net`})}if(await a.lidMapping.storeLIDPNMappings(j),j.length)for(let{pn:P,lid:J}of j)await a.migrateSession(P,J)}}else if(f?.reactionMessage){let y={...f.reactionMessage,key:n.key};i.emit("messages.reaction",[{reaction:y,key:f.reactionMessage?.key}])}else if(f?.encEventResponseMessage){let y=f.encEventResponseMessage,m=y.eventCreationMessageKey,_=await g(m);if(_)try{let T=uA(c),R=m.participant||m.remoteJid,F=qA(R)?await a.lidMapping.getPNForLID(R):R,K=gh({remoteJid:uA(F),fromMe:T===F},T),L=gh(n.key,T),q=_?.messageContextInfo?.messageSecret;if(!q)r?.warn({creationMsgKey:m},"event response: missing messageSecret for decryption");else{let z=d8e(y,{eventEncKey:q,eventCreatorJid:K,eventMsgId:m.id,responderJid:L}),j={eventResponseMessageKey:n.key,senderTimestampMs:z.timestampMs,response:z};i.emit("messages.update",[{key:m,update:{eventResponses:[j]}}])}}catch(T){r?.warn({err:T,creationMsgKey:m},"failed to decrypt event response")}else r?.warn({creationMsgKey:m},"event creation message not found, cannot decrypt response")}else if(n.messageStubType){let y=n.key?.remoteJid,m,_=K=>i.emit("group-participants.update",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participants:m,action:K}),T=K=>{i.emit("groups.update",[{id:y,...K,author:n.key.participant??void 0,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername}])},R=(K,L,q)=>{i.emit("group.join-request",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participant:K.lid,participantPn:K.pn,action:L,method:q})},F=()=>m.find(K=>Tt(c,K.phoneNumber));switch(n.messageStubType){case TA.GROUP_PARTICIPANT_CHANGE_NUMBER:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("modify");break;case TA.GROUP_PARTICIPANT_LEAVE:case TA.GROUP_PARTICIPANT_REMOVE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("remove"),F()&&(d.readOnly=!0);break;case TA.GROUP_PARTICIPANT_ADD:case TA.GROUP_PARTICIPANT_INVITE:case TA.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],F()&&(d.readOnly=!1),_("add");break;case TA.GROUP_PARTICIPANT_DEMOTE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("demote");break;case TA.GROUP_PARTICIPANT_PROMOTE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("promote");break;case TA.GROUP_CHANGE_ANNOUNCE:let K=n.messageStubParameters?.[0];T({announce:K==="true"||K==="on"});break;case TA.GROUP_CHANGE_RESTRICT:let L=n.messageStubParameters?.[0];T({restrict:L==="true"||L==="on"});break;case TA.GROUP_CHANGE_SUBJECT:let q=n.messageStubParameters?.[0];d.name=q,T({subject:q});break;case TA.GROUP_CHANGE_DESCRIPTION:let z=n.messageStubParameters?.[0];d.description=z,T({desc:z});break;case TA.GROUP_CHANGE_INVITE_LINK:let j=n.messageStubParameters?.[0];T({inviteCode:j});break;case TA.GROUP_MEMBER_ADD_MODE:let P=n.messageStubParameters?.[0];T({memberAddMode:P==="all_member_add"});break;case TA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:let J=n.messageStubParameters?.[0];T({joinApprovalMode:J==="on"});break;case TA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:let U=JSON.parse(n.messageStubParameters?.[0]),N=n.messageStubParameters?.[1],k=n.messageStubParameters?.[2];R(U,N,k);break}}Object.keys(d).length>1&&i.emit("chats.update",[d])},One=h8e;var C8e=["messaging-history.set","chats.upsert","chats.update","chats.delete","contacts.upsert","contacts.update","messages.upsert","messages.update","messages.delete","messages.reaction","message-receipt.update","groups.update"],u8e=new Set(C8e),bne=n=>{let t=new E8e,o=new Set,i=MU(),e=!1,a=null,A=null,r=0,s=1e4,g=3e4;t.on("event",d=>{for(let B in d)t.emit(B,d[B])});function c(){e||(n.debug("Event buffer activated"),e=!0,r=0,a&&clearTimeout(a),a=setTimeout(()=>{e&&(n.warn("Buffer timeout reached, auto-flushing"),I())},g)),r++}function I(){if(!e)return!1;n.debug({bufferCount:r},"Flushing event buffer"),e=!1,r=0,a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.size>s&&(n.debug({cacheSize:o.size},"Clearing history cache"),o.clear());let d=MU(),B=Object.values(i.chatUpdates),f=0;for(let y of B)y.conditional&&(f+=1,d.chatUpdates[y.id]=y,delete i.chatUpdates[y.id]);let Q=f8e(i);return Object.keys(Q).length&&t.emit("event",Q),i=d,n.trace({conditionalChatUpdatesLeft:f},"released buffered events"),!0}return{process(d){let B=async f=>{await d(f)};return t.on("event",B),()=>{t.off("event",B)}},emit(d,B){if(d==="messages.upsert"){let{type:f}=B,Q=Object.values(i.messageUpserts);if(Q.length>0){let y=Q[0].type;y!==f&&(n.debug({bufferedType:y,newType:f},"messages.upsert type mismatch, emitting buffered messages"),t.emit("event",{"messages.upsert":{messages:Q.map(m=>m.message),type:y}}),i.messageUpserts={})}}return e&&u8e.has(d)?(B8e(i,o,d,B,n),!0):t.emit("event",{[d]:B})},isBuffering(){return e},buffer:c,flush:I,createBufferedFunction(d){return async(...B)=>{c();try{let f=await d(...B);return r===1&&setTimeout(()=>{e&&r===1&&I()},100),f}catch(f){throw f}finally{r=Math.max(0,r-1),r===0&&(A||(A=setTimeout(I,100)))}}},on:(...d)=>t.on(...d),off:(...d)=>t.off(...d),removeAllListeners:(...d)=>t.removeAllListeners(...d),destroy(){a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.clear(),i=MU(),e=!1,r=0,t.removeAllListeners(),n.debug("Event buffer destroyed")}}},MU=()=>({historySets:{chats:{},messages:{},contacts:{},isLatest:!1,empty:!0},chatUpserts:{},chatUpdates:{},chatDeletes:new Set,contactUpserts:{},contactUpdates:{},messageUpserts:{},messageUpdates:{},messageReactions:{},messageDeletes:{},messageReceipts:{},groupUpdates:{}});function B8e(n,t,o,i,e){switch(o){case"messaging-history.set":for(let Q of i.chats){let y=Q.id||"",m=n.historySets.chats[y];m&&(m.endOfHistoryTransferType=Q.endOfHistoryTransferType),!m&&!t.has(y)&&(n.historySets.chats[y]=Q,t.add(y),a(Q))}for(let Q of i.contacts){let y=n.historySets.contacts[Q.id];if(y)Object.assign(y,nD(Q));else{let m=`c:${Q.id}`,_=Q.notify||Q.name||Q.verifiedName;(!t.has(m)||_)&&(n.historySets.contacts[Q.id]=Q,t.add(m))}}for(let Q of i.messages){let y=iE(Q.key);!n.historySets.messages[y]&&!t.has(y)&&(n.historySets.messages[y]=Q,t.add(y))}if(n.historySets.empty=!1,n.historySets.syncType=i.syncType,i.pastParticipants?.length){let Q=new Map,y=_=>`${_.userJid||""}:${_.leaveTs||""}:${_.leaveReason||""}`,m=_=>{let T=_.groupJid??JSON.stringify(_),R=Q.get(T);if(!R){Q.set(T,{..._,pastParticipants:[..._.pastParticipants||[]]});return}let F=new Set((R.pastParticipants||[]).map(y));for(let K of _.pastParticipants||[]){let L=y(K);F.has(L)||(R.pastParticipants.push(K),F.add(L))}};for(let _ of n.historySets.pastParticipants||[])m(_);for(let _ of i.pastParticipants)m(_);n.historySets.pastParticipants=[...Q.values()]}n.historySets.progress=i.progress,n.historySets.chunkOrder=i.chunkOrder,n.historySets.peerDataRequestSessionId=i.peerDataRequestSessionId,n.historySets.isLatest=i.isLatest||n.historySets.isLatest;break;case"chats.upsert":for(let Q of i){let y=Q.id||"",m=n.chatUpserts[y];y&&!m&&(m=n.historySets.chats[y],m&&e.debug({chatId:y},"absorbed chat upsert in chat set")),m?m=mb(m,Q):(m=Q,n.chatUpserts[y]=m),a(m),n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.update":for(let Q of i){let y=Q.id,m=Q.conditional?Q.conditional(n):!0;if(m){delete Q.conditional;let _=n.historySets.chats[y]||n.chatUpserts[y];if(_)mb(_,Q);else{let T=n.chatUpdates[y]||{};n.chatUpdates[y]=mb(T,Q)}}else m===void 0&&(n.chatUpdates[y]=Q);n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.delete":for(let Q of i)n.chatDeletes.has(Q)||n.chatDeletes.add(Q),n.chatUpdates[Q]&&delete n.chatUpdates[Q],n.chatUpserts[Q]&&delete n.chatUpserts[Q],n.historySets.chats[Q]&&delete n.historySets.chats[Q];break;case"contacts.upsert":for(let Q of i){let y=n.contactUpserts[Q.id];y||(y=n.historySets.contacts[Q.id],y&&e.debug({contactId:Q.id},"absorbed contact upsert in contact set")),y?y=Object.assign(y,nD(Q)):(y=Q,n.contactUpserts[Q.id]=y),n.contactUpdates[Q.id]&&(y=Object.assign(n.contactUpdates[Q.id],nD(Q)),delete n.contactUpdates[Q.id])}break;case"contacts.update":let r=i;for(let Q of r){let y=Q.id,m=n.historySets.contacts[y]||n.contactUpserts[y];if(m)Object.assign(m,Q);else{let _=n.contactUpdates[y]||{};n.contactUpdates[y]=Object.assign(_,Q)}}break;case"messages.upsert":let{messages:s,type:g}=i;for(let Q of s){let y=iE(Q.key),m=n.messageUpserts[y]?.message;m||(m=n.historySets.messages[y],m&&e.debug({messageId:y},"absorbed message upsert in message set")),m&&(Q.messageTimestamp=m.messageTimestamp),n.messageUpdates[y]&&(e.debug("absorbed prior message update in message upsert"),Object.assign(Q,n.messageUpdates[y].update),delete n.messageUpdates[y]),n.historySets.messages[y]?n.historySets.messages[y]=Q:n.messageUpserts[y]={message:Q,type:g==="notify"||n.messageUpserts[y]?.type==="notify"?"notify":g}}break;case"messages.update":let c=i;for(let{key:Q,update:y}of c){let m=iE(Q),_=n.historySets.messages[m]||n.messageUpserts[m]?.message;if(_)Object.assign(_,y),y.status===th.READ&&!Q.fromMe&&A(_);else{let T=n.messageUpdates[m]||{key:Q,update:{}};Object.assign(T.update,y),n.messageUpdates[m]=T}}break;case"messages.delete":let I=i;if("keys"in I){let{keys:Q}=I;for(let y of Q){let m=iE(y);n.messageDeletes[m]||(n.messageDeletes[m]=y),n.messageUpserts[m]&&delete n.messageUpserts[m],n.messageUpdates[m]&&delete n.messageUpdates[m]}}break;case"messages.reaction":let d=i;for(let{key:Q,reaction:y}of d){let m=iE(Q),_=n.messageUpserts[m];_?Z2(_.message,y):(n.messageReactions[m]=n.messageReactions[m]||{key:Q,reactions:[]},Z2(n.messageReactions[m],y))}break;case"message-receipt.update":let B=i;for(let{key:Q,receipt:y}of B){let m=iE(Q),_=n.messageUpserts[m];_?W2(_.message,y):(n.messageReceipts[m]=n.messageReceipts[m]||{key:Q,userReceipt:[]},W2(n.messageReceipts[m],y))}break;case"groups.update":let f=i;for(let Q of f){let y=Q.id,m=n.groupUpdates[y]||{};n.groupUpdates[y]||(n.groupUpdates[y]=Object.assign(m,Q))}break;default:throw new Error(`"${o}" cannot be buffered`)}function a(r){let s=r.id||"",g=n.chatUpdates[s];if(g){let c=g.conditional?g.conditional(n):!0;c?(delete g.conditional,e.debug({chatId:s},"absorbed chat update in existing chat"),Object.assign(r,mb(g,r)),delete n.chatUpdates[s]):c===!1&&(e.debug({chatId:s},"chat update condition fail, removing"),delete n.chatUpdates[s])}}function A(r){let s=r.key.remoteJid,g=n.chatUpdates[s]||n.chatUpserts[s];OU(r)&&bU(r)&&typeof g?.unreadCount=="number"&&g.unreadCount>0&&(e.debug({chatId:g.id},"decrementing chat counter"),g.unreadCount-=1,g.unreadCount===0&&delete g.unreadCount)}}function f8e(n){let t={};n.historySets.empty||(t["messaging-history.set"]={chats:Object.values(n.historySets.chats),messages:Object.values(n.historySets.messages),contacts:Object.values(n.historySets.contacts),pastParticipants:n.historySets.pastParticipants,syncType:n.historySets.syncType,progress:n.historySets.progress,isLatest:n.historySets.isLatest,chunkOrder:n.historySets.chunkOrder,peerDataRequestSessionId:n.historySets.peerDataRequestSessionId});let o=Object.values(n.chatUpserts);o.length&&(t["chats.upsert"]=o);let i=Object.values(n.chatUpdates);i.length&&(t["chats.update"]=i);let e=Array.from(n.chatDeletes);e.length&&(t["chats.delete"]=e);let a=Object.values(n.messageUpserts);if(a.length){let B=a[0].type;t["messages.upsert"]={messages:a.map(f=>f.message),type:B}}let A=Object.values(n.messageUpdates);A.length&&(t["messages.update"]=A);let r=Object.values(n.messageDeletes);r.length&&(t["messages.delete"]={keys:r});let s=Object.values(n.messageReactions).flatMap(({key:B,reactions:f})=>f.flatMap(Q=>({key:B,reaction:Q})));s.length&&(t["messages.reaction"]=s);let g=Object.values(n.messageReceipts).flatMap(({key:B,userReceipt:f})=>f.flatMap(Q=>({key:B,receipt:Q})));g.length&&(t["message-receipt.update"]=g);let c=Object.values(n.contactUpserts);c.length&&(t["contacts.upsert"]=c);let I=Object.values(n.contactUpdates);I.length&&(t["contacts.update"]=I);let d=Object.values(n.groupUpdates);return d.length&&(t["groups.update"]=d),t}function mb(n,t){return t.unreadCount===null&&n.unreadCount<0&&(n.unreadCount=void 0,t.unreadCount=void 0),typeof n.unreadCount=="number"&&typeof t.unreadCount=="number"&&(t={...t},t.unreadCount>=0&&(t.unreadCount=Math.max(t.unreadCount,0)+Math.max(n.unreadCount,0))),Object.assign(n,t)}var iE=n=>`${n.remoteJid},${n.id},${n.fromMe?"1":"0"}`;var Q8e=512,_U="\0",Mne=3600*1e3,y8e=3e3,qg;(function(n){n[n.UnknownError=0]="UnknownError",n[n.SignalErrorNoSession=1]="SignalErrorNoSession",n[n.SignalErrorInvalidKey=2]="SignalErrorInvalidKey",n[n.SignalErrorInvalidKeyId=3]="SignalErrorInvalidKeyId",n[n.SignalErrorInvalidMessage=4]="SignalErrorInvalidMessage",n[n.SignalErrorInvalidSignature=5]="SignalErrorInvalidSignature",n[n.SignalErrorFutureMessage=6]="SignalErrorFutureMessage",n[n.SignalErrorBadMac=7]="SignalErrorBadMac",n[n.SignalErrorInvalidSession=8]="SignalErrorInvalidSession",n[n.SignalErrorInvalidMsgKey=9]="SignalErrorInvalidMsgKey",n[n.BadBroadcastEphemeralSetting=10]="BadBroadcastEphemeralSetting",n[n.UnknownCompanionNoPrekey=11]="UnknownCompanionNoPrekey",n[n.AdvFailure=12]="AdvFailure",n[n.StatusRevokeDelay=13]="StatusRevokeDelay"})(qg||(qg={}));var _ne=new Set([qg.SignalErrorInvalidMessage,qg.SignalErrorBadMac]),Sb=class{constructor(t,o){this.logger=t,this.recentMessagesMap=new Mg({max:Q8e,ttl:300*1e3,ttlAutopurge:!0,dispose:(i,e)=>{let a=e.lastIndexOf(_U);if(a>-1){let A=e.slice(a+_U.length);this.messageKeyIndex.delete(A)}}}),this.messageKeyIndex=new Map,this.sessionRecreateHistory=new Mg({ttl:Mne*2,ttlAutopurge:!0}),this.retryCounters=new Mg({ttl:900*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),this.baseKeys=new Mg({max:1024,ttl:900*1e3,ttlAutopurge:!0}),this.pendingPhoneRequests={},this.maxMsgRetryCount=5,this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0},this.maxMsgRetryCount=o}addRecentMessage(t,o,i){let e={to:t,id:o},a=this.keyToString(e);this.recentMessagesMap.set(a,{message:i,timestamp:Date.now()}),this.messageKeyIndex.set(o,a),this.logger.debug(`Added message to retry cache: ${t}/${o}`)}getRecentMessage(t,o){let i={to:t,id:o},e=this.keyToString(i);return this.recentMessagesMap.get(e)}shouldRecreateSession(t,o,i){if(!o)return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,{reason:"we don't have a Signal session with them",recreate:!0};if(i!==void 0&&_ne.has(i))return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,this.logger.warn({jid:t,errorCode:qg[i]},"MAC error detected, forcing immediate session recreation"),{reason:`MAC error (code ${i}: ${qg[i]}), immediate session recreation`,recreate:!0};let e=Date.now(),a=this.sessionRecreateHistory.get(t);return!a||e-a>Mne?(this.sessionRecreateHistory.set(t,e),this.statistics.sessionRecreations++,{reason:"retry count > 1 and over an hour since last recreation",recreate:!0}):{reason:"",recreate:!1}}parseRetryErrorCode(t){if(t===void 0||t==="")return;let o=parseInt(t,10);if(!Number.isNaN(o))return o>=qg.UnknownError&&o<=qg.StatusRevokeDelay?o:qg.UnknownError}isMacError(t){return t!==void 0&&_ne.has(t)}incrementRetryCount(t){return this.retryCounters.set(t,(this.retryCounters.get(t)||0)+1),this.statistics.totalRetries++,this.retryCounters.get(t)}getRetryCount(t){return this.retryCounters.get(t)||0}hasExceededMaxRetries(t){return this.getRetryCount(t)>=this.maxMsgRetryCount}markRetrySuccess(t){this.statistics.successfulRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}markRetryFailed(t){this.statistics.failedRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}schedulePhoneRequest(t,o,i=y8e){this.cancelPendingPhoneRequest(t),this.pendingPhoneRequests[t]=setTimeout(()=>{delete this.pendingPhoneRequests[t],this.statistics.phoneRequests++,o()},i),this.logger.debug(`Scheduled phone request for message ${t} with ${i}ms delay`)}cancelPendingPhoneRequest(t){let o=this.pendingPhoneRequests[t];o&&(clearTimeout(o),delete this.pendingPhoneRequests[t],this.logger.debug(`Cancelled pending phone request for message ${t}`))}clear(){this.recentMessagesMap.clear(),this.messageKeyIndex.clear(),this.sessionRecreateHistory.clear(),this.retryCounters.clear(),this.baseKeys.clear();for(let t of Object.keys(this.pendingPhoneRequests))this.cancelPendingPhoneRequest(t);this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0}}saveBaseKey(t,o,i){this.baseKeys.set(`${t}:${o}`,i)}hasSameBaseKey(t,o,i){let e=this.baseKeys.get(`${t}:${o}`);if(!e||e.length!==i.length)return!1;for(let a=0;a["Ubuntu",n,"22.04.4"],macOS:n=>["Mac OS",n,"14.4.1"],baileys:n=>["Baileys",n,"6.5.0"],windows:n=>["Windows",n,"10.0.22631"],android:n=>[n,"Android",""],appropriate:n=>[w8e[m8e()]||"Ubuntu",n,S8e()]};var Gn;(function(n){n[n.UNKNOWN=0]="UNKNOWN",n[n.CHROME=1]="CHROME",n[n.EDGE=2]="EDGE",n[n.FIREFOX=3]="FIREFOX",n[n.IE=4]="IE",n[n.OPERA=5]="OPERA",n[n.SAFARI=6]="SAFARI",n[n.ELECTRON=7]="ELECTRON",n[n.UWP=8]="UWP",n[n.OTHER_WEB_CLIENT=9]="OTHER_WEB_CLIENT"})(Gn||(Gn={}));var D8e={Chrome:Gn.CHROME,Edge:Gn.EDGE,Firefox:Gn.FIREFOX,IE:Gn.IE,Opera:Gn.OPERA,Safari:Gn.SAFARI},O8e=([n,t])=>t==="Desktop"?n==="Windows"?Gn.UWP:Gn.ELECTRON:D8e[t]||Gn.OTHER_WEB_CLIENT,TU=n=>O8e(n).toString(),Tne=(n,t,o,i,e)=>"https://wa.me/settings/linked_devices#"+[n,t,o,i,TU(e)].join(",");async function Nne(n,t){let o=n.attrs.from;if(!o)return{action:"invalid_notification"};if(!le(n,"identity"))return{action:"no_identity_node"};t.logger.info({jid:o},"identity changed");let e=yA(o);if(e?.device&&e.device!==0)return t.logger.debug({jid:o,device:e.device},"ignoring identity change from companion device"),{action:"skipped_companion_device",device:e.device};if(t.meId&&(Tt(o,t.meId)||t.meLid&&Tt(o,t.meLid)))return t.logger.info({jid:o},"self primary identity changed"),{action:"skipped_self_primary"};if(t.debounceCache.get(o))return t.logger.debug({jid:o},"skipping identity assert (debounced)"),{action:"debounced"};t.debounceCache.set(o,!0);let A=!u7(n.attrs.offline);if(!(await t.validateSession(o)).exists)return t.logger.debug({jid:o},"no old session, skipping session refresh"),{action:"skipped_no_session"};if(t.logger.debug({jid:o},"old session exists, will refresh session"),A)return t.logger.debug({jid:o},"skipping session refresh during offline processing"),{action:"skipped_offline"};t.onBeforeSessionRefresh?.(o);try{return await t.assertSessions([o],!0),{action:"session_refreshed"}}catch(s){return t.logger.warn({error:s,jid:o},"failed to assert sessions after identity change"),{action:"session_refresh_failed",error:s}}}function Rne(n,t,o){let{tag:i,attrs:e}=n,a={tag:"ack",attrs:{id:e.id,to:e.from,class:i}};return t&&(a.attrs.error=t.toString()),e.participant&&(a.attrs.participant=e.participant),e.recipient&&(a.attrs.recipient=e.recipient),e.type&&(a.attrs.type=e.type),i==="message"&&o&&(a.attrs.from=o),a}function b8e(n){return n===null||n===""}function M8e(n){return n>2147483647||n<-2147483648?n&4294967295:n}function kne(n){let t=0;if(!b8e(n))for(let o=0;oo.iteration===t)}addSenderMessageKey(t){this.senderKeyStateStructure.senderMessageKeys.push({iteration:t.getIteration(),seed:t.getSeed()}),this.senderKeyStateStructure.senderMessageKeys.length>this.MAX_MESSAGE_KEYS&&this.senderKeyStateStructure.senderMessageKeys.shift()}removeSenderMessageKey(t){let o=this.senderKeyStateStructure.senderMessageKeys.findIndex(i=>i.iteration===t);if(o!==-1){let i=this.senderKeyStateStructure.senderMessageKeys[o];return this.senderKeyStateStructure.senderMessageKeys.splice(o,1),new tp(i.iteration,i.seed)}return null}getStructure(){return this.senderKeyStateStructure}};var zg=class n{constructor(t){if(this.MAX_STATES=5,this.senderKeyStates=[],t)for(let o of t)this.senderKeyStates.push(new rp(null,null,null,null,null,null,o))}isEmpty(){return this.senderKeyStates.length===0}getSenderKeyState(t){return t===void 0&&this.senderKeyStates.length?this.senderKeyStates[this.senderKeyStates.length-1]:this.senderKeyStates.find(o=>o.getKeyId()===t)}addSenderKeyState(t,o,i,e){this.senderKeyStates.push(new rp(t,o,i,null,e)),this.senderKeyStates.length>this.MAX_STATES&&this.senderKeyStates.shift()}setSenderKeyState(t,o,i,e){this.senderKeyStates.length=0,this.senderKeyStates.push(new rp(t,o,i,e))}serialize(){return this.senderKeyStates.map(t=>t.getStructure())}static deserialize(t){let o=Buffer.from(t).toString("utf-8"),i=JSON.parse(o,wB.reviver);return new n(i)}};var Gne=Je(vc(),1);import*as Db from"crypto";function Fne(){return Db.randomBytes(32)}function Lne(){return Db.randomInt(2147483647)}function Une(n){return n||(n=(0,Gne.generateKeyPair)()),{public:Buffer.from(n.pubKey),private:Buffer.from(n.privKey)}}var ap=class{constructor(){this.UNSUPPORTED_VERSION=1,this.CURRENT_VERSION=3,this.WHISPER_TYPE=2,this.PREKEY_TYPE=3,this.SENDERKEY_TYPE=4,this.SENDERKEY_DISTRIBUTION_TYPE=5,this.ENCRYPTED_MESSAGE_OVERHEAD=53}};var ip=class extends ap{constructor(t,o,i,e,a){if(super(),a)try{let A=a.slice(1),r=oe.SenderKeyDistributionMessage.decode(A).toJSON();this.serialized=a,this.id=r.id,this.iteration=r.iteration,this.chainKey=typeof r.chainKey=="string"?Buffer.from(r.chainKey,"base64"):r.chainKey,this.signatureKey=typeof r.signingKey=="string"?Buffer.from(r.signingKey,"base64"):r.signingKey}catch(A){throw new Error(String(A))}else{let A=this.intsToByteHighAndLow(this.CURRENT_VERSION,this.CURRENT_VERSION);this.id=t,this.iteration=o,this.chainKey=i,this.signatureKey=e;let r=oe.SenderKeyDistributionMessage.encode(oe.SenderKeyDistributionMessage.create({id:t,iteration:o,chainKey:i,signingKey:this.signatureKey})).finish();this.serialized=Buffer.concat([Buffer.from([A]),r])}}intsToByteHighAndLow(t,o){return((t<<4|o)&255)%256}serialize(){return this.serialized}getType(){return this.SENDERKEY_DISTRIBUTION_TYPE}getIteration(){return this.iteration}getChainKey(){return this.chainKey}getSignatureKey(){return this.signatureKey}getId(){return this.id}};var oE=class{constructor(t){this.senderKeyStore=t}async process(t,o){let i=await this.senderKeyStore.loadSenderKey(t);i.addSenderKeyState(o.getId(),o.getIteration(),o.getChainKey(),o.getSignatureKey()),await this.senderKeyStore.storeSenderKey(t,i)}async create(t){let o=await this.senderKeyStore.loadSenderKey(t);if(o.isEmpty()){let e=Lne(),a=Fne(),A=Une();o.setSenderKeyState(e,0,a,A),await this.senderKeyStore.storeSenderKey(t,o)}let i=o.getSenderKeyState();if(!i)throw new Error("No session state available");return new ip(i.getKeyId(),i.getSenderChainKey().getIteration(),i.getSenderChainKey().getSeed(),i.getSigningKeyPublic())}};var bb=Je(yl(),1);var Ob=Je(vc(),1);var nE=class extends ap{constructor(t,o,i,e,a){if(super(),this.SIGNATURE_LENGTH=64,a){let A=a[0],r=a.slice(1,a.length-this.SIGNATURE_LENGTH),s=a.slice(-1*this.SIGNATURE_LENGTH),g=oe.SenderKeyMessage.decode(r).toJSON();this.serialized=a,this.messageVersion=(A&255)>>4,this.keyId=g.id,this.iteration=g.iteration,this.ciphertext=typeof g.ciphertext=="string"?Buffer.from(g.ciphertext,"base64"):g.ciphertext,this.signature=s}else{let A=((this.CURRENT_VERSION<<4|this.CURRENT_VERSION)&255)%256,r=Buffer.from(i),s=oe.SenderKeyMessage.encode(oe.SenderKeyMessage.create({id:t,iteration:o,ciphertext:r})).finish(),g=this.getSignature(e,Buffer.concat([Buffer.from([A]),s]));this.serialized=Buffer.concat([Buffer.from([A]),s,Buffer.from(g)]),this.messageVersion=this.CURRENT_VERSION,this.keyId=t,this.iteration=o,this.ciphertext=r,this.signature=g}}getKeyId(){return this.keyId}getIteration(){return this.iteration}getCipherText(){return this.ciphertext}verifySignature(t){let o=this.serialized.slice(0,this.serialized.length-this.SIGNATURE_LENGTH),i=this.serialized.slice(-1*this.SIGNATURE_LENGTH);if(!(0,Ob.verifySignature)(t,o,i))throw new Error("Invalid signature!")}getSignature(t,o){return Buffer.from((0,Ob.calculateSignature)(t,o))}serialize(){return this.serialized}getType(){return 4}};var sE=class{constructor(t,o){this.senderKeyStore=t,this.senderKeyName=o}async encrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for encryption");let i=o.getSenderKeyState();if(!i)throw new Error("No session to encrypt message");let e=i.getSenderChainKey().getIteration(),a=this.getSenderKey(i,e===0?0:e+1),A=await this.getCipherText(a.getIv(),a.getCipherKey(),t),r=new nE(i.getKeyId(),a.getIteration(),A,i.getSigningKeyPrivate());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),r.serialize()}async decrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for decryption");let i=new nE(null,null,null,null,t),e=o.getSenderKeyState(i.getKeyId());if(!e)throw new Error("No session found to decrypt message");i.verifySignature(e.getSigningKeyPublic());let a=this.getSenderKey(e,i.getIteration()),A=await this.getPlainText(a.getIv(),a.getCipherKey(),i.getCipherText());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),A}getSenderKey(t,o){let i=t.getSenderChainKey();if(i.getIteration()>o){if(t.hasSenderMessageKey(o)){let e=t.removeSenderMessageKey(o);if(!e)throw new Error("No sender message key found for iteration");return e}throw new Error(`Received message with old counter: ${i.getIteration()}, ${o}`)}if(o-i.getIteration()>2e3)throw new Error("Over 2000 messages into the future!");for(;i.getIteration()0){let r=[...i];this.logger.trace(`Batch fetching ${r.length} LID mappings from database`);let s=await this.keys.get("lid-mapping",r);for(let g of r){let c=s[g];c&&(e.set(g,c),this.mappingCache.set(`pn:${g}`,c),this.mappingCache.set(`lid:${c}`,g))}}let a={};for(let{pnUser:r,lidUser:s}of o){if(e.get(r)===s){this.logger.debug({pnUser:r,lidUser:s},"LID mapping already exists, skipping");continue}a[r]=s}if(Object.keys(a).length===0)return;this.logger.trace({pairMap:a},`Storing ${Object.keys(a).length} pn mappings`);let A={};for(let[r,s]of Object.entries(a))A[r]=s,A[`${s}_reverse`]=r;await this.keys.transaction(async()=>{await this.keys.set({"lid-mapping":A})},"lid-mapping");for(let[r,s]of Object.entries(a))this.mappingCache.set(`pn:${r}`,s),this.mappingCache.set(`lid:${s}`,r)}async getLIDForPN(t){return(await this.getLIDsForPNs([t]))?.[0]?.lid||null}async getLIDsForPNs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightLIDLookups.get(i);if(e)return this.logger.trace(`Coalescing getLIDsForPNs request for ${o.length} PNs`),e;let a=this._getLIDsForPNsImpl(t);this.inflightLIDLookups.set(i,a);try{return await a}finally{this.inflightLIDLookups.delete(i)}}async _getLIDsForPNsImpl(t){let o={},i={},e=[],a=(A,r,s)=>{let g=s.toString();if(!g)return this.logger.warn(`Invalid or empty LID user for PN ${A}: lidUser = "${s}"`),!1;let c=r.device!==void 0?r.device:0,I=`${g}${c?`:${c}`:""}@${r.server==="hosted"?"hosted.lid":"lid"}`;return this.logger.trace(`getLIDForPN: ${A} \u2192 ${I} (user mapping with device ${c})`),i[A]={lid:I,pn:A},!0};for(let A of t){if(!_t(A)&&!ur(A))continue;let r=yA(A);if(!r)continue;let s=r.user,g=this.mappingCache.get(`pn:${s}`);if(g&&typeof g=="string"){if(!a(A,r,g)){this.logger.warn(`Invalid entry for ${A} (pair not resolved)`);continue}continue}e.push({pn:A,pnUser:s,decoded:r})}if(e.length){let A=[...new Set(e.map(s=>s.pnUser))],r=await this.keys.get("lid-mapping",A);for(let s of A){let g=r[s];g&&typeof g=="string"&&(this.mappingCache.set(`pn:${s}`,g),this.mappingCache.set(`lid:${g}`,s))}for(let{pn:s,pnUser:g,decoded:c}of e){let I=this.mappingCache.get(`pn:${g}`);if(I&&typeof I=="string"){if(!a(s,c,I)){this.logger.warn(`Invalid entry for ${s} (pair not resolved)`);continue}}else{this.logger.trace(`No LID mapping found for PN user ${g}; batch getting from USync`);let d=c.device||0,B=uA(s);ur(B)&&(B=`${g}@s.whatsapp.net`),o[B]?o[B]?.push(d):o[B]=[d]}}}if(Object.keys(o).length>0){let A=await this.pnToLIDFunc?.(Object.keys(o));if(A&&A.length>0){await this.storeLIDPNMappings(A);for(let r of A){let g=yA(r.pn)?.user;if(!g)continue;let c=yA(r.lid)?.user;if(c)for(let I of o[r.pn]){let d=`${c}${I?`:${I}`:""}@${I===99?"hosted.lid":"lid"}`;this.logger.trace(`getLIDForPN: USYNC success for ${r.pn} \u2192 ${d} (user mapping with device ${I})`);let B=`${g}${I?`:${I}`:""}@${I===99?"hosted":"s.whatsapp.net"}`;i[B]={lid:d,pn:B}}}}else this.logger.warn("USync fetch yielded no results for pending PNs")}return Object.values(i).length>0?Object.values(i):null}async getPNForLID(t){return(await this.getPNsForLIDs([t]))?.[0]?.pn||null}async getPNsForLIDs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightPNLookups.get(i);if(e)return this.logger.trace(`Coalescing getPNsForLIDs request for ${o.length} LIDs`),e;let a=this._getPNsForLIDsImpl(t);this.inflightPNLookups.set(i,a);try{return await a}finally{this.inflightPNLookups.delete(i)}}async _getPNsForLIDsImpl(t){let o={},i=[],e=(a,A,r)=>{if(!r||typeof r!="string")return!1;let s=A.device!==void 0?A.device:0,g=`${r}:${s}@${A.domainType===jt.HOSTED_LID?"hosted":"s.whatsapp.net"}`;return this.logger.trace(`Found reverse mapping: ${a} \u2192 ${g}`),o[a]={lid:a,pn:g},!0};for(let a of t){if(!qA(a))continue;let A=yA(a);if(!A)continue;let r=A.user,s=this.mappingCache.get(`lid:${r}`);if(s&&typeof s=="string"){e(a,A,s);continue}i.push({lid:a,lidUser:r,decoded:A})}if(i.length){let a=[...new Set(i.map(r=>`${r.lidUser}_reverse`))],A=await this.keys.get("lid-mapping",a);for(let{lid:r,lidUser:s,decoded:g}of i){let c=this.mappingCache.get(`lid:${s}`);(!c||typeof c!="string")&&(c=A[`${s}_reverse`],c&&typeof c=="string"&&(this.mappingCache.set(`lid:${s}`,c),this.mappingCache.set(`pn:${c}`,s))),c&&typeof c=="string"?e(r,g,c):this.logger.trace(`No reverse mapping found for LID user: ${s}`)}}return Object.values(o).length?Object.values(o):null}close(){this.mappingCache.clear()}};function _8e(n){try{if(!n||n.length<2||(n[0]&15)!==3)return;let o=Kne.PreKeyWhisperMessage.decode(n.slice(1));return o.identityKey?.length===33?new Uint8Array(o.identityKey):void 0}catch{return}}function xne(n,t,o){let i=new Mb(n.keys,t,o),e=T8e(n,i),a=n.keys,A=new Mg({ttl:4320*60*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),r=async(g,c)=>{let I=_b(g,c),d=I.toString(),{[d]:B}=await n.keys.get("sender-key",[d]);B||await e.storeSenderKey(I,new zg);let f=await new oE(e).create(I);return{senderName:I,skdm:f}};return{decryptGroupMessage({group:g,authorJid:c,msg:I}){let d=_b(g,c),B=new sE(e,d);return a.transaction(async()=>B.decrypt(I),g)},async processSenderKeyDistributionMessage({item:g,authorJid:c}){let I=new oE(e);if(!g.groupId)throw new Error("Group ID is required for sender key distribution message");let d=_b(g.groupId,c),B=new ip(null,null,null,null,g.axolotlSenderKeyDistributionMessage),f=d.toString(),{[f]:Q}=await n.keys.get("sender-key",[f]);return Q||await e.storeSenderKey(d,new zg),a.transaction(async()=>{let{[f]:y}=await n.keys.get("sender-key",[f]);y||await e.storeSenderKey(d,new zg),await I.process(d,B)},g.groupId)},async decryptMessage({jid:g,type:c,ciphertext:I}){let d=Fn(g),B=new Js.SessionCipher(e,d);if(c==="pkmsg"){let Q=_8e(I);if(Q){let y=d.toString();await e.saveIdentity(y,Q)&&t.info({jid:g,addr:y},"identity key changed or new contact, session will be re-established")}}async function f(){let Q;switch(c){case"pkmsg":Q=await B.decryptPreKeyWhisperMessage(I);break;case"msg":Q=await B.decryptWhisperMessage(I);break}return Q}return a.transaction(async()=>await f(),g)},async encryptMessage({jid:g,data:c}){let I=Fn(g),d=new Js.SessionCipher(e,I);return a.transaction(async()=>{let{type:B,body:f}=await d.encrypt(c);return{type:B===3?"pkmsg":"msg",ciphertext:Buffer.from(f,"binary")}},g)},async encryptGroupMessage({group:g,meId:c,data:I}){return a.transaction(async()=>{let{senderName:d,skdm:B}=await r(g,c);return{ciphertext:await new sE(e,d).encrypt(I),senderKeyDistributionMessage:B.serialize()}},g)},async getSenderKeyDistributionMessage({group:g,meId:c}){return a.transaction(async()=>{let{skdm:I}=await r(g,c);return I.serialize()},g)},async hasSenderKey({group:g,meId:c}){let I=_b(g,c).toString(),{[I]:d}=await n.keys.get("sender-key",[I]);return!!d},async getSessionInfo(g){let c=Fn(g).toString(),I=await e.loadSession(c);if(!I)return null;let d=I.getOpenSession?.(),B=d?.indexInfo?.baseKey,f=d?.registrationId;return!B||typeof f!="number"?null:{baseKey:new Uint8Array(B),registrationId:f}},async injectE2ESession({jid:g,session:c}){t.trace({jid:g},"injecting E2EE session");let I=new Js.SessionBuilder(e,Fn(g));return a.transaction(async()=>{await I.initOutgoing(c)},g)},jidToSignalProtocolAddress(g){return Fn(g).toString()},lidMapping:i,async validateSession(g){try{let c=Fn(g),I=await e.loadSession(c.toString());return I?I.haveOpenSession()?{exists:!0}:{exists:!1,reason:"no open session"}:{exists:!1,reason:"no session"}}catch{return{exists:!1,reason:"validation error"}}},async deleteSession(g){if(!g.length)return;let c={};return g.forEach(I=>{let d=Fn(I);c[d.toString()]=null}),a.transaction(async()=>{await n.keys.set({session:c})},`delete-${g.length}-sessions`)},close(){A.clear(),i.close()},async migrateSession(g,c){if(!g||!qA(c)&&!ga(c))return{migrated:0,skipped:0,total:0};if(!_t(g)&&!ur(g))return{migrated:0,skipped:0,total:1};let{user:I}=yA(g);t.debug({fromJid:g},"bulk device migration - loading all user devices");let{[I]:d}=await a.get("device-list",[I]);if(!d)return{migrated:0,skipped:0,total:0};let{device:B}=yA(g),f=B?.toString()||"0";d.includes(f)||d.push(f);let y=d.filter(T=>{let R=`${I}.${T}`;return!A.has(R)}).map(T=>`${I}.${T}`),m=await a.get("session",y),_=[];for(let[T,R]of Object.entries(m))if(R){let F=T.split(".")[1];if(!F)continue;let K=parseInt(F),L=K===0?`${I}@s.whatsapp.net`:`${I}:${K}@s.whatsapp.net`;K===99&&(L=`${I}:99@hosted`),_.push(L)}return t.debug({fromJid:g,totalDevices:d.length,devicesWithSessions:_.length,devices:_},"bulk device migration complete - all user devices processed"),a.transaction(async()=>{let T=_.map(j=>{let P=HX(j,c),J=yA(j),U=yA(P);return{fromJid:j,toJid:P,pnUser:J.user,lidUser:U.user,deviceId:J.device||0,fromAddr:Fn(j),toAddr:Fn(P)}}),R=T.length,F=0,K=Array.from(new Set(T.map(j=>j.fromAddr.toString()))),L=await a.get("session",K),q={};for(let j of T){let P=j.fromAddr.toString(),J=j.toAddr.toString(),U=L[P];if(U){let N=Js.SessionRecord.deserialize(U);N.haveOpenSession()&&(q[J]=N.serialize(),q[P]=null,F++)}}if(Object.keys(q).length>0){await a.set({session:q}),t.debug({migratedSessions:F},"bulk session migration complete");for(let j of T)if(q[j.toAddr.toString()]){let P=`${j.pnUser}.${j.deviceId}`;A.set(P,!0)}}let z=R-F;return{migrated:F,skipped:z,total:R}},`migrate-${_.length}-sessions-${yA(c)?.user}`)}}}var Fn=n=>{let t=yA(n),{user:o,device:i,server:e,domainType:a}=t;if(!o)throw new Error(`JID decoded but user is empty: "${n}" -> user: "${o}", server: "${e}", device: ${i}`);let A=a!==jt.WHATSAPP?`${o}_${a}`:o,r=i||0;if(i===99&&t.server!=="hosted"&&t.server!=="hosted.lid")throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:"+n);return new Js.ProtocolAddress(A,r)},_b=(n,t)=>new Mf(n,Fn(t));function T8e({creds:n,keys:t},o){let i=async e=>{if(e.includes(".")){let[a,A]=e.split("."),[r,s]=a.split("_"),g=parseInt(s||"0");if(g===jt.LID||g===jt.HOSTED_LID)return e;let c=`${r}${A!=="0"?`:${A}`:""}@${g===jt.HOSTED?"hosted":"s.whatsapp.net"}`,I=await o.getLIDForPN(c);if(I)return Fn(I).toString()}return e};return{loadSession:async e=>{try{let a=await i(e),{[a]:A}=await t.get("session",[a]);if(A)return Js.SessionRecord.deserialize(A)}catch{return null}return null},storeSession:async(e,a)=>{let A=await i(e);await t.set({session:{[A]:a.serialize()}})},isTrustedIdentity:()=>!0,loadIdentityKey:async e=>{let a=await i(e),{[a]:A}=await t.get("identity-key",[a]);return A||void 0},saveIdentity:async(e,a)=>{let A=await i(e),{[A]:r}=await t.get("identity-key",[A]),s=r?.length===a.length&&r.every((g,c)=>g===a[c]);return r&&!s?(await t.set({session:{[A]:null},"identity-key":{[A]:a}}),!0):r?!1:(await t.set({"identity-key":{[A]:a}}),!0)},loadPreKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("pre-key",[a]);if(A)return{privKey:Buffer.from(A.private),pubKey:Buffer.from(A.public)}},removePreKey:e=>t.set({"pre-key":{[e]:null}}),loadSignedPreKey:()=>{let e=n.signedPreKey;return{privKey:Buffer.from(e.keyPair.private),pubKey:Buffer.from(e.keyPair.public)}},loadSenderKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("sender-key",[a]);return A?zg.deserialize(A):new zg},storeSenderKey:async(e,a)=>{let A=e.toString(),r=JSON.stringify(a.serialize());await t.set({"sender-key":{[A]:Buffer.from(r,"utf-8")}})},getOurRegistrationId:()=>n.registrationId,getOurIdentity:()=>{let{signedIdentityKey:e}=n;return{privKey:Buffer.from(e.private),pubKey:Buffer.from(Yo(e.public))}}}}var Ace=Je(ece(),1),vf=(0,Ace.default)({timestamp:()=>`,"time":"${new Date().toJSON()}"`});var O5e=[2,3e3,1043857760];var uf="https://web.whatsapp.com",boe="https://call.whatsapp.com/video/",Moe="https://call.whatsapp.com/voice/",pE="CB:",tce="TAG:";var Koe=Buffer.from([6,0]),xoe=Buffer.from([6,1]),tU=Buffer.from([6,5]),vkA=Buffer.from([6,6]),Qf=10080*60,rce=1440*60,ace=336*60*60,zoe="Noise_XX_25519_AESGCM_SHA256\0\0\0\0",b5e=3,Rg=Buffer.from([5]),ice=Buffer.from([87,65,6,b5e]),_oe=/https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g,aU={SERIAL:0,ISSUER:"WhatsAppLongTerm1",PUBLIC_KEY:Buffer.from("142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b","hex")},Pf=[oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,oe.HistorySync.HistorySyncType.PUSH_NAME,oe.HistorySync.HistorySyncType.RECENT,oe.HistorySync.HistorySyncType.FULL,oe.HistorySync.HistorySyncType.ON_DEMAND,oe.HistorySync.HistorySyncType.NON_BLOCKING_DATA,oe.HistorySync.HistorySyncType.INITIAL_STATUS_V3],dI={SIGNAL_STORE:300,MSG_RETRY:3600,CALL_OFFER:300,USER_DEVICES:300},oce={version:O5e,browser:wb.macOS("Chrome"),waWebSocketUrl:"wss://web.whatsapp.com/ws/chat",connectTimeoutMs:2e4,keepAliveIntervalMs:3e4,logger:vf.child({class:"baileys"}),emitOwnEvents:!0,defaultQueryTimeoutMs:6e4,customUploadHosts:[],retryRequestDelayMs:250,maxMsgRetryCount:5,fireInitQueries:!0,auth:void 0,markOnlineOnConnect:!0,syncFullHistory:!0,patchMessageBeforeSending:n=>n,shouldSyncHistoryMessage:({syncType:n})=>n!==oe.HistorySync.HistorySyncType.FULL,shouldIgnoreJid:()=>!1,linkPreviewImageThumbnailWidth:192,transactionOpts:{maxCommitRetries:10,delayBetweenTriesMs:3e3},generateHighQualityLinkPreview:!1,enableAutoSessionRecreation:!0,enableRecentMessageCache:!0,options:{},appStateMacVerification:{patch:!1,snapshot:!1},countryCode:"US",getMessage:async()=>{},cachedGroupMetadata:async()=>{},makeSignalRepository:xne},J2={image:"/mms/image",video:"/mms/video",document:"/mms/document",audio:"/mms/audio",sticker:"/mms/image","thumbnail-link":"/mms/image","product-catalog-image":"/product/image","md-app-state":"","md-msg-hist":"/mms/md-app-state","biz-cover-photo":"/pps/biz-cover-photo"},Coe={audio:"Audio",document:"Document",gif:"Video",image:"Image",ppic:"",product:"Image",ptt:"Audio",sticker:"Image",video:"Video","thumbnail-document":"Document Thumbnail","thumbnail-image":"Image Thumbnail","thumbnail-video":"Video Thumbnail","thumbnail-link":"Link Thumbnail","md-msg-hist":"History","md-app-state":"App State","product-catalog-image":"","payment-bg-image":"Payment Background",ptv:"Video","biz-cover-photo":"Image"},Toe=Object.keys(J2),nce=12e4,Gf=5,sce=812,gce=3e4,bH={Minute:60*1e3,Hour:3600*1e3,Day:1440*60*1e3,Week:10080*60*1e3};var cce=Je(Lr(),1);import{createHash as M5e}from"crypto";import{createWriteStream as _5e,promises as T5e}from"fs";import{tmpdir as N5e}from"os";import{join as R5e}from"path";var Ice=n=>{let t=le(n,"product_catalog"),o=kA(t,"product").map(Ff),i=le(t,"paging");return{products:o,nextPageCursor:i?YA(i,"after"):void 0}},lce=n=>{let t=le(n,"collections");return{collections:kA(t,"collection").map(i=>{let e=YA(i,"id"),a=YA(i,"name"),A=kA(i,"product").map(Ff);return{id:e,name:a,products:A,status:P5e(i)}})}},pce=n=>{let t=le(n,"order"),o=kA(t,"product").map(a=>{let A=le(a,"image");return{id:YA(a,"id"),name:YA(a,"name"),imageUrl:YA(A,"url"),price:+YA(a,"price"),currency:YA(a,"currency"),quantity:+YA(a,"quantity")}}),i=le(t,"price");return{price:{total:+YA(i,"total"),currency:YA(i,"currency")},products:o}},MH=(n,t)=>{let o={},i=[];return typeof n<"u"&&i.push({tag:"id",attrs:{},content:Buffer.from(n)}),typeof t.name<"u"&&i.push({tag:"name",attrs:{},content:Buffer.from(t.name)}),typeof t.description<"u"&&i.push({tag:"description",attrs:{},content:Buffer.from(t.description)}),typeof t.retailerId<"u"&&i.push({tag:"retailer_id",attrs:{},content:Buffer.from(t.retailerId)}),t.images.length&&i.push({tag:"media",attrs:{},content:t.images.map(a=>{if(!("url"in a))throw new cce.Boom("Expected img for product to already be uploaded",{statusCode:400});return{tag:"image",attrs:{},content:[{tag:"url",attrs:{},content:Buffer.from(a.url.toString())}]}})}),typeof t.price<"u"&&i.push({tag:"price",attrs:{},content:Buffer.from(t.price.toString())}),typeof t.currency<"u"&&i.push({tag:"currency",attrs:{},content:Buffer.from(t.currency)}),"originCountryCode"in t&&(typeof t.originCountryCode>"u"?o.compliance_category="COUNTRY_ORIGIN_EXEMPT":i.push({tag:"compliance_info",attrs:{},content:[{tag:"country_code_origin",attrs:{},content:Buffer.from(t.originCountryCode)}]})),typeof t.isHidden<"u"&&(o.is_hidden=t.isHidden.toString()),{tag:"product",attrs:o,content:i}},Ff=n=>{let t=n.attrs.is_hidden==="true",o=YA(n,"id"),i=le(n,"media"),e=le(n,"status_info");return{id:o,imageUrls:v5e(i),reviewStatus:{whatsapp:YA(e,"status")},availability:"in stock",name:YA(n,"name"),retailerId:YA(n,"retailer_id"),url:YA(n,"url"),description:YA(n,"description"),price:+YA(n,"price"),currency:YA(n,"currency"),isHidden:t}};async function _H(n,t,o=3e4){return n={...n,images:n.images?await k5e(n.images,t,o):n.images},n}var k5e=async(n,t,o=3e4)=>await Promise.all(n.map(async e=>{if("url"in e){let I=e.url.toString();if(I.includes(".whatsapp.net"))return{url:I}}let{stream:a}=await Ef(e),A=M5e("sha256"),r=R5e(N5e(),"img"+Kr()),s=_5e(r);for await(let I of a)A.update(I),s.write(I);let g=A.digest("base64"),{directPath:c}=await t(r,{mediaType:"product-catalog-image",fileEncSha256B64:g,timeoutMs:o});return await T5e.unlink(r).catch(I=>console.log("Error deleting temp file ",I)),{url:Cf(c)}})),v5e=n=>{let t=le(n,"image");return{requested:YA(t,"request_image_url"),original:YA(t,"original_image_url")}},P5e=n=>{let t=le(n,"status_info");return{status:YA(t,"status"),canAppeal:YA(t,"can_appeal")==="true"}};var Uf=Je(Lr(),1);import{randomBytes as PH}from"crypto";var rn=null;try{rn=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function kt(n,t,o){this.low=n|0,this.high=t|0,this.unsigned=!!o}kt.prototype.__isLong__;Object.defineProperty(kt.prototype,"__isLong__",{value:!0});function $a(n){return(n&&n.__isLong__)===!0}function dce(n){var t=Math.clz32(n&-n);return n?31-t:t}kt.isLong=$a;var hce={},Ece={};function cp(n,t){var o,i,e;return t?(n>>>=0,(e=0<=n&&n<256)&&(i=Ece[n],i)?i:(o=yt(n,0,!0),e&&(Ece[n]=o),o)):(n|=0,(e=-128<=n&&n<128)&&(i=hce[n],i)?i:(o=yt(n,n<0?-1:0,!1),e&&(hce[n]=o),o))}kt.fromInt=cp;function an(n,t){if(isNaN(n))return t?Wg:Hn;if(t){if(n<0)return Wg;if(n>=fce)return mce}else{if(n<=-uce)return Yi;if(n+1>=uce)return yce}return n<0?an(-n,t).neg():yt(n%hE|0,n/hE|0,t)}kt.fromNumber=an;function yt(n,t,o){return new kt(n,t,o)}kt.fromBits=yt;var zb=Math.pow;function NH(n,t,o){if(n.length===0)throw Error("empty string");if(typeof t=="number"?(o=t,t=!1):t=!!t,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return t?Wg:Hn;if(o=o||10,o<2||360)throw Error("interior hyphen");if(i===0)return NH(n.substring(1),t,o).neg();for(var e=an(zb(o,8)),a=Hn,A=0;A>>0:this.low};Fe.toNumber=function(){return this.unsigned?(this.high>>>0)*hE+(this.low>>>0):this.high*hE+(this.low>>>0)};Fe.toString=function(t){if(t=t||10,t<2||36>>0,c=g.toString(t);if(A=s,A.isZero())return c+r;for(;c.length<6;)c="0"+c;r=""+c+r}};Fe.getHighBits=function(){return this.high};Fe.getHighBitsUnsigned=function(){return this.high>>>0};Fe.getLowBits=function(){return this.low};Fe.getLowBitsUnsigned=function(){return this.low>>>0};Fe.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Yi)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,o=31;o>0&&(t&1<>21;return t?this.unsigned?!1:t===-1&&!(this.low===0&&this.high===-2097152):!0};Fe.isZero=function(){return this.high===0&&this.low===0};Fe.eqz=Fe.isZero;Fe.isNegative=function(){return!this.unsigned&&this.high<0};Fe.isPositive=function(){return this.unsigned||this.high>=0};Fe.isOdd=function(){return(this.low&1)===1};Fe.isEven=function(){return(this.low&1)===0};Fe.equals=function(t){return $a(t)||(t=on(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};Fe.eq=Fe.equals;Fe.notEquals=function(t){return!this.eq(t)};Fe.neq=Fe.notEquals;Fe.ne=Fe.notEquals;Fe.lessThan=function(t){return this.comp(t)<0};Fe.lt=Fe.lessThan;Fe.lessThanOrEqual=function(t){return this.comp(t)<=0};Fe.lte=Fe.lessThanOrEqual;Fe.le=Fe.lessThanOrEqual;Fe.greaterThan=function(t){return this.comp(t)>0};Fe.gt=Fe.greaterThan;Fe.greaterThanOrEqual=function(t){return this.comp(t)>=0};Fe.gte=Fe.greaterThanOrEqual;Fe.ge=Fe.greaterThanOrEqual;Fe.compare=function(t){if($a(t)||(t=on(t)),this.eq(t))return 0;var o=this.isNegative(),i=t.isNegative();return o&&!i?-1:!o&&i?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};Fe.comp=Fe.compare;Fe.negate=function(){return!this.unsigned&&this.eq(Yi)?Yi:this.not().add(dE)};Fe.neg=Fe.negate;Fe.add=function(t){$a(t)||(t=on(t));var o=this.high>>>16,i=this.high&65535,e=this.low>>>16,a=this.low&65535,A=t.high>>>16,r=t.high&65535,s=t.low>>>16,g=t.low&65535,c=0,I=0,d=0,B=0;return B+=a+g,d+=B>>>16,B&=65535,d+=e+s,I+=d>>>16,d&=65535,I+=i+r,c+=I>>>16,I&=65535,c+=o+A,c&=65535,yt(d<<16|B,c<<16|I,this.unsigned)};Fe.subtract=function(t){return $a(t)||(t=on(t)),this.add(t.neg())};Fe.sub=Fe.subtract;Fe.multiply=function(t){if(this.isZero())return this;if($a(t)||(t=on(t)),rn){var o=rn.mul(this.low,this.high,t.low,t.high);return yt(o,rn.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Wg:Hn;if(this.eq(Yi))return t.isOdd()?Yi:Hn;if(t.eq(Yi))return this.isOdd()?Yi:Hn;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Bce)&&t.lt(Bce))return an(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,e=this.high&65535,a=this.low>>>16,A=this.low&65535,r=t.high>>>16,s=t.high&65535,g=t.low>>>16,c=t.low&65535,I=0,d=0,B=0,f=0;return f+=A*c,B+=f>>>16,f&=65535,B+=a*c,d+=B>>>16,B&=65535,B+=A*g,d+=B>>>16,B&=65535,d+=e*c,I+=d>>>16,d&=65535,d+=a*g,I+=d>>>16,d&=65535,d+=A*s,I+=d>>>16,d&=65535,I+=i*c+e*g+a*s+A*r,I&=65535,yt(B<<16|f,I<<16|d,this.unsigned)};Fe.mul=Fe.multiply;Fe.divide=function(t){if($a(t)||(t=on(t)),t.isZero())throw Error("division by zero");if(rn){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var o=(this.unsigned?rn.div_u:rn.div_s)(this.low,this.high,t.low,t.high);return yt(o,rn.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Wg:Hn;var i,e,a;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Wg;if(t.gt(this.shru(1)))return Qce;a=Wg}else{if(this.eq(Yi)){if(t.eq(dE)||t.eq(TH))return Yi;if(t.eq(Yi))return dE;var A=this.shr(1);return i=A.div(t).shl(1),i.eq(Hn)?t.isNegative()?dE:TH:(e=this.sub(t.mul(i)),a=i.add(e.div(t)),a)}else if(t.eq(Yi))return this.unsigned?Wg:Hn;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();a=Hn}for(e=this;e.gte(t);){i=Math.max(1,Math.floor(e.toNumber()/t.toNumber()));for(var r=Math.ceil(Math.log(i)/Math.LN2),s=r<=48?1:zb(2,r-48),g=an(i),c=g.mul(t);c.isNegative()||c.gt(e);)i-=s,g=an(i,this.unsigned),c=g.mul(t);g.isZero()&&(g=dE),a=a.add(g),e=e.sub(c)}return a};Fe.div=Fe.divide;Fe.modulo=function(t){if($a(t)||(t=on(t)),rn){var o=(this.unsigned?rn.rem_u:rn.rem_s)(this.low,this.high,t.low,t.high);return yt(o,rn.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};Fe.mod=Fe.modulo;Fe.rem=Fe.modulo;Fe.not=function(){return yt(~this.low,~this.high,this.unsigned)};Fe.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};Fe.clz=Fe.countLeadingZeros;Fe.countTrailingZeros=function(){return this.low?dce(this.low):dce(this.high)+32};Fe.ctz=Fe.countTrailingZeros;Fe.and=function(t){return $a(t)||(t=on(t)),yt(this.low&t.low,this.high&t.high,this.unsigned)};Fe.or=function(t){return $a(t)||(t=on(t)),yt(this.low|t.low,this.high|t.high,this.unsigned)};Fe.xor=function(t){return $a(t)||(t=on(t)),yt(this.low^t.low,this.high^t.high,this.unsigned)};Fe.shiftLeft=function(t){return $a(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?yt(this.low<>>32-t,this.unsigned):yt(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):yt(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};Fe.shr=Fe.shiftRight;Fe.shiftRightUnsigned=function(t){return $a(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?yt(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?yt(this.high,0,this.unsigned):yt(this.high>>>t-32,0,this.unsigned)};Fe.shru=Fe.shiftRightUnsigned;Fe.shr_u=Fe.shiftRightUnsigned;Fe.rotateLeft=function(t){var o;return $a(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?yt(this.high,this.low,this.unsigned):t<32?(o=32-t,yt(this.low<>>o,this.high<>>o,this.unsigned)):(t-=32,o=32-t,yt(this.high<>>o,this.low<>>o,this.unsigned))};Fe.rotl=Fe.rotateLeft;Fe.rotateRight=function(t){var o;return $a(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?yt(this.high,this.low,this.unsigned):t<32?(o=32-t,yt(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,o=32-t,yt(this.low<>>t,this.high<>>t,this.unsigned))};Fe.rotr=Fe.rotateRight;Fe.toSigned=function(){return this.unsigned?yt(this.low,this.high,!1):this};Fe.toUnsigned=function(){return this.unsigned?this:yt(this.low,this.high,!0)};Fe.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};Fe.toBytesLE=function(){var t=this.high,o=this.low;return[o&255,o>>>8&255,o>>>16&255,o>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};Fe.toBytesBE=function(){var t=this.high,o=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,o>>>24,o>>>16&255,o>>>8&255,o&255]};kt.fromBytes=function(t,o,i){return i?kt.fromBytesLE(t,o):kt.fromBytesBE(t,o)};kt.fromBytesLE=function(t,o){return new kt(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,o)};kt.fromBytesBE=function(t,o){return new kt(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],o)};typeof BigInt=="function"&&(kt.fromBigInt=function(t,o){var i=Number(BigInt.asIntN(32,t)),e=Number(BigInt.asIntN(32,t>>BigInt(32)));return yt(i,e,o)},kt.fromValue=function(t,o){return typeof t=="bigint"?kt.fromBigInt(t,o):on(t,o)},Fe.toBigInt=function(){var t=BigInt(this.low>>>0),o=BigInt(this.unsigned?this.high>>>0:this.high);return o<{let n=new Jg;return{mutex(t){return n.runExclusive(t)}}},Sce=()=>{let n=new Map;return{async mutex(t,o){let i=n.get(t);i||(i={mutex:new Jg,refCount:0},n.set(t,i)),i.refCount++;try{return await i.mutex.runExclusive(o)}finally{i.refCount--,i.refCount===0&&n.get(t)===i&&n.delete(t)}}}};function wce(n,t,o=10){let i=[],e=!1;return{enqueue:(A,r)=>{if(i.push({type:A,node:r}),e)return;e=!0,(async()=>{let g=0;for(;i.length&&t.isWsOpen();){let{type:c,node:I}=i.shift(),d=n.get(c);if(!d){t.onUnexpectedError(new Error(`unknown offline node type: ${c}`),"processing offline node");continue}await d(I).catch(B=>t.onUnexpectedError(B,`processing offline ${c}`)),g++,g>=o&&(g=0,await t.yieldToEventLoop())}e=!1})().catch(g=>t.onUnexpectedError(g,"processing offline nodes"))}}}var iM=Je(Lr(),1);var CI=Je(Lr(),1);var Vb=class{constructor(){this.name="devices"}getQueryElement(){return{tag:"devices",attrs:{version:"2"}}}getUserElement(){return null}parser(t){let o=[],i;if(t.tag==="devices"){Li(t);let e=le(t,"device-list"),a=le(t,"key-index-list");if(Array.isArray(e?.content))for(let{tag:A,attrs:r}of e.content){let s=+r.id,g=+r["key-index"];A==="device"&&o.push({id:s,keyIndex:g,isHosted:!!(r.is_hosted&&r.is_hosted==="true")})}a?.tag==="key-index-list"&&(i={timestamp:+a.attrs.ts,signedKeyIndex:a?.content,expectedTimestamp:a.attrs.expected_ts?+a.attrs.expected_ts:void 0})}return{deviceList:o,keyIndex:i}}};var Vs=class{withId(t){return this.id=t,this}withLid(t){return this.lid=t,this}withPhone(t){return this.phone=t,this}withUsername(t){return this.username=t,this}withUsernameKey(t){return this.usernameKey=t,this}withType(t){return this.type=t,this}withPersonaId(t){return this.personaId=t,this}};var Wb=class{constructor(){this.name="contact"}getQueryElement(){return{tag:"contact",attrs:{}}}getUserElement(t){return t.phone?{tag:"contact",attrs:{},content:t.phone}:t.username?{tag:"contact",attrs:{username:t.username,...t.usernameKey?{pin:t.usernameKey}:{},...t.lid?{lid:t.lid}:{}}}:t.type?{tag:"contact",attrs:{type:t.type}}:{tag:"contact",attrs:{}}}parser(t){return t.tag==="contact"?(Li(t),t?.attrs?.type==="in"):!1}};var Zb=class{constructor(){this.name="status"}getQueryElement(){return{tag:"status",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="status"){Li(t);let o=t?.content?.toString()??null,i=new Date(+(t?.attrs.t||0)*1e3);return o?typeof o=="string"&&o.length===0&&(o=null):t.attrs?.code&&+t.attrs.code==401?o="":o=null,{status:o,setAt:i}}}};var Xb=class{constructor(){this.name="disappearing_mode"}getQueryElement(){return{tag:"disappearing_mode",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="disappearing_mode"){Li(t);let o=+t?.attrs.duration,i=new Date(+(t?.attrs.t||0)*1e3);return{duration:o,setAt:i}}}};var $b=class{constructor(){this.name="username"}getQueryElement(){return{tag:"username",attrs:{}}}getUserElement(t){return null}parser(t){return t.tag==="username"?(Li(t),typeof t.content=="string"?t.content:null):null}};var eM=class{constructor(){this.name="bot"}getQueryElement(){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{v:"1"}}]}}getUserElement(t){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{persona_id:t.personaId}}]}}parser(t){let o=le(t,"bot"),i=le(o,"profile"),e=le(i,"commands"),a=le(i,"prompts"),A=[],r=[];for(let s of kA(e,"command"))A.push({name:YA(s,"name"),description:YA(s,"description")});for(let s of kA(a,"prompt"))r.push(`${YA(s,"emoji")} ${YA(s,"text")}`);return{isDefault:!!le(i,"default"),jid:t.attrs.jid,name:YA(i,"name"),attributes:YA(i,"attributes"),description:YA(i,"description"),category:YA(i,"category"),personaId:i.attrs.persona_id,commandsDescription:YA(e,"description"),commands:A,prompts:r}}};var AM=class{constructor(){this.name="lid"}getQueryElement(){return{tag:"lid",attrs:{}}}getUserElement(t){return t.lid?{tag:"lid",attrs:{jid:t.lid}}:null}parser(t){return t.tag==="lid"?t.attrs.val:null}};var Ws=class{constructor(){this.protocols=[],this.users=[],this.context="interactive",this.mode="query"}withMode(t){return this.mode=t,this}withContext(t){return this.context=t,this}withUser(t){return this.users.push(t),this}parseUSyncQueryResult(t){if(t?.attrs.type!=="result")return;let o=Object.fromEntries(this.protocols.map(A=>[A.name,A.parser])),i={list:[],sideList:[]},e=le(t,"usync"),a=e?le(e,"list"):void 0;return a?.content&&Array.isArray(a.content)&&(i.list=a.content.reduce((A,r)=>{let s=r?.attrs.jid;if(s){let g=Array.isArray(r?.content)?Object.fromEntries(r.content.map(c=>{let I=c.tag,d=o[I];return d?[I,d(c)]:[I,null]}).filter(([,c])=>c!==null)):{};A.push({...g,id:s})}return A},[])),i}withDeviceProtocol(){return this.protocols.push(new Vb),this}withContactProtocol(){return this.protocols.push(new Wb),this}withStatusProtocol(){return this.protocols.push(new Zb),this}withDisappearingModeProtocol(){return this.protocols.push(new Xb),this}withBotProfileProtocol(){return this.protocols.push(new eM),this}withLIDProtocol(){return this.protocols.push(new AM),this}withUsernameProtocol(){return this.protocols.push(new $b),this}};var qr=Je(Lr(),1);import{randomBytes as kH}from"crypto";import{URL as U5e}from"url";import{promisify as H5e}from"util";var tM=class{constructor(t={}){this.protocolVersion=5,this.sequence=0,this.events=[],this.buffer=[],Object.assign(this,t)}};import{EventEmitter as F5e}from"events";var rM=class extends F5e{constructor(t,o){super(),this.url=t,this.config=o,this.setMaxListeners(0)}};var aM=class extends rM{constructor(){super(...arguments),this.socket=null}get isOpen(){return this.socket?.readyState===Ro.OPEN}get isClosed(){return this.socket===null||this.socket?.readyState===Ro.CLOSED}get isClosing(){return this.socket===null||this.socket?.readyState===Ro.CLOSING}get isConnecting(){return this.socket?.readyState===Ro.CONNECTING}connect(){if(this.socket)return;this.socket=new Ro(this.url,{origin:uf,headers:this.config.options?.headers,handshakeTimeout:this.config.connectTimeoutMs,timeout:this.config.connectTimeoutMs,agent:this.config.agent}),this.socket.setMaxListeners(0);let t=["close","error","upgrade","message","open","ping","pong","unexpected-response"];for(let o of t)this.socket?.on(o,(...i)=>this.emit(o,...i))}async close(){if(!this.socket)return;let t=new Promise(o=>{this.socket?.once("close",o)});this.socket.close(),await t,this.socket=null}send(t,o){return this.socket?.send(t,o),!!this.socket}};var RH=Je(Lr(),1);var L5e=(n,t,o,i)=>o({tag:"iq",attrs:{id:i(),type:"get",to:OA,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:t},content:Buffer.from(JSON.stringify({variables:n}),"utf-8")}]}),Lf=async(n,t,o,i,e)=>{let a=await L5e(n,t,i,e),A=le(a,"result");if(A?.content){let s=JSON.parse(A.content.toString());if(s.errors&&s.errors.length>0){let c=s.errors.map(B=>B.message||"Unknown error").join(", "),I=s.errors[0],d=I.extensions?.error_code||400;throw new RH.Boom(`GraphQL server error: ${c}`,{statusCode:d,data:I})}let g=o?s?.data?.[o]:s?.data;if(typeof g<"u")return g}let r=(o||"").startsWith("xwa2_")?o.substring(5).replace(/_/g," "):o?.replace(/_/g," ");throw new RH.Boom(`Failed to ${r}, unexpected response structure.`,{statusCode:400,data:a})};var Dce=n=>{let{waWebSocketUrl:t,connectTimeoutMs:o,logger:i,keepAliveIntervalMs:e,browser:a,auth:A,printQRInTerminal:r,defaultQueryTimeoutMs:s,transactionOpts:g,qrTimeout:c,makeSignalRepository:I}=n,d=new tM,B=0,f=S7(),Q=()=>`${f}${fe++}`;r&&i.warn({},"\u26A0\uFE0F The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version."),a[1].toLocaleLowerCase().includes("android")&&i.warn("\u26A0\uFE0F Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk."),Pf.map(pe=>n.shouldSyncHistoryMessage({syncType:pe})).filter(pe=>pe===!1).length===Pf.length&&i.warn("\u26A0\uFE0F DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS");let m=typeof t=="string"?new U5e(t):t;if(n.mobile||m.protocol==="tcp:")throw new qr.Boom("Mobile API is not supported anymore",{statusCode:$t.loggedOut});m.protocol==="wss"&&A?.creds?.routingInfo&&m.searchParams.append("ED",A.creds.routingInfo.toString("base64url"));let _=Br.generateKeyPair(),T=qoe({keyPair:_,NOISE_HEADER:ice,logger:i,routingInfo:A?.creds?.routingInfo}),R=new aM(m,n);R.connect();let F=H5e(R.send),K=async pe=>{if(!R.isOpen)throw new qr.Boom("Connection Closed",{statusCode:$t.connectionClosed});let Ie=T.encodeFrame(pe);await Ih(o,async(be,oA)=>{try{await F.call(R,Ie),be()}catch(pA){oA(pA)}})},L=pe=>{i.level==="trace"&&i.trace({xml:_n(pe),msg:"xml send"});let Ie=KX(pe);return K(Ie)},q=async(pe,Ie=s)=>{let be,oA;try{return await Ih(Ie,(PA,Ht)=>(be=st=>{PA(st)},oA=st=>{Ht(st||new qr.Boom("Connection Closed",{statusCode:$t.connectionClosed}))},R.on(`TAG:${pe}`,be),R.on("close",oA),R.on("error",oA),()=>Ht(new qr.Boom("Query Cancelled"))))}catch(pA){if(pA instanceof qr.Boom&&pA.output?.statusCode===$t.timedOut){i?.warn?.({msgId:pe},"timed out waiting for message");return}throw pA}finally{be&&R.off(`TAG:${pe}`,be),oA&&(R.off("close",oA),R.off("error",oA))}},z=async(pe,Ie)=>{pe.attrs.id||(pe.attrs.id=Q());let be=pe.attrs.id,oA=await Ih(Ie,async(pA,PA)=>{let Ht=q(be,Ie).catch(PA);L(pe).then(async()=>pA(await Ht)).catch(PA)});return oA&&"tag"in oA&&Li(oA),oA},j=async()=>{let pe=await z({tag:"iq",attrs:{to:OA,type:"get",xmlns:"encrypt"},content:[{tag:"digest",attrs:{}}]});if(!le(pe,"digest"))throw await We(),new Error("encrypt/get digest returned no digest node")},P=async()=>{let pe=(V.signedPreKey.keyId||0)+1,Ie=await aD(V.signedIdentityKey,pe);await z({tag:"iq",attrs:{to:OA,type:"set",xmlns:"encrypt"},content:[{tag:"rotate",attrs:{},content:[yf(Ie)]}]}),k.emit("creds.update",{signedPreKey:Ie})},J=async pe=>{if(pe.protocols.length===0)throw new qr.Boom("USyncQuery must have at least one protocol");let be=pe.users.map(st=>({tag:"user",attrs:{jid:st.phone?void 0:st.id},content:pe.protocols.map(Qr=>Qr.getUserElement(st)).filter(Qr=>Qr!==null)})),oA={tag:"list",attrs:{},content:be},pA={tag:"query",attrs:{},content:pe.protocols.map(st=>st.getQueryElement())},PA={tag:"iq",attrs:{to:OA,type:"get",xmlns:"usync"},content:[{tag:"usync",attrs:{context:pe.context,mode:pe.mode,sid:Q(),last:"true",index:"0"},content:[pA,oA]}]},Ht=await z(PA);return pe.parseUSyncQueryResult(Ht)},U=async(...pe)=>{let Ie=new Ws,be=!1;for(let pA of pe)if(qA(pA)){i?.warn("LIDs are not supported with onWhatsApp");continue}else{be||(be=!0,Ie=Ie.withContactProtocol());let PA=`+${pA.replace("+","").split("@")[0]?.split(":")[0]}`;Ie.withUser(new Vs().withPhone(PA))}if(Ie.users.length===0)return[];let oA=await J(Ie);if(oA)return oA.list.filter(pA=>!!pA.contact).map(({contact:pA,id:PA})=>({jid:PA,exists:pA}))},N=async pe=>{let Ie=new Ws().withLIDProtocol().withContext("background");for(let oA of pe)if(qA(oA)){i?.warn("LID user found in LID fetch call");continue}else Ie.withUser(new Vs().withId(oA));if(Ie.users.length===0)return[];let be=await J(Ie);return be?be.list.filter(oA=>!!oA.lid).map(({lid:oA,id:pA})=>({pn:pA,lid:oA})):[]},k=bne(i),{creds:V}=A,Ae=Bne(A.keys,i,g),ie=I({creds:V,keys:Ae},i,N),De,fe=1,_e,Ee,Qe=!1,Le=[],AA=(pe,Ie)=>{i.error({err:pe},`unexpected error in '${Ie}'`)},aA=async pe=>{if(!R.isOpen)throw new qr.Boom("Connection Closed",{statusCode:$t.connectionClosed});let Ie,be,oA=Ih(o,(pA,PA)=>{Ie=pA,be=vH(PA),R.on("frame",Ie),R.on("close",be),R.on("error",be)}).finally(()=>{R.off("frame",Ie),R.off("close",be),R.off("error",be)});return pe&&K(pe).catch(be),oA},He=async()=>{let pe={clientHello:{ephemeral:_.public}};pe=oe.HandshakeMessage.fromObject(pe),i.info({browser:a,helloMsg:pe},"connected to WA");let Ie=oe.HandshakeMessage.encode(pe).finish(),be=await aA(Ie),oA=oe.HandshakeMessage.decode(be);i.trace({handshake:oA},"handshake recv from WA");let pA=T.processHandshake(oA,V.noiseKey),PA;V.me?(PA=Loe(V.me.id,n),i.info({node:PA},"logging in...")):(PA=Uoe(V,n),i.info({node:PA},"not logged in, attempting registration..."));let Ht=T.encrypt(oe.ClientPayload.encode(PA).finish());await K(oe.HandshakeMessage.encode({clientFinish:{static:pA,payload:Ht}}).finish()),await T.finishInit(),WA()},ce=async()=>{let pe=await z({tag:"iq",attrs:{id:Q(),xmlns:"encrypt",type:"get",to:OA},content:[{tag:"count",attrs:{}}]});return+le(pe,"count").attrs.value},Be=null,We=async(pe=Gf)=>{if(Be){i.debug("Pre-key upload already in progress, waiting for completion"),await Be;return}let Ie=async be=>{i.info({count:pe,retryCount:be},"uploading pre-keys");let oA=await Ae.transaction(async()=>{i.debug({requestedCount:pe},"generating pre-keys with requested count");let{update:pA,node:PA}=await Poe({creds:V,keys:Ae},pe);return k.emit("creds.update",pA),PA},V?.me?.id||"upload-pre-keys");try{await z(oA),i.info({count:pe},"uploaded pre-keys successfully")}catch(pA){if(i.error({uploadError:pA.toString(),count:pe},"Failed to upload pre-keys to server"),be<3){let PA=Math.min(1e3*Math.pow(2,be),1e4);return i.info(`Retrying pre-key upload in ${PA}ms`),await new Promise(Ht=>setTimeout(Ht,PA)),Ie(be+1)}throw pA}};Be=Promise.race([Ie(0),new Promise((be,oA)=>setTimeout(()=>oA(new qr.Boom("Pre-key upload timeout",{statusCode:408})),gce))]);try{await Be}finally{Be=null}},Ye=async()=>{let pe=V.nextPreKeyId-1;return pe<=0?{exists:!1,currentPreKeyId:0}:{exists:!!(await Ae.get("pre-key",[pe.toString()]))[pe.toString()],currentPreKeyId:pe}},Re=async()=>{try{let pe=0,Ie=await ce();Ie===0?pe=sce:pe=Gf;let{exists:be,currentPreKeyId:oA}=await Ye();i.info(`${Ie} pre-keys found on server`),i.info(`Current prekey ID: ${oA}, exists in storage: ${be}`);let pA=Ie<=pe,PA=!be&&oA>0;if(pA||PA){let st=[];pA&&st.push(`server count low (${Ie})`),PA&&st.push(`current prekey ${oA} missing from storage`),i.info(`Uploading PreKeys due to: ${st.join(", ")}`),await We(pe)}else i.info(`PreKey validation passed - Server: ${Ie}, Current prekey ${oA} exists`)}catch(pe){i.error({error:pe},"Failed to check/upload pre-keys during initialization")}},Ze=async pe=>{await T.decodeFrame(pe,Ie=>{De=new Date;let be=!1;if(be=R.emit("frame",Ie),!(Ie instanceof Uint8Array)){let oA=Ie.attrs.id;i.level==="trace"&&i.trace({xml:_n(Ie),msg:"recv xml"}),be=R.emit(`${tce}${oA}`,Ie)||be;let pA=Ie.tag,PA=Ie.attrs||{},Ht=Array.isArray(Ie.content)?Ie.content[0]?.tag:"";for(let st of Object.keys(PA))be=R.emit(`${pE}${pA},${st}:${PA[st]},${Ht}`,Ie)||be,be=R.emit(`${pE}${pA},${st}:${PA[st]}`,Ie)||be,be=R.emit(`${pE}${pA},${st}`,Ie)||be;be=R.emit(`${pE}${pA},,${Ht}`,Ie)||be,be=R.emit(`${pE}${pA}`,Ie)||be,!be&&i.level==="debug"&&i.debug({unhandled:!0,msgId:oA,fromMe:!1,frame:Ie},"communication recv")}})},iA=async pe=>{if(Qe){i.trace({trace:pe?.stack},"connection already closed");return}if(Qe=!0,i.info({trace:pe?.stack},pe?"connection errored":"connection closed"),clearInterval(_e),clearTimeout(Ee),R.removeAllListeners("close"),R.removeAllListeners("open"),R.removeAllListeners("message"),ie.close?.(),!R.isClosed&&!R.isClosing)try{await R.close()}catch{}for(let Ie of Le)try{await Ie(pe)}catch(be){i.error({err:be},"error in socket end handler")}k.emit("connection.update",{connection:"close",lastDisconnect:{error:pe,date:new Date}}),k.removeAllListeners("connection.update"),k.destroy()},gA=async()=>{if(R.isOpen)return;if(R.isClosed||R.isClosing)throw new qr.Boom("Connection Closed",{statusCode:$t.connectionClosed});let pe,Ie;await new Promise((be,oA)=>{pe=()=>be(void 0),Ie=vH(oA),R.on("open",pe),R.on("close",Ie),R.on("error",Ie)}).finally(()=>{R.off("open",pe),R.off("close",Ie),R.off("error",Ie)})},WA=()=>_e=setInterval(()=>{De||(De=new Date),Date.now()-De.getTime()>e+5e3?iA(new qr.Boom("Connection was lost",{statusCode:$t.connectionLost})):R.isOpen?z({tag:"iq",attrs:{id:Q(),to:OA,type:"get",xmlns:"w:p"},content:[{tag:"ping",attrs:{}}]}).catch(Ie=>{i.error({trace:Ie.stack},"error in sending keep alive")}):i.warn("keep alive called when WS not open")},e),FA=pe=>z({tag:"iq",attrs:{to:OA,xmlns:"passive",type:"set"},content:[{tag:pe,attrs:{}}]}),Me=async pe=>{let Ie=A.creds.me?.id;Ie&&await L({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"remove-companion-device",attrs:{jid:Ie,reason:"user_initiated"}}]}),iA(new qr.Boom(pe||"Intentional Logout",{statusCode:$t.loggedOut}))},CA=async(pe,Ie)=>{let be=Ie??M7(kH(5));if(Ie&&Ie?.length!==8)throw new Error("Custom pairing code must be exactly 8 chars");return A.creds.pairingCode=be,A.creds.me={id:Cr(pe,"s.whatsapp.net"),name:"~"},k.emit("creds.update",A.creds),await L({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:A.creds.me.id,stage:"companion_hello",should_show_push_notification:"true"},content:[{tag:"link_code_pairing_wrapped_companion_ephemeral_pub",attrs:{},content:await we()},{tag:"companion_server_auth_key_pub",attrs:{},content:A.creds.noiseKey.public},{tag:"companion_platform_id",attrs:{},content:TU(a)},{tag:"companion_platform_display",attrs:{},content:`${a[1]} (${a[0]})`},{tag:"link_code_pairing_nonce",attrs:{},content:"0"}]}]}),A.creds.pairingCode};async function we(){let pe=kH(32),Ie=kH(16),be=await iD(A.creds.pairingCode,pe),oA=l7(A.creds.pairingEphemeralKeyPair.public,be,Ie);return Buffer.concat([pe,Ie,oA])}let Ke=pe=>z({tag:"iq",attrs:{to:OA,id:Q(),xmlns:"w:stats"},content:[{tag:"add",attrs:{t:Math.round(Date.now()/1e3)+""},content:pe}]});R.on("message",Ze),R.on("open",async()=>{try{await He()}catch(pe){i.error({err:pe},"error in validating connection"),iA(pe)}}),R.on("error",vH(iA)),R.on("close",()=>void iA(new qr.Boom("Connection Terminated",{statusCode:$t.connectionClosed}))),R.on("CB:xmlstreamend",()=>void iA(new qr.Boom("Connection Terminated by Server",{statusCode:$t.connectionClosed}))),R.on("CB:iq,type:set,pair-device",async pe=>{let Ie={tag:"iq",attrs:{to:OA,type:"result",id:pe.attrs.id}};await L(Ie);let be=le(pe,"pair-device"),oA=kA(be,"ref"),pA=Buffer.from(V.noiseKey.public).toString("base64"),PA=Buffer.from(V.signedIdentityKey.public).toString("base64"),Ht=V.advSecretKey,st=c||6e4,Qr=()=>{if(!R.isOpen)return;let tr=oA.shift();if(!tr){iA(new qr.Boom("QR refs attempts ended",{statusCode:$t.timedOut}));return}let lo=tr.content.toString("utf-8"),ji=Tne(lo,pA,PA,Ht,a);k.emit("connection.update",{qr:ji}),Ee=setTimeout(Qr,st),st=c||2e4};Qr()}),R.on("CB:iq,,pair-success",async pe=>{i.debug("pair success recv");try{NA(pe);let{reply:Ie,creds:be}=Hoe(pe,V);i.info({me:be.me,platform:be.platform},"pairing configured successfully, expect to restart the connection..."),k.emit("creds.update",be),k.emit("connection.update",{isNewLogin:!0,qr:void 0}),await L(Ie),LA()}catch(Ie){i.info({trace:Ie.stack},"error in pairing"),iA(Ie)}}),R.on("CB:success",async pe=>{try{NA(pe),await Re(),await FA("active");try{await j()}catch(Ie){i.warn({e:Ie},"failed to run digest after login")}}catch(Ie){i.warn({err:Ie},"failed to send initial passive iq")}if(i.info("opened connection to WA"),clearTimeout(Ee),k.emit("creds.update",{me:{...A.creds.me,lid:pe.attrs.lid}}),k.emit("connection.update",{connection:"open"}),LA(),pe.attrs.lid&&A.creds.me?.id){let Ie=pe.attrs.lid;process.nextTick(async()=>{try{let be=A.creds.me.id;await ie.lidMapping.storeLIDPNMappings([{lid:Ie,pn:be}]);let{user:oA,device:pA}=yA(be);await A.keys.set({"device-list":{[oA]:[pA?.toString()||"0"]}}),await ie.migrateSession(be,Ie),i.info({myPN:be,myLID:Ie},"Own LID session created successfully")}catch(be){i.error({error:be,lid:Ie},"Failed to create own LID session")}})}}),R.on("CB:stream:error",pe=>{let[Ie]=ys(pe);i.error({reasonNode:Ie,fullErrorNode:pe},"stream errored out");let{reason:be,statusCode:oA}=D7(pe);iA(new qr.Boom(`Stream Errored (${be})`,{statusCode:oA,data:Ie||pe}))}),R.on("CB:failure",pe=>{let Ie=+(pe.attrs.reason||500);iA(new qr.Boom("Connection Failure",{statusCode:Ie,data:pe.attrs}))}),R.on("CB:ib,,downgrade_webclient",()=>{iA(new qr.Boom("Multi-device beta not joined",{statusCode:$t.multideviceMismatch}))}),R.on("CB:ib,,offline_preview",async pe=>{i.info("offline preview received",JSON.stringify(pe)),await L({tag:"ib",attrs:{},content:[{tag:"offline_batch",attrs:{count:"100"}}]})}),R.on("CB:ib,,edge_routing",pe=>{let Ie=le(pe,"edge_routing"),be=le(Ie,"routing_info");be?.content&&(A.creds.routingInfo=Buffer.from(be?.content),k.emit("creds.update",A.creds))});let Ve=!1;process.nextTick(()=>{V.me?.id&&(k.buffer(),Ve=!0),k.emit("connection.update",{connection:"connecting",receivedPendingNotifications:!1,qr:void 0})}),R.on("CB:ib,,offline",pe=>{let be=+(le(pe,"offline")?.attrs.count||0);i.info(`handled ${be} offline messages/notifications`),Ve&&(k.flush(),i.trace("flushed events for initial buffer")),k.emit("connection.update",{receivedPendingNotifications:!0})}),k.on("creds.update",pe=>{let Ie=pe.me?.name;V.me?.name!==Ie&&(i.debug({name:Ie},"updated pushName"),L({tag:"presence",attrs:{name:Ie}}).catch(be=>{i.warn({trace:be.stack},"error in sending presence update on name change")})),Object.assign(V,pe)});let NA=({attrs:pe})=>{let Ie=pe?.t;if(!Ie)return;let be=Number(Ie);if(Number.isNaN(be)||be<=0)return;let oA=Date.now();B=be*1e3-oA,i.debug({offset:B},"calculated server time offset")},wA=()=>{let pe=3*bH.Day;return((Date.now()+B+pe)%bH.Week).toString()},LA=async()=>{if(!R.isOpen)return;let pe={tag:"ib",attrs:{},content:[{tag:"unified_session",attrs:{id:wA()}}]};try{await L(pe)}catch(Ie){i.debug({error:Ie},"failed to send unified_session telemetry")}},JA=pe=>{Le.push(pe)},lt=async()=>{let pe=await Lf({},sa.REACHOUT_TIMELOCK,fa.xwa2_fetch_account_reachout_timelock,z,Q),Ie={isActive:!!pe?.is_active,timeEnforcementEnds:pe?.time_enforcement_ends&&pe?.time_enforcement_ends!=="0"?new Date(parseInt(pe.time_enforcement_ends,10)*1e3):void 0,enforcementType:pe?.enforcement_type??Hc.DEFAULT};return k.emit("connection.update",{reachoutTimeLock:Ie}),Ie},wt=async()=>Lf({input:{type:"INDIVIDUAL_NEW_CHAT_MSG"}},sa.MESSAGE_CAPPING_INFO,fa.xwa2_message_capping_info,z,Q);return{type:"md",ws:R,ev:k,authState:{creds:V,keys:Ae},signalRepository:ie,get user(){return A.creds.me},generateMessageTag:Q,query:z,waitForMessage:q,waitForSocketOpen:gA,sendRawMessage:K,sendNode:L,logout:Me,end:iA,registerSocketEndHandler:JA,onUnexpectedError:AA,uploadPreKeys:We,uploadPreKeysToServerIfRequired:Re,digestKeyBundle:j,rotateSignedPreKey:P,requestPairingCode:CA,updateServerTimeOffset:NA,sendUnifiedSession:LA,wamBuffer:d,waitForConnectionUpdate:m7(k),sendWAMBuffer:Ke,executeUSyncQuery:J,onWhatsApp:U,fetchAccountReachoutTimelock:lt,fetchNewChatMessageCap:wt}};function vH(n){return t=>{n(new qr.Boom(`WebSocket Error (${t?.message})`,{statusCode:b7(t),data:t}))}}var K5e=(n,t)=>{let o={tag:"picture",attrs:{type:n,query:"url"}};return t?.length&&(o.content=t),[o]},Oce=n=>{let{logger:t,markOnlineOnConnect:o,fireInitQueries:i,appStateMacVerification:e,shouldIgnoreJid:a,shouldSyncHistoryMessage:A,getMessage:r}=n,s=Dce(n),{ev:g,ws:c,authState:I,generateMessageTag:d,sendNode:B,query:f,signalRepository:Q,onUnexpectedError:y,sendUnifiedSession:m,registerSocketEndHandler:_}=s,T=Q.lidMapping.getLIDForPN.bind(Q.lidMapping),R,F={privacyTokenOn1to1:!0,profilePicPrivacyToken:!0,lidTrustedTokenIssueToLid:!1},K=na.Connecting,L=Zg(),q=Zg(),z=Zg(),j=Zg(),P,J={initialBootstrapComplete:!1,recentSyncComplete:!1},U,N=new Set,k=n.placeholderResendCache||new jg({stdTTL:dI.MSG_RETRY,useClones:!1}),V=async W=>{let{[W]:X}=await I.keys.get("app-state-sync-key",[W]);return X},Ae=async(W=!1)=>{if(!R||W){let{content:X}=await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"get"},content:[{tag:"privacy",attrs:{}}]});R=fF(X?.[0],"category")}return R},ie=async(W,X)=>{await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"set"},content:[{tag:"privacy",attrs:{},content:[{tag:"category",attrs:{name:W,value:X}}]}]})},De=async W=>{await ie("messages",W)},fe=async W=>{await ie("calladd",W)},_e=async W=>{await ie("last",W)},Ee=async W=>{await ie("online",W)},Qe=async W=>{await ie("profile",W)},Le=async W=>{await ie("status",W)},AA=async W=>{await ie("readreceipts",W)},aA=async W=>{await ie("groupadd",W)},He=async W=>{await f({tag:"iq",attrs:{xmlns:"disappearing_mode",to:OA,type:"set"},content:[{tag:"disappearing_mode",attrs:{duration:W.toString()}}]})},ce=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"bot",to:OA,type:"get"},content:[{tag:"bot",attrs:{v:"2"}}]}),X=le(W,"bot"),re=[];for(let ne of kA(X,"section"))if(ne.attrs.type==="all")for(let Oe of kA(ne,"bot"))re.push({jid:Oe.attrs.jid,personaId:Oe.attrs.persona_id});return re},Be=async(...W)=>{let X=new Ws().withStatusProtocol();for(let ne of W)X.withUser(new Vs().withId(ne));let re=await s.executeUSyncQuery(X);if(re)return re.list},We=async(...W)=>{let X=new Ws().withDisappearingModeProtocol();for(let ne of W)X.withUser(new Vs().withId(ne));let re=await s.executeUSyncQuery(X);if(re)return re.list},Ye=async(W,X,re)=>{let ne;if(!W)throw new CI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");uA(W)!==uA(I.creds.me.id)?ne=uA(W):ne=void 0;let{img:Oe}=await cb(X,re);await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...ne?{target:ne}:{}},content:[{tag:"picture",attrs:{type:"image"},content:Oe}]})},Re=async W=>{let X;if(!W)throw new CI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");uA(W)!==uA(I.creds.me.id)?X=uA(W):X=void 0,await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...X?{target:X}:{}}})},Ze=async W=>{await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"status"},content:[{tag:"status",attrs:{},content:Buffer.from(W,"utf-8")}]})},iA=async W=>{await wt({pushNameSetting:W},"")},gA=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"get"}}),X=le(W,"list");return kA(X,"item").map(re=>re.attrs.jid)},WA=async(W,X)=>{let re=uA(W),ne,Oe;if(qA(re)||ga(re)){if(ne=re,X==="block"){let he=await Q.lidMapping.getPNForLID(re);if(!he)throw new CI.Boom(`Unable to resolve PN JID for LID: ${W}`,{statusCode:400});Oe=uA(he)}}else if(_t(re)||ur(re)){let he=await Q.lidMapping.getLIDForPN(re);if(!he)throw new CI.Boom(`Unable to resolve LID for PN JID: ${W}`,{statusCode:400});ne=he,X==="block"&&(Oe=uA(re))}else throw new CI.Boom(`Invalid jid: ${W}`,{statusCode:400});let Ce={action:X,jid:ne};if(X==="block"){if(!Oe)throw new CI.Boom(`pn_jid required for block: ${W}`,{statusCode:400});Ce.pn_jid=Oe}await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"set"},content:[{tag:"item",attrs:Ce}]})},FA=async W=>{let X=await f({tag:"iq",attrs:{to:"s.whatsapp.net",xmlns:"w:biz",type:"get"},content:[{tag:"business_profile",attrs:{v:"244"},content:[{tag:"profile",attrs:{jid:W}}]}]}),re=le(X,"business_profile"),ne=le(re,"profile");if(ne){let Oe=le(ne,"address"),Ce=le(ne,"description"),he=le(ne,"website"),me=le(ne,"email"),je=le(le(ne,"categories"),"category"),lA=le(ne,"business_hours"),QA=lA?kA(lA,"business_hours_config"):void 0,$A=he?.content?.toString();return{wid:ne.attrs?.jid,address:Oe?.content?.toString(),description:Ce?.content?.toString()||"",website:$A?[$A]:[],email:me?.content?.toString(),category:je?.content?.toString(),business_hours:{timezone:lA?.attrs?.timezone,business_config:QA?.map(({attrs:RA})=>RA)}}}},Me=async(W,X)=>{t.info({fromTimestamp:X},"clean dirty bits "+W),await B({tag:"iq",attrs:{to:OA,type:"set",xmlns:"urn:xmpp:whatsapp:dirty",id:d()},content:[{tag:"clean",attrs:{type:W,...X?{timestamp:X.toString()}:null}}]})},CA=W=>({onMutation(X){cne(X,g,I.creds.me,W?{accountSettings:I.creds.accountSettings}:void 0,t)}}),we=g.createBufferedFunction(async(W,X)=>{let re=new Map,ne=async me=>{if(re.has(me))return re.get(me)??void 0;let je=await V(me);return re.set(me,je??null),je},Oe={},Ce={};await I.keys.transaction(async()=>{let me=new Set(W),je={},lA=new Set;for(;me.size;){let QA={},$A=[];for(let et of me){let tA=(await I.keys.get("app-state-sync-version",[et]))[et];tA?(tA=oU(tA),typeof Oe[et]>"u"&&(Oe[et]=tA.version)):tA=Eb(),QA[et]=tA;let At=lA.has(et);At&&lA.delete(et),t.info(`resyncing ${et} from v${tA.version}${At?" (forcing snapshot)":""}`),$A.push({tag:"collection",attrs:{name:et,version:tA.version.toString(),return_snapshot:(At||!tA.version).toString()}})}let RA=await f({tag:"iq",attrs:{to:OA,xmlns:"w:sync:app:state",type:"set"},content:[{tag:"sync",attrs:{},content:$A}]}),xA=await one(RA,n?.options);for(let et in xA){let ve=et,{patches:tA,hasMorePatches:At,snapshot:zr}=xA[ve];try{if(zr){let{state:rr,mutationMap:po}=await sne(ve,zr,ne,Oe[ve],e.snapshot,t);QA[ve]=rr,Object.assign(Ce,po),t.info(`restored state of ${ve} from snapshot to v${rr.version} with mutations`),await I.keys.set({"app-state-sync-version":{[ve]:rr}})}if(tA.length){let{state:rr,mutationMap:po}=await sU(ve,tA,QA[ve],ne,n.options,Oe[ve],t,e.patch);await I.keys.set({"app-state-sync-version":{[ve]:rr}}),t.info(`synced ${ve} to v${rr.version}`),Oe[ve]=rr.version,Object.assign(Ce,po)}At?t.info(`${ve} has more patches...`):me.delete(ve)}catch(rr){je[ve]=(je[ve]||0)+1;let po={name:ve,attempt:je[ve],version:QA[ve].version,statusCode:rr.output?.statusCode,errorType:rr.name,error:rr.stack};wf(rr)&&je[ve]>=nU?(t.warn(po,`${ve} blocked on missing key from v${QA[ve].version}, parking after ${je[ve]} attempts`),N.add(ve),me.delete(ve)):wf(rr)?(t.info(po,`${ve} blocked on missing key from v${QA[ve].version}, retrying with snapshot`),lA.add(ve)):rne(rr,je[ve])?(t.warn(po,`failed to sync ${ve} from v${QA[ve].version}, giving up`),me.delete(ve)):(t.info(po,`failed to sync ${ve} from v${QA[ve].version}, forcing snapshot retry`),lA.add(ve))}}}},I?.creds?.me?.id||"resync-app-state");let{onMutation:he}=CA(X);for(let me in Ce)he(Ce[me])}),Ke=async(W,X="preview",re)=>{let ne=uA(W),Oe=_t(ne)||qA(ne),Ce=I.creds.me,he=Ce&&(ne===uA(Ce.id)||Ce.lid&&ne===uA(Ce.lid)),me;F.profilePicPrivacyToken&&Oe&&!he&&(me=await wU({authState:I,jid:ne,getLIDForPN:T})),W=uA(W);let je=await f({tag:"iq",attrs:{target:W,to:OA,type:"get",xmlns:"w:profile:picture"},content:K5e(X,me)},re);return le(je,"picture")?.attrs?.url},Ve=async(W,X,re)=>{let ne=await f({tag:"call",attrs:{id:d(),to:"@call"},content:[{tag:"link_create",attrs:{media:W},content:X?[{tag:"event",attrs:{start_time:String(X.startTime)}}]:void 0}]},re);return le(ne,"link_create")?.attrs?.token},NA=async(W,X)=>{let re=I.creds.me,ne=W==="available";if(ne||W==="unavailable"){if(!re.name){t.warn("no name present, ignoring presence update request...");return}g.emit("connection.update",{isOnline:ne}),ne&&m(),await B({tag:"presence",attrs:{name:re.name.replace(/@/g,""),type:W}})}else{let{server:Oe}=yA(X);await B({tag:"chatstate",attrs:{from:Oe==="lid"?re.lid:re.id,to:X},content:[{tag:W==="recording"?"composing":W,attrs:W==="recording"?{media:"audio"}:{}}]})}},wA=async W=>{let X=uA(W),ne=_t(X)||qA(X)?await wU({authState:I,jid:X,getLIDForPN:T}):void 0;return B({tag:"presence",attrs:{to:W,id:d(),type:"subscribe"},content:ne})},LA=({tag:W,attrs:X,content:re})=>{let ne,Oe=X.from,Ce=X.participant||X.from;if(!(a(Oe)&&Oe!==OA)){if(W==="presence")ne={lastKnownPresence:X.type==="unavailable"?"unavailable":"available",lastSeen:X.last&&X.last!=="deny"?+X.last:void 0,groupOnlineCount:X.count?+X.count:void 0};else if(Array.isArray(re)){let[he]=re,me=he.tag;me==="paused"&&(me="available"),he.attrs?.media==="audio"&&(me="recording"),ne={lastKnownPresence:me}}else t.error({tag:W,attrs:X,content:re},"recv invalid presence node");ne&&g.emit("presence.update",{id:Oe,presences:{[Ce]:ne}})}},JA=async W=>{let X=W.type,re=I.creds.myAppStateKeyId;if(!re)throw new CI.Boom("App state key not present!",{statusCode:400});let ne,Oe;if(await z.mutex(async()=>{await I.keys.transaction(async()=>{t.debug({patch:W},"applying app patch"),await we([X],!1);let{[X]:Ce}=await I.keys.get("app-state-sync-version",[X]);ne=Ce?oU(Ce):Eb(),Oe=await ane(W,re,ne,V);let{patch:he,state:me}=Oe,je={tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:sync:app:state"},content:[{tag:"sync",attrs:{},content:[{tag:"collection",attrs:{name:X,version:(me.version-1).toString(),return_snapshot:"false"},content:[{tag:"patch",attrs:{},content:oe.SyncdPatch.encode(he).finish()}]}]}]};await f(je),await I.keys.set({"app-state-sync-version":{[X]:me}})},I?.creds?.me?.id||"app-patch")}),n.emitOwnEvents){let{onMutation:Ce}=CA(!1),{mutationMap:he}=await sU(X,[{...Oe.patch,version:{version:Oe.state.version}}],ne,V,n.options,void 0,t);for(let me in he)Ce(he[me])}},lt=async()=>{let W=await f({tag:"iq",attrs:{to:OA,xmlns:"abt",type:"get"},content:[{tag:"props",attrs:{protocol:"1",...I?.creds?.lastPropHash?{hash:I.creds.lastPropHash}:{}}}]}),X=le(W,"props"),re={};X&&(X.attrs?.hash&&(I.creds.lastPropHash=X?.attrs?.hash,g.emit("creds.update",I.creds)),re=fF(X,"prop"));let ne=re[10518]??re.privacy_token_sending_on_all_1_on_1_messages;ne!==void 0&&(F.privacyTokenOn1to1=ne==="true"||ne==="1");let Oe=re[9666]??re.profile_scraping_privacy_token_in_photo_iq;Oe!==void 0&&(F.profilePicPrivacyToken=Oe==="true"||Oe==="1");let Ce=re[14303]??re.lid_trusted_token_issue_to_lid;return Ce!==void 0&&(F.lidTrustedTokenIssueToLid=Ce==="true"||Ce==="1"),t.debug({serverProps:F},"fetched props"),re},wt=(W,X)=>{let re=gne(W,X);return JA(re)},pe=W=>wt({disableLinkPreviews:{isPreviewsDisabled:W}},""),Ie=(W,X,re)=>wt({star:{messages:X,star:re}},W),be=(W,X)=>wt({contact:X},W),oA=W=>wt({contact:null},W),pA=(W,X)=>wt({addLabel:{...X}},W),PA=(W,X)=>wt({addChatLabel:{labelId:X}},W),Ht=(W,X)=>wt({removeChatLabel:{labelId:X}},W),st=(W,X,re)=>wt({addMessageLabel:{messageId:X,labelId:re}},W),Qr=(W,X,re)=>wt({removeMessageLabel:{messageId:X,labelId:re}},W),tr=W=>wt({quickReply:W},""),lo=W=>wt({quickReply:{timestamp:W,deleted:!0}},""),ji=async()=>{await Promise.all([lt(),gA(),Ae()])},ee=g.createBufferedFunction(async(W,X)=>{if(g.emit("messages.upsert",{messages:[W],type:X}),W.pushName){let Ce=W.key.fromMe?I.creds.me.id:W.key.participant||W.key.remoteJid;Ce=uA(Ce),W.key.fromMe||g.emit("contacts.update",[{id:Ce,notify:W.pushName,verifiedName:W.verifiedBizName}]),W.key.fromMe&&W.pushName&&I.creds.me?.name!==W.pushName&&g.emit("creds.update",{me:{...I.creds.me,name:W.pushName}})}let re=hb(W.message),ne=re?A(re)&&Pf.includes(re.syncType):!1;if(re&&ne){let Ce=re.syncType;Ce===oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP&&!J.initialBootstrapComplete&&(J.initialBootstrapComplete=!0,g.emit("messaging-history.status",{syncType:Ce,status:"complete",explicit:!0})),Ce===oe.HistorySync.HistorySyncType.RECENT&&re.progress===100&&!J.recentSyncComplete&&(J.recentSyncComplete=!0,clearTimeout(U),U=void 0,g.emit("messaging-history.status",{syncType:Ce,status:"complete",explicit:!0})),Ce===oe.HistorySync.HistorySyncType.RECENT&&!J.recentSyncComplete&&(clearTimeout(U),U=setTimeout(()=>{J.recentSyncComplete||(J.recentSyncComplete=!0,g.emit("messaging-history.status",{syncType:oe.HistorySync.HistorySyncType.RECENT,status:"paused",explicit:!1})),U=void 0},nce))}re&&K===na.AwaitingInitialSync&&(P&&(clearTimeout(P),P=void 0),ne?(K=na.Syncing,t.info("Transitioned to Syncing state")):(K=na.Online,t.info("History sync skipped, transitioning to Online state and flushing buffer"),g.flush()));let Oe=async()=>{if(K===na.Syncing){N.clear(),t.info("Doing app state sync"),await we(NX,!0),K=na.Online,t.info("App state sync complete, transitioning to Online state and flushing buffer"),g.flush();let Ce=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:Ce})}};await Promise.all([(async()=>{ne&&await Oe()})(),One(W,{signalRepository:Q,shouldProcessHistoryMsg:ne,placeholderResendCache:k,ev:g,creds:I.creds,keyStore:I.keys,logger:t,options:n.options,getMessage:r})]),W.message?.protocolMessage?.appStateSyncKeyShare&&K===na.Syncing&&(t.info("App state sync key arrived, triggering app state sync"),await Oe())});return c.on("CB:presence",LA),c.on("CB:chatstate",LA),c.on("CB:ib,,dirty",async W=>{let{attrs:X}=le(W,"dirty");switch(X.type){case"account_sync":if(X.timestamp){let{lastAccountSyncTimestamp:ne}=I.creds;ne&&await Me("account_sync",ne),ne=+X.timestamp,g.emit("creds.update",{lastAccountSyncTimestamp:ne})}break;case"groups":break;default:t.info({node:W},"received unknown sync");break}}),g.on("connection.update",({connection:W,receivedPendingNotifications:X})=>{if(W==="close"&&(N.clear(),clearTimeout(U),U=void 0),W==="open"&&(i&&ji().catch(ne=>y(ne,"init queries")),NA(o?"available":"unavailable").catch(ne=>y(ne,"presence update requests"))),!X||K!==na.Connecting)return;if(J.initialBootstrapComplete=!1,J.recentSyncComplete=!1,clearTimeout(U),U=void 0,K=na.AwaitingInitialSync,t.info("Connection is now AwaitingInitialSync, buffering events"),g.buffer(),!A(oe.Message.HistorySyncNotification.create({syncType:oe.HistorySync.HistorySyncType.RECENT}))){t.info("History sync is disabled by config, not waiting for notification. Transitioning to Online."),K=na.Online,setTimeout(()=>g.flush(),0);return}if(I.creds.accountSyncCounter>0){t.info("Reconnection with existing sync data, skipping history sync wait. Transitioning to Online."),K=na.Online,setTimeout(()=>g.flush(),0);return}t.info("First connection, awaiting history sync notification with a 20s timeout."),P&&clearTimeout(P),P=setTimeout(()=>{if(K===na.AwaitingInitialSync){t.warn("Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer"),K=na.Online,g.flush();let ne=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:ne})}},2e4)}),g.on("creds.update",({myAppStateKeyId:W})=>{if(!W||N.size===0)return;if(K===na.Syncing){N.clear();return}let X=[...N];N.clear(),t.info({collections:X},"app state sync key arrived, re-syncing blocked collections"),we(X,!1).catch(re=>y(re,"blocked collections resync"))}),g.on("lid-mapping.update",async({lid:W,pn:X})=>{try{await Q.lidMapping.storeLIDPNMappings([{lid:W,pn:X}])}catch(re){t.warn({lid:W,pn:X,error:re},"Failed to store LID-PN mapping")}}),_(()=>{P&&(clearTimeout(P),P=void 0),!n.placeholderResendCache&&k.close&&k.close(),K=na.Connecting,R=void 0}),{...s,serverProps:F,createCallLink:Ve,getBotListV2:ce,messageMutex:L,receiptMutex:q,appStatePatchMutex:z,notificationMutex:j,fetchPrivacySettings:Ae,upsertMessage:ee,appPatch:JA,sendPresenceUpdate:NA,presenceSubscribe:wA,profilePictureUrl:Ke,fetchBlocklist:gA,fetchStatus:Be,fetchDisappearingDuration:We,updateProfilePicture:Ye,removeProfilePicture:Re,updateProfileStatus:Ze,updateProfileName:iA,updateBlockStatus:WA,updateDisableLinkPreviewsPrivacy:pe,updateCallPrivacy:fe,updateMessagesPrivacy:De,updateLastSeenPrivacy:_e,updateOnlinePrivacy:Ee,updateProfilePicturePrivacy:Qe,updateStatusPrivacy:Le,updateReadReceiptsPrivacy:AA,updateGroupsAddPrivacy:aA,updateDefaultDisappearingMode:He,getBusinessProfile:FA,resyncAppState:we,chatModify:wt,cleanDirtyBits:Me,addOrEditContact:be,removeContact:oA,placeholderResendCache:k,addLabel:pA,addChatLabel:PA,removeChatLabel:Ht,addMessageLabel:st,removeMessageLabel:Qr,star:Ie,addOrEditQuickReply:tr,removeQuickReply:lo}};var bce=n=>{let t=Oce(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(g,c,I)=>e({tag:"iq",attrs:{type:c,xmlns:"w:g2",to:g},content:I}),r=async g=>{let c=await A(g,"get",[{tag:"query",attrs:{request:"interactive"}}]);return EE(c)},s=async()=>{let g=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),c={},I=le(g,"groups");if(I){let d=kA(I,"group");for(let B of d){let f=EE({tag:"result",attrs:{},content:[B]});c[f.id]=f}}return t.ev.emit("groups.update",Object.values(c)),c};return t.ws.on("CB:ib,,dirty",async g=>{let{attrs:c}=le(g,"dirty");c.type==="groups"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,groupMetadata:r,groupCreate:async(g,c)=>{let I=Kr(),d=await A("@g.us","set",[{tag:"create",attrs:{subject:g,key:I},content:c.map(B=>({tag:"participant",attrs:{jid:B}}))}]);return EE(d)},groupLeave:async g=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"group",attrs:{id:g}}]}])},groupUpdateSubject:async(g,c)=>{await A(g,"set",[{tag:"subject",attrs:{},content:Buffer.from(c,"utf-8")}])},groupRequestParticipantsList:async g=>{let c=await A(g,"get",[{tag:"membership_approval_requests",attrs:{}}]),I=le(c,"membership_approval_requests");return kA(I,"membership_approval_request").map(B=>B.attrs)},groupRequestParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:I,attrs:{},content:c.map(y=>({tag:"participant",attrs:{jid:y}}))}]}]),B=le(d,"membership_requests_action"),f=le(B,I);return kA(f,"participant").map(y=>({status:y.attrs.error||"200",jid:y.attrs.jid}))},groupParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:I,attrs:{},content:c.map(Q=>({tag:"participant",attrs:{jid:Q}}))}]),B=le(d,I);return kA(B,"participant").map(Q=>({status:Q.attrs.error||"200",jid:Q.attrs.jid,content:Q}))},groupUpdateDescription:async(g,c)=>{let d=(await r(g)).descId??null;await A(g,"set",[{tag:"description",attrs:{...c?{id:Kr()}:{delete:"true"},...d?{prev:d}:{}},content:c?[{tag:"body",attrs:{},content:Buffer.from(c,"utf-8")}]:void 0}])},groupInviteCode:async g=>{let c=await A(g,"get",[{tag:"invite",attrs:{}}]);return le(c,"invite")?.attrs.code},groupRevokeInvite:async g=>{let c=await A(g,"set",[{tag:"invite",attrs:{}}]);return le(c,"invite")?.attrs.code},groupAcceptInvite:async g=>{let c=await A("@g.us","set",[{tag:"invite",attrs:{code:g}}]);return le(c,"group")?.attrs.jid},groupRevokeInviteV4:async(g,c)=>!!await A(g,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:c}}]}]),groupAcceptInviteV4:i.createBufferedFunction(async(g,c)=>{g=typeof g=="string"?{remoteJid:g}:g;let I=await A(c.groupJid,"set",[{tag:"accept",attrs:{code:c.inviteCode,expiration:c.inviteExpiration.toString(),admin:g.remoteJid}}]);return g.id&&(c=oe.Message.GroupInviteMessage.fromObject(c),c.inviteExpiration=0,c.inviteCode="",i.emit("messages.update",[{key:g,update:{message:{groupInviteMessage:c}}}])),await a({key:{remoteJid:c.groupJid,id:Kr(t.user?.id),fromMe:!1,participant:g.remoteJid},messageStubType:TA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:g.remoteJid,messageTimestamp:ya()},"notify"),I.attrs.from}),groupGetInviteInfo:async g=>{let c=await A("@g.us","get",[{tag:"invite",attrs:{code:g}}]);return EE(c)},groupToggleEphemeral:async(g,c)=>{let I=c?{tag:"ephemeral",attrs:{expiration:c.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(g,"set",[I])},groupSettingUpdate:async(g,c)=>{await A(g,"set",[{tag:c,attrs:{}}])},groupMemberAddMode:async(g,c)=>{await A(g,"set",[{tag:"member_add_mode",attrs:{},content:c}])},groupJoinApprovalMode:async(g,c)=>{await A(g,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"group_join",attrs:{state:c}}]}])},groupFetchAllParticipating:s}},EE=n=>{let t=le(n,"group");if(!t){let B=le(n,"error");if(B){let f=B.attrs.code?+B.attrs.code:500,Q=B.attrs.text||"group metadata query failed";throw new iM.Boom(Q,{statusCode:f,data:B})}throw new iM.Boom("Invalid group metadata response: missing node",{data:n})}if(!t.attrs.id)throw new iM.Boom("Invalid group metadata response: missing group id",{data:t});let o=le(t,"description"),i,e,a,A,r,s;o&&(i=YA(o,"body"),a=o.attrs.participant?uA(o.attrs.participant):void 0,A=o.attrs.participant_pn?uA(o.attrs.participant_pn):void 0,r=o.attrs.participant_username||void 0,s=+o.attrs.t,e=o.attrs.id);let g=t.attrs.id.includes("@")?t.attrs.id:Cr(t.attrs.id,"g.us"),c=le(t,"ephemeral")?.attrs.expiration,I=YA(t,"member_add_mode")==="all_member_add";return{id:g,notify:t.attrs.notify,addressingMode:t.attrs.addressing_mode==="lid"?dB.LID:dB.PN,subject:t.attrs.subject,subjectOwner:t.attrs.s_o,subjectOwnerPn:t.attrs.s_o_pn,subjectOwnerUsername:t.attrs.s_o_username,subjectTime:+t.attrs.s_t,size:t.attrs.size?+t.attrs.size:kA(t,"participant").length,creation:+t.attrs.creation,owner:t.attrs.creator?uA(t.attrs.creator):void 0,ownerPn:t.attrs.creator_pn?uA(t.attrs.creator_pn):void 0,ownerUsername:t.attrs.creator_username||void 0,owner_country_code:t.attrs.creator_country_code,desc:i,descId:e,descOwner:a,descOwnerPn:A,descOwnerUsername:r,descTime:s,linkedParent:le(t,"linked_parent")?.attrs.jid||void 0,restrict:!!le(t,"locked"),announce:!!le(t,"announcement"),isCommunity:!!le(t,"parent"),isCommunityAnnounce:!!le(t,"default_sub_group"),joinApprovalMode:!!le(t,"membership_approval_mode"),memberAddMode:I,participants:kA(t,"participant").map(({attrs:B})=>({id:B.jid,phoneNumber:qA(B.jid)&&_t(B.phone_number)?B.phone_number:void 0,lid:_t(B.jid)&&qA(B.lid)?B.lid:void 0,username:B.participant_username||B.username||void 0,admin:B.type||null})),ephemeralDuration:c?+c:void 0}};var CE=Je(Lr(),1);var x5e=n=>{let{id:t,thread_metadata:o,viewer_metadata:i}=n;return{id:t,owner:void 0,name:o.name.text,creation_time:parseInt(o.creation_time,10),description:o.description.text,invite:o.invite,subscribers:parseInt(o.subscribers_count,10),verification:o.verification,picture:{id:o.picture.id,directPath:o.picture.direct_path},mute_state:i.mute}},Y5e=n=>typeof n!="object"||n===null?null:"id"in n&&typeof n.id=="string"?n:"result"in n&&typeof n.result=="object"&&n.result!==null&&"id"in n.result?n.result:null,Mce=n=>{let t=bce(n),{query:o,generateMessageTag:i}=t,e=(A,r,s)=>Lf(A,r,s,o,i),a=async(A,r)=>{let s={newsletter_id:A,updates:{...r,settings:null}};return e(s,sa.UPDATE_METADATA,"xwa2_newsletter_update")};return{...t,newsletterCreate:async(A,r)=>{let g=await e({input:{name:A,description:r??null}},sa.CREATE,fa.xwa2_newsletter_create);return x5e(g)},newsletterUpdate:a,newsletterSubscribers:async A=>e({newsletter_id:A},sa.SUBSCRIBERS,fa.xwa2_newsletter_subscribers),newsletterMetadata:async(A,r)=>{let s={fetch_creation_time:!0,fetch_full_image:!0,fetch_viewer_metadata:!0,input:{key:r,type:A.toUpperCase()}},g=await e(s,sa.METADATA,fa.xwa2_newsletter_metadata);return Y5e(g)},newsletterFollow:A=>e({newsletter_id:A},sa.FOLLOW,fa.xwa2_newsletter_join_v2),newsletterUnfollow:A=>e({newsletter_id:A},sa.UNFOLLOW,fa.xwa2_newsletter_leave_v2),newsletterMute:A=>e({newsletter_id:A},sa.MUTE,fa.xwa2_newsletter_mute_v2),newsletterUnmute:A=>e({newsletter_id:A},sa.UNMUTE,fa.xwa2_newsletter_unmute_v2),newsletterUpdateName:async(A,r)=>await a(A,{name:r}),newsletterUpdateDescription:async(A,r)=>await a(A,{description:r}),newsletterUpdatePicture:async(A,r)=>{let{img:s}=await cb(r);return await a(A,{picture:s.toString("base64")})},newsletterRemovePicture:async A=>await a(A,{picture:""}),newsletterReactMessage:async(A,r,s)=>{await o({tag:"message",attrs:{to:A,...s?{}:{edit:"7"},type:"reaction",server_id:r,id:i()},content:[{tag:"reaction",attrs:s?{code:s}:{}}]})},newsletterFetchMessages:async(A,r,s,g)=>{let c={count:r.toString()};return typeof s=="number"&&(c.since=s.toString()),g&&(c.after=g.toString()),await o({tag:"iq",attrs:{id:i(),type:"get",xmlns:"newsletter",to:A},content:[{tag:"message_updates",attrs:c}]})},subscribeNewsletterUpdates:async A=>{let r=await o({tag:"iq",attrs:{id:i(),type:"set",xmlns:"newsletter",to:A},content:[{tag:"live_updates",attrs:{},content:[]}]}),g=le(r,"live_updates")?.attrs?.duration;return g?{duration:g}:null},newsletterAdminCount:async A=>(await e({newsletter_id:A},sa.ADMIN_COUNT,fa.xwa2_newsletter_admin_count)).admin_count,newsletterChangeOwner:async(A,r)=>{await e({newsletter_id:A,user_id:r},sa.CHANGE_OWNER,fa.xwa2_newsletter_change_owner)},newsletterDemote:async(A,r)=>{await e({newsletter_id:A,user_id:r},sa.DEMOTE,fa.xwa2_newsletter_demote)},newsletterDelete:async A=>{await e({newsletter_id:A},sa.DELETE,fa.xwa2_newsletter_delete_v2)}}};var _ce=n=>{let{logger:t,linkPreviewImageThumbnailWidth:o,generateHighQualityLinkPreview:i,options:e,patchMessageBeforeSending:a,cachedGroupMetadata:A,enableRecentMessageCache:r,maxMsgRetryCount:s}=n,g=Mce(n),{ev:c,authState:I,messageMutex:d,signalRepository:B,upsertMessage:f,query:Q,fetchPrivacySettings:y,sendNode:m,groupMetadata:_,groupToggleEphemeral:T,registerSocketEndHandler:R}=g,F=B.lidMapping.getLIDForPN.bind(B.lidMapping),K=new Set,L=n.userDevicesCache||new jg({stdTTL:dI.USER_DEVICES,useClones:!1}),q=Zg(),z=r?new Sb(t,s):null,j=Sce(),P,J=Y2,U=async(ce=!1)=>{let Be=await P;return(!Be||ce||new Date().getTime()-Be.fetchDate.getTime()>Be.ttl*1e3)&&(P=(async()=>{let We=await Q({tag:"iq",attrs:{type:"set",xmlns:"w:m",to:OA},content:[{tag:"media_conn",attrs:{}}]}),Ye=le(We,"media_conn"),Re={hosts:kA(Ye,"host").map(({attrs:Ze})=>({hostname:Ze.hostname,maxContentLengthBytes:+Ze.maxContentLengthBytes})),auth:Ye.attrs.auth,ttl:+Ye.attrs.ttl,fetchDate:new Date};return t.debug("fetched media conn"),Re.hosts[0]&&(J=Re.hosts[0].hostname),Re})()),P},N=async(ce,Be,We,Ye)=>{if(!We||We.length===0)throw new CE.Boom("missing ids in receipt");let Re={tag:"receipt",attrs:{id:We[0]}};(Ye==="read"||Ye==="read-self")&&(Re.attrs.t=ya().toString()),Ye==="sender"&&(_t(ce)||qA(ce))?(Re.attrs.recipient=ce,Re.attrs.to=Be):(Re.attrs.to=ce,Be&&(Re.attrs.participant=Be)),Ye&&(Re.attrs.type=Ye);let iA=We.slice(1);iA.length&&(Re.content=[{tag:"list",attrs:{},content:iA.map(gA=>({tag:"item",attrs:{id:gA}}))}]),t.debug({attrs:Re.attrs,messageIds:We},"sending receipt for messages"),await m(Re)},k=async(ce,Be)=>{let We=Doe(ce);for(let{jid:Ye,participant:Re,messageIds:Ze}of We)await N(Ye,Re,Ze,Be)},V=async ce=>{let We=(await y()).readreceipts==="all"?"read":"read-self";await k(ce,We)},Ae=async(ce,Be,We)=>{let Ye=[];Be||t.debug("not using cache for devices");let Re=[],Ze=ce.map(Me=>{let CA=yA(Me),we=CA?.user,Ke=CA?.device;return typeof Ke=="number"&&Ke>=0&&we?(Ye.push({user:we,device:Ke,jid:Me}),null):(Me=uA(Me),{jid:Me,user:we})}).filter(Me=>Me!==null),iA;if(Be&&L.mget){let Me=Ze.map(CA=>CA?.user).filter(Boolean);iA=await L.mget(Me)}for(let{jid:Me,user:CA}of Ze)if(Be){let we=iA?.[CA]||(L.mget?void 0:await L.get(CA));if(we){let Ke=we.map(Ve=>({...Ve,jid:Cr(Ve.user,Ve.server,Ve.device)}));Ye.push(...Ke),t.trace({user:CA},"using cache for devices")}else Re.push(Me)}else Re.push(Me);if(!Re.length)return Ye;let gA=new Set;for(let Me of Re)if(qA(Me)||ga(Me)){let CA=yA(Me)?.user;CA&&gA.add(CA)}let WA=new Ws().withContext("message").withDeviceProtocol().withLIDProtocol();for(let Me of Re)WA.withUser(new Vs().withId(Me));let FA=await g.executeUSyncQuery(WA);if(FA){let Me=FA.list.filter(Ve=>!!Ve.lid);if(Me.length>0){t.trace("Storing LID maps from device call"),await B.lidMapping.storeLIDPNMappings(Me.map(Ve=>({lid:Ve.lid,pn:Ve.id})));try{let Ve=Me.map(NA=>NA.lid);Ve.length&&await De(Ve,!0)}catch(Ve){t.warn({e:Ve,count:Me.length},"failed to assert sessions for newly mapped LIDs")}}let CA=voe(FA?.list,I.creds.me.id,I.creds.me.lid,We),we={};for(let Ve of CA)we[Ve.user]=we[Ve.user]||[],we[Ve.user]?.push(Ve);for(let[Ve,NA]of Object.entries(we)){let wA=gA.has(Ve);for(let LA of NA){let JA=wA?Cr(Ve,LA.server,LA.device):Cr(LA.user,LA.server,LA.device);Ye.push({...LA,jid:JA}),t.debug({user:LA.user,device:LA.device,finalJid:JA,usedLid:wA},"Processed device with LID priority")}}await q.mutex(async()=>{if(L.mset)await L.mset(Object.entries(we).map(([Ve,NA])=>({key:Ve,value:NA})));else for(let Ve in we)we[Ve]&&await L.set(Ve,we[Ve])});let Ke={};for(let[Ve,NA]of Object.entries(we))NA&&NA.length>0&&(Ke[Ve]=NA.map(wA=>wA.device?.toString()||"0"));if(Object.keys(Ke).length>0)try{await I.keys.set({"device-list":Ke}),t.debug({userCount:Object.keys(Ke).length},"stored user device lists for bulk migration")}catch(Ve){t.warn({error:Ve},"failed to store user device lists")}}return Ye},ie=(ce,Be)=>Ee(ce,{protocolMessage:{type:oe.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,memberLabel:{label:Be?.slice(0,30),labelTimestamp:ya()}}},{additionalNodes:[{tag:"meta",attrs:{tag_reason:"user_update",appdata:"member_tag"},content:void 0}]}),De=async(ce,Be)=>{let We=!1,Ye=[...new Set(ce)],Re=[];t.debug({jids:ce},"assertSessions call with jids");for(let Ze of Ye)!Be&&(await B.validateSession(Ze)).exists||Re.push(Ze);if(Re.length){let Ze=[...Re.filter(gA=>!!qA(gA)||!!ga(gA)),...(await B.lidMapping.getLIDsForPNs(Re.filter(gA=>!!_t(gA)||!!ur(gA)))||[]).map(gA=>gA.lid)];t.debug({jidsRequiringFetch:Re,wireJids:Ze},"fetching sessions");let iA=await Q({tag:"iq",attrs:{xmlns:"encrypt",type:"get",to:OA},content:[{tag:"key",attrs:{},content:Ze.map(gA=>{let WA={jid:gA};return Be&&(WA.reason="identity"),{tag:"user",attrs:WA}})}]});await koe(iA,B),We=!0}return We},fe=async ce=>{if(!I.creds.me?.id)throw new CE.Boom("Not authenticated");let Be={protocolMessage:{peerDataOperationRequestMessage:ce,type:oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE}},We=uA(I.creds.me.id);return await Ee(We,Be,{additionalAttributes:{category:"peer",push_priority:"high_force"},additionalNodes:[{tag:"meta",attrs:{appdata:"default"}}]})},_e=async(ce,Be,We,Ye)=>{if(!ce.length)return{nodes:[],shouldIncludeDeviceIdentity:!1};let Re=await a(Be,ce),Ze=Array.isArray(Re)?Re:ce.map(we=>({recipientJid:we,message:Re})),iA=!1,gA=I.creds.me.id,WA=I.creds.me?.lid,FA=WA?yA(WA)?.user:null,Me=Ze.map(async({recipientJid:we,message:Ke})=>{try{if(!we)return null;let Ve=Ke;if(Ye){let{user:JA}=yA(we),{user:lt}=yA(gA),wt=FA;(JA===lt||wt&&JA===wt)&&!(we===gA||WA&&we===WA)&&(Ve=Ye,t.debug({jid:we,targetUser:JA},"Using DSM for own device"))}let NA=ch(Ve),wA=we;return await j.mutex(wA,async()=>{let{type:JA,ciphertext:lt}=await B.encryptMessage({jid:we,data:NA});return JA==="pkmsg"&&(iA=!0),{tag:"to",attrs:{jid:we},content:[{tag:"enc",attrs:{v:"2",type:JA,...We||{}},content:lt}]}})}catch(Ve){return t.error({jid:we,err:Ve},"Failed to encrypt for recipient"),null}}),CA=(await Promise.all(Me)).filter(we=>we!==null);if(ce.length>0&&CA.length===0)throw new CE.Boom("All encryptions failed",{statusCode:500});return{nodes:CA,shouldIncludeDeviceIdentity:iA}},Ee=async(ce,Be,{messageId:We,participant:Ye,additionalAttributes:Re,additionalNodes:Ze,useUserDevicesCache:iA,useCachedGroupMetadata:gA,statusJidList:WA})=>{let FA=fne(I.creds),Me=I.creds.me?.lid,CA=!!Ye?.jid,we=CA,Ke="status@broadcast",{user:Ve,server:NA}=yA(ce),wA=NA==="g.us",LA=ce===Ke,JA=NA==="lid",lt=NA==="newsletter",wt=wA||LA,pe=ce;We=We||Kr(FA),iA=iA!==!1,gA=gA!==!1&&!LA;let Ie=[],be=LA?Ke:pe,oA=[],pA=[],PA,Ht={deviceSentMessage:{destinationJid:be,message:Be},messageContextInfo:Be.messageContextInfo},st={};if(Ye){!wA&&!LA&&(Re={...Re,device_fanout:"false"});let{user:Qr,device:tr}=yA(Ye.jid);pA.push({user:Qr,device:tr,jid:Ye.jid})}return await I.keys.transaction(async()=>{let Qr=Le(Be);if(Qr&&(st.mediatype=Qr),lt){let Ce=a?await a(Be,[]):Be,he=_7(Ce);oA.push({tag:"plaintext",attrs:{},content:he});let me={tag:"message",attrs:{to:ce,id:We,type:Qe(Be),...Re||{}},content:oA};t.debug({msgId:We},`sending newsletter message to ${ce}`),await m(me);return}if((Oa(Be)?.pinInChatMessage||Oa(Be)?.reactionMessage)&&(st["decrypt-fail"]="hide"),wt&&!CA){let[Ce,he]=await Promise.all([(async()=>{let tA=gA&&A?await A(ce):void 0;return tA&&Array.isArray(tA?.participants)?t.trace({jid:ce,participants:tA.participants.length},"using cached group metadata"):LA||(tA=await _(ce)),tA})(),(async()=>!Ye&&!LA?(await I.keys.get("sender-key-memory",[ce]))[ce]||{}:{})()]),me=Ce?Ce.participants.map(tA=>tA.id):[];Ce?.ephemeralDuration&&Ce.ephemeralDuration>0&&(Re={...Re,expiration:Ce.ephemeralDuration.toString()}),LA&&WA&&me.push(...WA);let je=await Ae(me,!!iA,!1);pA.push(...je),wA&&(Re={...Re,addressing_mode:Ce?.addressingMode||"lid"});let lA=await a(Be);if(Array.isArray(lA))throw new CE.Boom("Per-jid patching is not supported in groups");let QA=ch(lA);PA=lA;let RA=(Re?.addressing_mode||Ce?.addressingMode||"lid")==="lid"&&Me?Me:FA,{ciphertext:xA,senderKeyDistributionMessage:et}=await B.encryptGroupMessage({group:be,data:QA,meId:RA}),ve=[];for(let tA of pA){let At=tA.jid;(!!!he[At]||Ye)&&!ga(At)&&!ur(At)&&tA.device!==99&&(ve.push(At),he[At]=!0)}if(ve.length){t.debug({senderKeyJids:ve},"sending new sender key");let tA={senderKeyDistributionMessage:{axolotlSenderKeyDistributionMessage:et,groupId:be}};await De(ve);let zr=await _e(ve,tA,st);we=we||zr.shouldIncludeDeviceIdentity,Ie.push(...zr.nodes)}oA.push({tag:"enc",attrs:{v:"2",type:"skmsg",...st},content:xA}),await I.keys.set({"sender-key-memory":{[ce]:he}})}else{let Ce=FA;JA&&Me?(Ce=Me,t.debug({to:ce,ownId:Ce},"Using LID identity for @lid conversation")):t.debug({to:ce,ownId:Ce},"Using PN identity for @s.whatsapp.net conversation");let{user:he}=yA(Ce);if(!Ye){let tA=await a(Be,[ce]);PA=Array.isArray(tA)?tA.find(At=>At.recipientJid===ce)||tA[0]:tA}if(!CA){let tA=JA?"lid":"s.whatsapp.net";if(pA.push({user:Ve,device:0,jid:Cr(Ve,tA,0)}),Ve!==he){let At=JA?"lid":"s.whatsapp.net",zr=JA&&Me?yA(Me).user:yA(FA).user;pA.push({user:zr,device:0,jid:Cr(zr,At,0)})}if(Re?.category!=="peer"){pA.length=0;let At=JA&&Me?Cr(yA(Me)?.user,"lid",void 0):Cr(yA(FA)?.user,"s.whatsapp.net",void 0),zr=await Ae([At,ce],!0,!1);pA.push(...zr),t.debug({deviceCount:pA.length,devices:pA.map(rr=>`${rr.user}:${rr.device}@${yA(rr.jid)?.server}`)},"Device enumeration complete with unified addressing")}}let me=[],je=[],lA=[],{user:QA}=yA(FA),{user:$A}=Me?yA(Me):{user:null};for(let{user:tA,jid:At}of pA){if(At===FA||Me&&At===Me){t.debug({jid:At,meId:FA,meLid:Me},"Skipping exact sender device (whatsmeow pattern)");continue}tA===QA||tA===$A?je.push(At):lA.push(At),me.push(At)}await De(me);let[{nodes:RA,shouldIncludeDeviceIdentity:xA},{nodes:et,shouldIncludeDeviceIdentity:ve}]=await Promise.all([_e(je,Ht||Be,st),_e(lA,Be,st,Ht)]);Ie.push(...RA),Ie.push(...et),(je.length>0||lA.length>0)&&(st.phash=f7([...je,...lA])),we=we||xA||ve}if(CA){let Ce=qA(Ye.jid),he=Tt(Ye.jid,Ce?Me:FA),me=Be;if(wt){let $A;if(Me&&await B.hasSenderKey({group:be,meId:Me})?$A=Me:await B.hasSenderKey({group:be,meId:FA})&&($A=FA),$A)try{let RA=await B.getSenderKeyDistributionMessage({group:be,meId:$A});me={...Be,senderKeyDistributionMessage:{groupId:be,axolotlSenderKeyDistributionMessage:RA}}}catch(RA){t.warn({err:RA,jid:be},"failed to build SKDM for retry, sending without it")}}let je=he?ch({deviceSentMessage:{destinationJid:be,message:me}}):ch(me),{type:lA,ciphertext:QA}=await B.encryptMessage({data:je,jid:Ye.jid});oA.push({tag:"enc",attrs:{v:"2",type:lA,count:Ye.count.toString()},content:QA})}if(Ie.length)if(Re?.category==="peer"){let Ce=Ie[0]?.content?.[0];Ce&&oA.push(Ce)}else oA.push({tag:"participants",attrs:{},content:Ie});let tr={tag:"message",attrs:{id:We,to:be,type:Qe(Be),...Re||{}},content:oA};if(Ye?Ur(be)?(tr.attrs.to=be,tr.attrs.participant=Ye.jid):Tt(Ye.jid,FA)?(tr.attrs.to=Ye.jid,tr.attrs.recipient=be):tr.attrs.to=Ye.jid:tr.attrs.to=be,we&&(tr.content.push({tag:"device-identity",attrs:{},content:mf(I.creds.account,!0)}),t.debug({jid:ce},"adding device identity")),!lt&&!CA&&PA?.messageContextInfo?.messageSecret&&pb(PA))try{let Ce=ch(PA),he={id:We,fromMe:!0,remoteJid:be,participant:Ye?.jid},me=await Qoe(Ce,PA,he);me&&(tr.content.push(me),t.trace({jid:ce},"added reporting token to message"))}catch(Ce){t.warn({jid:ce,trace:Ce?.stack},"failed to attach reporting token")}let lo=Re?.category==="peer",ji=!wA&&!CA&&!LA&&!lt&&!lo,ee=ji?await js(be,F):be,X=(ji?await I.keys.get("tctoken",[ee]):{})[ee],re=X?.token;if(re?.length&&Ap(X?.timestamp)){t.debug({jid:be,timestamp:X?.timestamp},"tctoken expired, clearing"),re=void 0;let Ce=X?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:X.senderTimestamp}:null;try{await I.keys.set({tctoken:{[ee]:Ce}})}catch(he){t.debug({jid:be,err:he?.message},"failed to persist tctoken expiry cleanup")}}re?.length&&g.serverProps.privacyTokenOn1to1&&tr.content.push({tag:"tctoken",attrs:{},content:re}),Ze&&Ze.length>0&&tr.content.push(...Ze),t.debug({msgId:We},`sending message to ${Ie.length} devices`),await m(tr);let ne=!!Oa(Be)?.protocolMessage,Oe=be===FX||UX(be)||rh(be);if(ji&&!ne&&!Oe&&wne(X?.senderTimestamp)&&!K.has(ee)){K.add(ee);let Ce=ya(),he=B.lidMapping.getPNForLID.bind(B.lidMapping);bf(be,g.serverProps.lidTrustedTokenIssueToLid,F,he).then(me=>AA([me],Ce)).then(async me=>{await aE({result:me,fallbackJid:ee,keys:I.keys,getLIDForPN:F});let lA=(await I.keys.get("tctoken",[ee]))[ee],QA=await rE(I.keys,[ee]);await I.keys.set({tctoken:{[ee]:{token:Buffer.alloc(0),...lA,senderTimestamp:Ce},...QA}})}).catch(me=>{t.debug({jid:be,err:me?.message},"fire-and-forget tctoken issuance failed")}).finally(()=>{K.delete(ee)})}z&&!Ye&&z.addRecentMessage(be,We,Be)},FA),We},Qe=ce=>{let Be=Oa(ce);return Be?Be.reactionMessage||Be.encReactionMessage?"reaction":Be.pollCreationMessage||Be.pollCreationMessageV2||Be.pollCreationMessageV3||Be.pollUpdateMessage?"poll":Be.eventMessage?"event":Le(Be)!==""?"media":"text":"text"},Le=ce=>ce.imageMessage?"image":ce.videoMessage?ce.videoMessage.gifPlayback?"gif":"video":ce.audioMessage?ce.audioMessage.ptt?"ptt":"audio":ce.contactMessage?"vcard":ce.documentMessage?"document":ce.contactsArrayMessage?"contact_array":ce.liveLocationMessage?"livelocation":ce.stickerMessage?"sticker":ce.listMessage?"list":ce.listResponseMessage?"list_response":ce.buttonsResponseMessage?"buttons_response":ce.orderMessage?"order":ce.productMessage?"product":ce.interactiveResponseMessage?"native_flow_response":ce.groupInviteMessage?"url":"",AA=async(ce,Be)=>{let We=(Be??ya()).toString();return await Q({tag:"iq",attrs:{to:OA,type:"set",xmlns:"privacy"},content:[{tag:"tokens",attrs:{},content:ce.map(Re=>({tag:"token",attrs:{jid:uA(Re),t:We,type:"trusted_contact"}}))}]})},aA=loe(n,U),He=MF(c,"messages.media-update");return R(()=>{!n.userDevicesCache&&L.close&&L.close(),P=void 0,z&&z.clear()}),{...g,userDevicesCache:L,devicesMutex:q,issuePrivacyTokens:AA,assertSessions:De,relayMessage:Ee,sendReceipt:N,sendReceipts:k,readMessages:V,refreshMediaConn:U,getMediaHost:()=>J,waUploadToServer:aA,fetchPrivacySettings:y,sendPeerDataOperationMessage:fe,createParticipantNodes:_e,getUSyncDevices:Ae,messageRetryManager:z,updateMemberLabel:ie,updateMediaMessage:async ce=>{let Be=Ooe(ce.message),We=Be.mediaKey,Ye=I.creds.me.id,Re=doe(ce.key,We,Ye),Ze;if(await Promise.all([m(Re),He(async iA=>{let gA=iA.find(WA=>WA.key.id===ce.key.id);if(gA){if(gA.error)Ze=gA.error;else try{let WA=Eoe(gA.media,We,gA.key.id);if(WA.result!==oe.MediaRetryNotification.ResultType.SUCCESS){let FA=oe.MediaRetryNotification.ResultType[WA.result];throw new CE.Boom(`Media re-upload failed by device (${FA})`,{data:WA,statusCode:j2(WA.result)||404})}Be.directPath=WA.directPath,Be.url=Cf(Be.directPath,J),t.debug({directPath:WA.directPath,key:gA.key},"media update successful")}catch(WA){Ze=WA}return!0}})]),Ze)throw Ze;return c.emit("messages.update",[{key:ce.key,update:{message:ce.message}}]),ce},sendMessage:async(ce,Be,We={})=>{let Ye=I.creds.me.id;if(typeof Be=="object"&&"disappearingMessagesInChat"in Be&&typeof Be.disappearingMessagesInChat<"u"&&Ur(ce)){let{disappearingMessagesInChat:Re}=Be;await T(ce,typeof Re=="boolean"?Re?Qf:0:Re)}else{let Re=await Soe(ce,Be,{logger:t,userJid:Ye,getUrlInfo:we=>Sne(we,{thumbnailWidth:o,fetchOpts:{timeout:3e3,...e||{}},logger:t,uploadImage:i?aA:void 0}),getProfilePicUrl:g.profilePictureUrl,getCallLink:g.createCallLink,upload:aA,mediaCache:n.mediaCache,options:n.options,messageId:Kr(g.user?.id),...We}),Ze="event"in Be&&!!Be.event,iA="delete"in Be&&!!Be.delete,gA="edit"in Be&&!!Be.edit,WA="pin"in Be&&!!Be.pin,FA="poll"in Be&&!!Be.poll,Me={},CA=[];return iA?Ur(Be.delete?.remoteJid)&&!Be.delete?.fromMe?Me.edit="8":Me.edit="7":gA?Me.edit="1":WA?Me.edit="2":FA?CA.push({tag:"meta",attrs:{polltype:"creation"}}):Ze&&CA.push({tag:"meta",attrs:{event_type:"creation"}}),await Ee(ce,Re.message,{messageId:Re.key.id,useCachedGroupMetadata:We.useCachedGroupMetadata,additionalAttributes:Me,statusJidList:We.statusJidList,additionalNodes:CA}),n.emitOwnEvents&&process.nextTick(async()=>{await d.mutex(()=>f(Re,"append"))}),Re}}}};var j5e=new Set(Object.values(Hc));function J5e(n){return typeof n=="string"&&j5e.has(n)}var Tce=n=>{let{logger:t,retryRequestDelayMs:o,maxMsgRetryCount:i,getMessage:e,shouldIgnoreJid:a,enableAutoSessionRecreation:A}=n,r=_ce(n),{userDevicesCache:s,devicesMutex:g,ev:c,authState:I,ws:d,messageMutex:B,notificationMutex:f,receiptMutex:Q,signalRepository:y,query:m,upsertMessage:_,resyncAppState:T,onUnexpectedError:R,assertSessions:F,sendNode:K,relayMessage:L,sendReceipt:q,uploadPreKeys:z,sendPeerDataOperationMessage:j,messageRetryManager:P,registerSocketEndHandler:J,issuePrivacyTokens:U,fetchAccountReachoutTimelock:N,placeholderResendCache:k}=r,V=y.lidMapping.getLIDForPN.bind(y.lidMapping),Ae=Zg(),ie=n.msgRetryCounterCache||new jg({stdTTL:dI.MSG_RETRY,useClones:!1}),De=n.callOfferCache||new jg({stdTTL:dI.CALL_OFFER,useClones:!1}),fe=new jg({stdTTL:5,useClones:!1}),_e=!1,Ee=async(ee,W,X)=>{if(!I.creds.me?.id)throw new Uf.Boom("Not authenticated");let re={historySyncOnDemandRequest:{chatJid:W.remoteJid,oldestMsgFromMe:W.fromMe,oldestMsgId:W.id,oldestMsgTimestampMs:X,onDemandMsgCount:ee},peerDataOperationRequestType:oe.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND};return j(re)},Qe=async(ee,W)=>{if(!I.creds.me?.id)throw new Uf.Boom("Not authenticated");if(await k.get(ee?.id)){t.debug({messageKey:ee},"already requested resend");return}else await k.set(ee?.id,W||!0);if(await DB(2e3),!await k.get(ee?.id))return t.debug({messageKey:ee},"message received while resend requested"),"RESOLVED";let X={placeholderMessageResendRequest:[{messageKey:ee}],peerDataOperationRequestType:oe.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND};return setTimeout(async()=>{await k.get(ee?.id)&&(t.debug({messageKey:ee},"PDO message without response after 8 seconds. Phone possibly offline"),await k.del(ee?.id))},8e3),j(X)},Le=async ee=>{let W=le(ee,"update");if(W){let X=W.attrs?.op_name;if(!X){t.warn({node:_n(ee)},"mex notification missing op_name, fallback to legacy"),await He(ee);return}let re;try{re=JSON.parse(W.content.toString())}catch(Oe){t.error({err:Oe,opName:X},"failed to parse mex notification JSON");return}if(re.errors?.length){t.warn({errors:re.errors,opName:X},"mex notification has GQL errors");return}let ne=re.data;if(!ne){t.warn({opName:X},"mex notification has null data");return}switch(t.debug({opName:X},"processing mex notification"),X){case"NotificationUserReachoutTimelockUpdate":AA(ne);break;case"MessageCappingInfoNotification":aA(ne);break;case"NotificationNewsletterUpdate":case"NotificationLinkedProfilesUpdates":case"NotificationNewsletterAdminPromote":case"NotificationNewsletterAdminDemote":case"NotificationNewsletterUserSettingChange":case"NotificationNewsletterJoin":case"NotificationNewsletterLeave":case"NotificationNewsletterStateChange":case"NotificationNewsletterAdminMetadataUpdate":case"NotificationNewsletterOwnerUpdate":case"NotificationNewsletterAdminInviteRevoke":case"NotificationNewsletterWamoSubStatusChange":case"NotificationNewsletterBlockUser":case"NotificationNewsletterPaidPartnership":case"NotificationNewsletterMilestone":case"NewsletterResponseStateUpdate":await He(ee);break;default:t.debug({opName:X},"unhandled mex notification");break}return}await He(ee)},AA=ee=>{let W=ee.xwa2_notify_account_reachout_timelock;if(!W){t.warn("reachout timelock notification missing payload");return}if(!W.is_active){t.info("reachout timelock restriction lifted"),c.emit("connection.update",{reachoutTimeLock:{isActive:!1,enforcementType:Hc.DEFAULT}});return}let X=W.time_enforcement_ends?new Date(parseInt(W.time_enforcement_ends,10)*1e3):new Date(Date.now()+6e4),re=J5e(W.enforcement_type)?W.enforcement_type:Hc.DEFAULT;t.info({enforcementType:re,timeEnforcementEnds:X},"reachout timelock restriction set"),c.emit("connection.update",{reachoutTimeLock:{isActive:!0,timeEnforcementEnds:X,enforcementType:re}})},aA=ee=>{let W=ee.xwa2_notify_new_chat_messages_capping_info_update;if(!W){t.warn("message capping notification missing payload");return}t.info({payload:W},"received message capping update"),c.emit("message-capping.update",W)},He=async ee=>{let W=le(ee,"mex"),X=W?.content?null:le(ee,"update")||ys(ee)[0],re=W?.content?W:X;if(!re?.content){t.warn({node:_n(ee)},"invalid mex newsletter notification");return}let ne;try{let he=re.content;if(Array.isArray(he)){t.warn({payloadNode:re},"invalid mex newsletter notification payload format");return}let me=typeof he=="string"?Buffer.from(he,"binary"):Buffer.from(he);ne=JSON.parse(me.toString())}catch(he){t.error({err:he,node:_n(ee)},"failed to parse mex newsletter notification");return}let Oe=ne?.operation??re?.attrs?.op_name,Ce=ne?.updates;if(!Ce){let he=ne?.data?.xwa2_notify_linked_profiles;he&&(Ce=[he])}if(!Ce||!Oe){t.warn({data:ne},"invalid mex newsletter notification content");return}switch(t.info({operation:Oe,updates:Ce},"got mex newsletter notification"),Oe){case"NotificationNewsletterUpdate":for(let he of Ce)he.jid&&he.settings&&Object.keys(he.settings).length>0&&c.emit("newsletter-settings.update",{id:he.jid,update:he.settings});break;case"NotificationNewsletterAdminPromote":for(let he of Ce)he.jid&&he.user&&c.emit("newsletter-participants.update",{id:he.jid,author:ee.attrs.from,user:he.user,new_role:"ADMIN",action:"promote"});break;case"NotificationLinkedProfilesUpdates":for(let he of Ce){let me=he?.jid,je=Array.isArray(he?.added_profiles)?he.added_profiles:[],lA=[];for(let QA of je){let $A=typeof QA=="string"?QA:QA?.pn??QA?.jid??null;if(me&&$A){let RA={lid:me,pn:$A};c.emit("lid-mapping.update",RA),lA.push(RA)}}await y.lidMapping.storeLIDPNMappings(lA)}break;default:t.info({operation:Oe,data:ne},"unhandled mex newsletter notification");break}},ce=async ee=>{let W=ee.attrs.from,X=ys(ee),re=ee.attrs.participant;for(let ne of X)switch(t.debug({from:W,child:ne},"got newsletter notification"),ne.tag){case"reaction":{let Oe={id:W,server_id:ne.attrs.message_id,reaction:{code:YA(ne,"reaction"),count:1}};c.emit("newsletter.reaction",Oe);break}case"view":{let Oe={id:W,server_id:ne.attrs.message_id,count:parseInt(ne.content?.toString()||"0",10)};c.emit("newsletter.view",Oe);break}case"participant":{let Oe={id:W,author:re,user:ne.attrs.jid,action:ne.attrs.action,new_role:ne.attrs.role};c.emit("newsletter-participants.update",Oe);break}case"update":{let Oe=le(ne,"settings");if(Oe){let Ce={},he=le(Oe,"name");he?.content&&(Ce.name=he.content.toString());let me=le(Oe,"description");me?.content&&(Ce.description=me.content.toString()),c.emit("newsletter-settings.update",{id:W,update:Ce})}break}case"message":{let Oe=le(ne,"plaintext");if(Oe?.content)try{let Ce=typeof Oe.content=="string"?Buffer.from(Oe.content,"binary"):Buffer.from(Oe.content),he=oe.Message.decode(Ce).toJSON(),me=oe.WebMessageInfo.fromObject({key:{remoteJid:W,id:ne.attrs.message_id||ne.attrs.server_id,fromMe:!1},message:he,messageTimestamp:+ne.attrs.t}).toJSON();await _(me,"append"),t.debug("Processed plaintext newsletter message")}catch(Ce){t.error({error:Ce},"Failed to decode plaintext newsletter message")}break}default:t.warn({node:ee,child:ne},"Unknown newsletter notification child");break}},Be=async(ee,W)=>{let X=Rne(ee,W,I.creds.me.id);t.debug({recv:{tag:ee.tag,attrs:ee.attrs},sent:X.attrs},"sent ack"),await K(X)},We=async(ee,W)=>{let X={tag:"call",attrs:{from:I.creds.me.id,to:W},content:[{tag:"reject",attrs:{"call-id":ee,"call-creator":W,count:"0"},content:void 0}]};await m(X)},Ye=async(ee,W=!1)=>{let{fullMessage:X}=TF(ee,I.creds.me.id,I.creds.me.lid||""),{key:re}=X,ne=re.id;if(P){if(P.hasExceededMaxRetries(ne)){t.debug({msgId:ne},"reached retry limit with new retry manager, clearing"),P.markRetryFailed(ne);return}let xA=P.incrementRetryCount(ne),et=`${ne}:${re?.participant}`;await ie.set(et,xA)}else{let xA=`${ne}:${re?.participant}`,et=await ie.get(xA)||0;if(et>=i){t.debug({retryCount:et,msgId:ne},"reached retry limit, clearing"),await ie.del(xA);return}et+=1,await ie.set(xA,et)}let Oe=`${ne}:${re?.participant}`,Ce=await ie.get(Oe)||1,{account:he,signedPreKey:me,signedIdentityKey:je}=I.creds,lA=ee.attrs.from,QA=!1,$A="";if(A&&P&&Ce>1)try{let xA=y.jidToSignalProtocolAddress(lA),et=await y.validateSession(lA),ve=P.shouldRecreateSession(lA,et.exists);QA=ve.recreate,$A=ve.reason,QA&&(t.debug({fromJid:lA,retryCount:Ce,reason:$A},"recreating session for retry"),await I.keys.set({session:{[xA]:null}}),W=!0)}catch(xA){t.warn({error:xA,fromJid:lA},"failed to check session recreation")}if(Ce<=2)if(P)P.schedulePhoneRequest(ne,async()=>{try{let xA=await Qe(re);t.debug(`sendRetryRequest: requested placeholder resend (${xA}) for message ${ne} (scheduled)`)}catch(xA){t.warn({error:xA,msgId:ne},"failed to send scheduled phone request")}});else{let xA=await Qe(re);t.debug(`sendRetryRequest: requested placeholder resend for message ${xA}`)}let RA=mf(he,!0);await I.keys.transaction(async()=>{let xA={tag:"receipt",attrs:{id:ne,type:"retry",to:ee.attrs.from},content:[{tag:"retry",attrs:{count:Ce.toString(),id:ee.attrs.id,t:ee.attrs.t,v:"1",error:"0"}},{tag:"registration",attrs:{},content:kg(I.creds.registrationId)}]};if(ee.attrs.recipient&&(xA.attrs.recipient=ee.attrs.recipient),ee.attrs.participant&&(xA.attrs.participant=ee.attrs.participant),Ce>1||W||QA){let{update:et,preKeys:ve}=await AU(I,1),[tA]=Object.keys(ve),At=ve[+tA];xA.content.push({tag:"keys",attrs:{},content:[{tag:"type",attrs:{},content:Buffer.from(Rg)},{tag:"identity",attrs:{},content:je.public},eU(At,+tA),yf(me),{tag:"device-identity",attrs:{},content:RA}]}),c.emit("creds.update",et)}await K(xA),t.info({msgAttrs:ee.attrs,retryCount:Ce},"sent retry receipt")},I?.creds?.me?.id||"sendRetryRequest")},Re=new Set,Ze=ee=>{(async()=>{let W=uA(ee),X=await js(W,V),ne=(await I.keys.get("tctoken",[X]))?.[X]?.senderTimestamp;if(ne==null||Ap(ne))return;t.debug({jid:W,senderTimestamp:ne},"identity changed, re-issuing tctoken");let Oe=y.lidMapping.getPNForLID.bind(y.lidMapping),Ce=await bf(W,r.serverProps.lidTrustedTokenIssueToLid,V,Oe),he=await U([Ce],ne);await aE({result:he,fallbackJid:X,keys:I.keys,getLIDForPN:V,onNewJidStored:NA})})().catch(W=>{t.debug({jid:ee,err:W?.message},"failed to re-issue tctoken after identity change")})},iA=async ee=>{if(ee.attrs.from===OA){let X=ee.attrs.id;if(X&&Re.has(X))return;let ne=+le(ee,"count").attrs.value,Oe=ne{let re=ee.attrs.participant,ne=ee.attrs.participant_pn,Oe=ee.attrs.participant_username,Ce=le(W,"participant")?.attrs?.jid||re,he=le(W,"participant")?.attrs?.phone_number||ne;switch(W?.tag){case"create":let me=EE(W);X.messageStubType=TA.GROUP_CREATE,X.messageStubParameters=[me.subject],X.key={participant:me.owner,participantAlt:me.ownerPn},c.emit("chats.upsert",[{id:me.id,name:me.subject,conversationTimestamp:me.creation}]),c.emit("groups.upsert",[{...me,author:re,authorPn:ne,authorUsername:Oe}]);break;case"ephemeral":case"not_ephemeral":X.message={protocolMessage:{type:oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:+(W.attrs.expiration||0)}};break;case"modify":let je=kA(W,"participant").map(ve=>ve.attrs.jid);X.messageStubParameters=je||[],X.messageStubType=TA.GROUP_PARTICIPANT_CHANGE_NUMBER;break;case"promote":case"demote":case"remove":case"add":case"leave":let lA=`GROUP_PARTICIPANT_${W.tag.toUpperCase()}`;X.messageStubType=TA[lA];let QA=kA(W,"participant").map(({attrs:ve})=>({id:ve.jid,phoneNumber:qA(ve.jid)&&_t(ve.phone_number)?ve.phone_number:void 0,lid:_t(ve.jid)&&qA(ve.lid)?ve.lid:void 0,username:ve.participant_username||ve.username||void 0,admin:ve.type||null}));QA.length===1&&(Tt(QA[0].id,re)||Tt(QA[0].id,ne))&&W.tag==="remove"&&(X.messageStubType=TA.GROUP_PARTICIPANT_LEAVE),X.messageStubParameters=QA.map(ve=>JSON.stringify(ve));break;case"subject":X.messageStubType=TA.GROUP_CHANGE_SUBJECT,X.messageStubParameters=[W.attrs.subject];break;case"description":let $A=le(W,"body")?.content?.toString();X.messageStubType=TA.GROUP_CHANGE_DESCRIPTION,X.messageStubParameters=$A?[$A]:void 0;break;case"announcement":case"not_announcement":X.messageStubType=TA.GROUP_CHANGE_ANNOUNCE,X.messageStubParameters=[W.tag==="announcement"?"on":"off"];break;case"locked":case"unlocked":X.messageStubType=TA.GROUP_CHANGE_RESTRICT,X.messageStubParameters=[W.tag==="locked"?"on":"off"];break;case"invite":X.messageStubType=TA.GROUP_CHANGE_INVITE_LINK,X.messageStubParameters=[W.attrs.code];break;case"member_add_mode":let RA=W.content;RA&&(X.messageStubType=TA.GROUP_MEMBER_ADD_MODE,X.messageStubParameters=[RA.toString()]);break;case"membership_approval_mode":let xA=le(W,"group_join");xA&&(X.messageStubType=TA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE,X.messageStubParameters=[xA.attrs.state]);break;case"created_membership_requests":X.messageStubType=TA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,X.messageStubParameters=[JSON.stringify({lid:Ce,pn:he}),"created",W.attrs.request_method];break;case"revoked_membership_requests":let et=Tt(Ce,re);X.messageStubType=TA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,X.messageStubParameters=[JSON.stringify({lid:Ce,pn:he}),et?"revoked":"rejected"];break}},WA=async ee=>{let[W]=ys(ee),X=uA(ee.attrs.from);if(!W){t.debug({from:X},"devices notification missing child, skipping");return}let re=W.tag,ne=W.attrs.device_hash,Oe=kA(W,"device");if(Tt(X,I.creds.me.id)||Tt(X,I.creds.me.lid)){let he=Oe.map(me=>me.attrs.jid);t.info({deviceJids:he},"got my own devices")}if(!Oe.length){t.debug({from:X,tag:re},"no devices in notification, skipping");return}let Ce=[];for(let he of Oe){let me=he.attrs.jid;if(!me)continue;let je=yA(me);if(!je){t.debug({jid:me},"failed to decode device jid, skipping");continue}Ce.push({jid:me,user:je.user,server:je.server,device:je.device})}Ce.length&&await g.mutex(async()=>{let he=new Map;for(let me of Ce){let je=he.get(me.user)||[];je.push(me),he.set(me.user,je)}for(let[me,je]of he){if(re==="update"){t.debug({user:me},`${me}'s device list updated, dropping cached devices`),await s?.del(me);continue}re==="remove"&&await y.deleteSession(je.map(RA=>RA.jid));let lA=await s?.get(me)||[];if(!lA.length){t.debug({user:me,tag:re},"device list not cached, deferring to USync refresh");continue}let QA=new Set(je.map(RA=>RA.device)),$A;switch(re){case"add":t.info({deviceHash:ne,count:je.length},"devices added"),$A=[...lA.filter(RA=>!QA.has(RA.device)),...je.map(RA=>({user:RA.user,server:RA.server,device:RA.device}))];break;case"remove":t.info({deviceHash:ne,count:je.length},"devices removed"),$A=lA.filter(RA=>!QA.has(RA.device));break;default:t.debug({tag:re},"Unknown device list change tag");continue}$A.length===0?await s?.del(me):await s?.set(me,$A)}})},FA=async ee=>{let W={},[X]=ys(ee),re=ee.attrs.type,ne=uA(ee.attrs.from);switch(re){case"newsletter":await ce(ee);break;case"mex":await Le(ee);break;case"w:gp2":gA(ee,X,W);break;case"mediaretry":let Oe=hoe(ee);c.emit("messages.media-update",[Oe]);break;case"encrypt":await iA(ee);break;case"devices":try{await WA(ee)}catch(ho){t.error({error:ho,node:ee},"failed to handle devices notification")}break;case"server_sync":let Ce=le(ee,"collection");if(Ce){let ho=Ce.attrs.name;await T([ho],!1)}break;case"picture":let he=le(ee,"set"),me=le(ee,"delete");if(c.emit("contacts.update",[{id:uA(ee?.attrs?.from)||(he||me)?.attrs?.hash||"",imgUrl:he?"changed":"removed"}]),Ur(ne)){let ho=he||me;W.messageStubType=TA.GROUP_CHANGE_ICON,he&&(W.messageStubParameters=[he.attrs.id]),W.participant=ho?.attrs.author,W.key={...W.key||{},participant:he?.attrs.author}}break;case"account_sync":if(X.tag==="disappearing_mode"){let ho=+X.attrs.duration,dp=+X.attrs.t;t.info({newDuration:ho},"updated account disappearing mode"),c.emit("creds.update",{accountSettings:{...I.creds.accountSettings,defaultDisappearingMode:{ephemeralExpiration:ho,ephemeralSettingTimestamp:dp}}})}else if(X.tag==="blocklist"){let ho=kA(X,"item");for(let{attrs:dp}of ho){let EM=[dp.jid],CM=dp.action==="block"?"add":"remove";c.emit("blocklist.update",{blocklist:EM,type:CM})}}break;case"link_code_companion_reg":let je=le(ee,"link_code_companion_reg"),lA=JA(Qa(je,"link_code_pairing_ref")),QA=JA(Qa(je,"primary_identity_pub")),$A=JA(Qa(je,"link_code_pairing_wrapped_primary_ephemeral_pub")),RA=await LA($A),xA=Br.sharedKey(I.creds.pairingEphemeralKeyPair.private,RA),et=PH(32),ve=PH(32),tA=Rn(xA,32,{salt:ve,info:"link_code_pairing_key_bundle_encryption_key"}),At=Buffer.concat([Buffer.from(I.creds.signedIdentityKey.public),QA,et]),zr=PH(12),rr=Dl(At,tA,zr,Buffer.alloc(0)),po=Buffer.concat([ve,zr,rr]),dM=Br.sharedKey(I.creds.signedIdentityKey.private,QA),hM=Buffer.concat([xA,dM,et]);I.creds.advSecretKey=Buffer.from(Rn(hM,32,{info:"adv_secret"})).toString("base64"),await m({tag:"iq",attrs:{to:OA,type:"set",id:r.generateMessageTag(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:I.creds.me.id,stage:"companion_finish"},content:[{tag:"link_code_pairing_wrapped_key_bundle",attrs:{},content:po},{tag:"companion_identity_public",attrs:{},content:I.creds.signedIdentityKey.public},{tag:"link_code_pairing_ref",attrs:{},content:lA}]}]}),I.creds.registered=!0,c.emit("creds.update",I.creds);break;case"privacy_token":await wA(ee);break}if(Object.keys(W).length)return W},Me=new Set,CA=(async()=>{try{let ee=await yb(I.keys);for(let W of ee)Me.add(W);t.debug({count:Me.size},"loaded tctoken index")}catch(ee){t.warn({err:ee?.message},"failed to load tctoken index")}})(),we;async function Ke(){we&&(clearTimeout(we),we=void 0);let ee=await rE(I.keys,Me);return I.keys.set({tctoken:ee})}function Ve(){we&&clearTimeout(we),we=setTimeout(()=>{we=void 0,Ke().catch(ee=>{t.warn({err:ee?.message},"failed to save tctoken index")})},5e3)}function NA(ee){ee&&ee!==hI&&!Me.has(ee)&&(Me.add(ee),Ve())}let wA=async ee=>{if(!le(ee,"tokens"))return;let X=uA(ee.attrs.from),ne=(ee.attrs.sender_lid&&qA(uA(ee.attrs.sender_lid))?uA(ee.attrs.sender_lid):void 0)??await js(X,V);t.debug({from:X,storageJid:ne},"processing privacy token notification"),await aE({result:ee,fallbackJid:ne,keys:I.keys,getLIDForPN:V,onNewJidStored:NA})};async function LA(ee){let W=JA(ee),X=W.slice(0,32),re=await iD(I.creds.pairingCode,X),ne=W.slice(32,48),Oe=W.slice(48,80);return p7(Oe,re,ne)}function JA(ee){if(ee===void 0)throw new Uf.Boom("Invalid buffer",{statusCode:400});return ee instanceof Buffer?ee:Buffer.from(ee)}let lt=async(ee,W)=>{let X=`${ee}:${W}`;return(await ie.get(X)||0){let X=`${ee}:${W}`,re=(await ie.get(X)||0)+1;await ie.set(X,re)},pe=async(ee,W,X,re)=>{let ne=ee.remoteJid,Oe=ee.participant||ne,Ce=+X.attrs.count||1,he=W[0],me=[];for(let ve of W){let tA;if(P){let At=P.getRecentMessage(ne,ve);At&&(tA=At.message,t.debug({jid:ne,id:ve},"found message in retry cache"),P.markRetrySuccess(ve))}tA||(tA=await e({...ee,id:ve}),tA&&(t.debug({jid:ne,id:ve},"found message via getMessage"),P&&P.markRetrySuccess(ve))),me.push(tA)}let je=!yA(Oe)?.device,lA=y.jidToSignalProtocolAddress(Oe),QA=!1,$A=Roe(re);if($A)try{await y.injectE2ESession({jid:Oe,session:$A}),QA=!0,t.debug({participant:Oe,retryCount:Ce},"injected session from retry receipt key bundle")}catch(ve){t.warn({error:ve,participant:Oe},"failed to inject session from retry receipt")}if(!QA){let ve=xc(re,"registration",4);if(typeof ve=="number"&&Number.isInteger(ve)){let tA=await y.getSessionInfo(Oe);tA&&tA.registrationId!==0&&tA.registrationId!==ve&&(t.info({participant:Oe,stored:tA.registrationId,received:ve},"reg id mismatch on retry without bundle, deleting session"),await I.keys.set({session:{[lA]:null}}))}}let RA=2;if(he&&P){let ve=await y.getSessionInfo(Oe);ve&&(Ce===RA?P.saveBaseKey(lA,he,ve.baseKey):Ce>RA&&(P.hasSameBaseKey(lA,he,ve.baseKey)&&(t.warn({participant:Oe,retryCount:Ce},"base key collision on retry, forcing fresh session"),await I.keys.set({session:{[lA]:null}})),P.deleteBaseKey(lA,he)))}let xA=!1,et="";if(A&&P&&Ce>1&&!QA)try{let ve=await y.validateSession(Oe),tA=P.shouldRecreateSession(Oe,ve.exists);xA=tA.recreate,et=tA.reason,xA&&(t.debug({participant:Oe,retryCount:Ce,reason:et},"recreating session for outgoing retry"),await I.keys.set({session:{[lA]:null}}))}catch(ve){t.warn({error:ve,participant:Oe},"failed to check session recreation for outgoing retry")}QA||await F([Oe],!0),Ur(ne)&&await I.keys.set({"sender-key-memory":{[ne]:null}}),t.debug({participant:Oe,sendToAll:je,shouldRecreateSession:xA,recreateReason:et,injectedFromBundle:QA},"prepared session for retry resend");for(let[ve,tA]of me.entries())if(W[ve])if(tA&&await lt(W[ve],Oe)){await wt(W[ve],Oe);let At={messageId:W[ve]};je?At.useUserDevicesCache=!1:At.participant={jid:Oe,count:+X.attrs.count},await L(ee.remoteJid,tA,At)}else t.debug({jid:ee.remoteJid,id:W[ve]},"recv retry request, but message not available")},Ie=async ee=>{let{attrs:W,content:X}=ee,re=W.from.includes("lid"),ne=Tt(W.participant||W.from,re?I.creds.me?.lid:I.creds.me?.id),Oe=!ne||Ur(W.from)?W.from:W.recipient,Ce=!W.recipient||(W.type==="retry"||W.type==="sender")&&ne,he={remoteJid:Oe,id:"",fromMe:Ce,participant:W.participant},me=[W.id];if(Array.isArray(X)){let je=kA(X[0],"item");me.push(...je.map(lA=>lA.attrs.id))}try{await Promise.all([Q.mutex(async()=>{let je=w7(W.type);if(typeof je<"u"&&(je>=oe.WebMessageInfo.Status.SERVER_ACK||!ne))if(Ur(Oe)||Tg(Oe)){if(W.participant){let lA=je===oe.WebMessageInfo.Status.DELIVERY_ACK?"receiptTimestamp":"readTimestamp";c.emit("message-receipt.update",me.map(QA=>({key:{...he,id:QA},receipt:{userJid:uA(W.participant),[lA]:+W.t}})))}}else c.emit("messages.update",me.map(lA=>({key:{...he,id:lA},update:{status:je,messageTimestamp:Hr(+(W.t??0))}})));if(W.type==="retry"){he.participant=he.participant||W.from;let lA=le(ee,"retry");if(me[0]&&he.participant&&await lt(me[0],he.participant))if(he.fromMe)try{await wt(me[0],he.participant),t.debug({attrs:W,key:he},"recv retry request"),await pe(he,me,lA,ee)}catch(QA){t.error({key:he,ids:me,trace:QA instanceof Error?QA.stack:"Unknown error"},"error in sending message again")}else t.info({attrs:W,key:he},"recv retry for not fromMe message");else t.info({attrs:W,key:he},"will not send message again, as sent too many times")}})])}finally{await Be(ee).catch(je=>t.error({ackErr:je},"failed to ack receipt"))}},be=async ee=>{let W=ee.attrs.from;try{await Promise.all([f.mutex(async()=>{let X=await FA(ee);if(X){let re=Tt(ee.attrs.participant||W,I.creds.me.id),{senderAlt:ne,addressingMode:Oe}=gD(ee);X.key={remoteJid:W,fromMe:re,participant:ee.attrs.participant,participantAlt:ne,participantUsername:ee.attrs.participant_username,addressingMode:Oe,id:ee.attrs.id,...X.key||{}},X.participant??(X.participant=ee.attrs.participant),X.messageTimestamp=+ee.attrs.t;let Ce=oe.WebMessageInfo.fromObject(X);await _(Ce,"append")}})])}finally{await Be(ee).catch(X=>t.error({ackErr:X},"failed to ack notification"))}},oA=async ee=>{if(le(ee,"enc")?.attrs.type==="msmsg"){t.debug({key:ee.attrs.key},"ignored msmsg"),await Be(ee,Ml.MissingMessageSecret);return}let X=!1;try{let{fullMessage:re,category:ne,author:Oe,decrypt:Ce}=R7(ee,I.creds.me.id,I.creds.me.lid||"",y,t),he=re.key.participantAlt||re.key.remoteJidAlt;if(he){let me=yA(he)?.server,je=re.key.participant||re.key.remoteJid;me==="lid"?await y.lidMapping.getPNForLID(he)||(await y.lidMapping.storeLIDPNMappings([{lid:he,pn:je}]),await y.migrateSession(je,he)):(await y.lidMapping.storeLIDPNMappings([{lid:je,pn:he}]),await y.migrateSession(he,je))}await B.mutex(async()=>{if(await Ce(),re.key?.remoteJid&&re.key?.id&&re.message&&P&&P.addRecentMessage(re.key.remoteJid,re.key.id,re.message),re.messageStubType===oe.WebMessageInfo.StubType.CIPHERTEXT&&re.category!=="peer"){if(re?.messageStubParameters?.[0]===T7)return X=!0,Be(ee,Ml.ParsingError);if(re.messageStubParameters?.[0]===sD){let je=le(ee,"unavailable")?.attrs?.type;if(je==="bot_unavailable_fanout"||je==="hosted_unavailable_fanout"||je==="view_once_unavailable_fanout")return t.debug({msgId:re.key.id,unavailableType:je},"skipping placeholder resend for excluded unavailable type"),X=!0,Be(ee);let lA=ya()-Hr(re.messageTimestamp);if(lA>ace)return t.debug({msgId:re.key.id,messageAge:lA},"skipping placeholder resend for old message"),X=!0,Be(ee);let QA={remoteJid:re.key.remoteJid,fromMe:re.key.fromMe,id:re.key.id,participant:re.key.participant},$A={key:re.key,messageTimestamp:re.messageTimestamp,pushName:re.pushName,participant:re.participant,verifiedBizName:re.verifiedBizName};Qe(QA,$A).then(RA=>{RA&&RA!=="RESOLVED"&&(t.debug({msgId:re.key.id,requestId:RA},"requested placeholder resend for unavailable message"),c.emit("messages.update",[{key:re.key,update:{messageStubParameters:[sD,RA]}}]))}).catch(RA=>{t.warn({err:RA,msgId:re.key.id},"failed to request placeholder resend for unavailable message")}),X=!0,await Be(ee)}else{if(Tg(re.key.remoteJid)){let me=ya()-Hr(re.messageTimestamp);if(me>rce)return t.debug({msgId:re.key.id,messageAge:me,remoteJid:re.key.remoteJid},"skipping retry for expired status message"),X=!0,Be(ee)}t.debug("[handleMessage] Attempting retry request for failed decryption"),await Ae.mutex(async()=>{try{if(!d.isOpen){t.debug({node:ee},"Connection closed, skipping retry");return}let me=le(ee,"enc");await Ye(ee,!me),o&&await DB(o)}catch(me){t.error({err:me},"Failed to send retry")}X=!0,await Be(ee,Ml.UnhandledError)})}}else if(P&&re.key.id&&P.cancelPendingPhoneRequest(re.key.id),Kc(re.key.remoteJid))X=!0,await Be(ee),t.debug({key:re.key},"processed newsletter message without receipts");else{let je,lA=re.key.participant;if(ne==="peer"?je="peer_msg":re.key.fromMe?(je="sender",(qA(re.key.remoteJid)||qA(re.key.remoteJidAlt))&&(lA=Oe)):_e||(je="inactive"),X=!0,await q(re.key.remoteJid,lA,[re.key.id],je),hb(re.message)){let $A=uA(re.key.remoteJid);await q($A,void 0,[re.key.id],"hist_sync")}}Dne(re,I.creds.me.id,I.creds.me.lid),await _(re,ee.attrs.offline?"append":"notify")})}catch(re){t.error({error:re,node:_n(ee)},"error in handling message"),X||await Be(ee,Ml.UnhandledError).catch(ne=>t.error({ackErr:ne},"failed to ack message after error"))}},pA=async ee=>{try{let{attrs:W}=ee,[X]=ys(ee);if(!X)throw new Uf.Boom("Missing call info in call node");let re=O7(X),ne=X.attrs["call-id"],Oe=X.attrs.from||X.attrs["call-creator"],Ce={chatId:W.from,from:Oe,callerPn:X.attrs.caller_pn,id:ne,date:new Date(+W.t*1e3),offline:!!W.offline,status:re};if(re==="relaylatency"){let me=X.attrs.latency||X.attrs.latency_ms||X.attrs["latency-ms"],je=me?Number(me):void 0;Number.isFinite(je)&&(Ce.latencyMs=je)}re==="offer"&&(Ce.isVideo=!!le(X,"video"),Ce.isGroup=X.attrs.type==="group"||!!X.attrs["group-jid"],Ce.groupJid=X.attrs["group-jid"],await De.set(Ce.id,Ce));let he=await De.get(Ce.id);he&&(Ce.isVideo=he.isVideo,Ce.isGroup=he.isGroup,Ce.callerPn=Ce.callerPn||he.callerPn),(re==="reject"||re==="accept"||re==="timeout"||re==="terminate")&&await De.del(Ce.id),c.emit("call",[Ce])}catch(W){t.error({error:W,node:_n(ee)},"error in handling call")}finally{await Be(ee).catch(W=>t.error({ackErr:W},"failed to ack call"))}},PA=async({attrs:ee})=>{let W={remoteJid:ee.from,fromMe:!0,id:ee.id};if(ee.error){let X=ee.error===String(Ml.SenderReachoutTimelocked);if(ee.error===_F.MessageAccountRestriction){t.warn({msgId:ee.id,from:ee.from},"error 463: account restricted or missing tctoken for contact");let re=ee.from;re&&!lo.has(re)&&(lo.add(re),(async()=>{try{let ne=y.lidMapping.getPNForLID.bind(y.lidMapping),Oe=await js(re,V),Ce=await bf(re,r.serverProps.lidTrustedTokenIssueToLid,V,ne),he=await U([Ce],ya());await aE({result:he,fallbackJid:Oe,keys:I.keys,getLIDForPN:V,onNewJidStored:NA}),t.debug({from:re},"completed 463 token recovery issuance")}catch(ne){t.debug({from:re,err:ne?.message},"failed 463 token recovery issuance")}finally{lo.delete(re)}})())}else ee.error===_F.SmaxInvalid?t.warn({msgId:ee.id,from:ee.from},"smax-invalid (479): stanza rejected by server \u2014 likely stale device session or malformed addressing"):X?(await N().catch(re=>t.warn({err:re},"failed to fetch reachout timelock")),t.warn({attrs:ee},"received error in ack")):t.warn({attrs:ee},"received error in ack");c.emit("messages.update",[{key:W,update:{status:th.ERROR,messageStubParameters:X?[ee.error,N7]:[ee.error]}}])}},Ht=async(ee,W,X)=>{c.buffer(),await re(),c.flush();function re(){return X(ee,!1).catch(ne=>R(ne,W))}},st=wce(new Map([["message",oA],["call",pA],["receipt",Ie],["notification",be]]),{isWsOpen:()=>d.isOpen,onUnexpectedError:R,yieldToEventLoop:()=>new Promise(ee=>setImmediate(ee))}),Qr=async(ee,W,X,re)=>{let ne=W.attrs.from,Oe=ne;if(ee==="receipt"&&ne){let he=W.attrs,me=he.from.includes("lid");Oe=!Tt(he.participant||he.from,me?I.creds.me?.lid:I.creds.me?.id)||Ur(he.from)?he.from:he.recipient}if(Oe&&Oe!==OA&&a(Oe)){await Be(W,ee==="message"?Ml.UnhandledError:void 0);return}!!W.attrs.offline?st.enqueue(ee,W):await Ht(W,X,re)};d.on("CB:message",async ee=>{await Qr("message",ee,"processing message",oA)}),d.on("CB:call",async ee=>{await Qr("call",ee,"handling call",pA)}),d.on("CB:receipt",async ee=>{await Qr("receipt",ee,"handling receipt",Ie)}),d.on("CB:notification",async ee=>{await Qr("notification",ee,"handling notification",be)}),d.on("CB:ack,class:message",ee=>{PA(ee).catch(W=>R(W,"handling bad ack"))}),c.on("call",async([ee])=>{if(ee&&(ee.status==="timeout"||ee.status==="offer"&&ee.isGroup)){let W={key:{remoteJid:ee.chatId,id:ee.id,fromMe:!1},messageTimestamp:ya(ee.date)};ee.status==="timeout"?ee.isGroup?W.messageStubType=ee.isVideo?TA.CALL_MISSED_GROUP_VIDEO:TA.CALL_MISSED_GROUP_VOICE:W.messageStubType=ee.isVideo?TA.CALL_MISSED_VIDEO:TA.CALL_MISSED_VOICE:W.message={call:{callKey:Buffer.from(ee.id)}};let X=oe.WebMessageInfo.fromObject(W);await _(X,ee.offline?"append":"notify")}});let tr=0,lo=new Set;c.on("connection.update",({isOnline:ee,connection:W})=>{if(typeof ee<"u"&&(_e=ee,t.trace(`sendActiveReceipts set to "${_e}"`)),W==="close"&&we){clearTimeout(we),we=void 0;try{Promise.resolve(Ke()).catch(()=>{})}catch{}}if(ee){let X=Date.now(),re=1440*60*1e3;X-tr>=re&&(tr=X,ji())}}),J(()=>{!n.msgRetryCounterCache&&ie.close&&ie.close(),!n.callOfferCache&&De.close&&De.close(),fe.close(),_e=!1});async function ji(){try{await CA;let ee=await yb(I.keys),W=new Set(Me);for(let he of ee)W.add(he);if(!W.size)return;let X=[...W],re=await I.keys.get("tctoken",X),ne={},Oe=new Set,Ce=0;for(let he of X){let me=re[he];if(!me){Ce++;continue}let je=!!me.token?.length,lA=je&&Ap(me.timestamp),QA=me.senderTimestamp!==void 0,$A=QA&&Ap(me.senderTimestamp),RA=je&&!lA,xA=QA&&!$A;!RA&&!xA?(ne[he]=null,Ce++):lA&&xA?(ne[he]={token:Buffer.alloc(0),senderTimestamp:me.senderTimestamp},Oe.add(he),Ce++):Oe.add(he)}if(Ce===0)return;await I.keys.set({tctoken:{...ne,[hI]:{token:Buffer.from(JSON.stringify([...Oe]))}}}),Me.clear();for(let he of Oe)Me.add(he);t.debug({mutated:Ce,remaining:Oe.size},"pruned expired tctokens")}catch(ee){t.warn({err:ee?.message},"failed to prune expired tctokens")}}return{...r,sendMessageAck:Be,sendRetryRequest:Ye,rejectCall:We,fetchMessageHistory:Ee,requestPlaceholderResend:Qe,messageRetryManager:P}};var Nce=n=>{let t=Tce(n),{authState:o,query:i,waUploadToServer:e}=t,a=async f=>{let Q=[],y=["address","email","description"];return Q.push(...y.filter(_=>f[_]!==void 0&&f[_]!==null).map(_=>({tag:_,attrs:{},content:f[_]}))),f.websites!==void 0&&Q.push(...f.websites.map(_=>({tag:"website",attrs:{},content:_}))),f.hours!==void 0&&Q.push({tag:"business_hours",attrs:{timezone:f.hours.timezone},content:f.hours.days.map(_=>{let T={tag:"business_hours_config",attrs:{day_of_week:_.day,mode:_.mode}};return _.mode==="specific_hours"?{...T,attrs:{...T.attrs,open_time:_.openTimeInMinutes,close_time:_.closeTimeInMinutes}}:T})}),await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:Q}]})},A=async f=>{let{fileSha256:Q,filePath:y}=await gb(f,"biz-cover-photo"),m=Q.toString("base64"),{meta_hmac:_,fbid:T,ts:R}=await e(y,{fileEncSha256B64:m,mediaType:"biz-cover-photo"});return await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{id:String(T),op:"update",token:_,ts:String(R)}}]}]}),T},r=async f=>await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{op:"delete",id:f}}]}]}),s=async({jid:f,limit:Q,cursor:y})=>{f=f||o.creds.me?.id,f=uA(f);let m=[{tag:"limit",attrs:{},content:Buffer.from((Q||10).toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}];y&&m.push({tag:"after",attrs:{},content:y});let _=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog",attrs:{jid:f,allow_shop_source:"true"},content:m}]});return Ice(_)},g=async(f,Q=51)=>{f=f||o.creds.me?.id,f=uA(f);let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog",smax_id:"35"},content:[{tag:"collections",attrs:{biz_jid:f},content:[{tag:"collection_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"item_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]}]});return lce(y)},c=async(f,Q)=>{let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"fb:thrift_iq",smax_id:"5"},content:[{tag:"order",attrs:{op:"get",id:f},content:[{tag:"image_dimensions",attrs:{},content:[{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]},{tag:"token",attrs:{},content:Buffer.from(Q)}]}]});return pce(y)},I=async(f,Q)=>{Q=await _H(Q,e);let y=MH(f,Q),m=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_edit",attrs:{v:"1"},content:[y,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),_=le(m,"product_catalog_edit"),T=le(_,"product");return Ff(T)},d=async f=>{f.isHidden=!!f.isHidden,f=await _H(f,e);let Q=MH(void 0,f),y=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_add",attrs:{v:"1"},content:[Q,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),m=le(y,"product_catalog_add"),_=le(m,"product");return Ff(_)},B=async f=>{let Q=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_delete",attrs:{v:"1"},content:f.map(m=>({tag:"product",attrs:{},content:[{tag:"id",attrs:{},content:Buffer.from(m)}]}))}]});return{deleted:+(le(Q,"product_catalog_delete")?.attrs.deleted_count||0)}};return{...t,logger:n.logger,getOrderDetails:c,getCatalog:s,getCollections:g,productCreate:d,productDelete:B,productUpdate:I,updateBussinesProfile:a,updateCoverPhoto:A,removeCoverPhoto:r}};var Rce=n=>{let t=Nce(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(I,d,B)=>e({tag:"iq",attrs:{type:d,xmlns:"w:g2",to:I},content:B}),r=async I=>{let d=await A(I,"get",[{tag:"query",attrs:{request:"interactive"}}]);return GH(d)},s=async()=>{let I=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),d={},B=le(I,"communities");if(B){let f=kA(B,"community");for(let Q of f){let y=GH({tag:"result",attrs:{},content:[Q]});d[y.id]=y}}return t.ev.emit("groups.update",Object.values(d)),d};async function g(I){vf.info({node:I},"parseGroupResult");let d=le(I,"group");if(d)try{vf.info({groupNode:d},"groupNode");let B=await t.groupMetadata(`${d.attrs.id}@g.us`);return B||c.empty()}catch(B){return console.error("Error parsing group metadata:",B),c.empty()}return c.empty()}let c={empty:()=>null,of:I=>I!==null?{value:I}:null};return t.ws.on("CB:ib,,dirty",async I=>{let{attrs:d}=le(I,"dirty");d.type==="communities"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,communityMetadata:r,communityCreate:async(I,d)=>{let B=bF().substring(0,12),f=await A("@g.us","set",[{tag:"create",attrs:{subject:I},content:[{tag:"description",attrs:{id:B},content:[{tag:"body",attrs:{},content:Buffer.from(d||"","utf-8")}]},{tag:"parent",attrs:{default_membership_approval_mode:"request_required"}},{tag:"allow_non_admin_sub_group_creation",attrs:{}},{tag:"create_general_chat",attrs:{}}]}]);return await g(f)},communityCreateGroup:async(I,d,B)=>{let f=Kr(),Q=await A("@g.us","set",[{tag:"create",attrs:{subject:I,key:f},content:[...d.map(y=>({tag:"participant",attrs:{jid:y}})),{tag:"linked_parent",attrs:{jid:B}}]}]);return await g(Q)},communityLeave:async I=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"community",attrs:{id:I}}]}])},communityUpdateSubject:async(I,d)=>{await A(I,"set",[{tag:"subject",attrs:{},content:Buffer.from(d,"utf-8")}])},communityLinkGroup:async(I,d)=>{await A(d,"set",[{tag:"links",attrs:{},content:[{tag:"link",attrs:{link_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}]}])},communityUnlinkGroup:async(I,d)=>{await A(d,"set",[{tag:"unlink",attrs:{unlink_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}])},communityFetchLinkedGroups:async I=>{let d=I,B=!1,f=await t.groupMetadata(I);f.linkedParent?d=f.linkedParent:B=!0;let Q=await A(d,"get",[{tag:"sub_groups",attrs:{}}]),y=[],m=le(Q,"sub_groups");if(m){let _=kA(m,"group");for(let T of _)y.push({id:T.attrs.id?Cr(T.attrs.id,"g.us"):void 0,subject:T.attrs.subject||"",creation:T.attrs.creation?Number(T.attrs.creation):void 0,owner:T.attrs.creator?uA(T.attrs.creator):void 0,size:T.attrs.size?Number(T.attrs.size):void 0})}return{communityJid:d,isCommunity:B,linkedGroups:y}},communityRequestParticipantsList:async I=>{let d=await A(I,"get",[{tag:"membership_approval_requests",attrs:{}}]),B=le(d,"membership_approval_requests");return kA(B,"membership_approval_request").map(Q=>Q.attrs)},communityRequestParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:B,attrs:{},content:d.map(_=>({tag:"participant",attrs:{jid:_}}))}]}]),Q=le(f,"membership_requests_action"),y=le(Q,B);return kA(y,"participant").map(_=>({status:_.attrs.error||"200",jid:_.attrs.jid}))},communityParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:B,attrs:B==="remove"?{linked_groups:"true"}:{},content:d.map(m=>({tag:"participant",attrs:{jid:m}}))}]),Q=le(f,B);return kA(Q,"participant").map(m=>({status:m.attrs.error||"200",jid:m.attrs.jid,content:m}))},communityUpdateDescription:async(I,d)=>{let f=(await r(I)).descId??null;await A(I,"set",[{tag:"description",attrs:{...d?{id:bF()}:{delete:"true"},...f?{prev:f}:{}},content:d?[{tag:"body",attrs:{},content:Buffer.from(d,"utf-8")}]:void 0}])},communityInviteCode:async I=>{let d=await A(I,"get",[{tag:"invite",attrs:{}}]);return le(d,"invite")?.attrs.code},communityRevokeInvite:async I=>{let d=await A(I,"set",[{tag:"invite",attrs:{}}]);return le(d,"invite")?.attrs.code},communityAcceptInvite:async I=>{let d=await A("@g.us","set",[{tag:"invite",attrs:{code:I}}]);return le(d,"community")?.attrs.jid},communityRevokeInviteV4:async(I,d)=>!!await A(I,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:d}}]}]),communityAcceptInviteV4:i.createBufferedFunction(async(I,d)=>{I=typeof I=="string"?{remoteJid:I}:I;let B=await A(d.groupJid,"set",[{tag:"accept",attrs:{code:d.inviteCode,expiration:d.inviteExpiration.toString(),admin:I.remoteJid}}]);return I.id&&(d=oe.Message.GroupInviteMessage.fromObject(d),d.inviteExpiration=0,d.inviteCode="",i.emit("messages.update",[{key:I,update:{message:{groupInviteMessage:d}}}])),await a({key:{remoteJid:d.groupJid,id:Kr(t.user?.id),fromMe:!1,participant:I.remoteJid},messageStubType:TA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:I.remoteJid,messageTimestamp:ya()},"notify"),B.attrs.from}),communityGetInviteInfo:async I=>{let d=await A("@g.us","get",[{tag:"invite",attrs:{code:I}}]);return GH(d)},communityToggleEphemeral:async(I,d)=>{let B=d?{tag:"ephemeral",attrs:{expiration:d.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(I,"set",[B])},communitySettingUpdate:async(I,d)=>{await A(I,"set",[{tag:d,attrs:{}}])},communityMemberAddMode:async(I,d)=>{await A(I,"set",[{tag:"member_add_mode",attrs:{},content:d}])},communityJoinApprovalMode:async(I,d)=>{await A(I,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"community_join",attrs:{state:d}}]}])},communityFetchAllParticipating:s}},GH=n=>{let t=le(n,"community"),o=le(t,"description"),i,e;o&&(i=YA(o,"body"),e=o.attrs.id);let a=t.attrs.id?.includes("@")?t.attrs.id:Cr(t.attrs.id||"","g.us"),A=le(t,"ephemeral")?.attrs.expiration,r=YA(t,"member_add_mode")==="all_member_add";return{id:a,subject:t.attrs.subject||"",subjectOwner:t.attrs.s_o,subjectTime:Number(t.attrs.s_t||0),size:kA(t,"participant").length,creation:Number(t.attrs.creation||0),owner:t.attrs.creator?uA(t.attrs.creator):void 0,desc:i,descId:e,linkedParent:le(t,"linked_parent")?.attrs.jid||void 0,restrict:!!le(t,"locked"),announce:!!le(t,"announcement"),isCommunity:!!le(t,"parent"),isCommunityAnnounce:!!le(t,"default_sub_community"),joinApprovalMode:!!le(t,"membership_approval_mode"),memberAddMode:r,participants:kA(t,"participant").map(({attrs:g})=>({id:g.jid,admin:g.type||null})),ephemeralDuration:A?+A:void 0,addressingMode:YA(t,"addressing_mode")}};var q5e=n=>{let t={...oce,...n};return Rce(t)},kce=q5e;var vce=kce;var z5e=Object.freeze({key:"whatsapp",label:"WhatsApp",get connectionLabel(){return w(" Web \u5173\u8054\u8BBE\u5907")},reactions:Object.freeze({processing:"\u{1F440}",success:"\u2705",error:"\u274C"})}),oM=class extends $n{constructor(t){super({...t,descriptor:z5e})}};import{chmod as Pce,mkdir as V5e,readdir as W5e}from"node:fs/promises";var Z5e=Object.freeze({level:"silent",trace(){},debug(){},info(){},warn(){},error(){},fatal(){},child(){return this}}),X5e=6e4;function Gce(){return Object.assign(new Error("WhatsApp connection was cancelled"),{name:"AbortError"})}function $5e(n){return n?.output?.statusCode??n?.data?.statusCode??n?.statusCode??null}function eZe(n){let t=n;if(typeof t=="string"){if(!/^\d+$/.test(t))return null;t=Number(t)}else typeof t=="bigint"?t=Number(t):t&&typeof t=="object"&&(t=Number(t.valueOf()));return Number.isFinite(t)&&t>=0?t*1e3:null}async function FH(n){await V5e(n,{recursive:!0,mode:448}),await Pce(n,448);let t=await W5e(n,{withFileTypes:!0}).catch(()=>[]);await Promise.all(t.filter(o=>o.isFile()).map(o=>Pce(`${n}/${o.name}`,384).catch(()=>{})))}function AZe(n,t){let o=n.user??t.creds.me,i=uA(o?.id);if(!/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(i??""))throw new Error("WhatsApp did not return a valid linked account");return{accountJid:i,name:typeof o?.name=="string"&&o.name.trim()?o.name.trim().slice(0,100):w("WhatsApp\u673A\u5668\u4EBA")}}async function nM({authDir:n,onQr:t,onMessage:o,onDisconnect:i,signal:e,logger:a=console,makeSocket:A=vce,loadAuthState:r=mne}={}){if(!n||typeof t!="function")throw new TypeError("WhatsApp Web session requires an auth directory and QR callback");await FH(n);let s=Date.now(),{state:g,saveCreds:c}=await r(n),I=g.keys.set.bind(g.keys);g.keys.set=async z=>{await I(z),await FH(n)};let d=!1,B=!1,f,Q,y=Promise.resolve(),m=null,_=0,T=null,R=new Promise((z,j)=>{f=z,Q=j}),F=z=>{B||(B=!0,Q(z))},K=async()=>{d||(d=!0,_+=1,F(Gce()),await T?.catch(()=>{}),await y.catch(()=>{}),await m?.end(void 0).catch(()=>{}))},L=async()=>{d||(d=!0,_+=1,F(Gce()),await T?.catch(()=>{}),await y.catch(()=>{}),await m?.logout("Removed from DeepSeek Harness").catch(()=>{}))},q=()=>{let z=++_,j=!1,P=A({auth:g,browser:wb.macOS("DeepSeek Harness"),logger:Z5e,markOnlineOnConnect:!1,syncFullHistory:!1,shouldSyncHistoryMessage:()=>!1,getMessage:async()=>{},generateHighQualityLinkPreview:!1});m=P;let J=()=>{!j||!g.creds.me||B||y.then(()=>{d||B||z!==_||!j||!g.creds.me||(B=!0,f(AZe(P,g)))}).catch(U=>F(U))};P.ev.on("creds.update",()=>{d||z!==_||(y=y.then(async()=>{await c(),await FH(n)}),y.catch(()=>a.error?.("[dsh-im:whatsapp] failed to persist linked-device state")),J())}),P.ev.on("connection.update",U=>{if(!(d||z!==_)&&(typeof U.qr=="string"&&U.qr&&t(U.qr),U.connection==="open"&&(j=!0,J()),U.connection==="close")){let N=$5e(U.lastDisconnect?.error);if(N===$t.restartRequired){T??=y.then(async()=>{d||z!==_||(await P.end(void 0).catch(()=>{}),!(d||z!==_)&&q())}).catch(Ae=>F(Ae)).finally(()=>{T=null});return}let k=N===$t.loggedOut,V=Object.assign(new Error(k?"WhatsApp linked device was removed from the phone":"WhatsApp Web connection closed"),{code:k?"logged-out":"connection-closed"});B?i?.({error:V,loggedOut:k}):F(V)}}),P.ev.on("messages.upsert",({messages:U,type:N})=>{if(!(d||z!==_||N!=="notify"&&N!=="append"||typeof o!="function"))for(let k of Array.isArray(U)?U:[]){if(N==="append"){let V=eZe(k?.messageTimestamp);if(V===null||V{a.error?.("[dsh-im:whatsapp] failed to process an inbound WhatsApp message")})}})};return q(),e&&(e.aborted?await K():e.addEventListener("abort",()=>void K(),{once:!0})),Object.freeze({get socket(){return m},ready:R,close:K,logout:L})}var UH=new Set(["image/jpeg","image/png","image/webp","image/gif"]),rZe=5*1024*1024,LH=15e3,HH=12e4,aZe=["ephemeralMessage","viewOnceMessage","documentWithCaptionMessage","viewOnceMessageV2","viewOnceMessageV2Extension","editedMessage","associatedChildMessage","groupStatusMessage","groupStatusMessageV2"],iZe=new Set(["viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension"]);function oZe(n){let t=n;for(let o=0;o<5&&t&&typeof t=="object";o+=1){let i=aZe.find(e=>t[e]?.message);if(!i)return!1;if(iZe.has(i))return!0;t=t[i].message}return!1}function nZe(n){return n?.extendedTextMessage?.contextInfo??n?.imageMessage?.contextInfo??n?.videoMessage?.contextInfo??n?.documentMessage?.contextInfo??null}function sZe(n){return n?.conversation??n?.extendedTextMessage?.text??n?.imageMessage?.caption??n?.videoMessage?.caption??n?.documentMessage?.caption??""}function Uce(n){if(Number.isSafeInteger(n)&&n>=0)return n;let t;try{t=Number(n?.toString?.())}catch{return}return Number.isSafeInteger(t)&&t>=0?t:void 0}async function gZe(n,t,{signal:o,maxBytes:i=rZe}={}){o?.throwIfAborted();let e=AbortSignal.timeout(LH),a=o?AbortSignal.any([o,e]):e,A=Promise.resolve().then(()=>t(n,"stream",{options:{signal:a}})),r=await new Promise((I,d)=>{let B=!1,f=(y,m)=>B?!1:(B=!0,a.removeEventListener("abort",Q),y(m),!0),Q=()=>f(d,a.reason);a.addEventListener("abort",Q,{once:!0}),A.then(y=>{f(I,y)||y?.destroy?.()},y=>f(d,y)),a.aborted&&Q()}).catch(I=>{throw o?.aborted?o.reason??I:e.aborted?new Bt("image-download-failed",`WhatsApp image download timed out after ${LH} ms`,w("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}),s=[],g=0,c=()=>r?.destroy?.(a.reason);a.addEventListener("abort",c,{once:!0});try{for await(let I of r){a.throwIfAborted();let d=Buffer.from(I);if(g+=d.length,g>i)throw r.destroy?.(),new Bt("image-too-large",`WhatsApp image exceeded ${i} bytes`,w("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));s.push(d)}}catch(I){throw o?.aborted?o.reason??I:e.aborted?new Bt("image-download-failed",`WhatsApp image stream timed out after ${LH} ms`,w("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}finally{a.removeEventListener("abort",c)}return Buffer.concat(s,g)}function cZe(n,t,o,{viewOnce:i=!1}={}){let e,a;if(!i&&t?.imageMessage&&t.imageMessage.viewOnce!==!0)e=t.imageMessage;else if(t?.documentMessage){let r=typeof t.documentMessage.mimetype=="string"?t.documentMessage.mimetype.toLowerCase():"";if(!UH.has(r))return null;e=t.documentMessage,a=typeof e.fileName=="string"?e.fileName:void 0}if(!e)return null;let A=typeof e.mimetype=="string"?e.mimetype.toLowerCase():"";return UH.has(A)?{name:a,mediaType:A,size:Uce(e.fileLength),load:r=>gZe(n,o,r)}:null}function IZe(n,t,o){let i=t?.documentMessage;if(!i)return null;let e=typeof i.mimetype=="string"&&i.mimetype?i.mimetype.toLowerCase():void 0;return UH.has(e)?null:{name:typeof i.fileName=="string"&&i.fileName?i.fileName:"whatsapp-file",...e?{mediaType:e}:{},size:Uce(i.fileLength),async load({signal:a}={}){a?.throwIfAborted();let A=await o(n,"stream",{options:{signal:a}});return a?.throwIfAborted(),{stream:A}}}}function lZe({socket:n,logger:t=console,download:o=X2}={}){if(typeof o!="function")throw new TypeError("WhatsApp media downloader is required");return typeof n?.updateMediaMessage!="function"?o:(i,e,a)=>o(i,e,a,{logger:t,reuploadRequest:A=>n.updateMediaMessage(A)})}function pZe(n,t,{download:o=X2}={}){let i=typeof n?.key?.remoteJid=="string"?n.key.remoteJid:"",e=typeof n?.key?.remoteJidAlt=="string"?n.key.remoteJidAlt:"",a=typeof n?.key?.id=="string"?n.key.id:"";if(!i||!a||i==="status@broadcast"||i.endsWith("@newsletter"))return null;let A=i.endsWith("@g.us"),r=n.key.fromMe===!0,s=r&&!A&&[i,e].some(_=>_&&Tt(_,t));if(r&&!s&&!A)return null;let g=r?t:A?n.key.participant:i,c=A&&!r?n.key.participantAlt:e;if(typeof g!="string"||!g)return null;let I=oZe(n.message),d=Oa(n.message),B=nZe(d),f=Array.isArray(B?.mentionedJid)&&B.mentionedJid.some(_=>Tt(_,t)),Q=typeof B?.participant=="string"&&Tt(B.participant,t),y=cZe(n,d,o,{viewOnce:I}),m=IZe(n,d,o);return{messageId:`${i}:${a}`,providerMessageId:a,senderId:g,contextSource:()=>({senderName:n.pushName}),senderAlternateId:typeof c=="string"?c:"",senderIsBot:!1,kind:A?"group":"direct",conversationId:i,content:sZe(d),plainText:typeof d?.conversation=="string"||typeof d?.extendedTextMessage?.text=="string",images:y?[y]:[],files:m?[m]:[],addressed:!A||r||f||Q,selfChat:s,replyTarget:{jid:i,quoted:n,selfChat:s},reactionTarget:{jid:i,key:n.key}}}function dZe(n,{accessMode:t=zd.selfOnly,allowedNumbers:o=new Set}={}){if(t===zd.open)return!0;if(n?.kind!=="direct")return!1;if(n.selfChat===!0)return!0;if(t!==zd.privateAllowlist||!(o instanceof Set))return!1;let i=[n.senderId,n.senderAlternateId].filter(e=>typeof e=="string"&&e.endsWith("@s.whatsapp.net"));return[...o].some(e=>i.some(a=>Tt(a,`${e}@s.whatsapp.net`)))}var KH=class{#e=new Map;has(t){return this.#t(),this.#e.has(t)}remember(t){this.#A(t)}reserve(t){this.#A(t)}#A(t){if(!(typeof t!="string"||!t))for(this.#t(),this.#e.set(t,Date.now()+5*6e4);this.#e.size>256;)this.#e.delete(this.#e.keys().next().value)}#t(){let t=Date.now();for(let[o,i]of this.#e)i>t||this.#e.delete(o)}};function Hce(n){return n?.reason??new DOMException("The operation was aborted.","AbortError")}function Lce(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,Hce(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}function hZe(n){if(n?.code==="artifact-delivery-uncertain")return n;let t=new Error("WhatsApp could not confirm artifact delivery.");return t.code="artifact-delivery-uncertain",t.cause=n,t}function EZe(n){if(n?.code?.startsWith?.("artifact-"))return n;let t=n?.output?.statusCode??n?.data?.statusCode??n?.statusCode,o;if(t===401||t===403?o="artifact-permission-required":t===413?o="artifact-too-large":t===429?o="artifact-rate-limited":[400,404,405,406,410,415,422].includes(t)&&(o="artifact-provider-rejected"),!o)return hZe(n);let i=new Error("WhatsApp rejected artifact delivery.");return i.code=o,i.cause=n,i}var xH=class{#e;#A;#t;#r;#g=new Map;constructor(t,o,{signal:i,mediaUploadTimeoutMs:e=HH}={}){this.#e=t,this.#A=o,this.#t=i,this.#r=e}async sendText(t,o){await this.#i(t.jid);let i=[];for(let[e,a]of es(o,4e3).entries()){let A=Fce(10).toString("hex").toUpperCase(),r={...e===0&&t.quoted?{quoted:t.quoted}:{},messageId:A};typeof this.#A.reserve=="function"?this.#A.reserve(A):this.#A.remember(A);let s=await this.#e.sendMessage(t.jid,{text:a},r);this.#A.remember(s?.key?.id),typeof s?.key?.id=="string"&&s.key.id&&i.push(s.key.id)}return{providerMessageIds:i}}async sendFile(t,o){return this.#n(t,o,{document:o.bytes,mimetype:o.mediaType??"application/octet-stream",fileName:o.fileName},"file")}async sendImage(t,o){return this.#n(t,o,{image:o.bytes,mimetype:o.mediaType??"image/jpeg"},"image")}async addReaction(t,o,{signal:i}={}){if(typeof o!="string"||!o.trim())throw new TypeError("A WhatsApp reaction emoji is required");let e=o.trim();return await this.#a(t,e,i),e}removeReaction(t,o,{signal:i}={}){return this.#a(t,"",i)}async#a(t,o,i){if(typeof t?.jid!="string"||!t.jid||!t.key?.id)throw new TypeError("A WhatsApp reaction target is required");let e=i??this.#t;e?.throwIfAborted();let a=Fce(10).toString("hex").toUpperCase();typeof this.#A.reserve=="function"?this.#A.reserve(a):this.#A.remember(a);let A=this.#e.sendMessage(t.jid,{react:{text:o,key:t.key}},{messageId:a}),r=await Lce(A,e);return this.#A.remember(r?.key?.id),r}async#n(t,o,i,e){this.#t?.throwIfAborted(),await this.#i(t.jid),this.#t?.throwIfAborted();let a=typeof o.deliveryKey=="string"&&o.deliveryKey?o.deliveryKey:o.artifactId,A=e==="image"?`${a}:image`:a,r=typeof A=="string"&&A?tZe("sha256").update(A).digest("hex").slice(0,20).toUpperCase():void 0,s={...t.quoted?{quoted:t.quoted}:{},...r?{messageId:r}:{},mediaUploadTimeoutMs:this.#r};this.#A.remember(r);let g;try{let c=this.#e.sendMessage(t.jid,i,s);ln(o,c);let I=AbortSignal.timeout(this.#r),d=this.#t?AbortSignal.any([this.#t,I]):I;g=await Lce(c,d)}catch(c){throw this.#t?.aborted?Hce(this.#t):EZe(c)}return this.#t?.throwIfAborted(),this.#A.remember(g?.key?.id),g}async sendTyping(t){!t.selfChat&&t.quoted?.key&&await this.#e.readMessages([t.quoted.key]).catch(()=>{}),await this.#e.sendPresenceUpdate("composing",t.jid),await this.#i(t.jid,!1);let o=setInterval(()=>{this.#e.sendPresenceUpdate("composing",t.jid).catch(()=>{this.#i(t.jid)})},2e4);o.unref?.(),this.#g.set(t.jid,o)}async close(){let t=[...this.#g.keys()];await Promise.allSettled(t.map(o=>this.#i(o)))}async#i(t,o=!0){let i=this.#g.get(t);i&&clearInterval(i),this.#g.delete(t),o&&await this.#e.sendPresenceUpdate("paused",t).catch(()=>{})}};function CZe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...Xi()}}var Hf=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c=CZe();#p=null;#d=null;#h=null;#E=null;#C=null;constructor({config:t,authDir:o,harness:i,state:e,contextEnhancement:a,logger:A=console,replyTimeoutMs:r=6e5,connectTimeoutMs:s=3e4,mediaUploadTimeoutMs:g=HH,createSession:c=nM}){if(!t||!o||!i||!e||typeof c!="function")throw new TypeError("WhatsappRuntime requires config, auth directory, Harness, state, and session factory");if(this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,!Number.isSafeInteger(g)||g<=0)throw new TypeError("mediaUploadTimeoutMs must be a positive safe integer");this.#I=Math.min(g,HH),this.#s=c,this.setAccessPolicy(t)}get status(){return structuredClone(this.#c)}setAccessPolicy(t){let o=wg(t);return this.#l=o.accessMode,this.#o=new Set(o.allowedNumbers),this.#e={...this.#e,...o},o}async start(){return this.#c.ready&&this.#d?this.status:this.#C?this.#C:(this.#C=this.#f().finally(()=>{this.#C=null}),this.#C)}async#f(){await this.stop(),this.#c.startedAt=new Date().toISOString(),this.#c.connectionState="connecting",this.#c.lastError=null,await this.#t.ensureRunning(),this.#c.harnessReachable=!0;let t=new AbortController;this.#p=t;let o=new KH,i,e=new Promise((a,A)=>{i=A});e.catch(()=>{});try{let a=await this.#s({authDir:this.#A,signal:t.signal,logger:this.#a,onQr:()=>i(Object.assign(new Error("WhatsApp linked-device session must be scanned again"),{code:"relink-required"})),onMessage:async(c,I)=>{let d=pZe(c,this.#e.accountJid,{download:lZe({socket:I?.socket,logger:this.#a})});if(!(!d||o.has(d.providerMessageId)||!this.#E)){if(this.#c.lastCheckedAt=Date.now(),!dZe(d,{accessMode:this.#l,allowedNumbers:this.#o})){this.#c.messagesRejected+=1,this.#c.lastRejectedAt=new Date().toISOString();return}await this.#E.accept(d)}},onDisconnect:({error:c})=>{t.signal.aborted||(this.#c.ready=!1,this.#c.connectionState="failed",this.#c.lastError=c?.message??"WhatsApp Web connection closed")}});this.#d=a;let A,r=await Promise.race([a.ready,e,new Promise((c,I)=>{A=setTimeout(()=>I(new Error("WhatsApp Web did not connect in time")),this.#i)})]).finally(()=>clearTimeout(A));if(!Tt(r.accountJid,this.#e.accountJid))throw new Error("WhatsApp linked account does not match the saved bot");let s=new xH(a.socket,o,{signal:t.signal,mediaUploadTimeoutMs:this.#I});this.#h=s,this.#E=new oM({bot:s,harness:this.#t,state:this.#r,contextEnhancement:this.#g,status:this.#c,logger:this.#a,replyTimeoutMs:this.#n,signal:t.signal});let g=Date.now();return this.#c.ready=!0,this.#c.connectionState="connected",this.#c.lastCheckedAt=g,this.#c.lastConnectedAt=g,this.status}catch(a){throw this.#c.ready=!1,this.#c.connectionState="failed",this.#c.lastError=a?.message??String(a),await this.stop(),a}}async logout(){return await this.#d?.logout().catch(()=>{}),this.stop()}async sendConnectionTest(t){if(!this.#c.ready||!this.#h){let o=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw o.code="test-target-unavailable",o}if(typeof t!="string"||!t.trim())throw new TypeError("WhatsApp connection test text is required");return await this.#h.sendText({jid:this.#e.accountJid,selfChat:!0},t),{sent:!0}}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.jid=="string"?t.route.jid.trim():"",a=t?.kind==="user"&&/^[^@\s]+@(s\.whatsapp\.net|lid)$/.test(e),A=t?.kind==="group"&&/^[^@\s]+@g\.us$/.test(e);if(!a&&!A){let r=new TypeError("Invalid WhatsApp proactive delivery target");throw r.code="invalid-target",r}if(!this.#c.ready||!this.#h){let r=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw r.code="bot-not-connected",r}return i?.throwIfAborted(),this.#h.sendText({jid:e},o)}async stop(){let t=this.#d,o=this.#h,i=this.#E;return this.#p?.abort(),this.#p=null,this.#d=null,this.#h=null,this.#E=null,await o?.close().catch(()=>{}),await t?.close().catch(()=>{}),await Promise.race([i?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),this.#c.ready=!1,this.#c.connectionState="idle",this.status}};var QZe=/^[a-f0-9-]{36}$/;function yZe(n){let t=Xg(n.dshHome??process.env.DSH_HOME??uE(fZe(),".dsh")),o=Xg(n.dataDir??uE(t,"integrations","dsh-whatsapp")),i=Xg(n.authDir??uE(o,"auth")),e=a=>{if(!QZe.test(a??""))throw new TypeError("Invalid WhatsApp auth directory");return Xg(i,a)};return{config:Xg(n.configPath??uE(o,"config.json")),bots:Xg(n.botsDir??uE(o,"bots")),workspaces:Xg(n.workspacesPath??uE(o,"workspaces.json")),authPath:e}}async function YH(n,t={},o={}){let i=Aa(n,t),e=typeof n.logger=="function"?n.logger("dsh-im:whatsapp"):n.logger??console,a=()=>Ra(n),A=o.ConfigStore??ww,r=o.StateStore??Ow,s=o.HarnessClient??Dw,g=o.Controller??oB,c=o.Runtime??Hf,I=o.createSession??nM,d=o.createConnectionSupervisor??vp,B=yZe(t),f=await new A(B.config).load(),Q=Xg(t.workspace??process.cwd()),y=o.WorkspaceStore??ea,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=f.list();await m.reconcile(_.map(k=>k.botId)),await Promise.all(_.map(k=>m.ensure(k.botId,{defaultAgentPreset:t.agentPreset})));let T=typeof f.remove=="function"?Pa(f,{workspaces:m}):f,R=new Map,F=k=>Xg(B.bots,k,"state.json"),K=async k=>{let V=R.get(k);return V||(V=await new r(F(k)).load(),R.set(k,V)),V},L=Ua(n,o.commandExecutor),{controlExecutor:q,sessionMaintenanceExecutor:z,fileIngressExecutor:j}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),P=new s({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...L?{commandExecutor:L}:{},...q?{controlExecutor:q}:{},...z?{sessionMaintenanceExecutor:z}:{},...j?{fileIngressExecutor:j}:{}}),J=new g({configStore:T,authPath:B.authPath,createSession:I,logger:e,createRuntime:async({botId:k,config:V,authDir:Ae})=>{let ie=await K(k);await m.ensure(k,{defaultAgentPreset:t.agentPreset});let De=Ga(P,{botId:k,workspaces:m,state:ie,agentPresetCatalog:a});return new c({config:V,authDir:Ae,harness:De.harness,state:De.state,contextEnhancement:{botId:k,getSettings:()=>m.contextEnhancementFor(k)},replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??3e4,createSession:I,logger:{error:(...fe)=>e.error?.(`[${k}]`,...fe),warn:(...fe)=>e.warn?.(`[${k}]`,...fe),info:(...fe)=>e.info?.(`[${k}]`,...fe),debug:(...fe)=>e.debug?.(`[${k}]`,...fe)}})},deleteAuth:k=>uZe(B.authPath(k),{recursive:!0,force:!0}),deleteState:async({botId:k})=>{let V=R.get(k);if(R.delete(k),V&&typeof V.remove=="function")await V.remove();else try{await BZe(F(k))}catch(Ae){if(Ae?.code!=="ENOENT")throw Ae}}}),U=Fa(J,{workspaces:m,stateFor:K,agentPresetCatalog:a}),N=d({channel:"whatsapp",controller:U,harness:P,logger:e,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:U,deliveryAdapter:La({channel:"whatsapp",workspaces:m,coreController:J,stateFor:K}),ready:N.ready,async close(){await N.close(),await U.close(),P.stopManagedProcess()}}}import mZe from"qrcode";var Kce="/whatsapp",Or=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setAccessPolicy:"bot.access-policy.set",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),xce=Object.freeze(Object.values(Or)),SZe=new Set(["qrValue","accountJid","authDirectory"]);function JH(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Kf(n,t){return JH(n)&&Object.keys(n).every(o=>t.includes(o))}function sM(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function wZe(n,t){if(!JH(t))return"Payload must be an object.";if([Or.status,Or.beginProvisioning].includes(n))return Kf(t,[])?null:`${n} does not accept fields.`;if([Or.pollProvisioning,Or.cancelProvisioning].includes(n))return Kf(t,["attemptId"])&&sM(t.attemptId)?null:`${n} requires an attemptId.`;if(n===Or.reconnectBot)return Kf(t,["botId","sendTest"])&&sM(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId and optional sendTest flag.";if(n===Or.deleteBot)return Kf(t,["botId","confirm"])&&sM(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.";if(n===Or.setAccessPolicy){if(!Kf(t,["botId","accessMode","allowedNumbers"])||Object.keys(t).length!==3||!sM(t.botId))return"\u8BF7\u8F93\u5165\u6709\u6548\u7684 WhatsApp \u8BBF\u95EE\u6A21\u5F0F\u548C\u7535\u8BDD\u53F7\u7801\u3002";try{return wg(t),null}catch{return"\u8BF7\u8F93\u5165\u6709\u6548\u7684 WhatsApp \u8BBF\u95EE\u6A21\u5F0F\u548C\u7535\u8BDD\u53F7\u7801\u3002"}}return n===Or.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Or.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===Or.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown WhatsApp endpoint."}function BE(n){if(Array.isArray(n))return n.map(BE);if(!JH(n))return n;let t={};for(let[o,i]of Object.entries(n))SZe.has(o)||(t[o]=BE(i));return t}async function DZe(n){return mZe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function jH(n,t){return!n||typeof n.qrValue!="string"?BE(n):BE({...n,qrCodeDataUrl:await t(n.qrValue)})}async function Ip(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await jH(o.provisioning,t)),BE(o)}function Yce(n,{encodeQr:t=DZe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","reconnectBot","deleteBot","setAccessPolicy"])if(typeof n?.[e]!="function")throw new TypeError(`A complete WhatsApp controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!xce.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown WhatsApp endpoint."}};let r=wZe(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===Or.status)s=await Ip(await n.status(),i);else if(e===Or.beginProvisioning)s=await jH(await n.startProvisioning(),i);else if(e===Or.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await jH(g,i)}else if(e===Or.cancelProvisioning)s=BE(await n.cancelProvisioning(a.attemptId));else if(e===Or.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(s=await Ip(g,i),a.sendTest===!0){let c=null;if(!(g?.bots?.some(d=>d?.botId===a.botId&&d.connected===!0)===!0))c=new Error("WhatsApp bot is not connected"),c.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let d=new Error("Connection test is unavailable");throw d.code="test-target-unavailable",d}await n.sendConnectionTest(a.botId)}catch(d){c=d}s={...s,testMessage:ir(c)}}}else if(e===Or.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await Ip(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===Or.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>Ip(g,i))}else if(e===Or.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await Ip(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else e===Or.setAccessPolicy?s=await Ip(await n.setAccessPolicy(a.botId,wg(a)),i):s=await Ip(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"whatsapp-operation-failed",message:"WhatsApp \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function gM(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(Kce,Yce(t,o),{authority:hr(i)})}async function jce(n,t={}){if(t?.controller)return gM(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await YH(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=gM(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close WhatsApp Web connections"),e}var OZe="/dsh-im-delivery",bZe="DSH-IM \u4E3B\u52A8\u6295\u9012\u6D4B\u8BD5\u6210\u529F\u3002",pi=Object.freeze({send:"message.send",listTargets:"target.list",listSuggestions:"target.suggestion.list",createTarget:"target.create",updateTarget:"target.update",deleteTarget:"target.delete",testTarget:"target.test"}),MZe=new Set(Object.values(pi)),_Ze=new Set(["bad-request","unknown-bot","unknown-target","target-conflict","invalid-target","bot-not-connected","target-rejected","delivery-failed","cancelled"]);function Yf(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function uI(n,t){return Yf(n)&&Object.keys(n).length===t.length&&Object.keys(n).every(o=>t.includes(o))}function lp(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function xf(n){return typeof n=="string"&&/^[A-Za-z0-9._:@-]{1,128}$/.test(n)}function Jce(n,{targetId:t}){let o=t?["targetId","name","kind","route"]:["name","kind","route"];return!Yf(n)||Object.keys(n).some(i=>!o.includes(i))||t&&!xf(n.targetId)||n.name!==void 0&&(typeof n.name!="string"||!n.name.trim()||n.name.trim().length>80)?!1:typeof n.kind=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(n.kind)&&Yf(n.route)}function TZe(n){return uI(n,["kind","route"])&&typeof n.kind=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(n.kind)&&Yf(n.route)}function NZe(n,t){return!MZe.has(n)||!Yf(t)?!1:n===pi.send?uI(t,["botId","targetId","text"])&&lp(t.botId)&&xf(t.targetId)&&typeof t.text=="string"&&!!t.text.trim():n===pi.listTargets||n===pi.listSuggestions?uI(t,["botId"])&&lp(t.botId):n===pi.createTarget?uI(t,["botId","target"])&&lp(t.botId)&&Jce(t.target,{targetId:!0}):n===pi.updateTarget?uI(t,["botId","targetId","target"])&&lp(t.botId)&&xf(t.targetId)&&Jce(t.target,{targetId:!1}):n===pi.testTarget?uI(t,["botId","targetId"])&&lp(t.botId)&&xf(t.targetId)||uI(t,["botId","target"])&&lp(t.botId)&&TZe(t.target):uI(t,["botId","targetId"])&&lp(t.botId)&&xf(t.targetId)}function RZe(n){let t=_Ze.has(n?.code)?n.code:"delivery-failed";return{code:t,message:t,details:{}}}function qH(n){for(let t of["send","listTargets","listSuggestions","createTarget","updateTarget","deleteTarget"])if(typeof n?.[t]!="function")throw new TypeError(`A complete delivery service is required (${t})`);return async(t,o,i)=>{if(!NZe(t,o))return{ok:!1,error:{code:"bad-request",message:"Invalid delivery request.",details:{}}};if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"cancelled",details:{}}};try{let e;return t===pi.send?e=await n.send(o.botId,o.targetId,o.text,{signal:i}):t===pi.listTargets?e=await n.listTargets(o.botId):t===pi.listSuggestions?e=await n.listSuggestions(o.botId):t===pi.createTarget?e=await n.createTarget(o.botId,o.target):t===pi.updateTarget?e=await n.updateTarget(o.botId,o.targetId,o.target):t===pi.deleteTarget?e=await n.deleteTarget(o.botId,o.targetId):e=await n.send(o.botId,Object.hasOwn(o,"target")?o.target:o.targetId,bZe,{signal:i}),{ok:!0,value:e}}catch(e){return{ok:!1,error:RZe(e)}}}}function qce(n,t,{authority:o}={}){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(OZe,qH(t),{authority:hr(o)})}var zce="/api/dsh-im/delivery/messages",Vce=1024*1024,kZe=Object.freeze({"bad-request":400,"unknown-bot":404,"unknown-target":404,"target-conflict":409,"invalid-target":422,"bot-not-connected":503,"target-rejected":422,"delivery-failed":502,cancelled:408}),QE=class extends Error{constructor(t,o){super(o),this.status=t,this.code=o}};function fE(n,t,o,i={}){if(n.destroyed||n.writableEnded)return;let e=JSON.stringify(o);n.writeHead(t,{"cache-control":"no-store","content-type":"application/json; charset=utf-8","content-length":String(Buffer.byteLength(e)),...i}),n.end(e)}function vZe(n){return typeof n=="string"&&n.split(";",1)[0].trim().toLowerCase()==="application/json"}async function PZe(n){let t=Number(n.headers["content-length"]);if(Number.isFinite(t)&&t>Vce)throw new QE(413,"payload-too-large");let o=[],i=0;for await(let e of n){let a=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=a.length,i>Vce)throw new QE(413,"payload-too-large");o.push(a)}try{return JSON.parse(Buffer.concat(o,i).toString("utf8"))}catch{throw new QE(400,"bad-request")}}function GZe(n){let t=qH(n);return async(o,i)=>{if(o.method!=="POST"){fE(i,405,{error:{code:"method-not-allowed",message:"method-not-allowed",details:{}}},{allow:"POST"});return}if(!vZe(o.headers["content-type"])){fE(i,415,{error:{code:"unsupported-media-type",message:"unsupported-media-type",details:{}}});return}let e=new AbortController,a=()=>e.abort(),A=()=>{i.writableEnded||a()};o.once("aborted",a),i.once("close",A);try{let r=await PZe(o),s=await t(pi.send,r,e.signal);if(s.ok){fE(i,200,s.value);return}fE(i,kZe[s.error.code]??500,{error:s.error})}catch(r){if(r instanceof QE){fE(i,r.status,{error:{code:r.code,message:r.code,details:{}}});return}fE(i,500,{error:{code:"delivery-failed",message:"delivery-failed",details:{}}})}finally{o.off("aborted",a),i.off("close",A)}}}function Wce(n,t){if(!n?.webServer||typeof n.webServer.register!="function"||typeof n.effect!="function")throw new TypeError("DSH Host WebServer is required");let o={kind:"exact",path:zce,handler:GZe(t)};return n.effect(()=>n.webServer.register(o),`dsh-im: ${zce}`)}var FZe=/^[A-Za-z0-9_-]{1,128}$/,LZe=/^[A-Za-z0-9._:@-]{1,128}$/,UZe=/^[a-z][a-z0-9-]{0,31}$/,HZe="__test__",KZe=Object.freeze(["ownsBot","listTargets","listSuggestions","createTarget","updateTarget","deleteTarget","sendText"]),xZe=new Set(["bad-request","unknown-bot","unknown-target","target-conflict","invalid-target","bot-not-connected","target-rejected","delivery-failed","cancelled"]);function nn(n,t=n,o){let i=new Error(t,o);return i.code=n,i}function yE(n){if(typeof n!="string"||!FZe.test(n))throw nn("bad-request","Invalid bot id");return n}function cM(n){if(typeof n!="string"||!LZe.test(n))throw nn("bad-request","Invalid target id");return n}function zH(n,{includesTargetId:t}={}){if(!n||typeof n!="object"||Array.isArray(n))throw nn("bad-request","Invalid target");if(t)cM(n.targetId);else if(Object.hasOwn(n,"targetId"))throw nn("bad-request","A target id cannot be changed");return n}function YZe(n){zH(n);let t=Object.keys(n);if(t.length!==2||!t.includes("kind")||!t.includes("route"))throw nn("bad-request","Invalid draft target");return n}function Zce(n){if(n?.aborted)throw nn("cancelled","Request cancelled")}function pp(n,t="delivery-failed"){return n?.code==="workspace-bot-not-found"?nn("unknown-bot","Unknown bot",{cause:n}):xZe.has(n?.code)?n:nn(t,t,{cause:n})}function jZe(n){if(!n||typeof n!="object"||typeof n.channel!="string"||!UZe.test(n.channel))throw new TypeError("A delivery adapter with a valid channel is required");for(let t of KZe)if(typeof n[t]!="function")throw new TypeError(`A complete delivery adapter is required (${t})`);return n}var VH=class{#e=new Map;registerAdapter(t){let o=jZe(t),i=Object.freeze({adapter:o});return this.#e.set(o.channel,i),()=>this.#e.get(o.channel)!==i?!1:(this.#e.delete(o.channel),!0)}async listTargets(t){let o=yE(t),i=await this.#A(o);try{let e=await i.listTargets(o);if(!Array.isArray(e))throw new TypeError("Adapter returned invalid targets");return{botId:o,channel:i.channel,targets:e}}catch(e){throw pp(e)}}async listSuggestions(t){let o=yE(t),i=await this.#A(o);try{let e=await i.listSuggestions(o);if(!Array.isArray(e))throw new TypeError("Adapter returned invalid suggestions");return{botId:o,channel:i.channel,suggestions:e.map(a=>_p(i.channel,a,{targetIdRequired:!1}))}}catch(e){throw pp(e)}}async createTarget(t,o){let i=yE(t);zH(o,{includesTargetId:!0});let e=await this.#A(i);try{return await e.createTarget(i,o)}catch(a){throw pp(a)}}async updateTarget(t,o,i){let e=yE(t),a=cM(o);zH(i);let A=await this.#A(e);try{return await A.updateTarget(e,a,i)}catch(r){throw pp(r)}}async deleteTarget(t,o){let i=yE(t),e=cM(o),a=await this.#A(i);try{return await a.deleteTarget(i,e),{deleted:!0}}catch(A){throw pp(A)}}async send(t,o,i,{signal:e}={}){let a=yE(t),A=typeof o=="string"?cM(o):null,r=A===null?YZe(o):null;if(typeof i!="string"||!i.trim())throw nn("bad-request","Message text is required");Zce(e);let s=await this.#A(a);try{let g;if(r)g={targetId:HZe,...r};else{let c=await s.listTargets(a);if(!Array.isArray(c))throw new TypeError("Adapter returned invalid targets");if(g=c.find(I=>I?.targetId===A),!g)throw nn("unknown-target","Unknown target")}return Zce(e),await s.sendText(a,g,i,{signal:e}),{sent:!0}}catch(g){throw e?.aborted||g?.name==="AbortError"||g?.code==="ABORT_ERR"?nn("cancelled","Request cancelled",{cause:g}):pp(g)}}async#A(t){for(let{adapter:o}of this.#e.values()){let i;try{i=await o.ownsBot(t)}catch(e){throw pp(e)}if(i)return o}throw nn("unknown-bot","Unknown bot")}};function Xce(){return new VH}var jf=Je(DD(),1);import{createHash as JZe}from"node:crypto";import{readFile as AIe,realpath as Kn,stat as qZe}from"node:fs/promises";import{homedir as zZe}from"node:os";import{basename as VZe,dirname as ZH,isAbsolute as eK,join as $g,relative as WZe,resolve as lM,sep as ZZe}from"node:path";import{fileURLToPath as XZe}from"node:url";var BI="@xmanrui/dsh-im",Jf="https://registry.npmjs.org/",$Ze=15*6e4,e9e=1e4,$ce=16*1024;function xn(n,t={}){return Object.assign(new Error(n),{code:n,...t})}function IM(n,t){return typeof n?.get=="function"?n.get(t):n?.[t]}function XH(n,t){let o=WZe(n,t);return o!==".."&&!o.startsWith(`..${ZZe}`)&&!eK(o)}async function A9e(n){try{return await AIe(n,"utf8")}catch(t){if(t.code==="ENOENT")return"";throw t}}async function $H(n){let t=await AIe($g(n,"package.json"),"utf8");return{directory:await Kn(n),manifest:JSON.parse(t),contents:t}}async function WH(n,t){let o=ZH(await Kn(n));for(;;){try{let e=await $H(o);return e.manifest?.name===t?e:null}catch(e){if(e.code!=="ENOENT")throw e}let i=ZH(o);if(i===o)return null;o=i}}function t9e(n){return typeof n=="string"&&n.length>0&&Buffer.byteLength(n)<=255&&!n.startsWith("-")&&![".","..","node_modules"].includes(n)&&!/[\\/\x00-\x1f\x7f<>:"|?*]/u.test(n)}function r9e(n){if(n[0]==="web")return"web";let t;for(let o=0;o0&&(jf.default.validRange(n)!==null||/^[A-Za-z][A-Za-z0-9._-]*$/u.test(n))}async function o9e(n){if(n.manifest?.name!==BI||jf.default.valid(n.manifest.version)===null)return!1;let t=[n.manifest.main,n.manifest.exports?.["./client"],n.manifest.dsh?.bundle?.patch];for(let o of t){if(typeof o!="string"||!o||eK(o)||o.includes("\0"))return!1;let i=lM(n.directory,o);if(!XH(n.directory,i)||!XH(n.directory,await Kn(i))||!(await qZe(i)).isFile())return!1}return!0}function n9e(n){if(n==null||n==="")return!0;if(typeof n!="string")return!1;try{return new URL(n).href===Jf}catch{return!1}}async function eIe(n,{signal:t,timeoutMs:o,errorCode:i,capture:e=!1}){if(t?.aborted)throw xn("install-interrupted");let a=new AbortController,A,r,s=B=>{A??=B,a.abort(),r?.cancel?.()},g=()=>s("install-interrupted");t?.addEventListener("abort",g,{once:!0});let c=setTimeout(()=>s("install-timeout"),o),I="",d="";try{r=n(a.signal),r.stdout?.on("data",f=>{e&&(I=(I+f.toString()).slice(-$ce))}),r.stderr?.on("data",f=>{d=(d+f.toString()).slice(-$ce)}),r.stdout?.on("error",()=>s(i)),r.stderr?.on("error",()=>s(i));let B=await r.done;if(A)throw xn(A);if(B.exitCode!==0||B.signal)throw xn(i,{exitCode:B.exitCode,diagnosticCode:d.match(/\bERR_PNPM_[A-Z0-9_]+\b/u)?.[0]});return{exitCode:0,signal:null,...e?{stdout:I}:{}}}catch(B){throw A?xn(A):B.code===i?B:xn(i)}finally{clearTimeout(c),t?.removeEventListener("abort",g)}}function tIe(n={}){let t=n.ctx,o=n.env??process.env,i=n.argv??process.argv,e=n.execArgv??process.execArgv,a=n.execPath??process.execPath,A=n.cwd??process.cwd(),r=n.platform??process.platform,s=n.osHome??zZe(),g=n.electron??process.versions.electron,c=n.moduleUrl??import.meta.url,I=WH(XZe(c),BI).catch(()=>null),d;async function B(){let _=IM(t,"desktopProfiles"),T=IM(t,"desktopPnpm"),R=IM(t,"desktopPnpmBootstrap"),F=!!(g||_||T||R),K=_?.current,L=F?K?.name:r9e(i.slice(2)),q=F&&R?.homeDir?lM(R.homeDir):a9e(o,s),z={environmentKind:F?"desktop":"cli",homeDir:q,profileName:L};if(!t9e(L))return{...z,blockedReason:"unknown-profile"};let j=await Kn($g(q,"profiles",L)),P=await Kn(q),J={...z,homeDir:P,profileDir:j};if(F)try{if(typeof T?.runPlugin!="function"||typeof T?.run!="function"||!R||!K?.dir||R.activeProfileName!==L||await Kn(K.dir)!==j||await Kn(R.activeProfileDir)!==j||await Kn(R.appExecutable)!==await Kn(a))return{...J,blockedReason:"executor-unavailable"};let N=await WH(R.dshBootstrapPath,"dsh-plugin-desktop");return!N||VZe(R.dshBootstrapPath)!=="desktop-cli.js"||ZH(await Kn(R.dshBootstrapPath))!==$g(N.directory,"lib")?{...J,blockedReason:"executor-unavailable"}:{...J,desktop:T,executable:a,cliEntry:R.dshBootstrapPath}}catch{return{...J,blockedReason:"executor-unavailable"}}let U=IM(t,"subprocess");if(typeof U?.spawn!="function"||typeof i[1]!="string"||!eK(i[1])||r==="win32")return{...J,blockedReason:"executor-unavailable"};try{let N=await WH(i[1],"@deepseek-ai/dsh");if(!N)return{...J,blockedReason:"executor-unavailable"};let k=await Kn(i[1]),V=typeof N.manifest.bin=="string"?N.manifest.bin:N.manifest.bin?.dsh,Ae=typeof V=="string"?lM(N.directory,V):"";return k!==Ae&&k!==$g(N.directory,"src","bin.ts")?{...J,blockedReason:"executor-unavailable"}:{...J,subprocess:U,executable:a,cliEntry:k}}catch{return{...J,blockedReason:"executor-unavailable"}}}function f(_,T,R,F=!1){let K=_.subprocess.spawn({argv:F?["pnpm",...T]:[a,...e,_.cliEntry,...T],cwd:F?_.profileDir:A,env:{DSH_HOME:_.homeDir,CI:"true"},stdio:{stdin:"ignore",stdout:"pipe",stderr:"pipe"},graceMs:3e3,signal:R});return{stdout:K.stdout,stderr:K.stderr,cancel:()=>K.terminate(),done:(async()=>{try{return await K.done}finally{await K.waitForExit()}})()}}async function Q(_,T){let R=["config","get","@xmanrui:registry","--json"],K=(await eIe(q=>_.desktop?_.desktop.run(R,q):f(_,R,q,!0),{signal:T,timeoutMs:n.configTimeoutMs??e9e,errorCode:"registry-check-failed",capture:!0})).stdout.trim(),L;try{L=K===""||K==="undefined"?void 0:JSON.parse(K)}catch{throw xn("registry-check-failed")}if(!n9e(L))throw xn("registry-conflict")}async function y({preflight:_=!1}={}){let T,R={installedVersion:null,packageValid:!1,eligible:!1,installationKey:null};try{T=await B();for(let P of["homeDir","profileDir","profileName","environmentKind","executable","cliEntry"])R[P]=T[P]??null;if(!T.profileDir)return{...R,blockedReason:T.blockedReason??"unknown-profile"};let F=await $H(T.profileDir),K=await $H($g(T.profileDir,"node_modules",BI));R.sourceInstall=!i9e(F.manifest.dependencies?.[BI])||!XH($g(T.profileDir,"node_modules"),K.directory),R.installedVersion=typeof K.manifest.version=="string"?K.manifest.version:null,R.packageValid=await o9e(K);let L=await I,q=`${T.homeDir}\0${T.profileDir}\0${T.profileName}`,z=L?.directory===K.directory&&L?.manifest.version===K.manifest.version;d===void 0&&z&&R.packageValid&&(d=q);let j=await Promise.all(["pnpm-lock.yaml","pnpm-workspace.yaml","package-lock.json"].map(P=>A9e($g(T.profileDir,P))));return R.installationKey=JZe("sha256").update(JSON.stringify([q,F.contents,K.directory,K.contents,T.cliEntry,T.executable,...j])).digest("hex"),d!==void 0&&d!==q||!z&&d===void 0?R.blockedReason="installation-changed":R.packageValid?R.sourceInstall?R.blockedReason="source-install":T.blockedReason?R.blockedReason=T.blockedReason:z?_&&await Q(T):R.blockedReason="pending-restart":R.blockedReason="invalid-installation",R.eligible=!R.blockedReason,{...R,blockedReason:R.blockedReason??null}}catch(F){return{...R,blockedReason:["registry-conflict","registry-check-failed","install-timeout","install-interrupted"].includes(F.code)?F.code:T?.profileDir?"invalid-installation":"unknown-profile"}}}async function m(_,{signal:T,expectedInstallationKey:R}={}){if(jf.default.valid(_)!==_||jf.default.prerelease(_))throw xn("invalid-version");let F=await y();if(R!==void 0&&F.installationKey!==R)throw xn("installation-changed");if(!F.eligible)throw xn(F.blockedReason);let K=await B();await Q(K,T);let L=await y();if(!L.eligible||L.installationKey!==F.installationKey)throw xn("installation-changed");let q=["add","-w","--save-exact",`${BI}@${_}`,`--registry=${Jf}`];return eIe(z=>K.desktop?K.desktop.runPlugin(q,K.profileDir,z):f(K,["plugin","--profile",K.profileName,...q],z),{signal:T,timeoutMs:n.installTimeoutMs??$Ze,errorCode:"install-failed"})}return Object.freeze({inspect:y,install:m})}var fI=Je(DD(),1);import{createHash as s9e,randomUUID as tK}from"node:crypto";import{mkdir as g9e,open as c9e,readFile as nIe,rename as I9e,stat as sIe,unlink as gIe,writeFile as l9e}from"node:fs/promises";import{isAbsolute as rIe,join as zf}from"node:path";var Vf=new Set(["installing","verifying"]),p9e=new Set([...Vf,"restart-required","completed","failed","interrupted"]),aIe=256*1024,d9e=["package.json","pnpm-lock.yaml","pnpm-workspace.yaml"],pM=Symbol("no update lock");function Ot(n){return Object.assign(new Error(n),{code:n})}async function iIe(n=globalThis.fetch,t=1e4){let o;try{if(o=await n(`${Jf}${encodeURIComponent(BI)}/latest`,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(t)}),!o.ok)throw Ot("check-failed");if(Number(o.headers.get("content-length"))>aIe)throw Ot("invalid-release");let i=[],e=0;for await(let c of o.body){if(e+=c.byteLength,e>aIe)throw Ot("invalid-release");i.push(Buffer.from(c))}let a=JSON.parse(Buffer.concat(i).toString("utf8")),A=a.version;if(a.name!==BI||typeof A!="string"||fI.default.valid(A)!==A||fI.default.prerelease(A))throw Ot("invalid-release");let r=a.engines?.node;if(r!==void 0&&(typeof r!="string"||!fI.default.validRange(r)))throw Ot("invalid-release");let s=new URL(a.dist?.tarball),g=a.dist?.integrity;if(s.origin!==new URL(Jf).origin||s.username||s.password||s.search||s.hash||s.pathname!==`/@xmanrui/dsh-im/-/dsh-im-${A}.tgz`||typeof g!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(g))throw Ot("invalid-release");return{version:A,nodeRange:r??"*",integrity:g,tarball:s.href}}catch(i){throw i?.code==="invalid-release"||i instanceof SyntaxError||i instanceof TypeError&&o?.ok?Ot("invalid-release"):Ot("check-failed")}}function oIe(n){if(!rIe(n.homeDir??"")||!rIe(n.profileDir??""))return null;let t=s9e("sha256").update(n.profileDir).digest("hex").slice(0,24),o=zf(n.homeDir,"updates","dsh-im",t);return{directory:o,state:zf(o,"state.json"),lock:zf(o,"install.lock"),backup:zf(o,"before.json")}}async function AK(n,t=null){try{if((await sIe(n)).size>10*1024*1024)throw Ot("state-unavailable");return JSON.parse(await nIe(n,"utf8"))}catch(o){if(o.code==="ENOENT")return t;throw Ot("state-unavailable")}}async function qf(n,t){let o=`${n}.${tK()}.tmp`;try{await l9e(o,`${JSON.stringify(t,null,2)} -`,{mode:384,flag:"wx"}),await I9e(o,n)}catch{throw Ot("state-unavailable")}finally{await gIe(o).catch(i=>{if(i.code!=="ENOENT")throw Ot("state-unavailable")})}}function h9e(n){if(!Number.isSafeInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return t.code!=="ESRCH"}}function E9e(n){if(!n)return null;let{id:t,state:o,targetVersion:i,message:e}=n;return{id:t,state:o,targetVersion:i,message:e}}function cIe({runtime:n,runningVersion:t=IQ.version,nodeVersion:o=process.versions.node,fetchImpl:i=globalThis.fetch,now:e=Date.now,checkTimeoutMs:a=1e4,confirmationTtlMs:A=10*6e4,installTimeoutMs:r=15*6e4}={}){let s={},g=null,c=null,I=-1/0,d=null,B=null,f=null,Q=null,y=!1;function m(){if(y)throw Ot("disposed")}async function _(J){let U=oIe(J);if(!U)return null;if(Q?.statePath===U.state)return Q.job;let N=await AK(U.state),k=await AK(U.lock,pM);if(!N)return k!==pM?{id:"locked",state:"interrupted",message:"recovery-required",targetVersion:null}:null;if(!p9e.has(N.state)||typeof N.id!="string"||!fI.default.valid(N.targetVersion))throw Ot("state-unavailable");if(Vf.has(N.state)&&N.id!==d?.id&&(k===pM||k?.id!==N.id||!h9e(k?.pid))&&(N={...N,state:"interrupted",message:"recovery-required"}),N.id!==d?.id&&!Vf.has(N.state)){if(k!==pM)return{...N,state:"interrupted",message:"recovery-required"};if(["failed","interrupted"].includes(N.state)&&J.packageValid===!0&&J.installedVersion===t&&!J.blockedReason)return N.targetVersion===t?{...N,state:"completed",message:"recovered"}:{...N,recoverable:!0}}return N.state==="restart-required"||N.state==="completed"?J.installedVersion!==N.targetVersion||J.packageValid!==!0?{...N,state:"interrupted",message:"installation-changed"}:{...N,state:t===N.targetVersion?"completed":"restart-required"}:N}function T(J,U){let N=J.blockedReason??g?.blockedReason??null;U?.state==="interrupted"&&!U.recoverable||U?.state==="failed"&&J.installedVersion!==t?N="recovery-required":(U?.state==="restart-required"||J.installedVersion&&J.installedVersion!==t)&&(N="pending-restart");let k=Vf.has(U?.state),V=!!(J.eligible&&!N&&!k&&g?.checkId&&e(){try{let J=await n.inspect({preflight:!0}),U=await iIe(i,a);return m(),g={release:U,checkId:tK(),checkedAt:e(),expiresAt:e()+A,installationKey:J.installationKey,profileDir:J.profileDir,blockedReason:J.blockedReason??(fI.default.satisfies(o,U.nodeRange)?null:"incompatible-node")},T(J,await _(J))}catch(J){throw g&&(g={...g,checkId:null,expiresAt:0}),J}finally{c=null}})(),c))}async function K(J,U){(await AK(J.lock))?.id===U&&await gIe(J.lock)}async function L(J,U,N){let k={};for(let V of d9e)try{let Ae=zf(J.profileDir,V);if((await sIe(Ae)).size>3*1024*1024)throw Ot("state-unavailable");k[V]=await nIe(Ae,"utf8")}catch(Ae){if(Ae.code!=="ENOENT")throw Ot("state-unavailable")}await qf(U.backup,{jobId:N.id,previousVersion:N.previousVersion,files:k})}function q(J){d={...d,state:"interrupted",message:"state-unavailable"},Q={statePath:J.state,job:d}}async function z(J,U,N){let k=AbortSignal.timeout(r);try{if(await n.install(U.targetVersion,{signal:AbortSignal.any([f.signal,k]),expectedInstallationKey:N.installationKey}),y)throw Ot("interrupted");d={...d,state:"verifying",updatedAt:e()},await qf(J.state,d);let V=await n.inspect();if(V.homeDir!==N.homeDir||V.profileDir!==N.profileDir||V.profileName!==N.profileName||V.blockedReason==="installation-changed")throw Ot("installation-changed");if(V.installedVersion!==U.targetVersion||V.packageValid!==!0||V.blockedReason&&V.blockedReason!=="pending-restart")throw Ot("verify-failed");d={...d,state:"restart-required",message:null,updatedAt:e()},await qf(J.state,d)}catch(V){let Ae=k.aborted||V.code==="install-timeout",ie=y||f.signal.aborted||!Ae&&["interrupted","install-interrupted"].includes(V.code);d={...d,state:ie?"interrupted":"failed",message:ie?"interrupted":Ae?"install-timeout":["verify-failed","state-unavailable","installation-changed","registry-conflict"].includes(V.code)?V.code:"install-failed",updatedAt:e()};try{await qf(J.state,d)}catch{q(J);return}}await K(J,U.id)}function j({checkId:J,requestId:U}){return Zs(s,"install",async()=>{m();let N=await n.inspect({preflight:!0}),k=await _(N);if(k?.requestId===U)return T(N,k);if(Vf.has(k?.state)||k?.state==="restart-required")throw Ot("update-busy");let V=g;if(!V||!J||V.checkId!==J||e()>=V.expiresAt)throw Ot("check-expired");if(N.profileDir!==V.profileDir||N.installationKey!==V.installationKey)throw Ot("installation-changed");if(!T(N,k).canInstall)throw Ot(N.blockedReason??"update-busy");let Ae=oIe(N);if(!Ae)throw Ot("state-unavailable");let ie={id:tK(),requestId:U,state:"installing",message:null,targetVersion:V.release.version,previousVersion:N.installedVersion,startedAt:e(),updatedAt:e()},De=!1;try{await g9e(Ae.directory,{recursive:!0,mode:448});let fe=await c9e(Ae.lock,"wx",384);De=!0;try{await fe.writeFile(JSON.stringify({id:ie.id,pid:process.pid,startedAt:e()}))}finally{await fe.close()}let _e=await iIe(i,a);if(JSON.stringify(_e)!==JSON.stringify(V.release))throw Ot("check-expired");if(N=await n.inspect({preflight:!0}),N.profileDir!==V.profileDir||N.installationKey!==V.installationKey)throw Ot("installation-changed");if(!N.eligible||N.blockedReason)throw Ot(N.blockedReason??"update-busy");m(),await L(N,Ae,ie),await qf(Ae.state,ie),m()}catch(fe){throw De&&await K(Ae,ie.id),fe.code==="EEXIST"?Ot("update-busy"):fe.code?.startsWith("E")?Ot("state-unavailable"):fe}return d=ie,f=new AbortController,B=z(Ae,ie,N).catch(()=>{q(Ae)}),T(N,ie)})}async function P(){y=!0,f?.abort(),B&&await B}return Object.freeze({status:R,check:F,install:j,close:P})}var C9e="/dsh-im",u9e=Object.freeze(["update.status","update.check","update.install"]);function B9e(n,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let o=Object.keys(t);return n!=="update.install"?o.length===0:o.length===2&&o.every(i=>i==="checkId"||i==="requestId")&&["checkId","requestId"].every(i=>typeof t[i]=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(t[i]))}var f9e=new Set(["check-failed","invalid-release","check-expired","installation-changed","update-busy","install-failed","verify-failed","state-unavailable","interrupted","disposed","source-install","unknown-profile","unsupported-runtime","registry-conflict","incompatible-node","pending-restart","recovery-required","executor-unavailable","invalid-installation","registry-check-failed","install-timeout","install-interrupted","invalid-version"]);function Q9e(n){return async(t,o,i)=>{if(!u9e.includes(t)||!B9e(t,o))return{ok:!1,error:{code:"bad-request",message:"Invalid update request."}};if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"Request cancelled."}};try{return{ok:!0,value:t==="update.install"?await n.install(o):t==="update.check"?await n.check():await n.status()}}catch(e){let a=f9e.has(e?.code)?e.code:"update-failed";return{ok:!1,error:{code:a,message:a}}}}}function IIe(n,t={}){let o=t.runtime??tIe({ctx:n,moduleUrl:import.meta.url}),i=t.service??cIe({runtime:o}),e=n.connection.rpc.handle(C9e,Q9e(i),{authority:"loopback"});return n.effect(()=>()=>i.close(),"dsh-im: close update installer"),e}var lIe="dsh-im-host",y9e=["connection","credentials","typertGateway"];function m9e(n,t,o){let i=n[t]??{},e=n.rpcAuthority===void 0?i:{...i,rpcAuthority:n.rpcAuthority};return t==="office"?e:{...e,deliveryService:o}}function S9e(n={}){let t=n.installUpdateRpc??IIe,o=n.installDeliveryRpc??qce,i=n.installDeliveryHttp??Wce,e=n.createDeliveryService??Xce,a=n.applyFeishu??A5,A=n.applyWeixin??JZ,r=n.applyDingtalk??a1,s=n.applyWecom??EZ,g=n.applyQq??f5,c=n.applySlack??G5,I=n.applyTelegram??eZ,d=n.applyDiscord??M1,B=n.applyOffice??v1,f=n.applyWhatsapp??jce,Q=[["feishu",a],["weixin",A],["dingtalk",r],["wecom",s],["qq",g],["slack",c],["telegram",I],["discord",d],["whatsapp",f],["office",B]];return Object.freeze({name:lIe,inject:y9e,async apply(m,_={}){let T=e();typeof m?.provide=="function"&&m.provide("dshIm",Object.freeze({send:(F,K,L,q)=>T.send(F,K,L,q),listTargets:async F=>(await T.listTargets(F)).targets}));let R=async F=>{await y(F,_,T)};if(typeof m?.inject=="function"){let F=typeof m?.typertGateway?.stream=="function";await m.inject(F?["sessionController","workspaceController"]:["apiProxy"],R),m.inject(["webServer"],K=>{i(K,T)});return}await R(m),m?.webServer?.register&&typeof m?.effect=="function"&&i(m,T)}});async function y(m,_,T){KK(_.language??process.env.DSH_IM_LANGUAGE),typeof m?.inject=="function"?m.inject(["tools","systemPrompt"],K=>{o_(K)}):o_(m);let R=typeof m?.logger=="function"?m.logger(lIe):m?.logger??console;if(m?.connection?.rpc){try{t(m)}catch(K){R.error?.("[dsh-im] failed to activate update management; continuing with channels",K)}try{o(m,T,{authority:_.rpcAuthority})}catch(K){R.error?.("[dsh-im] failed to activate delivery management; continuing with channels",K)}}let F=[];for(let[K,L]of Q)try{await L(m,m9e(_,K,T))}catch(q){F.push(q),R.error?.(`[dsh-im] failed to activate ${K}; continuing with the remaining channels`,q)}if(F.length===Q.length)throw new AggregateError(F,"dsh-im failed to activate every channel")}}async function mLA(n,t={}){return S9e().apply(n,t)}export{mLA as apply,S9e as createImHostPlugin,y9e as inject,lIe as name}; +${n.stack}`:i}function BUe(n){n<1028||(Ng[n]=BB,BB=n)}function CB(n,t){return n=n>>>0,ah().subarray(n/1,n/1+t)}var wl=null;function Xe(){return(wl===null||wl.buffer.detached===!0||wl.buffer.detached===void 0&&wl.buffer!==ae.memory.buffer)&&(wl=new DataView(ae.memory.buffer)),wl}function Nr(n,t){return n=n>>>0,yUe(n,t)}var uB=null;function ah(){return(uB===null||uB.byteLength===0)&&(uB=new Uint8Array(ae.memory.buffer)),uB}function Pe(n){return Ng[n]}function Tr(n,t){try{return n.apply(this,t)}catch(o){ae.__wbindgen_export3(rA(o))}}var Ng=new Array(1024).fill(void 0);Ng.push(void 0,null,!0,!1);var BB=Ng.length;function Tn(n){return n==null}function fUe(n,t,o,i){let e={a:n,b:t,cnt:1,dtor:o},a=(...A)=>{e.cnt++;let r=e.a;e.a=0;try{return i(r,e.b,...A)}finally{e.a=r,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--e.cnt===0&&(e.dtor(e.a,e.b),e.a=0,i7.unregister(e))},i7.register(a,e,e),a}function Nt(n,t){let o=t(n.length*1,1)>>>0;return ah().set(n,o/1),HA=n.length,o}function o7(n,t){let o=t(n.length*4,4)>>>0,i=Xe();for(let e=0;e>>0;return ah().subarray(s,s+r.length).set(r),HA=r.length,s}let i=n.length,e=t(i,1)>>>0,a=ah(),A=0;for(;A127)break;a[e+A]=r}if(A!==i){A!==0&&(n=n.slice(A)),e=o(e,i,i=A+n.length*3,1)>>>0;let r=ah().subarray(e+A,e+i),s=fB.encodeInto(n,r);A+=s.written,e=o(e,i,A,1)>>>0}return HA=A,e}function mA(n){let t=Pe(n);return BUe(n),t}var Ww=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});Ww.decode();var QUe=2146435072,SF=0;function yUe(n,t){return SF+=t,SF>=QUe&&(Ww=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),Ww.decode(),SF=t),Ww.decode(ah().subarray(n,n+t))}var fB=new TextEncoder;"encodeInto"in fB||(fB.encodeInto=function(n,t){let o=fB.encode(n);return t.set(o),{read:n.length,written:o.length}});var HA=0,mUe,ae;function SUe(n,t){return ae=n.exports,mUe=t,wl=null,uB=null,ae}function s7(n){if(ae!==void 0)return ae;n!==void 0&&(Object.getPrototypeOf(n)===Object.prototype?{module:n}=n:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=EUe();n instanceof WebAssembly.Module||(n=new WebAssembly.Module(n));let o=new WebAssembly.Instance(n,t);return SUe(o,n)}var wUe=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function g7(n){let t=atob(n),o=new Uint8Array(t.length);for(let i=0;in.length===33?n:Buffer.concat([Rg,n]),Br={generateKeyPair:()=>{let{pubKey:n,privKey:t}=Jc.generateKeyPair();return{private:Buffer.from(t),public:Buffer.from(n.slice(1))}},sharedKey:(n,t)=>{let o=Jc.calculateAgreement(Yo(t),n);return Buffer.from(o)},sign:(n,t)=>Jc.calculateSignature(n,t),verify:(n,t,o)=>{try{return Jc.verifySignature(Yo(n),t,o),!0}catch{return!1}}},aD=(n,t)=>{let o=Br.generateKeyPair(),i=Yo(o.public),e=Br.sign(n.private,i);return{keyPair:o,signature:e,keyId:t}},I7=16;function Dl(n,t,o,i){let e=DF("aes-256-gcm",t,o);return e.setAAD(i),Buffer.concat([e.update(n),e.final(),e.getAuthTag()])}function Ol(n,t,o,i){let e=OF("aes-256-gcm",t,o),a=n.slice(0,n.length-I7),A=n.slice(n.length-I7);return e.setAAD(i),e.setAuthTag(A),Buffer.concat([e.update(a),e.final()])}function l7(n,t,o){let i=DF("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function p7(n,t,o){let i=OF("aes-256-ctr",t,o);return Buffer.concat([i.update(n),i.final()])}function d7(n,t){return RUe(n.subarray(16),t,n.subarray(0,16))}function RUe(n,t,o){let i=OF("aes-256-cbc",t,o);return Buffer.concat([i.update(n),i.final()])}function h7(n,t){let o=NUe(16),i=DF("aes-256-cbc",t,o);return Buffer.concat([o,i.update(n),i.final()])}function kn(n,t,o="sha256"){return TUe(o,t).update(n).digest()}function sh(n){return _Ue("sha256").update(n).digest()}async function iD(n,t){let i=new TextEncoder().encode(n),e=new Uint8Array(t instanceof Uint8Array?t:new Uint8Array(t)),a=await c7.importKey("raw",i,{name:"PBKDF2"},!1,["deriveBits"]),A=await c7.deriveBits({name:"PBKDF2",salt:e,iterations:2<<16,hash:"SHA-256"},a,256);return Buffer.from(A)}var wB={replacer:(n,t)=>Buffer.isBuffer(t)||t instanceof Uint8Array||t?.type==="Buffer"?{type:"Buffer",data:Buffer.from(t?.data||t).toString("base64")}:t,reviver:(n,t)=>{if(typeof t=="object"&&t!==null&&t.type==="Buffer"&&typeof t.data=="string")return Buffer.from(t.data,"base64");if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=Object.keys(t);if(o.length>0&&o.every(i=>!isNaN(parseInt(i,10)))){let i=Object.values(t);if(i.every(e=>typeof e=="number"))return Buffer.from(i)}}return t}},gh=(n,t="me")=>(n?.fromMe?t:n?.participantAlt||n?.remoteJidAlt||n?.participant||n?.remoteJid)||"",u7=n=>n==null||n==="",vUe=n=>{let o=(SB(1)[0]&15)+1;return Buffer.concat([n,Buffer.alloc(o,o)])},B7=n=>{let t=new Uint8Array(n);if(t.length===0)throw new Error("unpadPkcs7 given empty bytes");var o=t[t.length-1];if(o>t.length)throw new Error(`unpad given ${t.length} bytes, but pad is ${o}`);return new Uint8Array(t.buffer,t.byteOffset,t.length-o)},f7=n=>(n.sort(),"2:"+sh(Buffer.from(n.join(""))).toString("base64").slice(0,6)),ch=n=>vUe(oe.Message.encode(n).finish()),Q7=()=>Uint16Array.from(SB(2))[0]&16383,kg=(n,t=4)=>{let o=n,i=new Uint8Array(t);for(let e=t-1;e>=0;e--)i[e]=255&o,o>>>=8;return i},Hr=n=>typeof n=="object"&&n?"toNumber"in n?n.toNumber():n.low:n||0,ya=(n=new Date)=>Math.floor(n.getTime()/1e3);var DB=n=>y7(n).delay,y7=n=>{let t=new Error().stack,o,i;return{delay:new Promise((A,r)=>{o=setTimeout(A,n),i=r}),cancel:()=>{clearTimeout(o),i(new oD.Boom("Cancelled",{statusCode:500,data:{stack:t}}))}}};async function Ih(n,t){if(!n)return new Promise(t);let o=new Error().stack,{delay:i,cancel:e}=y7(n);return new Promise((A,r)=>{i.then(()=>r(new oD.Boom("Timed Out",{statusCode:$t.timedOut,data:{stack:o}}))).catch(s=>r(s)),t(A,r)}).finally(e)}var Kr=n=>{let t=Buffer.alloc(44);if(t.writeBigUInt64BE(BigInt(Math.floor(Date.now()/1e3))),n){let e=yA(n);e?.user&&(t.write(e.user,8),t.write("@c.us",8+e.user.length))}return SB(16).copy(t,28),"3EB0"+kUe("sha256").update(t).digest().toString("hex").toUpperCase().substring(0,18)},bF=()=>"3EB0"+SB(18).toString("hex").toUpperCase();function MF(n,t){return async(o,i)=>{let e,a;await Ih(i,(A,r)=>{a=({connection:s,lastDisconnect:g})=>{s==="close"&&r(g?.error||new oD.Boom("Connection Closed",{statusCode:$t.connectionClosed}))},n.on("connection.update",a),e=async s=>{await o(s)&&A()},n.on(t,e)}).finally(()=>{n.off(t,e),n.off("connection.update",a)})}}var m7=n=>MF(n,"connection.update");var S7=()=>{let n=SB(4);return`${n.readUInt16BE()}.${n.readUInt16BE(2)}-`},PUe={sender:oe.WebMessageInfo.Status.SERVER_ACK,played:oe.WebMessageInfo.Status.PLAYED,read:oe.WebMessageInfo.Status.READ,"read-self":oe.WebMessageInfo.Status.READ},w7=n=>{let t=PUe[n];return typeof n>"u"?oe.WebMessageInfo.Status.DELIVERY_ACK:t},GUe={conflict:$t.connectionReplaced},D7=n=>{let[t]=ys(n),o=t?.tag||"unknown",i=+(n.attrs.code||GUe[o]||$t.badSession);return i===$t.restartRequired&&(o="restart required"),{reason:o,statusCode:i}},O7=({tag:n,attrs:t})=>{let o;switch(n){case"offer":case"offer_notice":o="offer";break;case"terminate":t.reason==="timeout"?o="timeout":o="terminate";break;case"preaccept":o="preaccept";break;case"transport":o="transport";break;case"relaylatency":o="relaylatency";break;case"reject":o="reject";break;case"accept":o="accept";break;default:o="ringing";break}return o},E7="Unexpected server response: ",b7=n=>{let t=500;if(n?.message?.includes(E7)){let o=+n?.message.slice(E7.length);!Number.isNaN(o)&&o>=400&&(t=o)}else(n?.code?.startsWith("E")||n?.message?.includes("timed out"))&&(t=408);return t};function nD(n){for(let t in n)typeof n[t]>"u"&&delete n[t];return n}var C7="123456789ABCDEFGHJKLMNPQRSTVWXYZ";function M7(n){let t=0,o=0,i=[];for(let e of n)for(t=t<<8|e&255,o+=8;o>=5;)i.push(C7.charAt(t>>>o-5&31)),o-=5;return o>0&&i.push(C7.charAt(t<<5-o&31)),i.join("")}function _7(n){return oe.Message.encode(n).finish()}var bl=Je(Lr(),1);var FUe=async(n,t)=>qA(n)||ga(n)?n:await t.lidMapping.getLIDForPN(n)||n,LUe=async(n,t,o,i,e)=>{let{senderAlt:a}=gD(n);if(a&&qA(a)&&_t(t)&&i===t)try{await o.lidMapping.storeLIDPNMappings([{lid:a,pn:t}]),await o.migrateSession(t,a),e.debug({sender:t,senderAlt:a},"Stored LID mapping from envelope")}catch(A){e.warn({sender:t,senderAlt:a,error:A},"Failed to store LID mapping")}},sD="Message absent from node",T7="Key used already or never filled",N7="Your account has been restricted",UUe={maxRetries:3,baseDelayMs:100,sessionRecordErrors:["No session record","SessionError: No session record"]},Ml={SenderReachoutTimelocked:463,ParsingError:487,UnrecognizedStanza:488,UnrecognizedStanzaClass:489,UnrecognizedStanzaType:490,InvalidProtobuf:491,InvalidHostedCompanionStanza:493,MissingMessageSecret:495,SignalErrorOldCounter:496,MessageDeletedOnPeer:499,UnhandledError:500,UnsupportedAdminRevoke:550,UnsupportedLIDGroup:551,DBOperationFailed:552},_F={MessageAccountRestriction:"463",SmaxInvalid:"479"},gD=n=>{let t,o,i=n.attrs.participant||n.attrs.from,e=n.attrs.addressing_mode||(i?.endsWith("lid")?"lid":"pn");return e==="lid"?(t=n.attrs.participant_pn||n.attrs.sender_pn||n.attrs.peer_recipient_pn,o=n.attrs.recipient_pn):(t=n.attrs.participant_lid||n.attrs.sender_lid||n.attrs.peer_recipient_lid,o=n.attrs.recipient_lid),{addressingMode:e,senderAlt:t,recipientAlt:o}};function TF(n,t,o){let i,e,a,A=!1,r=n.attrs.id,s=n.attrs.from,g=n.attrs.participant,c=n.attrs.recipient;if(!r)throw new bl.Boom("Invalid message stanza: missing id attribute",{data:n});if(!s)throw new bl.Boom("Invalid message stanza: missing from attribute",{data:n});let I=gD(n),d=m=>Tt(m,t),B=m=>Tt(m,o);if(_t(s)||qA(s)||ga(s)||ur(s)){if(c&&!rh(c)){if(!d(s)&&!B(s))throw new bl.Boom("receipient present, but msg not from me",{data:n});(d(s)||B(s))&&(A=!0),e=c}else(d(s)||B(s))&&(A=!0),e=s;i="chat",a=s}else if(Ur(s)){if(!g)throw new bl.Boom("No participant in group message");(d(g)||B(g))&&(A=!0),i="group",a=g,e=s}else if(EB(s)){if(!g)throw new bl.Boom("No participant in group message");let m=d(g);Tg(s)?i=m?"direct_peer_status":"other_status":i=m?"peer_broadcast":"other_broadcast",A=m,e=s,a=g}else if(Kc(s))i="newsletter",e=s,a=s,(d(s)||B(s))&&(A=!0);else throw new bl.Boom("Unknown message type",{data:n});let f=n?.attrs?.notify,Q={remoteJid:e,remoteJidAlt:Ur(e)?void 0:I.senderAlt,remoteJidUsername:Ur(e)?void 0:n.attrs.peer_recipient_username||n.attrs.recipient_username,fromMe:A,id:r,participant:g,participantAlt:Ur(e)?I.senderAlt:void 0,participantUsername:n.attrs.participant?n.attrs.participant_username:void 0,addressingMode:I.addressingMode,...i==="newsletter"&&n.attrs.server_id?{server_id:n.attrs.server_id}:{}},y={key:Q,category:n.attrs.category,messageTimestamp:+n.attrs.t,pushName:f,broadcast:EB(s)};return Q.fromMe&&(y.status=oe.WebMessageInfo.Status.SERVER_ACK),{fullMessage:y,author:a,sender:i==="chat"?a:e}}var R7=(n,t,o,i,e)=>{let{fullMessage:a,author:A,sender:r}=TF(n,t,o);return{fullMessage:a,category:n.attrs.category,author:A,async decrypt(){let s=0;if(Array.isArray(n.content))for(let{tag:g,attrs:c,content:I}of n.content){if(g==="verified_name"&&I instanceof Uint8Array){let f=oe.VerifiedNameCertificate.decode(I),Q=oe.VerifiedNameCertificate.Details.decode(f.details);a.verifiedBizName=Q.verifiedName}if(g==="unavailable"&&c.type==="view_once"&&(a.key.isViewOnce=!0),c.count&&g==="enc"&&(a.retryCount=Number(c.count)),g!=="enc"&&g!=="plaintext"||!(I instanceof Uint8Array))continue;s+=1;let d,B=await FUe(A,i);g!=="plaintext"&&await LUe(n,A,i,B,e);try{let f=g==="plaintext"?"plaintext":c.type;switch(f){case"skmsg":d=await i.decryptGroupMessage({group:r,authorJid:A,msg:I});break;case"pkmsg":case"msg":d=await i.decryptMessage({jid:B,type:f,ciphertext:I});break;case"plaintext":d=I;break;default:throw new Error(`Unknown e2e type: ${f}`)}let Q=oe.Message.decode(f!=="plaintext"?B7(d):d);if(Q=Q.deviceSentMessage?.message||Q,Q.senderKeyDistributionMessage)try{await i.processSenderKeyDistributionMessage({authorJid:A,item:Q.senderKeyDistributionMessage})}catch(y){e.error({key:a.key,err:y},"failed to process sender key distribution message")}a.message?Object.assign(a.message,Q):a.message=Q}catch(f){let Q={key:a.key,err:f,messageType:g==="plaintext"?"plaintext":c.type,sender:r,author:A,isSessionRecordError:HUe(f)};e.error(Q,"failed to decrypt message"),a.messageStubType=oe.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[f.message.toString()]}}!s&&!a.key?.isViewOnce&&(a.messageStubType=oe.WebMessageInfo.StubType.CIPHERTEXT,a.messageStubParameters=[sD])}}};function HUe(n){let t=n?.message||n?.toString()||"";return UUe.sessionRecordErrors.some(o=>t.includes(o))}var Yg=Je(Lr(),1);import{randomBytes as z2}from"crypto";import{promises as V2}from"fs";var Pn=Je(Lr(),1);import{exec as Hqe}from"child_process";import*as Io from"crypto";import{once as Zh}from"events";import{createReadStream as sb,createWriteStream as U2,promises as $h}from"fs";import{tmpdir as aoe}from"os";import{join as ob}from"path";import{Readable as hf,Transform as Kqe}from"stream";import{URL as H2}from"url";var K2=()=>aoe(),ioe=async()=>{let[n,t]=await Promise.all([import("jimp").catch(()=>{}),Promise.resolve().then(()=>(YAe(),xAe)).catch(()=>{})]);if(t)return{sharp:t};if(n)return{jimp:n};throw new Pn.Boom("No image processing library available")},xqe=n=>`WhatsApp ${Coe[n]} Keys`,gb=async(n,t,o)=>{let{stream:i}=await Ef(n);o?.debug("got stream for raw upload");let e=Io.createHash("sha256"),a=ob(aoe(),t+Kr()),A=U2(a),r=0;try{for await(let g of i)r+=g.length,e.update(g),A.write(g)||await Zh(A,"drain");A.end(),await Zh(A,"finish"),i.destroy();let s=e.digest();return o?.debug("hashed data for raw upload"),{filePath:a,fileSha256:s,fileLength:r}}catch(s){A.destroy(),i.destroy();try{await $h.unlink(a)}catch{}throw s}};async function ooe(n,t){if(!n)throw new Pn.Boom("Cannot derive from empty media key");typeof n=="string"&&(n=Buffer.from(n.replace("data:;base64,",""),"base64"));let o=Rn(n,112,{info:xqe(t)});return{iv:o.slice(0,16),cipherKey:o.slice(16,48),macKey:o.slice(48,80)}}var Yqe=async(n,t,o,i)=>new Promise((e,a)=>{let A=`ffmpeg -ss ${o} -i ${n} -y -vf scale=${i.width}:-1 -vframes 1 -f image2 ${t}`;Hqe(A,r=>{r?a(r):e()})}),x2=async(n,t=32)=>{n instanceof hf&&(n=await nb(n));let o=await ioe();if("sharp"in o&&typeof o.sharp?.default=="function"){let i=o.sharp.default(n),e=await i.metadata();return{buffer:await i.resize(t).jpeg({quality:50}).toBuffer(),original:{width:e.width,height:e.height}}}else if("jimp"in o&&typeof o.jimp?.Jimp=="object"){let i=await o.jimp.Jimp.read(n),e={width:i.width,height:i.height};return{buffer:await i.resize({w:t,mode:o.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50}),original:e}}else throw new Pn.Boom("No image processing library available")},jqe=n=>encodeURIComponent(n.replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")),cb=async(n,t)=>{let o,{width:i=640,height:e=640}=t||{};if(Buffer.isBuffer(n))o=n;else{let{stream:r}=await Ef(n);o=await nb(r)}let a=await ioe(),A;if("sharp"in a&&typeof a.sharp?.default=="function")A=a.sharp.default(o).resize(i,e).jpeg({quality:50}).toBuffer();else if("jimp"in a&&typeof a.jimp?.Jimp=="function"){let r=await a.jimp.Jimp.read(o),s=Math.min(r.width,r.height);A=r.crop({x:0,y:0,w:s,h:s}).resize({w:i,h:e,mode:a.jimp.ResizeStrategy.BILINEAR}).getBuffer("image/jpeg",{quality:50})}else throw new Pn.Boom("No image processing library available");return{img:await A}};async function noe(n){let t=await Promise.resolve().then(()=>(toe(),Aoe)),o,i={duration:!0};return Buffer.isBuffer(n)?o=await t.parseBuffer(n,void 0,i):typeof n=="string"?o=await t.parseFile(n,i):o=await t.parseStream(n,void 0,i),o.format.duration}async function soe(n,t){try{let{default:o}=await import("audio-decode"),i;if(Buffer.isBuffer(n))i=n;else if(typeof n=="string"){let d=sb(n);i=await nb(d)}else i=await nb(n);let a=(await o(i)).getChannelData(0),A=64,r=Math.floor(a.length/A),s=[];for(let d=0;dd*g);return new Uint8Array(c.map(d=>Math.floor(100*d)))}catch(o){t?.debug("Failed to generate waveform: "+o)}}var roe=n=>{let t=new hf({read:()=>{}});return t.push(n),t.push(null),t},nb=async n=>{let t=[];for await(let o of n)t.push(o);return n.destroy(),Buffer.concat(t)},Ef=async(n,t)=>{if(Buffer.isBuffer(n))return{stream:roe(n),type:"buffer"};if("stream"in n)return{stream:n.stream,type:"readable"};let o=n.url.toString();if(o.startsWith("data:")){let i=Buffer.from(o.split(",")[1],"base64");return{stream:roe(i),type:"buffer"}}return o.startsWith("http://")||o.startsWith("https://")?{stream:await Ib(n.url,t),type:"remote"}:{stream:sb(n.url),type:"file"}};async function goe(n,t,o){let i,e;if(t==="image"){let{buffer:a,original:A}=await x2(n);i=a.toString("base64"),A.width&&A.height&&(e={width:A.width,height:A.height})}else if(t==="video"){let a=ob(K2(),Kr()+".jpg");try{await Yqe(n,a,"00:00:00",{width:32,height:32}),i=(await $h.readFile(a)).toString("base64"),await $h.unlink(a)}catch(A){o.logger?.debug("could not generate video thumb: "+A)}}return{thumbnail:i,originalImageDimensions:e}}var Ib=async(n,t={})=>{let o=await fetch(n.toString(),{dispatcher:t.dispatcher,method:"GET",headers:t.headers});if(!o.ok)throw new Pn.Boom(`Failed to fetch stream from ${n}`,{statusCode:o.status,data:{url:n}});return o.body instanceof hf?o.body:hf.fromWeb(o.body)},coe=async(n,t,{logger:o,saveOriginalFileIfRequired:i,opts:e}={})=>{let{stream:a,type:A}=await Ef(n,e);o?.debug("fetched media stream");let r=Io.randomBytes(32),{cipherKey:s,iv:g,macKey:c}=await ooe(r,t),I=ob(K2(),t+Kr()+"-enc"),d=U2(I),B,f;i&&(f=ob(K2(),t+Kr()+"-original"),B=U2(f));let Q=0,y=Io.createCipheriv("aes-256-cbc",s,g),m=Io.createHmac("sha256",c).update(g),_=Io.createHash("sha256"),T=Io.createHash("sha256"),R=async L=>{T.update(L),m.update(L),d.write(L)||await Zh(d,"drain")};try{for await(let j of a){if(Q+=j.length,A==="remote"&&e?.maxContentLength&&Q+j.length>e.maxContentLength)throw new Pn.Boom(`content length exceeded when encrypting "${A}"`,{data:{media:n,type:A}});B&&(B.write(j)||await Zh(B,"drain")),_.update(j),await R(y.update(j))}await R(y.final());let L=m.digest().slice(0,10);T.update(L);let U=_.digest(),F=T.digest();d.write(L);let q=Zh(d,"finish"),z=B?Zh(B,"finish"):Promise.resolve();return d.end(),B?.end?.(),a.destroy(),await q,await z,o?.debug("encrypted data successfully"),{mediaKey:r,originalFilePath:f,encFilePath:I,mac:L,fileEncSha256:F,fileSha256:U,fileLength:Q}}catch(L){d.destroy(),B?.destroy?.(),y.destroy(),m.destroy(),_.destroy(),T.destroy(),a.destroy();try{await $h.unlink(I),f&&await $h.unlink(f)}catch(U){o?.error({err:U},"failed deleting tmp files")}throw L}},Y2="mmg.whatsapp.net",Xh=16,L2=n=>Math.floor(n/Xh)*Xh,Cf=(n,t=Y2)=>`https://${t}${n}`,Jqe=n=>{if(n)try{return new H2(n).host}catch{return}},eE=async({mediaKey:n,directPath:t,url:o},i,e={})=>{let a=e.host??Jqe(o),A=t?Cf(t,a):o;if(!A)throw new Pn.Boom("No valid media URL or directPath present in message",{statusCode:400});let r=await ooe(n,i);return qqe(A,r,e)},qqe=async(n,{cipherKey:t,iv:o},{startByte:i,endByte:e,options:a}={})=>{let A=0,r=0,s=!1;if(i){let m=L2(i||0);m&&(r=m-Xh,A=m,s=!0)}let g=e?L2(e||0)+Xh:void 0,c=a?.headers?a.headers:void 0,I={...c?Array.isArray(c)?Object.fromEntries(c):c:{},Origin:uf};(r||g)&&(I.Range=`bytes=${r}-`,g&&(I.Range+=g));let d=await Ib(n,{...a||{},headers:I}),B=Buffer.from([]),f,Q=(m,_)=>{if(i||e){let T=A>=i?void 0:Math.max(i-A,0),R=A+m.lengththis.push(U)),T()}catch(U){T(U)}},final(m){try{Q(f.final(),_=>this.push(_)),m()}catch(_){m(_)}}});return d.pipe(y,{end:!0})};var zqe=()=>typeof process<"u"&&process.versions?.node!==null&&typeof process.versions.bun>"u"&&typeof globalThis.Deno>"u",Ioe=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e},a=0)=>{if(a>5)throw new Error("Too many redirects");let A=new H2(n),r=A.protocol==="https:"?await import("https"):await import("http"),g=(await $h.stat(t)).size;return new Promise((c,I)=>{let d=r.request({hostname:A.hostname,port:A.port||(A.protocol==="https:"?443:80),path:A.pathname+A.search,method:"POST",headers:{...o,"Content-Length":g},agent:e,timeout:i},f=>{if(f.statusCode&&f.statusCode>=300&&f.statusCode<400&&f.headers.location){f.resume();let y=new H2(f.headers.location,n).toString();c(Ioe({url:y,filePath:t,headers:o,timeoutMs:i,agent:e},a+1));return}let Q="";f.on("data",y=>Q+=y),f.on("end",()=>{try{c(JSON.parse(Q))}catch{c(void 0)}})});d.on("error",I),d.on("timeout",()=>{d.destroy(),I(new Error("Upload timeout"))});let B=sb(t);B.pipe(d),B.on("error",f=>{d.destroy(),I(f)})})},Vqe=async({url:n,filePath:t,headers:o,timeoutMs:i,agent:e})=>{let a=sb(t),A=hf.toWeb(a),r=typeof e?.dispatch=="function"?e:void 0,s=await fetch(n,{...r?{dispatcher:r}:{},method:"POST",body:A,headers:o,duplex:"half",signal:i?AbortSignal.timeout(i):void 0});try{return await s.json()}catch{return}},Wqe=async(n,t)=>zqe()?(t?.debug("Using Node.js https module for upload (avoids undici buffering bug)"),Ioe(n)):(t?.debug("Using web-standard Fetch API for upload"),Vqe(n)),loe=({customUploadHosts:n,fetchAgent:t,logger:o,options:i},e)=>async(a,{mediaType:A,fileEncSha256B64:r,timeoutMs:s})=>{let g=await e(!1),c,I=[...n,...g.hosts];r=jqe(r);let B={...(()=>{let f=i?.headers;return f?Array.isArray(f)?Object.fromEntries(f):f:{}})(),"Content-Type":"application/octet-stream",Origin:uf};for(let{hostname:f}of I){o.debug(`uploading to "${f}"`);let Q=encodeURIComponent(g.auth),y=`https://${f}${J2[A]}/${r}?auth=${Q}&token=${r}`,m;try{if(m=await Wqe({url:y,filePath:a,headers:B,timeoutMs:s,agent:t},o),m?.url||m?.direct_path){c={mediaUrl:m.url,directPath:m.direct_path,meta_hmac:m.meta_hmac,fbid:m.fbid,ts:m.ts};break}else throw g=await e(!0),new Error(`upload failed, reason: ${JSON.stringify(m)}`)}catch(_){let T=f===I[g.hosts.length-1]?.hostname;o.warn({trace:_?.stack,uploadResult:m},`Error in uploading to ${f} ${T?"":", retrying..."}`)}}if(!c)throw new Pn.Boom("Media upload failed on all hosts",{statusCode:500});return c},poe=n=>Rn(n,32,{info:"WhatsApp Media Retry Notification"}),doe=(n,t,o)=>{let i={stanzaId:n.id},e=oe.ServerErrorReceipt.encode(i).finish(),a=Io.randomBytes(12),A=poe(t),r=Dl(e,A,a,Buffer.from(n.id));return{tag:"receipt",attrs:{id:n.id,to:uA(o),type:"server-error"},content:[{tag:"encrypt",attrs:{},content:[{tag:"enc_p",attrs:{},content:r},{tag:"enc_iv",attrs:{},content:a}]},{tag:"rmr",attrs:{jid:n.remoteJid,from_me:(!!n.fromMe).toString(),participant:n.participant||void 0}}]}},hoe=n=>{let t=le(n,"rmr"),o={key:{id:n.attrs.id,remoteJid:t.attrs.jid,fromMe:t.attrs.from_me==="true",participant:t.attrs.participant}},i=le(n,"error");if(i){let e=+i.attrs.code;o.error=new Pn.Boom(`Failed to re-upload media (${e})`,{data:i.attrs,statusCode:j2(e)})}else{let e=le(n,"encrypt"),a=Qa(e,"enc_p"),A=Qa(e,"enc_iv");a&&A?o.media={ciphertext:a,iv:A}:o.error=new Pn.Boom("Failed to re-upload media (missing ciphertext)",{statusCode:404})}return o},Eoe=({ciphertext:n,iv:t},o,i)=>{let e=poe(o),a=Ol(n,e,t,Buffer.from(i));return oe.MediaRetryNotification.decode(a)},j2=n=>Zqe[n],Zqe={[oe.MediaRetryNotification.ResultType.SUCCESS]:200,[oe.MediaRetryNotification.ResultType.DECRYPTION_ERROR]:412,[oe.MediaRetryNotification.ResultType.NOT_FOUND]:404,[oe.MediaRetryNotification.ResultType.GENERAL_ERROR]:418};import{createHmac as Xqe}from"crypto";var $qe=[{f:1},{f:3,s:[{f:2},{f:3},{f:8},{f:11},{f:17,s:[{f:21},{f:22}]},{f:25}]},{f:4,s:[{f:1},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:5,s:[{f:3},{f:4},{f:5},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:6,s:[{f:1},{f:17,s:[{f:21},{f:22}]},{f:30}]},{f:7,s:[{f:2},{f:7},{f:10},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:8,s:[{f:2},{f:7},{f:9},{f:17,s:[{f:21},{f:22}]},{f:21}]},{f:9,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:12,s:[{f:1},{f:2},{f:14,m:!0},{f:15}]},{f:18,s:[{f:6},{f:16},{f:17,s:[{f:21},{f:22}]}]},{f:26,s:[{f:4},{f:5},{f:8},{f:13},{f:17,s:[{f:21},{f:22}]}]},{f:28,s:[{f:1},{f:2},{f:4},{f:5},{f:6},{f:7,s:[{f:21},{f:22}]}]},{f:37,s:[{f:1,m:!0}]},{f:49,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:53,s:[{f:1,m:!0}]},{f:55,s:[{f:1,m:!0}]},{f:58,s:[{f:1,m:!0}]},{f:59,s:[{f:1,m:!0}]},{f:60,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:64,s:[{f:2},{f:3,s:[{f:1},{f:2}]},{f:5,s:[{f:21},{f:22}]},{f:8,s:[{f:1},{f:2}]}]},{f:66,s:[{f:2},{f:6},{f:7},{f:13},{f:17,s:[{f:21},{f:22}]},{f:20}]},{f:74,s:[{f:1,m:!0}]},{f:87,s:[{f:1,m:!0}]},{f:88,s:[{f:1},{f:2,s:[{f:1}]},{f:3,s:[{f:21},{f:22}]}]},{f:92,s:[{f:1,m:!0}]},{f:93,s:[{f:1,m:!0}]},{f:94,s:[{f:1,m:!0}]}],Boe=n=>{let t=new Map;for(let o of n)t.set(o.f,{m:o.m,children:o.s?Boe(o.s):void 0});return t},e4e=Boe($qe),A4e=new Map,t4e="Report Token",lb={VARINT:0,FIXED64:1,BYTES:2,FIXED32:5},pb=n=>!n.reactionMessage&&!n.encReactionMessage&&!n.encEventResponseMessage&&!n.pollUpdateMessage,r4e=(n,t,o,i,e)=>{let a=Buffer.concat([Buffer.from(t,"utf8"),Buffer.from(o,"utf8"),Buffer.from(i,"utf8"),Buffer.from(n,"utf8")]);return Rn(e,32,{info:a.toString("latin1")})},foe=(n,t)=>{let o=[],i=0;for(;i>3,A=e.value&7,r=i;i+=e.bytes;let s=t.get(a),g=I=>I>n.length?!1:(o.push({num:a,bytes:n.subarray(r,I)}),i=I,!0),c=I=>I>n.length?!1:(i=I,!0);if(A===lb.VARINT){let I=q2(n,i);if(!I.ok)return null;let d=i+I.bytes;if(!s){if(!c(d))return null;continue}if(!g(d))return null;continue}if(A===lb.FIXED64){let I=i+8;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===lb.FIXED32){let I=i+4;if(!s){if(!c(I))return null;continue}if(!g(I))return null;continue}if(A===lb.BYTES){let I=q2(n,i);if(!I.ok)return null;let d=i+I.bytes,B=d+I.value;if(B>n.length)return null;if(!s){i=B;continue}if(s.m||s.children){let f=foe(n.subarray(d,B),s.children??A4e);if(f===null)return null;if(f.length>0){let Q=uoe(e.value),y=uoe(f.length);o.push({num:a,bytes:Buffer.concat([Q,y,f])})}i=B;continue}o.push({num:a,bytes:n.subarray(r,B)}),i=B;continue}return null}return o.length===0?Buffer.alloc(0):(o.sort((e,a)=>e.num-a.num),Buffer.concat(o.map(e=>e.bytes)))},q2=(n,t)=>{let o=0,i=0,e=0;for(;t+i35)return{value:0,bytes:0,ok:!1}}return{value:0,bytes:0,ok:!1}},uoe=n=>{let t=[],o=n>>>0;for(;o>127;)t.push(o&127|128),o>>>=7;return t.push(o),Buffer.from(t)},Qoe=async(n,t,o)=>{let i=t.messageContextInfo?.messageSecret;if(!i||!o.id)return null;let e=o.fromMe?o.remoteJid:o.participant||o.remoteJid,a=o.fromMe&&o.participant||o.remoteJid,A=r4e(t4e,o.id,e,a,i),r=foe(n,e4e);if(!r||r.length===0)return null;let s=Xqe("sha256",A).update(r).digest().subarray(0,16);return{tag:"reporting",attrs:{},content:[{tag:"reporting_token",attrs:{v:"2"},content:s}]}};var a4e={image:"image/jpeg",video:"video/mp4",document:"application/pdf",audio:"audio/ogg; codecs=opus",sticker:"image/webp","product-catalog-image":"image/jpeg"},yoe={image:oe.Message.ImageMessage,video:oe.Message.VideoMessage,audio:oe.Message.AudioMessage,sticker:oe.Message.StickerMessage,document:oe.Message.DocumentMessage},i4e=n=>n.match(_oe)?.[0],o4e=async(n,t,o)=>{let i=i4e(n);if(t&&i)try{return await t(i)}catch(e){o?.warn({trace:e.stack},"url generation failed")}},moe=async n=>{let t;if(typeof n=="number")t=n>0?n:4294967295+Number(n)+1;else{let o=n.trim().replace("#","");return o.length<=6&&(o="FF"+o.padStart(6,"0")),t=parseInt(o,16),t}},Bf=async(n,t)=>{let o=t.logger,i;for(let U of Toe)U in n&&(i=U);if(!i)throw new Yg.Boom("Invalid media type",{statusCode:400});let e={...n,media:n[i]};delete e[i];let a=typeof e.media=="object"&&"url"in e.media&&!!e.media.url&&!!t.mediaCache&&i+":"+e.media.url.toString();if(i==="document"&&!e.fileName&&(e.fileName="file"),e.mimetype||(e.mimetype=a4e[i]),a){let U=await t.mediaCache.get(a);if(U){o?.debug({cacheableKey:a},"got media cache hit");let F=oe.Message.decode(U),q=`${i}Message`;return Object.assign(F[q],{...e,media:void 0}),F}}if(!!t.jid&&Kc(t.jid)){o?.info({key:a},"Preparing raw media for newsletter");let{filePath:U,fileSha256:F,fileLength:q}=await gb(e.media,t.mediaTypeOverride||i,o),z=F.toString("base64"),{mediaUrl:j,directPath:P}=await t.upload(U,{fileEncSha256B64:z,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});await V2.unlink(U);let J=oe.Message.fromObject({[`${i}Message`]:yoe[i].fromObject({url:j,directPath:P,fileSha256:F,fileLength:q,...e,media:void 0})});return e.ptv&&(J.ptvMessage=J.videoMessage,delete J.videoMessage),J.stickerMessage&&(J.stickerMessage.stickerSentTs=Date.now()),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,oe.Message.encode(J).finish())),J}let r=i==="audio"&&typeof e.seconds>"u",s=(i==="image"||i==="video")&&typeof e.jpegThumbnail>"u",g=i==="audio"&&e.ptt===!0&&typeof e.waveform>"u",c=t.backgroundColor&&i==="audio"&&e.ptt===!0,I=r||s,{mediaKey:d,encFilePath:B,originalFilePath:f,fileEncSha256:Q,fileSha256:y,fileLength:m}=await coe(e.media,t.mediaTypeOverride||i,{logger:o,saveOriginalFileIfRequired:I,opts:t.options}),_=Q.toString("base64"),[{mediaUrl:T,directPath:R}]=await Promise.all([(async()=>{let U=await t.upload(B,{fileEncSha256B64:_,mediaType:i,timeoutMs:t.mediaUploadTimeoutMs});return o?.debug({mediaType:i,cacheableKey:a},"uploaded media"),U})(),(async()=>{try{if(s){let{thumbnail:U,originalImageDimensions:F}=await goe(f,i,t);e.jpegThumbnail=U,!e.width&&F&&(e.width=F.width,e.height=F.height,o?.debug("set dimensions")),o?.debug("generated thumbnail")}r&&(e.seconds=await noe(f),o?.debug("computed audio duration")),g&&(e.waveform=await soe(f,o),o?.debug("processed waveform")),c&&(e.backgroundArgb=await moe(t.backgroundColor),o?.debug("computed backgroundColor audio status"))}catch(U){o?.warn({trace:U.stack},"failed to obtain extra info")}})()]).finally(async()=>{try{await V2.unlink(B),f&&await V2.unlink(f),o?.debug("removed tmp files")}catch{o?.warn("failed to remove tmp file")}}),L=oe.Message.fromObject({[`${i}Message`]:yoe[i].fromObject({url:T,directPath:R,mediaKey:d,fileEncSha256:Q,fileSha256:y,fileLength:m,mediaKeyTimestamp:ya(),...e,media:void 0})});return e.ptv&&(L.ptvMessage=L.videoMessage,delete L.videoMessage),a&&(o?.debug({cacheableKey:a},"set cache"),await t.mediaCache.set(a,oe.Message.encode(L).finish())),L},n4e=n=>{n=n||0;let t={ephemeralMessage:{message:{protocolMessage:{type:oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:n}}}};return oe.Message.fromObject(t)},s4e=(n,t)=>{let o=n.message;if(!o)throw new Yg.Boom("no content in message",{statusCode:400});o=Oa(o),o=oe.Message.decode(oe.Message.encode(o).finish());let i=Object.keys(o)[0],e=o?.[i]?.contextInfo?.forwardingScore||0;e+=n.key.fromMe&&!t?0:1,i==="conversation"&&(o.extendedTextMessage={text:o[i]},delete o.conversation,i="extendedTextMessage");let a=o?.[i];return e>0?a.contextInfo={forwardingScore:e,isForwarded:!0}:a.contextInfo={},o},da=(n,t)=>typeof n=="object"&&n!==null&&t in n&&n[t]!==null&&n[t]!==void 0;function Xl(n,t){return typeof n=="object"&&n!==null&&t in n&&n[t]!==null}var g4e=async(n,t)=>{var o,i;let e={};if(da(n,"text")){let a={text:n.text},A=n.linkPreview;if(typeof A>"u"&&(A=await o4e(n.text,t.getUrlInfo,t.logger)),A){a.matchedText=A["matched-text"],a.jpegThumbnail=A.jpegThumbnail,a.description=A.description,a.title=A.title,a.previewType=0;let r=A.highQualityThumbnail;r&&(a.thumbnailDirectPath=r.directPath,a.mediaKey=r.mediaKey,a.mediaKeyTimestamp=r.mediaKeyTimestamp,a.thumbnailWidth=r.width,a.thumbnailHeight=r.height,a.thumbnailSha256=r.fileSha256,a.thumbnailEncSha256=r.fileEncSha256)}t.backgroundColor&&(a.backgroundArgb=await moe(t.backgroundColor)),t.font&&(a.font=t.font),e.extendedTextMessage=a}else if(da(n,"contacts")){let a=n.contacts.contacts.length;if(!a)throw new Yg.Boom("require atleast 1 contact",{statusCode:400});a===1?e.contactMessage=oe.Message.ContactMessage.create(n.contacts.contacts[0]):e.contactsArrayMessage=oe.Message.ContactsArrayMessage.create(n.contacts)}else if(da(n,"location"))e.locationMessage=oe.Message.LocationMessage.create(n.location);else if(da(n,"react"))n.react.senderTimestampMs||(n.react.senderTimestampMs=Date.now()),e.reactionMessage=oe.Message.ReactionMessage.create(n.react);else if(da(n,"delete"))e.protocolMessage={key:n.delete,type:oe.Message.ProtocolMessage.Type.REVOKE};else if(da(n,"forward"))e=s4e(n.forward,n.force);else if(da(n,"disappearingMessagesInChat")){let a=typeof n.disappearingMessagesInChat=="boolean"?n.disappearingMessagesInChat?Qf:0:n.disappearingMessagesInChat;e=n4e(a)}else if(da(n,"groupInvite")){if(e.groupInviteMessage={},e.groupInviteMessage.inviteCode=n.groupInvite.inviteCode,e.groupInviteMessage.inviteExpiration=n.groupInvite.inviteExpiration,e.groupInviteMessage.caption=n.groupInvite.text,e.groupInviteMessage.groupJid=n.groupInvite.jid,e.groupInviteMessage.groupName=n.groupInvite.subject,t.getProfilePicUrl){let a=await t.getProfilePicUrl(n.groupInvite.jid,"preview");if(a){let A=await fetch(a,{method:"GET",dispatcher:t?.options?.dispatcher});if(A.ok){let r=Buffer.from(await A.arrayBuffer());e.groupInviteMessage.jpegThumbnail=r}}}}else if(da(n,"pin"))e.pinInChatMessage={},e.messageContextInfo={},e.pinInChatMessage.key=n.pin,e.pinInChatMessage.type=n.type,e.pinInChatMessage.senderTimestampMs=Date.now(),e.messageContextInfo.messageAddOnDurationInSecs=n.type===1?n.time||86400:0;else if(da(n,"buttonReply"))switch(n.type){case"template":e.templateButtonReplyMessage={selectedDisplayText:n.buttonReply.displayText,selectedId:n.buttonReply.id,selectedIndex:n.buttonReply.index};break;case"plain":e.buttonsResponseMessage={selectedButtonId:n.buttonReply.id,selectedDisplayText:n.buttonReply.displayText,type:oe.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT};break}else if(Xl(n,"ptv")&&n.ptv){let{videoMessage:a}=await Bf({video:n.video},t);e.ptvMessage=a}else if(da(n,"product")){let{imageMessage:a}=await Bf({image:n.product.productImage},t);e.productMessage=oe.Message.ProductMessage.create({...n,product:{...n.product,productImage:a}})}else if(da(n,"listReply"))e.listResponseMessage={...n.listReply};else if(da(n,"event")){e.eventMessage={};let a=Math.floor(n.event.startDate.getTime()/1e3);if(n.event.call&&t.getCallLink){let A=await t.getCallLink(n.event.call,{startTime:a});e.eventMessage.joinLink=(n.event.call==="audio"?Moe:boe)+A}e.messageContextInfo={messageSecret:n.event.messageSecret||z2(32)},e.eventMessage.name=n.event.name,e.eventMessage.description=n.event.description,e.eventMessage.startTime=a,e.eventMessage.endTime=n.event.endDate?n.event.endDate.getTime()/1e3:void 0,e.eventMessage.isCanceled=n.event.isCancelled??!1,e.eventMessage.extraGuestsAllowed=n.event.extraGuestsAllowed,e.eventMessage.isScheduleCall=n.event.isScheduleCall??!1,e.eventMessage.location=n.event.location}else if(da(n,"poll")){if((o=n.poll).selectableCount||(o.selectableCount=0),(i=n.poll).toAnnouncementGroup||(i.toAnnouncementGroup=!1),!Array.isArray(n.poll.values))throw new Yg.Boom("Invalid poll values",{statusCode:400});if(n.poll.selectableCount<0||n.poll.selectableCount>n.poll.values.length)throw new Yg.Boom(`poll.selectableCount in poll should be >= 0 and <= ${n.poll.values.length}`,{statusCode:400});e.messageContextInfo={messageSecret:n.poll.messageSecret||z2(32)};let a={name:n.poll.name,selectableOptionsCount:n.poll.selectableCount,options:n.poll.values.map(A=>({optionName:A}))};n.poll.toAnnouncementGroup?e.pollCreationMessageV2=a:n.poll.selectableCount===1?e.pollCreationMessageV3=a:e.pollCreationMessage=a}else da(n,"album")?e.albumMessage={expectedImageCount:n.album.expectedImageCount,expectedVideoCount:n.album.expectedVideoCount}:da(n,"sharePhoneNumber")?e.protocolMessage={type:oe.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER}:da(n,"requestPhoneNumber")?e.requestPhoneNumberMessage={}:da(n,"limitSharing")?e.protocolMessage={type:oe.Message.ProtocolMessage.Type.LIMIT_SHARING,limitSharing:{sharingLimited:n.limitSharing===!0,trigger:1,limitSharingSettingTimestamp:Date.now(),initiatedByMe:!0}}:e=await Bf(n,t);if(Xl(n,"viewOnce")&&n.viewOnce&&(e={viewOnceMessage:{message:e}}),Xl(n,"mentions")&&n.mentions?.length||Xl(n,"mentionAll")&&n.mentionAll){let a=Object.keys(e)[0],A=e[a];A&&"contextInfo"in A?(A.contextInfo=A.contextInfo||{},n.mentions?.length&&(A.contextInfo.mentionedJid=n.mentions),n.mentionAll&&(A.contextInfo.nonJidMentions=1)):A&&(A.contextInfo={mentionedJid:n.mentions,nonJidMentions:n.mentionAll?1:0})}if(Xl(n,"edit")&&(e={protocolMessage:{key:n.edit,editedMessage:e,timestampMs:Date.now(),type:oe.Message.ProtocolMessage.Type.MESSAGE_EDIT}}),Xl(n,"contextInfo")&&n.contextInfo){let a=Object.keys(e)[0],A=e[a];"contextInfo"in A&&A.contextInfo?A.contextInfo={...A.contextInfo,...n.contextInfo}:A&&(A.contextInfo=n.contextInfo)}return Xl(n,"albumParentKey")&&n.albumParentKey&&(e.messageContextInfo={...e.messageContextInfo,messageAssociation:{associationType:oe.MessageAssociation.AssociationType.MEDIA_ALBUM,parentMessageKey:n.albumParentKey}}),pb(e)&&(e.messageContextInfo=e.messageContextInfo||{},e.messageContextInfo.messageSecret||(e.messageContextInfo.messageSecret=z2(32))),oe.Message.create(e)},c4e=(n,t,o)=>{o.timestamp||(o.timestamp=new Date);let i=Oa(t),e=ff(i),a=ya(o.timestamp),{quoted:A,userJid:r}=o;if(A&&!Kc(n)){let g=A.key.fromMe?r:A.participant||A.key.participant||A.key.remoteJid,c=Oa(A.message),I=ff(c);c=oe.Message.create({[I]:c[I]});let d=c[I];typeof d=="object"&&d&&"contextInfo"in d&&delete d.contextInfo;let B="contextInfo"in i[e]&&i[e]?.contextInfo||{};B.participant=uA(g),B.stanzaId=A.key.id,B.quotedMessage=c,n!==A.key.remoteJid&&(B.remoteJid=A.key.remoteJid),B&&i[e]&&(i[e].contextInfo=B)}o?.ephemeralExpiration&&e!=="protocolMessage"&&e!=="ephemeralMessage"&&!Kc(n)&&(i[e].contextInfo={...i[e].contextInfo||{},expiration:o.ephemeralExpiration||Qf}),t=oe.Message.create(t);let s={key:{remoteJid:n,fromMe:!0,id:o?.messageId||Kr()},message:t,messageTimestamp:a,messageStubParameters:[],participant:Ur(n)||Tg(n)?r:void 0,status:th.PENDING};return oe.WebMessageInfo.fromObject(s)},Soe=async(n,t,o)=>(o.logger=o?.logger?.child({msgId:o.messageId}),c4e(n,await g4e(t,{...o,jid:n}),o)),ff=n=>{if(n)return Object.keys(n).find(i=>(i==="conversation"||i.includes("Message"))&&i!=="senderKeyDistributionMessage")},Oa=n=>{if(!n)return;for(let o=0;o<5;o++){let i=t(n);if(!i)break;n=i.message}return n;function t(o){return o?.ephemeralMessage||o?.viewOnceMessage||o?.documentWithCaptionMessage||o?.viewOnceMessageV2||o?.viewOnceMessageV2Extension||o?.editedMessage||o?.associatedChildMessage||o?.groupStatusMessage||o?.groupStatusMessageV2}},woe=n=>{let t=o=>o.imageMessage?{imageMessage:o.imageMessage}:o.documentMessage?{documentMessage:o.documentMessage}:o.videoMessage?{videoMessage:o.videoMessage}:o.locationMessage?{locationMessage:o.locationMessage}:{conversation:"contentText"in o?o.contentText:"hydratedContentText"in o?o.hydratedContentText:""};return n=Oa(n),n?.buttonsMessage?t(n.buttonsMessage):n?.templateMessage?.hydratedFourRowTemplate?t(n?.templateMessage?.hydratedFourRowTemplate):n?.templateMessage?.hydratedTemplate?t(n?.templateMessage?.hydratedTemplate):n?.templateMessage?.fourRowTemplate?t(n?.templateMessage?.fourRowTemplate):n};var W2=(n,t)=>{n.userReceipt=n.userReceipt||[];let o=n.userReceipt.find(i=>i.userJid===t.userJid);o?Object.assign(o,t):n.userReceipt.push(t)},Z2=(n,t)=>{let o=gh(t.key),i=(n.reactions||[]).filter(e=>gh(e.key)!==o);t.text=t.text||"",i.push(t),n.reactions=i};var Doe=n=>{let t={};for(let{remoteJid:o,id:i,participant:e,fromMe:a}of n)if(!a){let A=`${o}:${e||""}`;t[A]||(t[A]={jid:o,participant:e,messageIds:[]}),t[A].messageIds.push(i)}return Object.values(t)},I4e=[410,404],X2=async(n,t,o,i)=>{return await a().catch(async A=>{if(i&&typeof A?.status=="number"&&I4e.includes(A.status))return i.logger.info({key:n.key},"sending reupload media request..."),n=await i.reuploadRequest(n),await a();throw A});async function a(){let A=woe(n.message);if(!A)throw new Yg.Boom("No message present",{statusCode:400,data:n});let r=ff(A),s=r?.replace("Message",""),g=A[r];if(!g||typeof g!="object"||!("url"in g)&&!("thumbnailDirectPath"in g))throw new Yg.Boom(`"${r}" message is not a media message`);let c;"thumbnailDirectPath"in g&&!("url"in g)?(c={directPath:g.thumbnailDirectPath,mediaKey:g.mediaKey},s="thumbnail-link"):c=g;let I=await eE(c,s,o);if(t==="buffer"){let d=[];for await(let B of I)d.push(B);return Buffer.concat(d)}return I}},Ooe=n=>{n=woe(n);let t=n?.documentMessage||n?.imageMessage||n?.videoMessage||n?.audioMessage||n?.stickerMessage;if(!t)throw new Yg.Boom("given message is not a media message",{statusCode:400,data:n});return t};var db=Je(Lr(),1);import{createHash as h4e}from"crypto";function l4e(n,t){let o=[];for(let i=0;i({identifier:{name:n,deviceId:0},identifierKey:Yo(t)}),p4e=async({get:n},t,o)=>{let i=[];for(let e=t;e{let o=n.nextPreKeyId-n.firstUnuploadedPreKeyId,i=t-o,e=n.nextPreKeyId+i-1,a={};if(i>0)for(let A=n.nextPreKeyId;A<=e;A++)a[A]=Br.generateKeyPair();return{newPreKeys:a,lastPreKeyId:e,preKeysRange:[n.firstUnuploadedPreKeyId,t]}},yf=n=>({tag:"skey",attrs:{},content:[{tag:"id",attrs:{},content:kg(n.keyId,3)},{tag:"value",attrs:{},content:n.keyPair.public},{tag:"signature",attrs:{},content:n.signature}]}),eU=(n,t)=>({tag:"key",attrs:{},content:[{tag:"id",attrs:{},content:kg(t,3)},{tag:"value",attrs:{},content:n.public}]}),$2=n=>typeof n=="number"&&Number.isInteger(n),Roe=n=>{let t=le(n,"keys");if(!t)return null;let o=Qa(t,"type");if(!o||o.length!==1||o[0]!==Rg[0])return null;let i=Qa(t,"identity"),e=le(t,"skey");if(!i||i.length!==32||!e)return null;let a=xc(n,"registration",4);if(!$2(a))return null;let A=Qa(e,"value"),r=Qa(e,"signature"),s=xc(e,"id",3);if(!A||A.length!==32||!r||!$2(s))return null;let g=le(t,"key"),c;if(g){let I=Qa(g,"value"),d=xc(g,"id",3);if(!I||I.length!==32||!$2(d))return null;c={keyId:d,publicKey:Yo(I)}}return{registrationId:a,identityKey:Yo(i),signedPreKey:{keyId:s,publicKey:Yo(A),signature:r},preKey:c}},koe=async(n,t)=>{let o=A=>A?{keyId:xc(A,"id",3),publicKey:Yo(Qa(A,"value")),signature:Qa(A,"signature")}:void 0,i=kA(le(n,"list"),"user");for(let A of i)Li(A);let a=l4e(i,100);for(let A of a)for(let r of A){let s=le(r,"skey"),g=le(r,"key"),c=Qa(r,"identity"),I=r.attrs.jid,d=xc(r,"registration",4);await t.injectE2ESession({jid:I,session:{registrationId:d,identityKey:Yo(c),signedPreKey:o(s),preKey:o(g)}})}},voe=(n,t,o,i)=>{let{user:e,device:a}=yA(t),A=[];for(let r of n){let{devices:s,id:g}=r,c=yA(g),{user:I,server:d}=c,{domainType:B}=c,f=s?.deviceList;if(Array.isArray(f))for(let{id:Q,keyIndex:y,isHosted:m}of f)(!i||Q!==0)&&(e!==I&&o!==I||a!==Q)&&(Q===0||y)&&(m&&(B=B===jt.LID?jt.HOSTED_LID:jt.HOSTED),A.push({user:I,device:Q,domainType:B,server:LX(d,B)}))}return A},AU=async({creds:n,keys:t},o)=>{let{newPreKeys:i,lastPreKeyId:e,preKeysRange:a}=d4e(n,o),A={nextPreKeyId:Math.max(e+1,n.nextPreKeyId),firstUnuploadedPreKeyId:Math.max(n.firstUnuploadedPreKeyId,e+1)};await t.set({"pre-key":i});let r=await p4e(t,a[0],a[0]+a[1]);return{update:A,preKeys:r}},Poe=async(n,t)=>{let{creds:o}=n,{update:i,preKeys:e}=await AU(n,t),a={tag:"iq",attrs:{xmlns:"encrypt",type:"set",to:OA},content:[{tag:"registration",attrs:{},content:kg(o.registrationId)},{tag:"type",attrs:{},content:Rg},{tag:"identity",attrs:{},content:o.signedIdentityKey.public},{tag:"list",attrs:{},content:Object.keys(e).map(A=>eU(e[+A],+A))},yf(o.signedPreKey)]};return{update:i,node:a}};var E4e=n=>({appVersion:{primary:n.version[0],secondary:n.version[1],tertiary:n.version[2]},platform:n.browser[1].toLocaleLowerCase().includes("android")?oe.ClientPayload.UserAgent.Platform.ANDROID:oe.ClientPayload.UserAgent.Platform.WEB,releaseChannel:oe.ClientPayload.UserAgent.ReleaseChannel.RELEASE,osVersion:"0.1",device:"Desktop",osBuildNumber:"0.1",localeLanguageIso6391:"en",mnc:"000",mcc:"000",localeCountryIso31661Alpha2:n.countryCode}),Goe={"Mac OS":oe.ClientPayload.WebInfo.WebSubPlatform.DARWIN,Windows:oe.ClientPayload.WebInfo.WebSubPlatform.WIN32},C4e=n=>{let t=oe.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;return n.syncFullHistory&&Goe[n.browser[0]]&&n.browser[1]==="Desktop"&&(t=Goe[n.browser[0]]),{webSubPlatform:t}},Foe=n=>{let t={connectType:oe.ClientPayload.ConnectType.WIFI_UNKNOWN,connectReason:oe.ClientPayload.ConnectReason.USER_ACTIVATED,userAgent:E4e(n)};return n.browser[1].toLocaleLowerCase().includes("android")||(t.webInfo=C4e(n)),n.pushName&&(t.pushName=n.pushName),t},Loe=(n,t)=>{let{user:o,device:i}=yA(n),e={...Foe(t),passive:!0,pull:!0,username:+o,device:i,lidDbMigrated:!1};return oe.ClientPayload.fromObject(e)},u4e=n=>{let t=n.toUpperCase();return t==="ANDROID"?oe.DeviceProps.PlatformType.ANDROID_PHONE:oe.DeviceProps.PlatformType[t]||oe.DeviceProps.PlatformType.CHROME},Uoe=({registrationId:n,signedPreKey:t,signedIdentityKey:o},i)=>{let e=h4e("md5").update(i.version.join(".")).digest(),a={os:i.browser[0],platformType:u4e(i.browser[1]),requireFullSync:i.syncFullHistory,historySyncConfig:{storageQuotaMb:10240,inlineInitialPayloadInE2EeMsg:!0,recentSyncDaysLimit:void 0,supportCallLogHistory:!1,supportBotUserAgentChatHistory:!0,supportCagReactionsAndPolls:!0,supportBizHostedMsg:!0,supportRecentSyncChunkMessageCountTuning:!0,supportHostedGroupMsg:!0,supportFbidBotChatHistory:!0,supportAddOnHistorySyncMigration:void 0,supportMessageAssociation:!0,supportGroupHistory:!1,onDemandReady:void 0,supportGuestChat:void 0},version:{primary:10,secondary:15,tertiary:7}},A=oe.DeviceProps.encode(a).finish(),r={...Foe(i),passive:!1,pull:!1,devicePairingData:{buildHash:e,deviceProps:A,eRegid:kg(n),eKeytype:Rg,eIdent:o.public,eSkeyId:kg(t.keyId,3),eSkeyVal:t.keyPair.public,eSkeySig:t.signature}};return oe.ClientPayload.fromObject(r)},Hoe=(n,{advSecretKey:t,signedIdentityKey:o,signalIdentities:i})=>{let e=n.attrs.id,a=le(n,"pair-success"),A=le(a,"device-identity"),r=le(a,"platform"),s=le(a,"device"),g=le(a,"biz");if(!A||!s)throw new db.Boom("Missing device-identity or device in pair success node",{data:n});let c=g?.attrs.name,I=s.attrs.jid,d=s.attrs.lid,{details:B,hmac:f,accountType:Q}=oe.ADVSignedDeviceIdentityHMAC.decode(A.content),y=Buffer.from([]);Q!==void 0&&Q===oe.ADVEncryptionType.HOSTED&&(y=tU);let m=kn(Buffer.concat([y,B]),Buffer.from(t,"base64"));if(Buffer.compare(f,m)!==0)throw new db.Boom("Invalid account signature");let _=oe.ADVSignedDeviceIdentity.decode(B),{accountSignatureKey:T,accountSignature:R,details:L}=_,U=oe.ADVDeviceIdentity.decode(L),F=U.deviceType===oe.ADVEncryptionType.HOSTED?tU:Koe,q=Buffer.concat([F,L,o.public]);if(!Br.verify(T,q,R))throw new db.Boom("Failed to verify account signature");let z=Buffer.concat([xoe,L,o.public,T]);_.deviceSignature=Br.sign(o.private,z);let j=Noe(d,T),P=mf(_,!1),J={tag:"iq",attrs:{to:OA,type:"result",id:e},content:[{tag:"pair-device-sign",attrs:{},content:[{tag:"device-identity",attrs:{"key-index":U.keyIndex.toString()},content:P}]}]};return{creds:{account:_,me:{id:I,name:c,lid:d},signalIdentities:[...i||[],j],platform:r?.attrs.name},reply:J}},mf=(n,t)=>(n={...n},(!t||!n.accountSignatureKey?.length)&&(n.accountSignatureKey=null),oe.ADVSignedDeviceIdentity.encode(n).finish());var AE=Je(Lr(),1);var Joe=12,Yoe=Buffer.alloc(0),joe=n=>{let t=new ArrayBuffer(Joe);return new DataView(t).setUint32(8,n),new Uint8Array(t)},rU=class{constructor(t,o){this.encKey=t,this.decKey=o,this.readCounter=0,this.writeCounter=0,this.iv=new Uint8Array(Joe)}encrypt(t){let o=this.writeCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,Dl(t,this.encKey,this.iv,Yoe)}decrypt(t){let o=this.readCounter++;return this.iv[8]=o>>>24&255,this.iv[9]=o>>>16&255,this.iv[10]=o>>>8&255,this.iv[11]=o&255,Ol(t,this.decKey,this.iv,Yoe)}},qoe=({keyPair:{private:n,public:t},NOISE_HEADER:o,logger:i,routingInfo:e})=>{i=i.child({class:"ns"});let a=Buffer.from(zoe),A=a.byteLength===32?a:sh(a),r=A,s=A,g=A,c=0,I=!1,d=Buffer.alloc(0),B=null,f=!1,Q=null,y;e?(y=Buffer.alloc(7+e.byteLength+o.length),y.write("ED",0,"utf8"),y.writeUint8(0,2),y.writeUint8(1,3),y.writeUint8(e.byteLength>>16,4),y.writeUint16BE(e.byteLength&65535,5),y.set(e,7),y.set(o,7+e.byteLength)):y=Buffer.from(o);let m=q=>{B||(A=sh(Buffer.concat([A,q])))},_=q=>{if(B)return B.encrypt(q);let z=Dl(q,s,joe(c++),A);return m(z),z},T=q=>{if(B)return B.decrypt(q);let z=Ol(q,g,joe(c++),A);return m(q),z},R=q=>{let z=Rn(Buffer.from(q),64,{salt:r,info:""});return[z.subarray(0,32),z.subarray(32)]},L=q=>{let[z,j]=R(q);r=z,s=j,g=j,c=0},U=async()=>{f=!0;let[q,z]=R(new Uint8Array(0));B=new rU(q,z),f=!1,i.trace("Noise handler transitioned to Transport state"),Q&&(i.trace({length:d.length},"Flushing buffered frames after transport ready"),await F(Q),Q=null)},F=async q=>{let z;for(;;){if(d.length<3||(z=d[0]<<16|d[1]<<8|d[2],d.length{m(q.ephemeral),L(Br.sharedKey(n,q.ephemeral));let j=T(q.static);L(Br.sharedKey(n,j));let P=T(q.payload),{intermediate:J,leaf:H}=oe.CertChain.decode(P);if(!H?.details||!H?.signature)throw new AE.Boom("invalid noise leaf certificate",{statusCode:400});if(!J?.details||!J?.signature)throw new AE.Boom("invalid noise intermediate certificate",{statusCode:400});let N=oe.CertChain.NoiseCertificate.Details.decode(J.details),{issuerSerial:k}=N,V=Br.verify(N.key,H.details,H.signature),Ae=Br.verify(aU.PUBLIC_KEY,J.details,J.signature);if(!V)throw new AE.Boom("noise certificate signature invalid",{statusCode:400});if(!Ae)throw new AE.Boom("noise intermediate certificate signature invalid",{statusCode:400});if(k!==aU.SERIAL)throw new AE.Boom("certification match failed",{statusCode:400});let ie=_(z.public);return L(Br.sharedKey(z.private,q.ephemeral)),ie},encodeFrame:q=>{B&&(q=B.encrypt(q));let z=q.byteLength,j=I?0:y.length,P=Buffer.allocUnsafe(j+3+z);return I||(P.set(y),I=!0),P[j]=z>>>16&255,P[j+1]=z>>>8&255,P[j+2]=z&255,P.set(q,j+3),P},decodeFrame:async(q,z)=>{if(f){d=Buffer.concat([d,q]),Q=z;return}d.length===0?d=Buffer.from(q):d=Buffer.concat([d,q]),await F(z)}}};import{pipeline as B4e}from"stream/promises";import{promisify as f4e}from"util";import{createInflate as Q4e,inflate as y4e}from"zlib";var m4e=f4e(y4e),S4e=n=>{for(let t of n){let o=t.message;if(!o?.key?.fromMe||!o.userReceipt?.length)continue;let i=o.userReceipt[0]?.userJid;if(i&&(_t(i)||ur(i)))return i}},w4e=async(n,t)=>{let o=await eE(n,"md-msg-hist",{options:t}),i=Q4e(),e=[];i.on("data",r=>e.push(r)),await B4e(o,i);let a=Buffer.concat(e);return oe.HistorySync.decode(a)},D4e=(n,t)=>{let o=[],i=[],e=[],a=[];t?.trace({progress:n.progress},"processing history of type "+n.syncType?.toString());for(let A of n.phoneNumberToLidMappings||[])A.lidJid&&A.pnJid&&a.push({lid:A.lidJid,pn:A.pnJid});switch(n.syncType){case oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:case oe.HistorySync.HistorySyncType.RECENT:case oe.HistorySync.HistorySyncType.FULL:case oe.HistorySync.HistorySyncType.ON_DEMAND:for(let A of n.conversations){i.push({id:A.id,name:A.displayName||A.name||A.username||void 0,username:A.username||void 0,lid:A.lidJid||A.accountLid||void 0,phoneNumber:A.pnJid||void 0});let r=A.id,s=qA(r)||ga(r),g=_t(r)||ur(r);if(s&&A.pnJid)a.push({lid:r,pn:A.pnJid});else if(g&&A.lidJid)a.push({lid:A.lidJid,pn:r});else if(s&&!A.pnJid){let I=S4e(A.messages||[]);I&&a.push({lid:r,pn:I})}let c=A.messages||[];delete A.messages;for(let I of c){let d=I.message;o.push(d),A.messages?.length||(A.messages=[{message:d}]),!d.key.fromMe&&!A.lastMessageRecvTimestamp&&(A.lastMessageRecvTimestamp=Hr(d.messageTimestamp)),(d.messageStubType===TA.BIZ_PRIVACY_MODE_TO_BSP||d.messageStubType===TA.BIZ_PRIVACY_MODE_TO_FB)&&d.messageStubParameters?.[0]&&i.push({id:d.key.participant||d.key.remoteJid,verifiedName:d.messageStubParameters?.[0]})}e.push(A)}break;case oe.HistorySync.HistorySyncType.PUSH_NAME:for(let A of n.pushnames)i.push({id:A.id,notify:A.pushname});break}return{chats:e,contacts:i,messages:o,lidPnMappings:a,pastParticipants:n.pastParticipants,syncType:n.syncType,progress:n.progress}},Voe=async(n,t,o)=>{let i;return n.initialHistBootstrapInlinePayload?i=oe.HistorySync.decode(await m4e(n.initialHistBootstrapInlinePayload)):i=await w4e(n,t),D4e(i,o)},hb=n=>(n?Oa(n):void 0)?.protocolMessage?.historySyncNotification;var en=Je(Lr(),1);var Ys;(function(n){n.Chat="label_jid",n.Message="label_message"})(Ys||(Ys={}));var Woe=new ih;var Zoe=(n,t,o)=>{let i=[];if(!t)return o?.warn({hasFullName:!!n.fullName,hasLidJid:!!n.lidJid,hasPnJid:!!n.pnJid},"contactAction sync: missing id in index"),i;let e=n.lidJid,a=_t(t),A=a?t:n.pnJid||void 0;return i.push({event:"contacts.upsert",data:[{id:t,name:n.fullName||n.firstName||n.username||void 0,username:n.username||void 0,lid:e||void 0,phoneNumber:A}]}),e&&qA(e)&&a&&i.push({event:"lid-mapping.update",data:{lid:e,pn:t}}),i},Xoe=(n,t)=>{for(let o of t)o.event==="contacts.upsert"?n.emit("contacts.upsert",o.data):n.emit("lid-mapping.update",o.data)};var Sf=n=>{let t=n7(n);return{indexKey:t.indexKey,valueEncryptionKey:t.valueEncryptionKey,valueMacKey:t.valueMacKey,snapshotMacKey:t.snapshotMacKey,patchMacKey:t.patchMacKey}},$oe=(n,t,o,i)=>{let e=n===oe.SyncdMutation.SyncdOperation.SET?1:2,a=typeof o=="string"?Buffer.from(o,"base64"):o,A=new Uint8Array(1+a.length);A[0]=e,A.set(a,1);let r=new Uint8Array(8);r[7]=A.length;let s=new Uint8Array(A.length+t.length+r.length);return s.set(A,0),s.set(t,A.length),s.set(r,A.length+t.length),kn(s,i,"sha512").subarray(0,32)},ene=n=>{let t=Buffer.alloc(8);return t.writeUint32BE(n,4),t},Ane=({indexValueMap:n,hash:t})=>{n={...n};let o=[],i=[];return{mix:({indexMac:e,valueMac:a,operation:A})=>{let r=Buffer.from(e).toString("base64"),s=n[r];if(A===oe.SyncdMutation.SyncdOperation.REMOVE){if(!s)return;delete n[r]}else o.push(a),n[r]={valueMac:a};s&&i.push(s.valueMac)},finish:()=>{let e=Woe.subtractThenAdd(t,i,o);return{hash:Buffer.from(e),indexValueMap:n}}}},iU=(n,t,o,i)=>{let e=Buffer.concat([n,ene(t),Buffer.from(o,"utf-8")]);return kn(e,i,"sha256")},tne=(n,t,o,i,e)=>{let a=Buffer.concat([n,...t,ene(o),Buffer.from(i,"utf-8")]);return kn(a,e)},Eb=()=>({version:0,hash:Buffer.alloc(128),indexValueMap:{}}),oU=n=>((typeof n.version!="number"||isNaN(n.version))&&(n.version=0),n),nU=2,wf=n=>n?.data?.isMissingKey===!0,rne=(n,t)=>t>=nU||n?.name==="TypeError",ane=async({type:n,index:t,syncAction:o,apiVersion:i,operation:e},a,A,r)=>{let s=a?await r(a):void 0;if(!s)throw new en.Boom(`myAppStateKey ("${a}") not present`,{data:{isMissingKey:!0}});let g=Buffer.from(a,"base64");A={...A,indexValueMap:{...A.indexValueMap}};let c=Buffer.from(JSON.stringify(t)),I=oe.SyncActionData.fromObject({index:c,value:o,padding:new Uint8Array(0),version:i}),d=oe.SyncActionData.encode(I).finish(),B=Sf(s.keyData),f=h7(d,B.valueEncryptionKey),Q=$oe(e,f,g,B.valueMacKey),y=kn(c,B.indexKey),m=Ane(A);m.mix({indexMac:y,valueMac:Q,operation:e}),Object.assign(A,m.finish()),A.version+=1;let _=iU(A.hash,A.version,n,B.snapshotMacKey),T={patchMac:tne(_,[Q],A.version,n,B.patchMacKey),snapshotMac:_,keyId:{id:g},mutations:[{operation:e,record:{index:{blob:y},value:{blob:Buffer.concat([f,Q])},keyId:{id:g}}}]},R=y.toString("base64");return A.indexValueMap[R]={valueMac:Q},{patch:T,state:A}},ine=async(n,t,o,i,e)=>{let a=Ane(t),A=new Map;for(let s of n){let g="operation"in s?s.operation:oe.SyncdMutation.SyncdOperation.SET,c="record"in s&&s.record?s.record:s,I;try{I=await r(c.keyId.id)}catch(_){if(wf(_))throw _;continue}let d=c.value.blob,B=d.subarray(0,-32),f=d.subarray(-32);if(e){let _=$oe(g,B,c.keyId.id,I.valueMacKey);if(Buffer.compare(_,f)!==0)continue}let Q;try{Q=d7(B,I.valueEncryptionKey)}catch{continue}let y=oe.SyncActionData.decode(Q);if(e){let _=kn(y.index,I.indexKey);if(Buffer.compare(_,c.index.blob)!==0)throw new en.Boom("HMAC index verification failed")}let m=Buffer.from(y.index).toString();i({syncAction:y,index:JSON.parse(m)}),a.mix({indexMac:c.index.blob,valueMac:f,operation:g})}return a.finish();async function r(s){let g=Buffer.from(s).toString("base64"),c=A.get(g);if(c)return c;let I=await o(g);if(!I)throw new en.Boom(`failed to find key "${g}" to decode mutation`,{data:{isMissingKey:!0,msgMutations:n}});let d=Sf(I.keyData);return A.set(g,d),d}},O4e=async(n,t,o,i,e,a)=>{if(a){let r=Buffer.from(n.keyId.id).toString("base64"),s=await i(r);if(!s)throw new en.Boom(`failed to find key "${r}" to decode patch`,{data:{isMissingKey:!0,msg:n}});let g=Sf(s.keyData),c=n.mutations.map(d=>d.record.value.blob.slice(-32)),I=tne(n.snapshotMac,c,Hr(n.version.version),t,g.patchMacKey);if(Buffer.compare(I,n.patchMac)!==0)throw new en.Boom("Invalid patch mac")}return await ine(n.mutations,o,i,e,a)},one=async(n,t)=>{let o=le(n,"sync"),i=kA(o,"collection"),e={};return await Promise.all(i.map(async a=>{let A=le(a,"patches"),r=kA(A||a,"patch"),s=le(a,"snapshot"),g=[],c=a.attrs.name,I=a.attrs.has_more_patches==="true",d;if(s&&s.content){Buffer.isBuffer(s)||(s.content=Buffer.from(Object.values(s.content)));let B=oe.ExternalBlobReference.decode(s.content),f=await nne(B,t);d=oe.SyncdSnapshot.decode(f)}for(let{content:B}of r)if(B){Buffer.isBuffer(B)||(B=Buffer.from(Object.values(B)));let f=oe.SyncdPatch.decode(B);f.version||(f.version={version:+a.attrs.version+1}),g.push(f)}e[c]={patches:g,hasMorePatches:I,snapshot:d}})),e},nne=async(n,t)=>{let o=await eE(n,"md-app-state",{options:t}),i=[];for await(let e of o)i.push(e);return Buffer.concat(i)},b4e=async(n,t)=>{let o=await nne(n,t);return oe.SyncdMutations.decode(o)},sne=async(n,t,o,i,e=!0,a)=>{let A=Eb();A.version=Hr(t.version.version);let r={},s=typeof i>"u"||A.version>i,{hash:g,indexValueMap:c}=await ine(t.records,A,o,s?I=>{let d=I.syncAction.index?.toString();r[d]=I}:()=>{},e);if(A.hash=g,A.indexValueMap=c,e){let I=Buffer.from(t.keyId.id).toString("base64"),d=await o(I);if(!d)throw new en.Boom(`failed to find key "${I}" to decode mutation`,{data:{isMissingKey:!0}});let B=Sf(d.keyData),f=iU(A.hash,A.version,n,B.snapshotMacKey);Buffer.compare(t.mac,f)!==0&&a?.warn({name:n,version:A.version},"LTHash verification failed on snapshot, continuing with partial state")}return{state:A,mutationMap:r}},sU=async(n,t,o,i,e,a,A,r=!0)=>{let s={...o,indexValueMap:{...o.indexValueMap}},g={};for(let c of t){let{version:I,keyId:d,snapshotMac:B}=c;if(c.externalMutations){A?.trace({name:n,version:I},"downloading external patch");let m=await b4e(c.externalMutations,e);A?.debug({name:n,version:I,mutations:m.mutations.length},"downloaded external patch"),c.mutations?.push(...m.mutations)}let f=Hr(I.version);s.version=f;let Q=typeof a>"u"||f>a,y;try{y=await O4e(c,n,s,i,Q?m=>{let _=m.syncAction.index?.toString();g[_]=m}:()=>{},r)}catch(m){if(wf(m))throw m;A?.warn({name:n,version:f,error:m.message},"failed to decode patch, skipping");continue}if(s.hash=y.hash,s.indexValueMap=y.indexValueMap,r){let m=Buffer.from(d.id).toString("base64"),_=await i(m);if(!_)throw new en.Boom(`failed to find key "${m}" to decode mutation`,{data:{isMissingKey:!0}});let T=Sf(_.keyData),R=iU(s.hash,s.version,n,T.snapshotMacKey);if(Buffer.compare(B,R)!==0){A?.warn({name:n,version:s.version},"LTHash verification failed, skipping remaining patches");break}}c.mutations=[]}return{state:s,mutationMap:g}},gne=(n,t)=>{let o=oe.SyncdMutation.SyncdOperation,i=a=>{let A;return Array.isArray(a)?A={lastMessageTimestamp:a[a.length-1]?.messageTimestamp,messages:a?.length?a.map(s=>{if(!s.key?.id||!s.key?.remoteJid)throw new en.Boom("Incomplete key",{statusCode:400,data:s});if(Ur(s.key.remoteJid)&&!s.key.fromMe&&!s.key.participant)throw new en.Boom("Expected not from me message to have participant",{statusCode:400,data:s});if(!s.messageTimestamp||!Hr(s.messageTimestamp))throw new en.Boom("Missing timestamp in last message list",{statusCode:400,data:s});return s.key.participant&&(s.key.participant=uA(s.key.participant)),s}):void 0}:A=a,A},e;if("mute"in n)e={syncAction:{muteAction:{muted:!!n.mute,muteEndTimestamp:n.mute||void 0}},index:["mute",t],type:"regular_high",apiVersion:2,operation:o.SET};else if("archive"in n)e={syncAction:{archiveChatAction:{archived:!!n.archive,messageRange:i(n.lastMessages)}},index:["archive",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("markRead"in n)e={syncAction:{markChatAsReadAction:{read:n.markRead,messageRange:i(n.lastMessages)}},index:["markChatAsRead",t],type:"regular_low",apiVersion:3,operation:o.SET};else if("deleteForMe"in n){let{timestamp:a,key:A,deleteMedia:r}=n.deleteForMe;e={syncAction:{deleteMessageForMeAction:{deleteMedia:r,messageTimestamp:a}},index:["deleteMessageForMe",t,A.id,A.fromMe?"1":"0","0"],type:"regular_high",apiVersion:3,operation:o.SET}}else if("clear"in n)e={syncAction:{clearChatAction:{messageRange:i(n.lastMessages)}},index:["clearChat",t,"1","0"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pin"in n)e={syncAction:{pinAction:{pinned:!!n.pin}},index:["pin_v1",t],type:"regular_low",apiVersion:5,operation:o.SET};else if("contact"in n)e={syncAction:{contactAction:n.contact||{}},index:["contact",t],type:"critical_unblock_low",apiVersion:2,operation:n.contact?o.SET:o.REMOVE};else if("disableLinkPreviews"in n)e={syncAction:{privacySettingDisableLinkPreviewsAction:n.disableLinkPreviews||{}},index:["setting_disableLinkPreviews"],type:"regular",apiVersion:8,operation:o.SET};else if("star"in n){let a=n.star.messages[0];e={syncAction:{starAction:{starred:!!n.star.star}},index:["star",t,a.id,a.fromMe?"1":"0","0"],type:"regular_low",apiVersion:2,operation:o.SET}}else if("delete"in n)e={syncAction:{deleteChatAction:{messageRange:i(n.lastMessages)}},index:["deleteChat",t,"1"],type:"regular_high",apiVersion:6,operation:o.SET};else if("pushNameSetting"in n)e={syncAction:{pushNameSetting:{name:n.pushNameSetting}},index:["setting_pushName"],type:"critical_block",apiVersion:1,operation:o.SET};else if("quickReply"in n)e={syncAction:{quickReplyAction:{count:0,deleted:n.quickReply.deleted||!1,keywords:[],message:n.quickReply.message||"",shortcut:n.quickReply.shortcut||""}},index:["quick_reply",n.quickReply.timestamp||String(Math.floor(Date.now()/1e3))],type:"regular",apiVersion:2,operation:o.SET};else if("addLabel"in n)e={syncAction:{labelEditAction:{name:n.addLabel.name,color:n.addLabel.color,predefinedId:n.addLabel.predefinedId,deleted:n.addLabel.deleted}},index:["label_edit",n.addLabel.id],type:"regular",apiVersion:3,operation:o.SET};else if("addChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[Ys.Chat,n.addChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("removeChatLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Ys.Chat,n.removeChatLabel.labelId,t],type:"regular",apiVersion:3,operation:o.SET};else if("addMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!0}},index:[Ys.Message,n.addMessageLabel.labelId,t,n.addMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else if("removeMessageLabel"in n)e={syncAction:{labelAssociationAction:{labeled:!1}},index:[Ys.Message,n.removeMessageLabel.labelId,t,n.removeMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:o.SET};else throw new en.Boom("not supported");return e.syncAction.timestamp=Date.now(),e},cne=(n,t,o,i,e)=>{let a=!!i,A=i?.accountSettings;e?.trace({syncAction:n,initialSync:!!i},"processing sync action");let{syncAction:{value:r},index:[s,g,c,I]}=n;if(r?.muteAction)t.emit("chats.update",[{id:g,muteEndTime:r.muteAction?.muted?Hr(r.muteAction.muteEndTimestamp):null,conditional:d(g,void 0)}]);else if(r?.archiveChatAction||s==="archive"||s==="unarchive"){let f=r?.archiveChatAction,Q=f?f.archived:s==="archive",y=A?.unarchiveChats?f?.messageRange:void 0;t.emit("chats.update",[{id:g,archived:Q,conditional:d(g,y)}])}else if(r?.markChatAsReadAction){let f=r.markChatAsReadAction,Q=a&&f.read;t.emit("chats.update",[{id:g,unreadCount:Q?null:f?.read?0:-1,conditional:d(g,f?.messageRange)}])}else if(r?.deleteMessageForMeAction||s==="deleteMessageForMe")t.emit("messages.delete",{keys:[{remoteJid:g,id:c,fromMe:I==="1"}]});else if(r?.contactAction){let f=Zoe(r.contactAction,g,e);Xoe(t,f)}else if(r?.pushNameSetting){let f=r?.pushNameSetting?.name;f&&o?.name!==f&&t.emit("creds.update",{me:{...o,name:f}})}else if(r?.pinAction)t.emit("chats.update",[{id:g,pinned:r.pinAction?.pinned?Hr(r.timestamp):null,conditional:d(g,void 0)}]);else if(r?.unarchiveChatsSetting){let f=!!r.unarchiveChatsSetting.unarchiveChats;t.emit("creds.update",{accountSettings:{unarchiveChats:f}}),e?.info(`archive setting updated => '${r.unarchiveChatsSetting.unarchiveChats}'`),A&&(A.unarchiveChats=f)}else if(r?.starAction||s==="star"){let f=r?.starAction?.starred;typeof f!="boolean"&&(f=n.index[n.index.length-1]==="1"),t.emit("messages.update",[{key:{remoteJid:g,id:c,fromMe:I==="1"},update:{starred:f}}])}else if(r?.deleteChatAction||s==="deleteChat")a||t.emit("chats.delete",[g]);else if(r?.labelEditAction){let{name:f,color:Q,deleted:y,predefinedId:m}=r.labelEditAction;t.emit("labels.edit",{id:g,name:f,color:Q,deleted:y,predefinedId:m?String(m):void 0})}else r?.labelAssociationAction?t.emit("labels.association",{type:r.labelAssociationAction.labeled?"add":"remove",association:s===Ys.Chat?{type:Ys.Chat,chatId:n.index[2],labelId:n.index[1]}:{type:Ys.Message,chatId:n.index[2],messageId:n.index[3],labelId:n.index[1]}}):r?.localeSetting?.locale?t.emit("settings.update",{setting:"locale",value:r.localeSetting.locale}):r?.timeFormatAction?t.emit("settings.update",{setting:"timeFormat",value:r.timeFormatAction}):r?.pnForLidChatAction?r.pnForLidChatAction.pnJid&&t.emit("lid-mapping.update",{lid:g,pn:r.pnForLidChatAction.pnJid}):r?.privacySettingRelayAllCalls?t.emit("settings.update",{setting:"privacySettingRelayAllCalls",value:r.privacySettingRelayAllCalls}):r?.statusPrivacy?t.emit("settings.update",{setting:"statusPrivacy",value:r.statusPrivacy}):r?.lockChatAction?t.emit("chats.lock",{id:g,locked:!!r.lockChatAction.locked}):r?.privacySettingDisableLinkPreviewsAction?t.emit("settings.update",{setting:"disableLinkPreviews",value:r.privacySettingDisableLinkPreviewsAction}):r?.notificationActivitySettingAction?.notificationActivitySetting?t.emit("settings.update",{setting:"notificationActivitySetting",value:r.notificationActivitySettingAction.notificationActivitySetting}):r?.lidContactAction?t.emit("contacts.upsert",[{id:g,name:r.lidContactAction.fullName||r.lidContactAction.firstName||r.lidContactAction.username||void 0,username:r.lidContactAction.username||void 0,lid:g,phoneNumber:void 0}]):r?.privacySettingChannelsPersonalisedRecommendationAction?t.emit("settings.update",{setting:"channelsPersonalisedRecommendation",value:r.privacySettingChannelsPersonalisedRecommendationAction}):e?.debug({syncAction:n,id:g},"unprocessable update");function d(f,Q){return a?y=>{let m=y.historySets.chats[f]||y.chatUpserts[f];if(m)return Q?B(m,Q):!0}:void 0}function B(f,Q){let y=Number(Q?.lastMessageTimestamp||Q?.lastSystemMessageTimestamp||0),m=Number(f?.lastMessageRecvTimestamp||0);return y>=m}};var M4e=class{_eventListeners;_maxListeners;_logger;_throwOnEmitError=!1;_throwOnEmptyListeners=!1;_errorEvent="error";constructor(n){this._eventListeners=new Map,this._maxListeners=100,this._logger=n?.logger,n?.throwOnEmitError!==void 0&&(this._throwOnEmitError=n.throwOnEmitError),n?.throwOnEmptyListeners!==void 0&&(this._throwOnEmptyListeners=n.throwOnEmptyListeners)}get logger(){return this._logger}set logger(n){this._logger=n}get throwOnEmitError(){return this._throwOnEmitError}set throwOnEmitError(n){this._throwOnEmitError=n}get throwOnEmptyListeners(){return this._throwOnEmptyListeners}set throwOnEmptyListeners(n){this._throwOnEmptyListeners=n}once(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.on(n,o),this}listenerCount(n){if(n===void 0)return this.getAllListeners().length;let t=this._eventListeners.get(n);return t?t.length:0}eventNames(){return[...this._eventListeners.keys()]}rawListeners(n){return n===void 0?this.getAllListeners():this._eventListeners.get(n)??[]}prependListener(n,t){let o=this._eventListeners.get(n)??[];return o.unshift(t),this._eventListeners.set(n,o),this}prependOnceListener(n,t){let o=(...i)=>{this.off(n,o),t(...i)};return this.prependListener(n,o),this}maxListeners(){return this._maxListeners}addListener(n,t){return this.on(n,t),this}on(n,t){this._eventListeners.has(n)||this._eventListeners.set(n,[]);let o=this._eventListeners.get(n);return o&&(o.length>=this._maxListeners&&console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${o.length+1} ${n} listeners added. Use setMaxListeners() to increase limit.`),o.push(t)),this}removeListener(n,t){return this.off(n,t),this}off(n,t){let o=this._eventListeners.get(n)??[],i=o.indexOf(t);return i!==-1&&o.splice(i,1),o.length===0&&this._eventListeners.delete(n),this}emit(n,...t){let o=!1,i=this._eventListeners.get(n);if(i&&i.length>0)for(let e of i)e(...t),o=!0;if(n===this._errorEvent){let e=t[0]instanceof Error?t[0]:new Error(`${t[0]}`);if(this._throwOnEmitError&&!o)throw e;if(this.listeners(this._errorEvent).length===0&&this._throwOnEmptyListeners===!0)throw e}return this.sendLog(n,t),o}listeners(n){return this._eventListeners.get(n)??[]}removeAllListeners(n){return n!==void 0?this._eventListeners.delete(n):this._eventListeners.clear(),this}setMaxListeners(n){this._maxListeners=n;for(let t of this._eventListeners.values())t.length>n&&t.splice(n)}getAllListeners(){let n=[];for(let t of this._eventListeners.values())n=[...n,...t];return n}sendLog(n,t){if(!this._logger)return;let o;switch(typeof t=="string"?o=t:Array.isArray(t)&&t.length>0&&t[0]instanceof Error?o=t[0].message:t instanceof Error?o=t.message:Array.isArray(t)&&t.length>0&&typeof t[0]?.message=="string"?o=t[0].message:o=JSON.stringify(t),n){case"error":{this._logger.error?.(o,{event:n,data:t});break}case"warn":{this._logger.warn?.(o,{event:n,data:t});break}case"trace":{this._logger.trace?.(o,{event:n,data:t});break}case"debug":{this._logger.debug?.(o,{event:n,data:t});break}case"fatal":{this._logger.fatal?.(o,{event:n,data:t});break}default:{this._logger.info?.(o,{event:n,data:t});break}}}},lI=class extends M4e{_hooks;_throwOnHookError=!1;_enforceBeforeAfter=!1;_deprecatedHooks;_allowDeprecated=!0;constructor(n){super({logger:n?.logger,throwOnEmitError:n?.throwOnEmitError,throwOnEmptyListeners:n?.throwOnEmptyListeners}),this._hooks=new Map,this._deprecatedHooks=n?.deprecatedHooks?new Map(n.deprecatedHooks):new Map,n?.throwOnHookError!==void 0?this._throwOnHookError=n.throwOnHookError:n?.throwHookErrors!==void 0&&(this._throwOnHookError=n.throwHookErrors),n?.enforceBeforeAfter!==void 0&&(this._enforceBeforeAfter=n.enforceBeforeAfter),n?.allowDeprecated!==void 0&&(this._allowDeprecated=n.allowDeprecated)}get hooks(){return this._hooks}get throwHookErrors(){return this._throwOnHookError}set throwHookErrors(n){this._throwOnHookError=n}get throwOnHookError(){return this._throwOnHookError}set throwOnHookError(n){this._throwOnHookError=n}get enforceBeforeAfter(){return this._enforceBeforeAfter}set enforceBeforeAfter(n){this._enforceBeforeAfter=n}get deprecatedHooks(){return this._deprecatedHooks}set deprecatedHooks(n){this._deprecatedHooks=n}get allowDeprecated(){return this._allowDeprecated}set allowDeprecated(n){this._allowDeprecated=n}validateHookName(n){if(this._enforceBeforeAfter){let t=n.trim().toLocaleLowerCase();if(!t.startsWith("before")&&!t.startsWith("after"))throw new Error(`Hook event "${n}" must start with "before" or "after" when enforceBeforeAfter is enabled`)}}checkDeprecatedHook(n){if(this._deprecatedHooks.has(n)){let t=this._deprecatedHooks.get(n),o=`Hook "${n}" is deprecated${t?`: ${t}`:""}`;return this.emit("warn",{hook:n,message:o}),this._allowDeprecated}return!0}onHook(n,t){this.onHookEntry({event:n,handler:t})}onHookEntry(n){if(this.validateHookName(n.event),!this.checkDeprecatedHook(n.event))return;let t=this._hooks.get(n.event);t?t.push(n.handler):this._hooks.set(n.event,[n.handler])}addHook(n,t){this.onHookEntry({event:n,handler:t})}onHooks(n){for(let t of n)this.onHook(t.event,t.handler)}prependHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);o?o.unshift(t):this._hooks.set(n,[t])}prependOnceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.prependHook(n,o)}onceHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=async(...i)=>(this.removeHook(n,o),t(...i));this.onHook(n,o)}removeHook(n,t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){let i=o.indexOf(t);i!==-1&&o.splice(i,1)}}removeHooks(n){for(let t of n)this.removeHook(t.event,t.handler)}async hook(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o)for(let i of o)try{await i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}hookSync(n,...t){if(this.validateHookName(n),!this.checkDeprecatedHook(n))return;let o=this._hooks.get(n);if(o){for(let i of o)if(i.constructor.name!=="AsyncFunction")try{i(...t)}catch(e){let a=`${n}: ${e.message}`;if(this.emit("error",new Error(a)),this._throwOnHookError)throw new Error(a)}}}async beforeHook(n,...t){await this.hook(`before:${n}`,...t)}async afterHook(n,...t){await this.hook(`after:${n}`,...t)}async callHook(n,...t){await this.hook(n,...t)}getHooks(n){if(this.validateHookName(n),!!this.checkDeprecatedHook(n))return this._hooks.get(n)}clearHooks(){this._hooks.clear()}};var _4e=class{_enabled=!0;_maxSize=4e3;_store=new Map;_keys=[];constructor(n){n?.enabled!==void 0&&(this._enabled=n.enabled),n?.maxSize!==void 0&&(this._maxSize=n.maxSize)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get maxSize(){return this._maxSize}set maxSize(n){this._maxSize=n}get store(){return this._store}get size(){return this._store.size}get(n){return this._store.get(n)}set(n,t){if(this._enabled){if(this._store.has(n)){this._store.set(n,t);return}if(this._store.size>=this._maxSize){let o=this._keys.shift();o&&this._store.delete(o)}this._keys.push(n),this._store.set(n,t)}}has(n){return this._store.has(n)}clear(){this._store.clear(),this._keys=[]}},T4e=class{get name(){return"crc32"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let a=n;t=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}let o=3988292384,i=4294967295;for(let a=0;a>>1^o&-(i&1)}return i=(i^4294967295)>>>0,i.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},Cb=class{_algorithm="SHA-256";constructor(n){n?.algorithm&&(this._algorithm=n?.algorithm)}get name(){return this._algorithm}async toHash(n){let t=await crypto.subtle.digest(this._algorithm,n);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}},N4e=class{get name(){return"djb2"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let e=n;t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let o=5381;for(let e=0;e>>0;return o.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},R4e=class{get name(){return"fnv1"}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let A=n;t=new Uint8Array(A.buffer,A.byteOffset,A.byteLength)}let o=2166136261,i=16777619,e=o;for(let A=0;A>>0;return e.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}},k4e=class{_seed;constructor(n=0){this._seed=n>>>0}get name(){return"murmur"}get seed(){return this._seed}toHashSync(n){let t;if(n instanceof Uint8Array)t=n;else if(n instanceof ArrayBuffer)t=new Uint8Array(n);else if(n instanceof DataView)t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else{let c=n;t=new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let o=3432918353,i=461845907,e=t.length,a=Math.floor(e/4),A=this._seed;for(let c=0;c>>16,A=this._imul(A,2246822507),A^=A>>>13,A=this._imul(A,3266489909),A^=A>>>16,A=A>>>0,A.toString(16).padStart(8,"0")}async toHash(n){return this.toHashSync(n)}_imul(n,t){if(Math.imul)return Math.imul(n,t);let o=n>>>16&65535,i=n&65535,e=t>>>16&65535,a=t&65535;return i*a+(o*a+i*e<<16>>>0)|0}_rotl32(n,t){return n<>>32-t}},v4e=class{_providers=new Map;_getFuzzy=!0;constructor(n){n?.providers&&this.loadProviders(n?.providers),n?.getFuzzy!==void 0&&(this._getFuzzy=!!n?.getFuzzy)}loadProviders(n){for(let t of n)this._providers.set(t.name,t)}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return Array.from(this._providers.keys())}get(n,t){let o=t?.fuzzy??this._getFuzzy;n=n.trim();let i=this._providers.get(n);return i===void 0&&o===!0&&(n=n.toLowerCase(),i=this._providers.get(n)),i===void 0&&o===!0&&(n=n.replaceAll("-",""),i=this._providers.get(n)),i}add(n){this._providers.set(n.name,n)}remove(n){return this._providers.delete(n)}},gU=class extends lI{_parse=JSON.parse;_stringify=JSON.stringify;_providers=new v4e;_defaultAlgorithm="SHA-256";_defaultAlgorithmSync="djb2";_cache;constructor(n){super(n),n?.parse&&(this._parse=n.parse),n?.stringify&&(this._stringify=n.stringify),n?.defaultAlgorithm&&(this._defaultAlgorithm=n.defaultAlgorithm),n?.defaultAlgorithmSync&&(this._defaultAlgorithmSync=n.defaultAlgorithmSync),this._cache=new _4e(n?.cache),this.loadProviders(n?.providers,{includeBase:n?.includeBase??!0})}get parse(){return this._parse}set parse(n){this._parse=n}get stringify(){return this._stringify}set stringify(n){this._stringify=n}get providers(){return this._providers}set providers(n){this._providers=n}get names(){return this._providers.names}get defaultAlgorithm(){return this._defaultAlgorithm}set defaultAlgorithm(n){this._defaultAlgorithm=n}get defaultAlgorithmSync(){return this._defaultAlgorithmSync}set defaultAlgorithmSync(n){this._defaultAlgorithmSync=n}get cache(){return this._cache}async toHash(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithm,maxLength:t?.maxLength};await this.beforeHook("toHash",o);let i=this._stringify(o.data),e=`${o.algorithm}:${i}`;if(this._cache.enabled){let c=this._cache.get(e);if(c!==void 0){let I=c;t?.maxLength&&I.length>t.maxLength&&(I=I.substring(0,t.maxLength));let d={hash:I,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",d),d.hash}}let A=new TextEncoder().encode(i),r=this._providers.get(o.algorithm);r||(this.emit("warn",`Invalid algorithm '${o.algorithm}' not found. Falling back to default algorithm '${this._defaultAlgorithm}'.`),r=new Cb({algorithm:this._defaultAlgorithm}));let s=await r.toHash(A);this._cache.enabled&&this._cache.set(e,s),t?.maxLength&&s.length>t?.maxLength&&(s=s.substring(0,t.maxLength));let g={hash:s,data:o.data,algorithm:o.algorithm};return await this.afterHook("toHash",g),g.hash}async toNumber(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithm,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=await this.toHash(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}toHashSync(n,t){let o={data:n,algorithm:t?.algorithm??this._defaultAlgorithmSync,maxLength:t?.maxLength};this.hookSync("before:toHashSync",o);let i=o.algorithm,e=this._stringify(o.data),a=`${i}:${e}`;if(this._cache.enabled){let I=this._cache.get(a);if(I!==void 0){let d=I;t?.maxLength&&d.length>t.maxLength&&(d=d.substring(0,t.maxLength));let B={hash:d,data:o.data,algorithm:i};return this.hookSync("after:toHashSync",B),B.hash}}let r=new TextEncoder().encode(e),s=this._providers.get(i);if(!s&&(this.emit("warn",`Invalid algorithm '${i}' not found. Falling back to default algorithm '${this._defaultAlgorithmSync}'.`),s=this._providers.get(this._defaultAlgorithmSync),!s))throw new Error(`Hash provider '${this._defaultAlgorithmSync}' (default) not found`);if(!s.toHashSync)throw new Error(`Hash provider '${i}' does not support synchronous hashing. Use toHash() instead or choose a different algorithm (djb2, fnv1, murmur, crc32).`);let g=s.toHashSync(r);this._cache.enabled&&this._cache.set(a,g),t?.maxLength&&g.length>t?.maxLength&&(g=g.substring(0,t.maxLength));let c={hash:g,data:o.data,algorithm:o.algorithm};return this.hookSync("after:toHashSync",c),c.hash}toNumberSync(n,t={}){let{min:o=0,max:i=100,algorithm:e=this._defaultAlgorithmSync,hashLength:a=16}=t;if(o>i)throw new Error("min cannot be greater than max");let A=this.toHashSync(n,{algorithm:e,maxLength:a}),r=Number.parseInt(A,16),s=i-o+1;return o+r%s}loadProviders(n,t={includeBase:!0}){if(n)for(let o of n)this._providers.add(o);t.includeBase&&(this.providers.add(new Cb({algorithm:"SHA-256"})),this.providers.add(new Cb({algorithm:"SHA-384"})),this.providers.add(new Cb({algorithm:"SHA-512"})),this.providers.add(new T4e),this.providers.add(new N4e),this.providers.add(new R4e),this.providers.add(new k4e))}};var lU=n=>{let t;if(n!==void 0){if(typeof n=="number")t=n;else{if(typeof n!="string")return;if(n=n.trim(),Number.isNaN(Number(n))){let o=/^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(n);if(!o)throw new Error(`Unsupported time format: "${n}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);let[,i,e]=o,a=Number.parseFloat(i);switch(e.toLowerCase()){case"ms":t=a;break;case"s":t=a*1e3;break;case"m":t=a*1e3*60;break;case"h":t=a*1e3*60*60;break;case"hr":t=a*1e3*60*60;break;case"d":t=a*1e3*60*60*24;break;default:t=Number(n)}}else t=Number(n)}return t}},$l=(n,t)=>{t??=new Date;let o=lU(n);return o===void 0?t.getTime():t.getTime()+o};var Df=(function(n){return n.SHA256="SHA-256",n.SHA384="SHA-384",n.SHA512="SHA-512",n.DJB2="djb2",n.FNV1="fnv1",n.MURMER="murmer",n.CRC32="crc32",n})({});function cU(n,t={algorithm:"djb2",serialize:JSON.stringify}){let o=t?.algorithm??"djb2",i=(t?.serialize??JSON.stringify)(n);return new gU().toHashSync(i,{algorithm:o})}function Ine(n,t={min:0,max:10,algorithm:"djb2",serialize:JSON.stringify}){let o=t?.min??0,i=t?.max??10,e=t?.algorithm??"djb2",a=t?.serialize??JSON.stringify,A=t?.hashLength??16;if(o>=i)throw new Error(`Invalid range: min (${o}) must be less than max (${i})`);let r=a(n);return new gU().toNumberSync(r,{algorithm:e,min:o,max:i,hashLength:A})}function pU(n,t){let{ttl:o,keyPrefix:i,cache:e,serialize:a}=t;return(...A)=>{let r=P4e(n,A,{keyPrefix:i,serialize:a});t.createKey&&(r=t.createKey(n,A,t));let s=e.get(r);if(s===void 0)try{s=n(...A),e.set(r,s,o)}catch(g){e.emit("error",g),t.cacheErrors&&e.set(r,g,o)}return s}}function dU(n,t,o){let i=typeof n=="function"?n(o):n,e;try{e=o.cache.get(i)}catch(a){if(o.cache.emit("error",a),o.throwErrors===!0||o.throwErrors==="store")throw a}if(e===void 0)try{try{e=t()}catch(a){throw new ub(a,"function")}try{o.cache.set(i,e,o.ttl)}catch(a){throw new ub(a,"store")}}catch(a){let A=a instanceof ub?a.context:void 0,r=a instanceof ub?a.error:a;if(o.cache.emit("error",r),o.cacheErrors&&A==="function")try{o.cache.set(i,r,o.ttl)}catch(s){o.cache.emit("error",s)}if(o.throwErrors===!0||o.throwErrors===A)throw r}return e}function P4e(n,t,o){let{keyPrefix:i,serialize:e}=o||{};return i?`${i}::${n.name}::${cU(t,{serialize:e})}`:`${n.name}::${cU(t,{serialize:e})}`}var ub=class{error;context;constructor(n,t){this.error=n,this.context=t}};var pI=class{_counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0};_vsize=0;_ksize=0;_enabled=!1;_lastUpdated;_lastReset;_subscriptions=[];_trackedKeys=new Map;_trackKeys=!1;_maxTrackedKeys;constructor(n){n?.enabled&&(this._enabled=n.enabled),n?.trackKeys&&(this._trackKeys=n.trackKeys),n?.maxTrackedKeys!==void 0&&(this._maxTrackedKeys=n.maxTrackedKeys),n?.emitter&&n?.eventMap&&this.subscribe(n.emitter,n.eventMap)}get enabled(){return this._enabled}set enabled(n){this._enabled=n}get trackKeys(){return this._trackKeys}set trackKeys(n){this._trackKeys=n}get maxTrackedKeys(){return this._maxTrackedKeys}set maxTrackedKeys(n){this._maxTrackedKeys=n}get trackedKeys(){return this._trackedKeys}get hits(){return this._counters.hits}get misses(){return this._counters.misses}get gets(){return this._counters.gets}get sets(){return this._counters.sets}get deletes(){return this._counters.deletes}get clears(){return this._counters.clears}get vsize(){return this._vsize}get ksize(){return this._ksize}get count(){return this._counters.count}get hitRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.hits/n}get missRate(){let n=this._counters.hits+this._counters.misses;return n===0?0:this._counters.misses/n}get lastUpdated(){return this._lastUpdated}get lastReset(){return this._lastReset}increment(n,t=1){this._enabled&&(this._counters[n]+=t,this.touch())}decrement(n,t=1){this._enabled&&(this._counters[n]-=t,this.touch())}incrementHits(n=1){this.increment("hits",n)}incrementMisses(n=1){this.increment("misses",n)}incrementGets(n=1){this.increment("gets",n)}incrementSets(n=1){this.increment("sets",n)}incrementDeletes(n=1){this.increment("deletes",n)}incrementClears(n=1){this.increment("clears",n)}incrementVSize(n){this._enabled&&(this._vsize+=this.roughSizeOfObject(n),this.touch())}decreaseVSize(n){this._enabled&&(this._vsize=Math.max(0,this._vsize-this.roughSizeOfObject(n)),this.touch())}incrementKSize(n){this._enabled&&(this._ksize+=this.roughSizeOfString(n),this.touch())}decreaseKSize(n){this._enabled&&(this._ksize=Math.max(0,this._ksize-this.roughSizeOfString(n)),this.touch())}incrementCount(n=1){this.increment("count",n)}decreaseCount(n=1){this._enabled&&(this._counters.count=Math.max(0,this._counters.count-n),this.touch())}setCount(n){this._enabled&&(this._counters.count=n,this.touch())}roughSizeOfString(n){return n.length*2}roughSizeOfObject(n){let t=[],o=[n],i=0;for(;o.length>0;){let e=o.pop();if(typeof e=="boolean")i+=4;else if(typeof e=="string")i+=e.length*2;else if(typeof e=="number")i+=8;else{if(e==null){i+=4;continue}if(t.includes(e))continue;t.push(e);for(let a in e)i+=a.length*2,o.push(e[a])}}return i}enable(){this._enabled=!0}disable(){this._enabled=!1}clear(){this.reset()}reset(){this._counters={hits:0,misses:0,gets:0,sets:0,deletes:0,clears:0,count:0},this._vsize=0,this._ksize=0,this._trackedKeys.clear(),this._lastReset=Date.now(),this._lastUpdated=void 0}resetStoreValues(){this._vsize=0,this._ksize=0,this._counters.count=0}toJSON(){return{enabled:this._enabled,hits:this._counters.hits,misses:this._counters.misses,gets:this._counters.gets,sets:this._counters.sets,deletes:this._counters.deletes,clears:this._counters.clears,vsize:this._vsize,ksize:this._ksize,count:this._counters.count,hitRate:this.hitRate,missRate:this.missRate,trackedKeys:this._trackedKeys.size,lastUpdated:this._lastUpdated,lastReset:this._lastReset}}snapshot(){return this.toJSON()}recordKey(n,t,o=1){if(!this._enabled||!this._trackKeys)return;let i=this._trackedKeys.get(n);i||(i={hits:0,misses:0,gets:0,sets:0,deletes:0},this._trackedKeys.set(n,i),this.pruneTrackedKeys(n)),i[t]+=o,this.touch()}mostUsedKeys(n=100,t){return this.sortedKeyEntries(t,"desc").slice(0,n)}leastUsedKeys(n=100,t){return this.sortedKeyEntries(t,"asc").slice(0,n)}keyStats(n){let t=this._trackedKeys.get(n);return t?this.toKeyEntry(n,t):void 0}clearKeys(){this._trackedKeys.clear()}totalOf(n){return n.hits+n.misses+n.gets+n.sets+n.deletes}toKeyEntry(n,t){let o=t.hits+t.misses;return{key:n,count:this.totalOf(t),hits:t.hits,misses:t.misses,gets:t.gets,sets:t.sets,deletes:t.deletes,hitRate:o===0?0:t.hits/o}}sortedKeyEntries(n,t){let o=[];for(let[e,a]of this._trackedKeys)o.push(this.toKeyEntry(e,a));let i=t==="asc"?1:-1;return o.sort((e,a)=>{let A=n?e[n]:e.count,r=n?a[n]:a.count;return A!==r?(A-r)*i:e.keythis.totalOf(i[1])-this.totalOf(e[1]));for(let[i]of o){if(this._trackedKeys.size<=t)break;i!==n&&this._trackedKeys.delete(i)}}subscribe(n,t){for(let[o,i]of Object.entries(t)){let e=(...a)=>{this.applyEvent(i,a)};n.on(o,e),this._subscriptions.push({emitter:n,event:o,listener:e})}}unsubscribe(n){let t=[];for(let o of this._subscriptions){if(n&&o.emitter!==n){t.push(o);continue}(o.emitter.off??o.emitter.removeListener)?.call(o.emitter,o.event,o.listener)}this._subscriptions=t}applyEvent(n,t){if(this._enabled){if(typeof n=="function"){n(this,...t);return}if(Array.isArray(n)){for(let o of n)this.increment(o);return}this.increment(n)}}touch(){this._lastUpdated=Date.now()}};var G4e=class{value;prev=void 0;next=void 0;constructor(n){this.value=n}},hU=class{head=void 0;tail=void 0;nodesMap=new Map;addToFront(n){let t=new G4e(n);this.head?(t.next=this.head,this.head.prev=t,this.head=t):this.head=this.tail=t,this.nodesMap.set(n,t)}moveToFront(n){let t=this.nodesMap.get(n);if(!t||this.head===t)return;t.prev&&(t.prev.next=t.next);t.next&&(t.next.prev=t.prev);t===this.tail&&(this.tail=t.prev),t.prev=void 0,t.next=this.head;this.head&&(this.head.prev=t),this.head=t,this.tail??=t}getOldest(){return this.tail?this.tail.value:void 0}removeOldest(){if(!this.tail)return;let n=this.tail.value;return this.tail.prev?(this.tail=this.tail.prev,this.tail.next=void 0):this.head=this.tail=void 0,this.nodesMap.delete(n),n}remove(n){let t=this.nodesMap.get(n);return t?(t.prev?t.prev.next=t.next:(this.head=t.next,this.head&&(this.head.prev=void 0)),t.next?t.next.prev=t.prev:(this.tail=t.prev,this.tail&&(this.tail.next=void 0)),this.nodesMap.delete(n),!0):!1}get size(){return this.nodesMap.size}};var lne=16777216,EU=class extends lI{_lru=new hU;_storeHashSize=16;_storeHashAlgorithm=Df.DJB2;_store=Array.from({length:this._storeHashSize},()=>new Map);_ttl;_maxTtl;_useClone=!0;_lruSize=0;_checkInterval=0;_interval=0;_stats=new pI({enabled:!1});constructor(n){super(),n?.ttl&&this.setTtl(n.ttl),n?.maxTtl!==void 0&&this.setMaxTtl(n.maxTtl),n?.useClone!==void 0&&(this._useClone=n.useClone),n?.stats&&(this._stats.enabled=n.stats),n?.storeHashSize&&n.storeHashSize>0&&(this._storeHashSize=n.storeHashSize),n?.lruSize&&(n.lruSize>16777216?this.emit("error",new Error(`LRU size cannot be larger than ${lne} due to Map limitations.`)):this._lruSize=n.lruSize),n?.checkInterval&&(this._checkInterval=n.checkInterval),n?.storeHashAlgorithm&&(this._storeHashAlgorithm=n.storeHashAlgorithm),this._store=Array.from({length:this._storeHashSize},()=>new Map),this.startIntervalCheck()}get ttl(){return this._ttl}set ttl(n){this.setTtl(n)}get maxTtl(){return this._maxTtl}set maxTtl(n){this.setMaxTtl(n)}get useClone(){return this._useClone}set useClone(n){this._useClone=n}get lruSize(){return this._lruSize}set lruSize(n){if(n>16777216){this.emit("error",new Error(`LRU size cannot be larger than ${lne} due to Map limitations.`));return}if(this._lruSize=n,this._lruSize===0){this._lru=new hU;return}this.lruResize()}get checkInterval(){return this._checkInterval}set checkInterval(n){this._checkInterval=n}get size(){let n=0;for(let t of this._store)n+=t.size;return n}get stats(){return this._stats}get storeHashSize(){return this._storeHashSize}set storeHashSize(n){n!==this._storeHashSize&&(this._storeHashSize=n,this._store=Array.from({length:this._storeHashSize},()=>new Map),this._stats.enabled&&this._stats.resetStoreValues())}get storeHashAlgorithm(){return this._storeHashAlgorithm}set storeHashAlgorithm(n){this._storeHashAlgorithm=n}get keys(){let n=[];for(let t of this._store)for(let o of t.keys()){let i=t.get(o);if(i&&this.hasExpired(i)){this.recordExpiration(i),t.delete(o),this.lruRemove(o);continue}n.push(o)}return n.values()}get items(){let n=[];for(let t of this._store)for(let o of t.values()){if(this.hasExpired(o)){this.recordExpiration(o),t.delete(o.key),this.lruRemove(o.key);continue}n.push(o)}return n.values()}get store(){return this._store}get(n){this.hookSync("BEFORE_GET",n);let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1),this.hookSync("AFTER_GET",{key:n,result:void 0});return}this.lruMoveToFront(n);let i;return this._useClone?i=this.clone(o.value):i=o.value,this.recordRead(!0),this.hookSync("AFTER_GET",{key:n,result:i}),i}getMany(n){this.hookSync("BEFORE_GET_MANY",n);let t=[];for(let o of n)t.push(this.get(o));return this.hookSync("AFTER_GET_MANY",{keys:n,result:t}),t}getRaw(n){let t=this.getStore(n),o=t.get(n);if(!o){this.recordRead(!1);return}if(o.expires&&Date.now()>o.expires){this.recordExpiration(o),t.delete(n),this.lruRemove(n),this.recordRead(!1);return}return this.lruMoveToFront(n),this.recordRead(!0),o}getManyRaw(n){let t=[];for(let o of n)t.push(this.getRaw(o));return t}set(n,t,o){let i={key:n,value:t,ttl:o};this.hookSync("BEFORE_SET",i);let e=this.getStore(i.key),a,A=i.ttl;if(A!==void 0||this._ttl!==void 0)if(typeof A=="object"){if(A.expire&&(a=typeof A.expire=="number"?A.expire:A.expire.getTime()),A.ttl){let s=$l(A.ttl);s!==void 0&&(a=s)}}else{let s=$l(A??this._ttl);s!==void 0&&(a=s)}if(this._maxTtl!==void 0){let s=$l(this._maxTtl);(a===void 0||a>s)&&(a=s)}if(this._lruSize>0){if(e.has(i.key))this.lruMoveToFront(i.key);else if(this.lruAddToFront(i.key),this._lru.size>this._lruSize){let s=this._lru.getOldest();s&&(this._lru.removeOldest(),this.delete(s))}}if(this._stats.enabled){let s=e.get(i.key);s?this._stats.decreaseVSize(s.value):(this._stats.incrementKSize(i.key),this._stats.incrementCount()),this._stats.incrementVSize(i.value),this._stats.incrementSets()}let r={key:i.key,value:i.value,expires:a};e.set(i.key,r),this.hookSync("AFTER_SET",i)}setMany(n){this.hookSync("BEFORE_SET_MANY",n);for(let t of n)this.set(t.key,t.value,t.ttl);this.hookSync("AFTER_SET_MANY",n)}has(n){return!!this.get(n)}hasMany(n){let t=[];for(let o of n){let i=this.get(o);t.push(!!i)}return t}take(n){let t=this.get(n);if(t)return this.delete(n),t}takeMany(n){let t=[];for(let o of n)t.push(this.take(o));return t}delete(n){this.hookSync("BEFORE_DELETE",n);let t=this.getStore(n);if(this._stats.enabled){let o=t.get(n);o&&(this._stats.decreaseKSize(n),this._stats.decreaseVSize(o.value),this._stats.decreaseCount(),this._stats.incrementDeletes())}t.delete(n),this.lruRemove(n),this.hookSync("AFTER_DELETE",n)}deleteMany(n){this.hookSync("BEFORE_DELETE_MANY",n);for(let t of n)this.delete(t);this.hookSync("AFTER_DELETE_MANY",n)}clear(){this.hookSync("BEFORE_CLEAR"),this._store=Array.from({length:this._storeHashSize},()=>new Map),this._lru=new hU,this._stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears()),this.hookSync("AFTER_CLEAR")}getStore(n){let t=this.getKeyStoreHash(n);return this._store[t]||=new Map,this._store[t]}getKeyStoreHash(n){return this._store.length===1?0:typeof this._storeHashAlgorithm=="function"?this._storeHashAlgorithm(n,this._storeHashSize):Ine(n,{min:0,max:this._storeHashSize-1,algorithm:this._storeHashAlgorithm})}clone(n){return this.isPrimitive(n)?n:structuredClone(n)}lruAddToFront(n){this._lruSize!==0&&this._lru.addToFront(n)}lruMoveToFront(n){this._lruSize!==0&&this._lru.moveToFront(n)}lruRemove(n){this._lruSize!==0&&this._lru.remove(n)}lruResize(){for(;this._lru.size>this._lruSize;){let n=this._lru.getOldest();n&&(this._lru.removeOldest(),this.delete(n))}}checkExpiration(){for(let n of this._store)for(let t of n.values())t.expires&&Date.now()>t.expires&&(this.recordExpiration(t),n.delete(t.key),this.lruRemove(t.key))}startIntervalCheck(){if(this._checkInterval>0){this._interval&&clearInterval(this._interval),this._interval=setInterval(()=>{this.checkExpiration()},this._checkInterval).unref()}}stopIntervalCheck(){this._interval&&clearInterval(this._interval),this._interval=0,this._checkInterval=0}wrap(n,t){return pU(n,{ttl:t?.ttl??this._ttl,keyPrefix:t?.keyPrefix,createKey:t?.createKey,cache:this})}getOrSet(n,t,o){return dU(n,t,{cache:this,ttl:o?.ttl??this._ttl,cacheErrors:o?.cacheErrors,throwErrors:o?.throwErrors})}recordRead(n){this._stats.enabled&&(n?this._stats.incrementHits():this._stats.incrementMisses(),this._stats.incrementGets())}recordExpiration(n){this._stats.enabled&&(this._stats.decreaseKSize(n.key),this._stats.decreaseVSize(n.value),this._stats.decreaseCount())}isPrimitive(n){return n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"}setTtl(n){typeof n=="string"||n===void 0?this._ttl=n:n>0?this._ttl=n:this._ttl=void 0}setMaxTtl(n){typeof n=="string"||n===void 0?this._maxTtl=n:n>0?this._maxTtl=n:this._maxTtl=void 0}hasExpired(n){return!!(n.expires&&Date.now()>n.expires)}};var Y4e=class extends lI{options={stdTTL:0,checkperiod:600,useClones:!0,deleteOnExpire:!0,maxKeys:-1};store=new Map;_stats=new pI({enabled:!0});_cacheable=new EU;intervalId=0;constructor(n){super(),n&&(this.options={...this.options,...n}),this.startInterval()}set(n,t,o=0){if(typeof n!="string"&&typeof n!="number")throw this.createError("The key argument has to be of type `string` or `number`. Found: `__key`",n);if(o&&typeof o!="number"&&typeof o!="string")throw this.createError("The ttl argument has to be a number or a string for shorthand ttl.",this.formatKey(n));let i=this.formatKey(n),e=0;this.options.stdTTL&&(e=this.getExpirationTimestamp(this.options.stdTTL)),o&&(e=this.getExpirationTimestamp(o));let a=0;if(e&&e>0&&(a=e),this.options.maxKeys){let{maxKeys:A}=this.options;if(A>-1&&this.store.size>=A)throw this.createError("Cache max keys amount exceeded",this.formatKey(n))}return this.store.set(i,{key:i,value:t,ttl:a}),this.emit("set",i,t,e),this._stats.incrementKSize(i),this._stats.incrementVSize(t),this._stats.setCount(this.store.size),!0}mset(n){if(!Array.isArray(n))throw this.createError("The keys argument has to be an array.");for(let t of n)this.set(t.key,t.value,t.ttl);return!0}get(n){let t=this.store.get(this.formatKey(n));if(t){if(t.ttl>0){if(t.ttl0){let n=this.options.checkperiod*1e3;this.intervalId=setInterval(()=>{this.checkData()},n).unref();return}this.intervalId=0}stopInterval(){this.intervalId!==0&&(clearInterval(this.intervalId),this.intervalId=0)}formatKey(n){return n.toString()}getExpirationTimestamp(n){if(typeof n=="string")return $l(n);let t=Date.now(),o=n*1e3;return t+o}checkData(){for(let[n,t]of this.store.entries())t.ttl>0&&t.ttl{let a={resolve:i,reject:e,weight:t,priority:o},A=dne(this._queue,r=>o<=r.priority);A===-1&&t<=this._value?this._dispatchItem(a):this._queue.splice(A+1,0,a)})}runExclusive(t){return J4e(this,arguments,void 0,function*(o,i=1,e=0){let[a,A]=yield this.acquire(i,e);try{return yield o(a)}finally{A()}})}waitForUnlock(t=1,o=0){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return this._couldLockImmediately(t,o)?Promise.resolve():new Promise(i=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),q4e(this._weightedWaiters[t-1],{resolve:i,priority:o})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatchQueue()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatchQueue()}cancel(){this._queue.forEach(t=>t.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(t){let o=this._value;this._value-=t.weight,t.resolve([o,this._newReleaser(t.weight)])}_newReleaser(t){let o=!1;return()=>{o||(o=!0,this.release(t))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let t=this._value;t>0;t--){let o=this._weightedWaiters[t-1];o&&(o.forEach(i=>i.resolve()),this._weightedWaiters[t-1]=[])}else{let t=this._queue[0].priority;for(let o=this._value;o>0;o--){let i=this._weightedWaiters[o-1];if(!i)continue;let e=i.findIndex(a=>a.priority<=t);(e===-1?i:i.splice(0,e)).forEach((a=>a.resolve()))}}}_couldLockImmediately(t,o){return(this._queue.length===0||this._queue[0].priorityt.priority<=i.priority);n.splice(o+1,0,t)}function dne(n,t){for(let o=n.length-1;o>=0;o--)if(t(n[o]))return o;return-1}var z4e=function(n,t,o,i){function e(a){return a instanceof o?a:new o(function(A){A(a)})}return new(o||(o=Promise))(function(a,A){function r(c){try{g(i.next(c))}catch(I){A(I)}}function s(c){try{g(i.throw(c))}catch(I){A(I)}}function g(c){c.done?a(c.value):e(c.value).then(r,s)}g((i=i.apply(n,t||[])).next())})},Jg=class{constructor(t){this._semaphore=new CU(1,t)}acquire(){return z4e(this,arguments,void 0,function*(t=0){let[,o]=yield this._semaphore.acquire(1,t);return o})}runExclusive(t,o=0){return this._semaphore.runExclusive(()=>t(),1,o)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(t=0){return this._semaphore.waitForUnlock(1,t)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};import{randomBytes as $4e}from"crypto";var BU=Je(Ene(),1);var fU=class n extends Error{name="TimeoutError";constructor(t,o){super(t,o),Error.captureStackTrace?.(this,n)}},Cne=n=>n.reason??new DOMException("This operation was aborted.","AbortError");function QU(n,t){let{milliseconds:o,fallback:i,message:e,customTimers:a={setTimeout,clearTimeout},signal:A}=t,r,s,c=new Promise((I,d)=>{if(typeof o!="number"||Math.sign(o)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);if(A?.aborted){d(Cne(A));return}if(A&&(s=()=>{d(Cne(A))},A.addEventListener("abort",s,{once:!0})),n.then(I,d),o===Number.POSITIVE_INFINITY)return;let B=new fU;r=a.setTimeout.call(void 0,()=>{if(i){try{I(i())}catch(f){d(f)}return}typeof n.cancel=="function"&&n.cancel(),e===!1?I():e instanceof Error?d(e):(B.message=e??`Promise timed out after ${o} milliseconds`,d(B))},o)}).finally(()=>{c.clear(),s&&A&&A.removeEventListener("abort",s)});return c.clear=()=>{a.clearTimeout.call(void 0,r),r=void 0},c}function yU(n,t,o){let i=0,e=n.length;for(;e>0;){let a=Math.trunc(e/2),A=i+a;o(n[A],t)<=0?(i=++A,e-=a+1):e=a}return i}var Z4e=100,tE=class{#e=[];#A=0;enqueue(t,o){let{priority:i=0,id:e}=o??{},{size:a}=this,A={priority:i,id:e,run:t};if(a===0){this.#e.length=0,this.#A=0,this.#e.push(A);return}if(this.#e.at(-1).priority>=i){this.#e.push(A);return}this.#t();let r=yU(this.#e,A,(s,g)=>g.priority-s.priority);this.#e.splice(r,0,A)}setPriority(t,o){let i=this.#e.findIndex((a,A)=>A>=this.#A&&a.id===t);if(i===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[e]=this.#e.splice(i,1);this.enqueue(e.run,{priority:o,id:t})}remove(t){let o=this.#e.findIndex((i,e)=>eZ4e&&this.#A>this.#e.length/2&&this.#t(),t?.run}filter(t){let o=[];for(let i=this.#A;i=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);if(t.strict&&t.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(t.strict&&t.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=t.carryoverIntervalCount??t.carryoverConcurrencyCount??!1,this.#A=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#r=t.intervalCap,this.#n=t.interval,this.#o=t.strict,this.#p=new t.queueClass,this.#d=t.queueClass,this.concurrency=t.concurrency,t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);this.timeout=t.timeout,this.#C=t.autoStart===!1,this.#Y()}#S(t){for(;this.#c=this.#n)this.#c++;else break}(this.#c>100&&this.#c>this.#s.length/2||this.#c===this.#s.length)&&(this.#s=this.#s.slice(this.#c),this.#c=0)}#Q(t){this.#o?this.#s.push(t):this.#t++}#m(){this.#o?this.#s.length>this.#c&&this.#s.pop():this.#t>0&&this.#t--}#u(){return this.#s.length-this.#c}get#b(){return this.#A?!0:this.#o?this.#u()=this.#r){let i=this.#s[this.#c],e=this.#n-(t-i);return this.#k(e),!0}return!1}if(this.#I===void 0){let o=this.#i-t;if(o<0)this.#t=this.#e?this.#h:0;else return this.#k(o),!0}return!1}#k(t){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#w()},t))}#M(){this.#I&&(clearInterval(this.#I),this.#I=void 0)}#L(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#_(){if(this.#p.size===0){if(this.#M(),this.emit("empty"),this.#h===0){if(this.#L(),this.#o&&this.#c>0){let o=Date.now();this.#S(o)}this.emit("idle")}return!1}let t=!1;if(!this.#C){let o=Date.now(),i=!this.#T(o);if(this.#b&&this.#R){let e=this.#p.dequeue();this.#A||(this.#Q(o),this.#H()),i&&this.#U(),this.emit("active"),e(),t=!0}}return t}#U(){this.#A||this.#I!==void 0||this.#o||(this.#I=setInterval(()=>{this.#v()},this.#n),this.#i=Date.now()+this.#n)}#v(){this.#o||(this.#I!==void 0&&(this.#t===0&&this.#h===0?this.#M():this.#i=Date.now()+this.#n),this.#t=this.#e?this.#h:0),this.#P(),this.#H()}#P(){for(;this.#_(););}get concurrency(){return this.#E}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#E=t,this.#P()}setPriority(t,o){if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${o}\` (${typeof o})`);this.#p.setPriority(t,o)}async add(t,o={}){if(o={timeout:this.timeout,...o,id:o.id??(this.#f++).toString()},o.timeout!==void 0&&!(Number.isFinite(o.timeout)&&o.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${o.timeout}\` (${typeof o.timeout})`);return new Promise((i,e)=>{let a=Symbol(`task-${o.id}`),A=()=>{},r=async()=>{A(),this.#h++,this.#B.set(a,{id:o.id,priority:o.priority??0,startTime:Date.now(),timeout:o.timeout});let g;try{try{o.signal?.throwIfAborted()}catch(d){throw this.#q(),this.#B.delete(a),d}let c=t({signal:o.signal});if(o.timeout!==void 0&&(c=QU(Promise.resolve(c),{milliseconds:o.timeout,message:`Task timed out after ${o.timeout}ms (queue has ${this.#h} running, ${this.#p.size} waiting)`})),o.signal){let{signal:d}=o;c=Promise.race([c,new Promise((B,f)=>{g=()=>{f(d.reason)},d.addEventListener("abort",g,{once:!0})})])}let I=await c;i(I),this.emit("completed",I)}catch(c){e(c),this.emit("error",c)}finally{g&&o.signal?.removeEventListener("abort",g),this.#B.delete(a),queueMicrotask(()=>{this.#D()})}};this.#p.enqueue(r,o);let s=()=>{if(this.#p instanceof tE){this.#p.remove(r);return}this.#p.remove?.(o.id)};if(o.signal){let{signal:g}=o,c=()=>{A(),s(),e(g.reason),this.#_(),this.emit("next")};if(A=()=>{g.removeEventListener("abort",c),this.#y.delete(A)},g.aborted){c();return}g.addEventListener("abort",c,{once:!0}),this.#y.add(A)}this.emit("add"),this.#_()})}async addAll(t,o){return Promise.all(t.map(async i=>this.add(i,o)))}start(){return this.#C?(this.#C=!1,this.#P(),this):this}pause(){this.#C=!0}clear(){for(let t of this.#y)t();this.#p=new this.#d,this.#M(),this.#z(),this.emit("empty"),this.#h===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#p.size!==0&&await this.#N("empty")}async onSizeLessThan(t){this.#p.sizethis.#p.size{let i=e=>{this.off("error",i),o(e)};this.on("error",i)})}async#N(t,o){let i=Array.isArray(t)?t:[t];return new Promise(e=>{let a=()=>{if(!(o&&!o())){for(let A of i)this.off(A,a);e()}};for(let A of i)this.on(A,a)})}get size(){return this.#p.size}sizeBy(t){return this.#p.filter(t).length}get pending(){return this.#h}get isPaused(){return this.#C}#Y(){this.#A||(this.on("add",()=>{this.#p.size>0&&this.#H()}),this.on("next",()=>{this.#H()}))}#H(){this.#A||this.#a||(this.#a=!0,queueMicrotask(()=>{this.#a=!1,this.#z()}))}#q(){this.#A||(this.#m(),this.#H())}#z(){let t=this.#g;if(this.#A||this.#p.size===0){t&&(this.#g=!1,this.emit("rateLimitCleared"));return}let o;if(this.#o){let e=Date.now();this.#S(e),o=this.#u()}else o=this.#t;let i=o>=this.#r;i!==t&&(this.#g=i,this.emit(i?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#g}get isSaturated(){return this.#h===this.#E&&this.#p.size>0||this.isRateLimited&&this.#p.size>0}get runningTasks(){return[...this.#B.values()].map(t=>({...t,timeoutRemaining:t.timeout?Math.max(0,t.startTime+t.timeout-Date.now()):void 0}))}};var fb=class{constructor(t,o){this.store=t,this.logger=o,this.queues=new Map}getQueue(t){return this.queues.has(t)||this.queues.set(t,new ep({concurrency:1})),this.queues.get(t)}async processOperations(t,o,i,e,a){let A=t[o];if(A)return this.getQueue(o).add(async()=>{i[o]=i[o]||{},e[o]=e[o]||{};let r=[],s={};for(let g in A)A[g]===null?r.push(g):s[g]=A[g];Object.keys(s).length>0&&(Object.assign(i[o],s),Object.assign(e[o],s)),r.length>0&&await this.processDeletions(o,r,i,e,a)})}async processDeletions(t,o,i,e,a){if(a)for(let A of o)i[t]?.[A]?(i[t][A]=null,e[t][A]=null):this.logger.warn(`Skipping deletion of non-existent ${t} in transaction: ${A}`);else{let A=await this.store.get(t,o);for(let r of o)A[r]?(i[t][r]=null,e[t][r]=null):this.logger.warn(`Skipping deletion of non-existent ${t}: ${r}`)}}async validateDeletions(t,o){let i=t[o];if(i)return this.getQueue(o).add(async()=>{let e=Object.keys(i).filter(A=>i[A]===null);if(e.length===0)return;let a=await this.store.get(o,e);for(let A of e)a[A]||(this.logger.warn(`Skipping deletion of non-existent ${o}: ${A}`),delete t[o][A])})}};var Bne=(n,t,{maxCommitRetries:o,delayBetweenTriesMs:i})=>{let e=new X4e,a=new Map,A=new Map,r=new Map,s=new fb(n,t);function g(Q){return a.has(Q)||a.set(Q,new ep({concurrency:1})),a.get(Q)}function c(Q){return A.has(Q)||(A.set(Q,new Jg),r.set(Q,0)),A.get(Q)}function I(Q){let y=r.get(Q)??0;r.set(Q,y+1)}function d(Q){let y=(r.get(Q)??1)-1;if(r.set(Q,y),y<=0){let m=A.get(Q);m&&!m.isLocked()&&(A.delete(Q),r.delete(Q))}}function B(){return!!e.getStore()}async function f(Q){if(Object.keys(Q).length===0){t.trace("no mutations in transaction");return}t.trace("committing transaction");for(let y=0;y{let m=e.getStore();if(!m)return n.get(Q,y);let _=m.cache[Q]||{},T=y.filter(L=>!(L in _));if(T.length>0){m.dbQueries++,t.trace({type:Q,count:T.length},"fetching missing keys in transaction");let L=await c(Q).runExclusive(()=>n.get(Q,T));m.cache[Q]=m.cache[Q]||{},Object.assign(m.cache[Q],L)}let R={};for(let L of y){let U=m.cache[Q]?.[L];U!=null&&(R[L]=U)}return R},set:async Q=>{let y=e.getStore();if(!y){let m=Object.keys(Q);for(let _ of m){let T=_;T==="pre-key"&&await s.validateDeletions(Q,T)}await Promise.all(m.map(_=>g(_).add(async()=>{let T={[_]:Q[_]};await n.set(T)})));return}t.trace({types:Object.keys(Q)},"caching in transaction");for(let m in Q){let _=m;y.cache[_]=y.cache[_]||{},y.mutations[_]=y.mutations[_]||{},_==="pre-key"?await s.processOperations(Q,_,y.cache,y.mutations,!0):(Object.assign(y.cache[_],Q[_]),Object.assign(y.mutations[_],Q[_]))}},isInTransaction:B,transaction:async(Q,y)=>{if(e.getStore())return t.trace("reusing existing transaction context"),Q();let _=c(y);I(y);try{return await _.runExclusive(async()=>{let T={cache:{},mutations:{},dbQueries:0};t.trace("entering transaction");try{let R=await e.run(T,Q);return await f(T.mutations),t.trace({dbQueries:T.dbQueries},"transaction completed"),R}catch(R){throw t.error({error:R},"transaction failed, rolling back"),R}})}finally{d(y)}}}},fne=n=>{let t=n.me?.id;if(!t)throw new une.Boom("Cannot proceed: socket is not authenticated yet (creds.me.id is missing)",{statusCode:401});return t},Qne=()=>{let n=Br.generateKeyPair();return{noiseKey:Br.generateKeyPair(),pairingEphemeralKeyPair:Br.generateKeyPair(),signedIdentityKey:n,signedPreKey:aD(n,1),registrationId:Q7(),advSecretKey:$4e(32).toString("base64"),processedHistoryMessages:[],nextPreKeyId:1,firstUnuploadedPreKeyId:1,accountSyncCounter:0,accountSettings:{unarchiveChats:!1},registered:!1,pairingCode:void 0,lastPropHash:void 0,routingInfo:void 0,additionalData:void 0}};import{mkdir as e8e,readFile as A8e,stat as t8e,unlink as r8e,writeFile as a8e}from"fs/promises";import{join as mU}from"path";var yne=new Map,SU=n=>{let t=yne.get(n);return t||(t=new Jg,yne.set(n,t)),t},mne=async n=>{let t=async(r,s)=>{let g=mU(n,a(s));return SU(g).acquire().then(async I=>{try{await a8e(g,JSON.stringify(r,wB.replacer))}finally{I()}})},o=async r=>{try{let s=mU(n,a(r));return await SU(s).acquire().then(async c=>{try{let I=await A8e(s,{encoding:"utf-8"});return JSON.parse(I,wB.reviver)}finally{c()}})}catch{return null}},i=async r=>{try{let s=mU(n,a(r));return SU(s).acquire().then(async c=>{try{await r8e(s)}catch{}finally{c()}})}catch{}},e=await t8e(n).catch(()=>{});if(e){if(!e.isDirectory())throw new Error(`found something that is not a directory at ${n}, either delete it or specify a different location`)}else await e8e(n,{recursive:!0});let a=r=>r?.replace(/\//g,"__")?.replace(/:/g,"-"),A=await o("creds.json")||Qne();return{state:{creds:A,keys:{get:async(r,s)=>{let g={};return await Promise.all(s.map(async c=>{let I=await o(`${r}-${c}.json`);r==="app-state-sync-key"&&I&&(I=oe.Message.AppStateSyncKeyData.fromObject(I)),g[c]=I})),g},set:async r=>{let s=[];for(let g in r)for(let c in r[g]){let I=r[g][c],d=`${g}-${c}.json`;s.push(I?t(I,d):i(d))}await Promise.all(s)}}},saveCreds:async()=>t(A,"creds.json")}};var i8e=192,o8e=async(n,{thumbnailWidth:t,fetchOpts:o})=>{let i=await Ib(n,o);return await x2(i,t)},Sne=async(n,t={thumbnailWidth:i8e,fetchOpts:{timeout:3e3}})=>{try{let o=0,i=5,{getLinkPreview:e}=await import("link-preview-js"),a=n;!n.startsWith("https://")&&!n.startsWith("http://")&&(a="https://"+a);let A=await e(a,{...t.fetchOpts,followRedirects:"follow",handleRedirects:(r,s)=>{let g=new URL(r),c=new URL(s);return o>=i?!1:c.hostname===g.hostname||c.hostname==="www."+g.hostname||"www."+c.hostname===g.hostname?(o+=1,!0):!1},headers:t.fetchOpts?.headers});if(A&&"title"in A&&A.title){let[r]=A.images,s={"canonical-url":A.url,"matched-text":n,title:A.title,description:A.description,originalThumbnailUrl:r};if(t.uploadImage){let{imageMessage:g}=await Bf({image:{url:r}},{upload:t.uploadImage,mediaTypeOverride:"thumbnail-link",options:t.fetchOpts});s.jpegThumbnail=g?.jpegThumbnail?Buffer.from(g.jpegThumbnail):void 0,s.highQualityThumbnail=g||void 0}else try{s.jpegThumbnail=r?(await o8e(r,t)).buffer:void 0}catch(g){t.logger?.debug({err:g.stack,url:a},"error in generating thumbnail")}return s}}catch(o){if(!o.message.includes("receive a valid"))throw o}};import E8e from"events";var DU=Je(Lr(),1);var n8e=/^1313555\d{4}$|^131655500\d{2}$/;function s8e(n){if(!n)return!1;let t=n.split("@")[0]??"";return t==="0"||n8e.test(t)||rh(n)?!1:!!(_t(n)||qA(n)||ur(n)||ga(n)||n.endsWith("@c.us"))}var Qb=604800,g8e=4,hI="__index";async function yb(n){let o=(await n.get("tctoken",[hI]))[hI];if(!o?.token?.length)return[];try{let i=JSON.parse(Buffer.from(o.token).toString());return Array.isArray(i)?i.filter(e=>typeof e=="string"&&e.length>0&&e!==hI):[]}catch{return[]}}async function rE(n,t){let o=await yb(n),i=new Set(o);for(let e of t)e&&e!==hI&&i.add(e);return{[hI]:{token:Buffer.from(JSON.stringify([...i]))}}}function Ap(n){if(n==null)return!0;let t=typeof n=="string"?parseInt(n):n;if(isNaN(t))return!0;let o=Math.floor(Date.now()/1e3),a=(Math.floor(o/Qb)-(g8e-1))*Qb;return ti}async function js(n,t){return qA(n)?n:await t(n)??n}async function bf(n,t,o,i){return t?qA(n)?n:await o(n)??n:qA(n)&&i?await i(n)??n:n}async function wU({authState:n,jid:t,baseContent:o=[],getLIDForPN:i}){try{let e=await js(t,i),A=(await n.keys.get("tctoken",[e]))?.[e],r=A?.token,s=A?.timestamp;if(!r?.length||s===void 0||Ap(s)){if(r){let g=A?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:A.senderTimestamp}:null;await n.keys.set({tctoken:{[e]:g}})}return o.length>0?o:void 0}return o.push({tag:"tctoken",attrs:{t:String(s)},content:r}),o}catch{return o.length>0?o:void 0}}async function aE({result:n,fallbackJid:t,keys:o,getLIDForPN:i,onNewJidStored:e}){let a=le(n,"tokens");if(!a)return;let A=kA(a,"token");for(let r of A){if(r.attrs.type!=="trusted_contact"||!(r.content instanceof Uint8Array))continue;let s=uA(t||r.attrs.jid);if(!s8e(s))continue;let g=await js(s,i),I=(await o.get("tctoken",[g]))[g],d=I?.timestamp?Number(I.timestamp):0,B=r.attrs.t?Number(r.attrs.t):0;B&&(d>0&&d>B||(await o.set({tctoken:{[g]:{...I,token:Buffer.from(r.content),timestamp:r.attrs.t}}}),e?.(g)))}}var c8e=new Set([TA.CALL_MISSED_GROUP_VIDEO,TA.CALL_MISSED_GROUP_VOICE,TA.CALL_MISSED_VIDEO,TA.CALL_MISSED_VOICE]),I8e=new Set([TA.GROUP_PARTICIPANT_ADD]);async function l8e(n,t,o,i){let e=t.lidMapping.getLIDForPN.bind(t.lidMapping),a=[];for(let g of n){let c=g.tcTokenTimestamp?Hr(g.tcTokenTimestamp):0;if(g.tcToken?.length&&c>0){let I=uA(g.id),d=await js(I,e);a.push({storageJid:d,token:Buffer.from(g.tcToken),ts:c,senderTs:g.tcTokenSenderTimestamp?Hr(g.tcTokenSenderTimestamp):void 0})}}if(!a.length)return;let A=a.map(g=>g.storageJid),r=await o.get("tctoken",A),s={};for(let g of a){let c=r[g.storageJid],I=c?.timestamp?Number(c.timestamp):0;I>0&&I>=g.ts||(s[g.storageJid]={...c,token:g.token,timestamp:String(g.ts),...g.senderTs!==void 0?{senderTimestamp:g.senderTs}:{}})}if(Object.keys(s).length){i?.debug({count:Object.keys(s).length},"storing tctokens from history sync");try{let g=await rE(o,Object.keys(s));await o.set({tctoken:{...s,...g}})}catch(g){i?.warn({err:g},"failed to store tctokens from history sync")}}}var Dne=(n,t,o)=>{ur(n.key.remoteJid)||ga(n.key.remoteJid)?n.key.remoteJid=Cr(yA(n.key?.remoteJid)?.user,ur(n.key.remoteJid)?"s.whatsapp.net":"lid"):n.key.remoteJid=uA(n.key.remoteJid),ur(n.key.participant)||ga(n.key.participant)?n.key.participant=Cr(yA(n.key.participant)?.user,ur(n.key.participant)?"s.whatsapp.net":"lid"):n.key.participant=uA(n.key.participant);let i=Oa(n.message);i?.reactionMessage&&e(i.reactionMessage.key),i?.pollUpdateMessage&&e(i.pollUpdateMessage.pollCreationMessageKey);function e(a){n.key.fromMe||(a.fromMe=a.fromMe?!1:Tt(a.participant||a.remoteJid,t)||Tt(a.participant||a.remoteJid,o),a.remoteJid=n.key.remoteJid,a.participant=a.participant||n.key.participant)}},OU=n=>{let t=Oa(n.message),o=!!ff(t);return(!!t||c8e.has(n.messageStubType)||I8e.has(n.messageStubType))&&o&&!t?.protocolMessage&&!t?.reactionMessage&&!t?.pollUpdateMessage},bU=n=>!n.key.fromMe&&!n.messageStubType,p8e=({remoteJid:n,participant:t,fromMe:o})=>{if(!n)throw new DU.Boom("Cannot derive chat id: message key is missing remoteJid",{data:{remoteJid:n,participant:t,fromMe:o}});if(EB(n)&&!Tg(n)&&!o){if(!t)throw new DU.Boom("Cannot derive chat id: broadcast message key is missing participant",{data:{remoteJid:n,fromMe:o}});return t}return n};function d8e({encPayload:n,encIv:t},{eventCreatorJid:o,eventMsgId:i,eventEncKey:e,responderJid:a}){let A=Buffer.concat([I(i),I(o),I(a),I("Event Response"),new Uint8Array([1])]),r=kn(e,new Uint8Array(32),"sha256"),s=kn(A,r,"sha256"),g=I(`${i}\0${a}`),c=Ol(n,s,t,g);return oe.Message.EventResponseMessage.decode(c);function I(d){return Buffer.from(d)}}var h8e=async(n,{shouldProcessHistoryMsg:t,placeholderResendCache:o,ev:i,creds:e,signalRepository:a,keyStore:A,logger:r,options:s,getMessage:g})=>{let c=e.me.id,{accountSettings:I}=e,d={id:uA(p8e(n.key))},B=OU(n);B&&(d.messages=[{message:n}],d.conversationTimestamp=Hr(n.messageTimestamp),bU(n)&&(d.unreadCount=(d.unreadCount||0)+1));let f=Oa(n.message);(B||f?.reactionMessage?.key?.fromMe)&&I?.unarchiveChats&&(d.archived=!1,d.readOnly=!1);let Q=f?.protocolMessage;if(Q){let y=new Set([oe.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,oe.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,oe.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE]);if(Q.type!==null&&Q.type!==void 0&&y.has(Q.type)&&!n.key.fromMe){r?.warn({msgId:n.key.id,type:Q.type,from:n.key.participant||n.key.remoteJid},"dropping spoofed self-only protocolMessage from non-self origin");return}switch(Q.type){case oe.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:let m=Q.historySyncNotification,_=t,T=!e.processedHistoryMessages?.length;if(r?.info({histNotification:m,process:_,id:n.key.id,isLatest:T},"got history notification"),_){m.syncType!==oe.HistorySync.HistorySyncType.ON_DEMAND&&i.emit("creds.update",{processedHistoryMessages:[...e.processedHistoryMessages||[],{key:n.key,messageTimestamp:n.messageTimestamp}]});let P=await Voe(m,s,r);P.lidPnMappings?.length&&(r?.debug({count:P.lidPnMappings.length},"processing LID-PN mappings from history sync"),await a.lidMapping.storeLIDPNMappings(P.lidPnMappings).catch(J=>r?.warn({err:J},"failed to store LID-PN mappings from history sync"))),await l8e(P.chats,a,A,r),i.emit("messaging-history.set",{...P,isLatest:m.syncType!==oe.HistorySync.HistorySyncType.ON_DEMAND?T:void 0,chunkOrder:m.chunkOrder,peerDataRequestSessionId:m.peerDataRequestSessionId})}break;case oe.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:let R=Q.appStateSyncKeyShare.keys;if(R?.length){let P="";await A.transaction(async()=>{let J=[];for(let{keyData:H,keyId:N}of R){let k=Buffer.from(N.keyId).toString("base64");J.push(k),await A.set({"app-state-sync-key":{[k]:H}}),P=k}r?.info({newAppStateSyncKeyId:P,newKeys:J},"injecting new app state sync keys")},c),i.emit("creds.update",{myAppStateKeyId:P})}else r?.info({protocolMsg:Q},"recv app state sync with 0 keys");break;case oe.Message.ProtocolMessage.Type.REVOKE:i.emit("messages.update",[{key:{...n.key,id:Q.key.id},update:{message:null,messageStubType:TA.REVOKE,key:n.key}}]);break;case oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:Object.assign(d,{ephemeralSettingTimestamp:Hr(n.messageTimestamp),ephemeralExpiration:Q.ephemeralExpiration||null});break;case oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:let L=Q.peerDataOperationRequestResponseMessage;if(L){let P=L.peerDataOperationResult||[];for(let J of P){let H=J?.placeholderMessageResendResponse;if(H?.webMessageInfoBytes)try{let N=oe.WebMessageInfo.decode(H.webMessageInfoBytes),k=N.key?.id,V=k?await o?.get(k):void 0;k&&await o?.del(k);let Ae;V&&typeof V=="object"?(V.message=N.message,N.messageTimestamp&&(V.messageTimestamp=N.messageTimestamp),Ae=V):Ae=N,r?.debug({msgId:k,requestId:L.stanzaId},"received placeholder resend"),i.emit("messages.upsert",{messages:[Ae],type:"notify",requestId:L.stanzaId})}catch(N){r?.warn({err:N,stanzaId:L.stanzaId},"failed to decode placeholder resend response")}}}break;case oe.Message.ProtocolMessage.Type.MESSAGE_EDIT:i.emit("messages.update",[{key:{...n.key,id:Q.key?.id},update:{message:{editedMessage:{message:Q.editedMessage}},messageTimestamp:Q.timestampMs?Math.floor(Hr(Q.timestampMs)/1e3):n.messageTimestamp}}]);break;case oe.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:let U=Q.memberLabel;U?.label&&i.emit("group.member-tag.update",{groupId:d.id,label:U.label,participant:n.key.participant,participantAlt:n.key.participantAlt,messageTimestamp:Number(n.messageTimestamp)});break;case oe.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:let F=Q.lidMigrationMappingSyncMessage?.encodedMappingPayload,{pnToLidMappings:q,chatDbMigrationTimestamp:z}=oe.LIDMigrationMappingSyncPayload.decode(F);r?.debug({pnToLidMappings:q,chatDbMigrationTimestamp:z},"got lid mappings and chat db migration timestamp");let j=[];for(let{pn:P,latestLid:J,assignedLid:H}of q){let N=J||H;j.push({lid:`${N}@lid`,pn:`${P}@s.whatsapp.net`})}if(await a.lidMapping.storeLIDPNMappings(j),j.length)for(let{pn:P,lid:J}of j)await a.migrateSession(P,J)}}else if(f?.reactionMessage){let y={...f.reactionMessage,key:n.key};i.emit("messages.reaction",[{reaction:y,key:f.reactionMessage?.key}])}else if(f?.encEventResponseMessage){let y=f.encEventResponseMessage,m=y.eventCreationMessageKey,_=await g(m);if(_)try{let T=uA(c),R=m.participant||m.remoteJid,L=qA(R)?await a.lidMapping.getPNForLID(R):R,U=gh({remoteJid:uA(L),fromMe:T===L},T),F=gh(n.key,T),q=_?.messageContextInfo?.messageSecret;if(!q)r?.warn({creationMsgKey:m},"event response: missing messageSecret for decryption");else{let z=d8e(y,{eventEncKey:q,eventCreatorJid:U,eventMsgId:m.id,responderJid:F}),j={eventResponseMessageKey:n.key,senderTimestampMs:z.timestampMs,response:z};i.emit("messages.update",[{key:m,update:{eventResponses:[j]}}])}}catch(T){r?.warn({err:T,creationMsgKey:m},"failed to decrypt event response")}else r?.warn({creationMsgKey:m},"event creation message not found, cannot decrypt response")}else if(n.messageStubType){let y=n.key?.remoteJid,m,_=U=>i.emit("group-participants.update",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participants:m,action:U}),T=U=>{i.emit("groups.update",[{id:y,...U,author:n.key.participant??void 0,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername}])},R=(U,F,q)=>{i.emit("group.join-request",{id:y,author:n.key.participant,authorPn:n.key.participantAlt,authorUsername:n.key.participantUsername,participant:U.lid,participantPn:U.pn,action:F,method:q})},L=()=>m.find(U=>Tt(c,U.phoneNumber));switch(n.messageStubType){case TA.GROUP_PARTICIPANT_CHANGE_NUMBER:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("modify");break;case TA.GROUP_PARTICIPANT_LEAVE:case TA.GROUP_PARTICIPANT_REMOVE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("remove"),L()&&(d.readOnly=!0);break;case TA.GROUP_PARTICIPANT_ADD:case TA.GROUP_PARTICIPANT_INVITE:case TA.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],L()&&(d.readOnly=!1),_("add");break;case TA.GROUP_PARTICIPANT_DEMOTE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("demote");break;case TA.GROUP_PARTICIPANT_PROMOTE:m=n.messageStubParameters.map(V=>JSON.parse(V))||[],_("promote");break;case TA.GROUP_CHANGE_ANNOUNCE:let U=n.messageStubParameters?.[0];T({announce:U==="true"||U==="on"});break;case TA.GROUP_CHANGE_RESTRICT:let F=n.messageStubParameters?.[0];T({restrict:F==="true"||F==="on"});break;case TA.GROUP_CHANGE_SUBJECT:let q=n.messageStubParameters?.[0];d.name=q,T({subject:q});break;case TA.GROUP_CHANGE_DESCRIPTION:let z=n.messageStubParameters?.[0];d.description=z,T({desc:z});break;case TA.GROUP_CHANGE_INVITE_LINK:let j=n.messageStubParameters?.[0];T({inviteCode:j});break;case TA.GROUP_MEMBER_ADD_MODE:let P=n.messageStubParameters?.[0];T({memberAddMode:P==="all_member_add"});break;case TA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:let J=n.messageStubParameters?.[0];T({joinApprovalMode:J==="on"});break;case TA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:let H=JSON.parse(n.messageStubParameters?.[0]),N=n.messageStubParameters?.[1],k=n.messageStubParameters?.[2];R(H,N,k);break}}Object.keys(d).length>1&&i.emit("chats.update",[d])},One=h8e;var C8e=["messaging-history.set","chats.upsert","chats.update","chats.delete","contacts.upsert","contacts.update","messages.upsert","messages.update","messages.delete","messages.reaction","message-receipt.update","groups.update"],u8e=new Set(C8e),bne=n=>{let t=new E8e,o=new Set,i=MU(),e=!1,a=null,A=null,r=0,s=1e4,g=3e4;t.on("event",d=>{for(let B in d)t.emit(B,d[B])});function c(){e||(n.debug("Event buffer activated"),e=!0,r=0,a&&clearTimeout(a),a=setTimeout(()=>{e&&(n.warn("Buffer timeout reached, auto-flushing"),I())},g)),r++}function I(){if(!e)return!1;n.debug({bufferCount:r},"Flushing event buffer"),e=!1,r=0,a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.size>s&&(n.debug({cacheSize:o.size},"Clearing history cache"),o.clear());let d=MU(),B=Object.values(i.chatUpdates),f=0;for(let y of B)y.conditional&&(f+=1,d.chatUpdates[y.id]=y,delete i.chatUpdates[y.id]);let Q=f8e(i);return Object.keys(Q).length&&t.emit("event",Q),i=d,n.trace({conditionalChatUpdatesLeft:f},"released buffered events"),!0}return{process(d){let B=async f=>{await d(f)};return t.on("event",B),()=>{t.off("event",B)}},emit(d,B){if(d==="messages.upsert"){let{type:f}=B,Q=Object.values(i.messageUpserts);if(Q.length>0){let y=Q[0].type;y!==f&&(n.debug({bufferedType:y,newType:f},"messages.upsert type mismatch, emitting buffered messages"),t.emit("event",{"messages.upsert":{messages:Q.map(m=>m.message),type:y}}),i.messageUpserts={})}}return e&&u8e.has(d)?(B8e(i,o,d,B,n),!0):t.emit("event",{[d]:B})},isBuffering(){return e},buffer:c,flush:I,createBufferedFunction(d){return async(...B)=>{c();try{let f=await d(...B);return r===1&&setTimeout(()=>{e&&r===1&&I()},100),f}catch(f){throw f}finally{r=Math.max(0,r-1),r===0&&(A||(A=setTimeout(I,100)))}}},on:(...d)=>t.on(...d),off:(...d)=>t.off(...d),removeAllListeners:(...d)=>t.removeAllListeners(...d),destroy(){a&&(clearTimeout(a),a=null),A&&(clearTimeout(A),A=null),o.clear(),i=MU(),e=!1,r=0,t.removeAllListeners(),n.debug("Event buffer destroyed")}}},MU=()=>({historySets:{chats:{},messages:{},contacts:{},isLatest:!1,empty:!0},chatUpserts:{},chatUpdates:{},chatDeletes:new Set,contactUpserts:{},contactUpdates:{},messageUpserts:{},messageUpdates:{},messageReactions:{},messageDeletes:{},messageReceipts:{},groupUpdates:{}});function B8e(n,t,o,i,e){switch(o){case"messaging-history.set":for(let Q of i.chats){let y=Q.id||"",m=n.historySets.chats[y];m&&(m.endOfHistoryTransferType=Q.endOfHistoryTransferType),!m&&!t.has(y)&&(n.historySets.chats[y]=Q,t.add(y),a(Q))}for(let Q of i.contacts){let y=n.historySets.contacts[Q.id];if(y)Object.assign(y,nD(Q));else{let m=`c:${Q.id}`,_=Q.notify||Q.name||Q.verifiedName;(!t.has(m)||_)&&(n.historySets.contacts[Q.id]=Q,t.add(m))}}for(let Q of i.messages){let y=iE(Q.key);!n.historySets.messages[y]&&!t.has(y)&&(n.historySets.messages[y]=Q,t.add(y))}if(n.historySets.empty=!1,n.historySets.syncType=i.syncType,i.pastParticipants?.length){let Q=new Map,y=_=>`${_.userJid||""}:${_.leaveTs||""}:${_.leaveReason||""}`,m=_=>{let T=_.groupJid??JSON.stringify(_),R=Q.get(T);if(!R){Q.set(T,{..._,pastParticipants:[..._.pastParticipants||[]]});return}let L=new Set((R.pastParticipants||[]).map(y));for(let U of _.pastParticipants||[]){let F=y(U);L.has(F)||(R.pastParticipants.push(U),L.add(F))}};for(let _ of n.historySets.pastParticipants||[])m(_);for(let _ of i.pastParticipants)m(_);n.historySets.pastParticipants=[...Q.values()]}n.historySets.progress=i.progress,n.historySets.chunkOrder=i.chunkOrder,n.historySets.peerDataRequestSessionId=i.peerDataRequestSessionId,n.historySets.isLatest=i.isLatest||n.historySets.isLatest;break;case"chats.upsert":for(let Q of i){let y=Q.id||"",m=n.chatUpserts[y];y&&!m&&(m=n.historySets.chats[y],m&&e.debug({chatId:y},"absorbed chat upsert in chat set")),m?m=mb(m,Q):(m=Q,n.chatUpserts[y]=m),a(m),n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.update":for(let Q of i){let y=Q.id,m=Q.conditional?Q.conditional(n):!0;if(m){delete Q.conditional;let _=n.historySets.chats[y]||n.chatUpserts[y];if(_)mb(_,Q);else{let T=n.chatUpdates[y]||{};n.chatUpdates[y]=mb(T,Q)}}else m===void 0&&(n.chatUpdates[y]=Q);n.chatDeletes.has(y)&&n.chatDeletes.delete(y)}break;case"chats.delete":for(let Q of i)n.chatDeletes.has(Q)||n.chatDeletes.add(Q),n.chatUpdates[Q]&&delete n.chatUpdates[Q],n.chatUpserts[Q]&&delete n.chatUpserts[Q],n.historySets.chats[Q]&&delete n.historySets.chats[Q];break;case"contacts.upsert":for(let Q of i){let y=n.contactUpserts[Q.id];y||(y=n.historySets.contacts[Q.id],y&&e.debug({contactId:Q.id},"absorbed contact upsert in contact set")),y?y=Object.assign(y,nD(Q)):(y=Q,n.contactUpserts[Q.id]=y),n.contactUpdates[Q.id]&&(y=Object.assign(n.contactUpdates[Q.id],nD(Q)),delete n.contactUpdates[Q.id])}break;case"contacts.update":let r=i;for(let Q of r){let y=Q.id,m=n.historySets.contacts[y]||n.contactUpserts[y];if(m)Object.assign(m,Q);else{let _=n.contactUpdates[y]||{};n.contactUpdates[y]=Object.assign(_,Q)}}break;case"messages.upsert":let{messages:s,type:g}=i;for(let Q of s){let y=iE(Q.key),m=n.messageUpserts[y]?.message;m||(m=n.historySets.messages[y],m&&e.debug({messageId:y},"absorbed message upsert in message set")),m&&(Q.messageTimestamp=m.messageTimestamp),n.messageUpdates[y]&&(e.debug("absorbed prior message update in message upsert"),Object.assign(Q,n.messageUpdates[y].update),delete n.messageUpdates[y]),n.historySets.messages[y]?n.historySets.messages[y]=Q:n.messageUpserts[y]={message:Q,type:g==="notify"||n.messageUpserts[y]?.type==="notify"?"notify":g}}break;case"messages.update":let c=i;for(let{key:Q,update:y}of c){let m=iE(Q),_=n.historySets.messages[m]||n.messageUpserts[m]?.message;if(_)Object.assign(_,y),y.status===th.READ&&!Q.fromMe&&A(_);else{let T=n.messageUpdates[m]||{key:Q,update:{}};Object.assign(T.update,y),n.messageUpdates[m]=T}}break;case"messages.delete":let I=i;if("keys"in I){let{keys:Q}=I;for(let y of Q){let m=iE(y);n.messageDeletes[m]||(n.messageDeletes[m]=y),n.messageUpserts[m]&&delete n.messageUpserts[m],n.messageUpdates[m]&&delete n.messageUpdates[m]}}break;case"messages.reaction":let d=i;for(let{key:Q,reaction:y}of d){let m=iE(Q),_=n.messageUpserts[m];_?Z2(_.message,y):(n.messageReactions[m]=n.messageReactions[m]||{key:Q,reactions:[]},Z2(n.messageReactions[m],y))}break;case"message-receipt.update":let B=i;for(let{key:Q,receipt:y}of B){let m=iE(Q),_=n.messageUpserts[m];_?W2(_.message,y):(n.messageReceipts[m]=n.messageReceipts[m]||{key:Q,userReceipt:[]},W2(n.messageReceipts[m],y))}break;case"groups.update":let f=i;for(let Q of f){let y=Q.id,m=n.groupUpdates[y]||{};n.groupUpdates[y]||(n.groupUpdates[y]=Object.assign(m,Q))}break;default:throw new Error(`"${o}" cannot be buffered`)}function a(r){let s=r.id||"",g=n.chatUpdates[s];if(g){let c=g.conditional?g.conditional(n):!0;c?(delete g.conditional,e.debug({chatId:s},"absorbed chat update in existing chat"),Object.assign(r,mb(g,r)),delete n.chatUpdates[s]):c===!1&&(e.debug({chatId:s},"chat update condition fail, removing"),delete n.chatUpdates[s])}}function A(r){let s=r.key.remoteJid,g=n.chatUpdates[s]||n.chatUpserts[s];OU(r)&&bU(r)&&typeof g?.unreadCount=="number"&&g.unreadCount>0&&(e.debug({chatId:g.id},"decrementing chat counter"),g.unreadCount-=1,g.unreadCount===0&&delete g.unreadCount)}}function f8e(n){let t={};n.historySets.empty||(t["messaging-history.set"]={chats:Object.values(n.historySets.chats),messages:Object.values(n.historySets.messages),contacts:Object.values(n.historySets.contacts),pastParticipants:n.historySets.pastParticipants,syncType:n.historySets.syncType,progress:n.historySets.progress,isLatest:n.historySets.isLatest,chunkOrder:n.historySets.chunkOrder,peerDataRequestSessionId:n.historySets.peerDataRequestSessionId});let o=Object.values(n.chatUpserts);o.length&&(t["chats.upsert"]=o);let i=Object.values(n.chatUpdates);i.length&&(t["chats.update"]=i);let e=Array.from(n.chatDeletes);e.length&&(t["chats.delete"]=e);let a=Object.values(n.messageUpserts);if(a.length){let B=a[0].type;t["messages.upsert"]={messages:a.map(f=>f.message),type:B}}let A=Object.values(n.messageUpdates);A.length&&(t["messages.update"]=A);let r=Object.values(n.messageDeletes);r.length&&(t["messages.delete"]={keys:r});let s=Object.values(n.messageReactions).flatMap(({key:B,reactions:f})=>f.flatMap(Q=>({key:B,reaction:Q})));s.length&&(t["messages.reaction"]=s);let g=Object.values(n.messageReceipts).flatMap(({key:B,userReceipt:f})=>f.flatMap(Q=>({key:B,receipt:Q})));g.length&&(t["message-receipt.update"]=g);let c=Object.values(n.contactUpserts);c.length&&(t["contacts.upsert"]=c);let I=Object.values(n.contactUpdates);I.length&&(t["contacts.update"]=I);let d=Object.values(n.groupUpdates);return d.length&&(t["groups.update"]=d),t}function mb(n,t){return t.unreadCount===null&&n.unreadCount<0&&(n.unreadCount=void 0,t.unreadCount=void 0),typeof n.unreadCount=="number"&&typeof t.unreadCount=="number"&&(t={...t},t.unreadCount>=0&&(t.unreadCount=Math.max(t.unreadCount,0)+Math.max(n.unreadCount,0))),Object.assign(n,t)}var iE=n=>`${n.remoteJid},${n.id},${n.fromMe?"1":"0"}`;var Q8e=512,_U="\0",Mne=3600*1e3,y8e=3e3,qg;(function(n){n[n.UnknownError=0]="UnknownError",n[n.SignalErrorNoSession=1]="SignalErrorNoSession",n[n.SignalErrorInvalidKey=2]="SignalErrorInvalidKey",n[n.SignalErrorInvalidKeyId=3]="SignalErrorInvalidKeyId",n[n.SignalErrorInvalidMessage=4]="SignalErrorInvalidMessage",n[n.SignalErrorInvalidSignature=5]="SignalErrorInvalidSignature",n[n.SignalErrorFutureMessage=6]="SignalErrorFutureMessage",n[n.SignalErrorBadMac=7]="SignalErrorBadMac",n[n.SignalErrorInvalidSession=8]="SignalErrorInvalidSession",n[n.SignalErrorInvalidMsgKey=9]="SignalErrorInvalidMsgKey",n[n.BadBroadcastEphemeralSetting=10]="BadBroadcastEphemeralSetting",n[n.UnknownCompanionNoPrekey=11]="UnknownCompanionNoPrekey",n[n.AdvFailure=12]="AdvFailure",n[n.StatusRevokeDelay=13]="StatusRevokeDelay"})(qg||(qg={}));var _ne=new Set([qg.SignalErrorInvalidMessage,qg.SignalErrorBadMac]),Sb=class{constructor(t,o){this.logger=t,this.recentMessagesMap=new Mg({max:Q8e,ttl:300*1e3,ttlAutopurge:!0,dispose:(i,e)=>{let a=e.lastIndexOf(_U);if(a>-1){let A=e.slice(a+_U.length);this.messageKeyIndex.delete(A)}}}),this.messageKeyIndex=new Map,this.sessionRecreateHistory=new Mg({ttl:Mne*2,ttlAutopurge:!0}),this.retryCounters=new Mg({ttl:900*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),this.baseKeys=new Mg({max:1024,ttl:900*1e3,ttlAutopurge:!0}),this.pendingPhoneRequests={},this.maxMsgRetryCount=5,this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0},this.maxMsgRetryCount=o}addRecentMessage(t,o,i){let e={to:t,id:o},a=this.keyToString(e);this.recentMessagesMap.set(a,{message:i,timestamp:Date.now()}),this.messageKeyIndex.set(o,a),this.logger.debug(`Added message to retry cache: ${t}/${o}`)}getRecentMessage(t,o){let i={to:t,id:o},e=this.keyToString(i);return this.recentMessagesMap.get(e)}shouldRecreateSession(t,o,i){if(!o)return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,{reason:"we don't have a Signal session with them",recreate:!0};if(i!==void 0&&_ne.has(i))return this.sessionRecreateHistory.set(t,Date.now()),this.statistics.sessionRecreations++,this.logger.warn({jid:t,errorCode:qg[i]},"MAC error detected, forcing immediate session recreation"),{reason:`MAC error (code ${i}: ${qg[i]}), immediate session recreation`,recreate:!0};let e=Date.now(),a=this.sessionRecreateHistory.get(t);return!a||e-a>Mne?(this.sessionRecreateHistory.set(t,e),this.statistics.sessionRecreations++,{reason:"retry count > 1 and over an hour since last recreation",recreate:!0}):{reason:"",recreate:!1}}parseRetryErrorCode(t){if(t===void 0||t==="")return;let o=parseInt(t,10);if(!Number.isNaN(o))return o>=qg.UnknownError&&o<=qg.StatusRevokeDelay?o:qg.UnknownError}isMacError(t){return t!==void 0&&_ne.has(t)}incrementRetryCount(t){return this.retryCounters.set(t,(this.retryCounters.get(t)||0)+1),this.statistics.totalRetries++,this.retryCounters.get(t)}getRetryCount(t){return this.retryCounters.get(t)||0}hasExceededMaxRetries(t){return this.getRetryCount(t)>=this.maxMsgRetryCount}markRetrySuccess(t){this.statistics.successfulRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}markRetryFailed(t){this.statistics.failedRetries++,this.retryCounters.delete(t),this.cancelPendingPhoneRequest(t),this.removeRecentMessage(t)}schedulePhoneRequest(t,o,i=y8e){this.cancelPendingPhoneRequest(t),this.pendingPhoneRequests[t]=setTimeout(()=>{delete this.pendingPhoneRequests[t],this.statistics.phoneRequests++,o()},i),this.logger.debug(`Scheduled phone request for message ${t} with ${i}ms delay`)}cancelPendingPhoneRequest(t){let o=this.pendingPhoneRequests[t];o&&(clearTimeout(o),delete this.pendingPhoneRequests[t],this.logger.debug(`Cancelled pending phone request for message ${t}`))}clear(){this.recentMessagesMap.clear(),this.messageKeyIndex.clear(),this.sessionRecreateHistory.clear(),this.retryCounters.clear(),this.baseKeys.clear();for(let t of Object.keys(this.pendingPhoneRequests))this.cancelPendingPhoneRequest(t);this.statistics={totalRetries:0,successfulRetries:0,failedRetries:0,mediaRetries:0,sessionRecreations:0,phoneRequests:0}}saveBaseKey(t,o,i){this.baseKeys.set(`${t}:${o}`,i)}hasSameBaseKey(t,o,i){let e=this.baseKeys.get(`${t}:${o}`);if(!e||e.length!==i.length)return!1;for(let a=0;a["Ubuntu",n,"22.04.4"],macOS:n=>["Mac OS",n,"14.4.1"],baileys:n=>["Baileys",n,"6.5.0"],windows:n=>["Windows",n,"10.0.22631"],android:n=>[n,"Android",""],appropriate:n=>[w8e[m8e()]||"Ubuntu",n,S8e()]};var Gn;(function(n){n[n.UNKNOWN=0]="UNKNOWN",n[n.CHROME=1]="CHROME",n[n.EDGE=2]="EDGE",n[n.FIREFOX=3]="FIREFOX",n[n.IE=4]="IE",n[n.OPERA=5]="OPERA",n[n.SAFARI=6]="SAFARI",n[n.ELECTRON=7]="ELECTRON",n[n.UWP=8]="UWP",n[n.OTHER_WEB_CLIENT=9]="OTHER_WEB_CLIENT"})(Gn||(Gn={}));var D8e={Chrome:Gn.CHROME,Edge:Gn.EDGE,Firefox:Gn.FIREFOX,IE:Gn.IE,Opera:Gn.OPERA,Safari:Gn.SAFARI},O8e=([n,t])=>t==="Desktop"?n==="Windows"?Gn.UWP:Gn.ELECTRON:D8e[t]||Gn.OTHER_WEB_CLIENT,TU=n=>O8e(n).toString(),Tne=(n,t,o,i,e)=>"https://wa.me/settings/linked_devices#"+[n,t,o,i,TU(e)].join(",");async function Nne(n,t){let o=n.attrs.from;if(!o)return{action:"invalid_notification"};if(!le(n,"identity"))return{action:"no_identity_node"};t.logger.info({jid:o},"identity changed");let e=yA(o);if(e?.device&&e.device!==0)return t.logger.debug({jid:o,device:e.device},"ignoring identity change from companion device"),{action:"skipped_companion_device",device:e.device};if(t.meId&&(Tt(o,t.meId)||t.meLid&&Tt(o,t.meLid)))return t.logger.info({jid:o},"self primary identity changed"),{action:"skipped_self_primary"};if(t.debounceCache.get(o))return t.logger.debug({jid:o},"skipping identity assert (debounced)"),{action:"debounced"};t.debounceCache.set(o,!0);let A=!u7(n.attrs.offline);if(!(await t.validateSession(o)).exists)return t.logger.debug({jid:o},"no old session, skipping session refresh"),{action:"skipped_no_session"};if(t.logger.debug({jid:o},"old session exists, will refresh session"),A)return t.logger.debug({jid:o},"skipping session refresh during offline processing"),{action:"skipped_offline"};t.onBeforeSessionRefresh?.(o);try{return await t.assertSessions([o],!0),{action:"session_refreshed"}}catch(s){return t.logger.warn({error:s,jid:o},"failed to assert sessions after identity change"),{action:"session_refresh_failed",error:s}}}function Rne(n,t,o){let{tag:i,attrs:e}=n,a={tag:"ack",attrs:{id:e.id,to:e.from,class:i}};return t&&(a.attrs.error=t.toString()),e.participant&&(a.attrs.participant=e.participant),e.recipient&&(a.attrs.recipient=e.recipient),e.type&&(a.attrs.type=e.type),i==="message"&&o&&(a.attrs.from=o),a}function b8e(n){return n===null||n===""}function M8e(n){return n>2147483647||n<-2147483648?n&4294967295:n}function kne(n){let t=0;if(!b8e(n))for(let o=0;oo.iteration===t)}addSenderMessageKey(t){this.senderKeyStateStructure.senderMessageKeys.push({iteration:t.getIteration(),seed:t.getSeed()}),this.senderKeyStateStructure.senderMessageKeys.length>this.MAX_MESSAGE_KEYS&&this.senderKeyStateStructure.senderMessageKeys.shift()}removeSenderMessageKey(t){let o=this.senderKeyStateStructure.senderMessageKeys.findIndex(i=>i.iteration===t);if(o!==-1){let i=this.senderKeyStateStructure.senderMessageKeys[o];return this.senderKeyStateStructure.senderMessageKeys.splice(o,1),new tp(i.iteration,i.seed)}return null}getStructure(){return this.senderKeyStateStructure}};var zg=class n{constructor(t){if(this.MAX_STATES=5,this.senderKeyStates=[],t)for(let o of t)this.senderKeyStates.push(new rp(null,null,null,null,null,null,o))}isEmpty(){return this.senderKeyStates.length===0}getSenderKeyState(t){return t===void 0&&this.senderKeyStates.length?this.senderKeyStates[this.senderKeyStates.length-1]:this.senderKeyStates.find(o=>o.getKeyId()===t)}addSenderKeyState(t,o,i,e){this.senderKeyStates.push(new rp(t,o,i,null,e)),this.senderKeyStates.length>this.MAX_STATES&&this.senderKeyStates.shift()}setSenderKeyState(t,o,i,e){this.senderKeyStates.length=0,this.senderKeyStates.push(new rp(t,o,i,e))}serialize(){return this.senderKeyStates.map(t=>t.getStructure())}static deserialize(t){let o=Buffer.from(t).toString("utf-8"),i=JSON.parse(o,wB.reviver);return new n(i)}};var Gne=Je(vc(),1);import*as Db from"crypto";function Fne(){return Db.randomBytes(32)}function Lne(){return Db.randomInt(2147483647)}function Une(n){return n||(n=(0,Gne.generateKeyPair)()),{public:Buffer.from(n.pubKey),private:Buffer.from(n.privKey)}}var ap=class{constructor(){this.UNSUPPORTED_VERSION=1,this.CURRENT_VERSION=3,this.WHISPER_TYPE=2,this.PREKEY_TYPE=3,this.SENDERKEY_TYPE=4,this.SENDERKEY_DISTRIBUTION_TYPE=5,this.ENCRYPTED_MESSAGE_OVERHEAD=53}};var ip=class extends ap{constructor(t,o,i,e,a){if(super(),a)try{let A=a.slice(1),r=oe.SenderKeyDistributionMessage.decode(A).toJSON();this.serialized=a,this.id=r.id,this.iteration=r.iteration,this.chainKey=typeof r.chainKey=="string"?Buffer.from(r.chainKey,"base64"):r.chainKey,this.signatureKey=typeof r.signingKey=="string"?Buffer.from(r.signingKey,"base64"):r.signingKey}catch(A){throw new Error(String(A))}else{let A=this.intsToByteHighAndLow(this.CURRENT_VERSION,this.CURRENT_VERSION);this.id=t,this.iteration=o,this.chainKey=i,this.signatureKey=e;let r=oe.SenderKeyDistributionMessage.encode(oe.SenderKeyDistributionMessage.create({id:t,iteration:o,chainKey:i,signingKey:this.signatureKey})).finish();this.serialized=Buffer.concat([Buffer.from([A]),r])}}intsToByteHighAndLow(t,o){return((t<<4|o)&255)%256}serialize(){return this.serialized}getType(){return this.SENDERKEY_DISTRIBUTION_TYPE}getIteration(){return this.iteration}getChainKey(){return this.chainKey}getSignatureKey(){return this.signatureKey}getId(){return this.id}};var oE=class{constructor(t){this.senderKeyStore=t}async process(t,o){let i=await this.senderKeyStore.loadSenderKey(t);i.addSenderKeyState(o.getId(),o.getIteration(),o.getChainKey(),o.getSignatureKey()),await this.senderKeyStore.storeSenderKey(t,i)}async create(t){let o=await this.senderKeyStore.loadSenderKey(t);if(o.isEmpty()){let e=Lne(),a=Fne(),A=Une();o.setSenderKeyState(e,0,a,A),await this.senderKeyStore.storeSenderKey(t,o)}let i=o.getSenderKeyState();if(!i)throw new Error("No session state available");return new ip(i.getKeyId(),i.getSenderChainKey().getIteration(),i.getSenderChainKey().getSeed(),i.getSigningKeyPublic())}};var bb=Je(yl(),1);var Ob=Je(vc(),1);var nE=class extends ap{constructor(t,o,i,e,a){if(super(),this.SIGNATURE_LENGTH=64,a){let A=a[0],r=a.slice(1,a.length-this.SIGNATURE_LENGTH),s=a.slice(-1*this.SIGNATURE_LENGTH),g=oe.SenderKeyMessage.decode(r).toJSON();this.serialized=a,this.messageVersion=(A&255)>>4,this.keyId=g.id,this.iteration=g.iteration,this.ciphertext=typeof g.ciphertext=="string"?Buffer.from(g.ciphertext,"base64"):g.ciphertext,this.signature=s}else{let A=((this.CURRENT_VERSION<<4|this.CURRENT_VERSION)&255)%256,r=Buffer.from(i),s=oe.SenderKeyMessage.encode(oe.SenderKeyMessage.create({id:t,iteration:o,ciphertext:r})).finish(),g=this.getSignature(e,Buffer.concat([Buffer.from([A]),s]));this.serialized=Buffer.concat([Buffer.from([A]),s,Buffer.from(g)]),this.messageVersion=this.CURRENT_VERSION,this.keyId=t,this.iteration=o,this.ciphertext=r,this.signature=g}}getKeyId(){return this.keyId}getIteration(){return this.iteration}getCipherText(){return this.ciphertext}verifySignature(t){let o=this.serialized.slice(0,this.serialized.length-this.SIGNATURE_LENGTH),i=this.serialized.slice(-1*this.SIGNATURE_LENGTH);if(!(0,Ob.verifySignature)(t,o,i))throw new Error("Invalid signature!")}getSignature(t,o){return Buffer.from((0,Ob.calculateSignature)(t,o))}serialize(){return this.serialized}getType(){return 4}};var sE=class{constructor(t,o){this.senderKeyStore=t,this.senderKeyName=o}async encrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for encryption");let i=o.getSenderKeyState();if(!i)throw new Error("No session to encrypt message");let e=i.getSenderChainKey().getIteration(),a=this.getSenderKey(i,e===0?0:e+1),A=await this.getCipherText(a.getIv(),a.getCipherKey(),t),r=new nE(i.getKeyId(),a.getIteration(),A,i.getSigningKeyPrivate());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),r.serialize()}async decrypt(t){let o=await this.senderKeyStore.loadSenderKey(this.senderKeyName);if(!o)throw new Error("No SenderKeyRecord found for decryption");let i=new nE(null,null,null,null,t),e=o.getSenderKeyState(i.getKeyId());if(!e)throw new Error("No session found to decrypt message");i.verifySignature(e.getSigningKeyPublic());let a=this.getSenderKey(e,i.getIteration()),A=await this.getPlainText(a.getIv(),a.getCipherKey(),i.getCipherText());return await this.senderKeyStore.storeSenderKey(this.senderKeyName,o),A}getSenderKey(t,o){let i=t.getSenderChainKey();if(i.getIteration()>o){if(t.hasSenderMessageKey(o)){let e=t.removeSenderMessageKey(o);if(!e)throw new Error("No sender message key found for iteration");return e}throw new Error(`Received message with old counter: ${i.getIteration()}, ${o}`)}if(o-i.getIteration()>2e3)throw new Error("Over 2000 messages into the future!");for(;i.getIteration()0){let r=[...i];this.logger.trace(`Batch fetching ${r.length} LID mappings from database`);let s=await this.keys.get("lid-mapping",r);for(let g of r){let c=s[g];c&&(e.set(g,c),this.mappingCache.set(`pn:${g}`,c),this.mappingCache.set(`lid:${c}`,g))}}let a={};for(let{pnUser:r,lidUser:s}of o){if(e.get(r)===s){this.logger.debug({pnUser:r,lidUser:s},"LID mapping already exists, skipping");continue}a[r]=s}if(Object.keys(a).length===0)return;this.logger.trace({pairMap:a},`Storing ${Object.keys(a).length} pn mappings`);let A={};for(let[r,s]of Object.entries(a))A[r]=s,A[`${s}_reverse`]=r;await this.keys.transaction(async()=>{await this.keys.set({"lid-mapping":A})},"lid-mapping");for(let[r,s]of Object.entries(a))this.mappingCache.set(`pn:${r}`,s),this.mappingCache.set(`lid:${s}`,r)}async getLIDForPN(t){return(await this.getLIDsForPNs([t]))?.[0]?.lid||null}async getLIDsForPNs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightLIDLookups.get(i);if(e)return this.logger.trace(`Coalescing getLIDsForPNs request for ${o.length} PNs`),e;let a=this._getLIDsForPNsImpl(t);this.inflightLIDLookups.set(i,a);try{return await a}finally{this.inflightLIDLookups.delete(i)}}async _getLIDsForPNsImpl(t){let o={},i={},e=[],a=(A,r,s)=>{let g=s.toString();if(!g)return this.logger.warn(`Invalid or empty LID user for PN ${A}: lidUser = "${s}"`),!1;let c=r.device!==void 0?r.device:0,I=`${g}${c?`:${c}`:""}@${r.server==="hosted"?"hosted.lid":"lid"}`;return this.logger.trace(`getLIDForPN: ${A} \u2192 ${I} (user mapping with device ${c})`),i[A]={lid:I,pn:A},!0};for(let A of t){if(!_t(A)&&!ur(A))continue;let r=yA(A);if(!r)continue;let s=r.user,g=this.mappingCache.get(`pn:${s}`);if(g&&typeof g=="string"){if(!a(A,r,g)){this.logger.warn(`Invalid entry for ${A} (pair not resolved)`);continue}continue}e.push({pn:A,pnUser:s,decoded:r})}if(e.length){let A=[...new Set(e.map(s=>s.pnUser))],r=await this.keys.get("lid-mapping",A);for(let s of A){let g=r[s];g&&typeof g=="string"&&(this.mappingCache.set(`pn:${s}`,g),this.mappingCache.set(`lid:${g}`,s))}for(let{pn:s,pnUser:g,decoded:c}of e){let I=this.mappingCache.get(`pn:${g}`);if(I&&typeof I=="string"){if(!a(s,c,I)){this.logger.warn(`Invalid entry for ${s} (pair not resolved)`);continue}}else{this.logger.trace(`No LID mapping found for PN user ${g}; batch getting from USync`);let d=c.device||0,B=uA(s);ur(B)&&(B=`${g}@s.whatsapp.net`),o[B]?o[B]?.push(d):o[B]=[d]}}}if(Object.keys(o).length>0){let A=await this.pnToLIDFunc?.(Object.keys(o));if(A&&A.length>0){await this.storeLIDPNMappings(A);for(let r of A){let g=yA(r.pn)?.user;if(!g)continue;let c=yA(r.lid)?.user;if(c)for(let I of o[r.pn]){let d=`${c}${I?`:${I}`:""}@${I===99?"hosted.lid":"lid"}`;this.logger.trace(`getLIDForPN: USYNC success for ${r.pn} \u2192 ${d} (user mapping with device ${I})`);let B=`${g}${I?`:${I}`:""}@${I===99?"hosted":"s.whatsapp.net"}`;i[B]={lid:d,pn:B}}}}else this.logger.warn("USync fetch yielded no results for pending PNs")}return Object.values(i).length>0?Object.values(i):null}async getPNForLID(t){return(await this.getPNsForLIDs([t]))?.[0]?.pn||null}async getPNsForLIDs(t){if(t.length===0)return null;let o=[...new Set(t)].sort(),i=o.join(","),e=this.inflightPNLookups.get(i);if(e)return this.logger.trace(`Coalescing getPNsForLIDs request for ${o.length} LIDs`),e;let a=this._getPNsForLIDsImpl(t);this.inflightPNLookups.set(i,a);try{return await a}finally{this.inflightPNLookups.delete(i)}}async _getPNsForLIDsImpl(t){let o={},i=[],e=(a,A,r)=>{if(!r||typeof r!="string")return!1;let s=A.device!==void 0?A.device:0,g=`${r}:${s}@${A.domainType===jt.HOSTED_LID?"hosted":"s.whatsapp.net"}`;return this.logger.trace(`Found reverse mapping: ${a} \u2192 ${g}`),o[a]={lid:a,pn:g},!0};for(let a of t){if(!qA(a))continue;let A=yA(a);if(!A)continue;let r=A.user,s=this.mappingCache.get(`lid:${r}`);if(s&&typeof s=="string"){e(a,A,s);continue}i.push({lid:a,lidUser:r,decoded:A})}if(i.length){let a=[...new Set(i.map(r=>`${r.lidUser}_reverse`))],A=await this.keys.get("lid-mapping",a);for(let{lid:r,lidUser:s,decoded:g}of i){let c=this.mappingCache.get(`lid:${s}`);(!c||typeof c!="string")&&(c=A[`${s}_reverse`],c&&typeof c=="string"&&(this.mappingCache.set(`lid:${s}`,c),this.mappingCache.set(`pn:${c}`,s))),c&&typeof c=="string"?e(r,g,c):this.logger.trace(`No reverse mapping found for LID user: ${s}`)}}return Object.values(o).length?Object.values(o):null}close(){this.mappingCache.clear()}};function _8e(n){try{if(!n||n.length<2||(n[0]&15)!==3)return;let o=Kne.PreKeyWhisperMessage.decode(n.slice(1));return o.identityKey?.length===33?new Uint8Array(o.identityKey):void 0}catch{return}}function xne(n,t,o){let i=new Mb(n.keys,t,o),e=T8e(n,i),a=n.keys,A=new Mg({ttl:4320*60*1e3,ttlAutopurge:!0,updateAgeOnGet:!0}),r=async(g,c)=>{let I=_b(g,c),d=I.toString(),{[d]:B}=await n.keys.get("sender-key",[d]);B||await e.storeSenderKey(I,new zg);let f=await new oE(e).create(I);return{senderName:I,skdm:f}};return{decryptGroupMessage({group:g,authorJid:c,msg:I}){let d=_b(g,c),B=new sE(e,d);return a.transaction(async()=>B.decrypt(I),g)},async processSenderKeyDistributionMessage({item:g,authorJid:c}){let I=new oE(e);if(!g.groupId)throw new Error("Group ID is required for sender key distribution message");let d=_b(g.groupId,c),B=new ip(null,null,null,null,g.axolotlSenderKeyDistributionMessage),f=d.toString(),{[f]:Q}=await n.keys.get("sender-key",[f]);return Q||await e.storeSenderKey(d,new zg),a.transaction(async()=>{let{[f]:y}=await n.keys.get("sender-key",[f]);y||await e.storeSenderKey(d,new zg),await I.process(d,B)},g.groupId)},async decryptMessage({jid:g,type:c,ciphertext:I}){let d=Fn(g),B=new Js.SessionCipher(e,d);if(c==="pkmsg"){let Q=_8e(I);if(Q){let y=d.toString();await e.saveIdentity(y,Q)&&t.info({jid:g,addr:y},"identity key changed or new contact, session will be re-established")}}async function f(){let Q;switch(c){case"pkmsg":Q=await B.decryptPreKeyWhisperMessage(I);break;case"msg":Q=await B.decryptWhisperMessage(I);break}return Q}return a.transaction(async()=>await f(),g)},async encryptMessage({jid:g,data:c}){let I=Fn(g),d=new Js.SessionCipher(e,I);return a.transaction(async()=>{let{type:B,body:f}=await d.encrypt(c);return{type:B===3?"pkmsg":"msg",ciphertext:Buffer.from(f,"binary")}},g)},async encryptGroupMessage({group:g,meId:c,data:I}){return a.transaction(async()=>{let{senderName:d,skdm:B}=await r(g,c);return{ciphertext:await new sE(e,d).encrypt(I),senderKeyDistributionMessage:B.serialize()}},g)},async getSenderKeyDistributionMessage({group:g,meId:c}){return a.transaction(async()=>{let{skdm:I}=await r(g,c);return I.serialize()},g)},async hasSenderKey({group:g,meId:c}){let I=_b(g,c).toString(),{[I]:d}=await n.keys.get("sender-key",[I]);return!!d},async getSessionInfo(g){let c=Fn(g).toString(),I=await e.loadSession(c);if(!I)return null;let d=I.getOpenSession?.(),B=d?.indexInfo?.baseKey,f=d?.registrationId;return!B||typeof f!="number"?null:{baseKey:new Uint8Array(B),registrationId:f}},async injectE2ESession({jid:g,session:c}){t.trace({jid:g},"injecting E2EE session");let I=new Js.SessionBuilder(e,Fn(g));return a.transaction(async()=>{await I.initOutgoing(c)},g)},jidToSignalProtocolAddress(g){return Fn(g).toString()},lidMapping:i,async validateSession(g){try{let c=Fn(g),I=await e.loadSession(c.toString());return I?I.haveOpenSession()?{exists:!0}:{exists:!1,reason:"no open session"}:{exists:!1,reason:"no session"}}catch{return{exists:!1,reason:"validation error"}}},async deleteSession(g){if(!g.length)return;let c={};return g.forEach(I=>{let d=Fn(I);c[d.toString()]=null}),a.transaction(async()=>{await n.keys.set({session:c})},`delete-${g.length}-sessions`)},close(){A.clear(),i.close()},async migrateSession(g,c){if(!g||!qA(c)&&!ga(c))return{migrated:0,skipped:0,total:0};if(!_t(g)&&!ur(g))return{migrated:0,skipped:0,total:1};let{user:I}=yA(g);t.debug({fromJid:g},"bulk device migration - loading all user devices");let{[I]:d}=await a.get("device-list",[I]);if(!d)return{migrated:0,skipped:0,total:0};let{device:B}=yA(g),f=B?.toString()||"0";d.includes(f)||d.push(f);let y=d.filter(T=>{let R=`${I}.${T}`;return!A.has(R)}).map(T=>`${I}.${T}`),m=await a.get("session",y),_=[];for(let[T,R]of Object.entries(m))if(R){let L=T.split(".")[1];if(!L)continue;let U=parseInt(L),F=U===0?`${I}@s.whatsapp.net`:`${I}:${U}@s.whatsapp.net`;U===99&&(F=`${I}:99@hosted`),_.push(F)}return t.debug({fromJid:g,totalDevices:d.length,devicesWithSessions:_.length,devices:_},"bulk device migration complete - all user devices processed"),a.transaction(async()=>{let T=_.map(j=>{let P=HX(j,c),J=yA(j),H=yA(P);return{fromJid:j,toJid:P,pnUser:J.user,lidUser:H.user,deviceId:J.device||0,fromAddr:Fn(j),toAddr:Fn(P)}}),R=T.length,L=0,U=Array.from(new Set(T.map(j=>j.fromAddr.toString()))),F=await a.get("session",U),q={};for(let j of T){let P=j.fromAddr.toString(),J=j.toAddr.toString(),H=F[P];if(H){let N=Js.SessionRecord.deserialize(H);N.haveOpenSession()&&(q[J]=N.serialize(),q[P]=null,L++)}}if(Object.keys(q).length>0){await a.set({session:q}),t.debug({migratedSessions:L},"bulk session migration complete");for(let j of T)if(q[j.toAddr.toString()]){let P=`${j.pnUser}.${j.deviceId}`;A.set(P,!0)}}let z=R-L;return{migrated:L,skipped:z,total:R}},`migrate-${_.length}-sessions-${yA(c)?.user}`)}}}var Fn=n=>{let t=yA(n),{user:o,device:i,server:e,domainType:a}=t;if(!o)throw new Error(`JID decoded but user is empty: "${n}" -> user: "${o}", server: "${e}", device: ${i}`);let A=a!==jt.WHATSAPP?`${o}_${a}`:o,r=i||0;if(i===99&&t.server!=="hosted"&&t.server!=="hosted.lid")throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:"+n);return new Js.ProtocolAddress(A,r)},_b=(n,t)=>new Mf(n,Fn(t));function T8e({creds:n,keys:t},o){let i=async e=>{if(e.includes(".")){let[a,A]=e.split("."),[r,s]=a.split("_"),g=parseInt(s||"0");if(g===jt.LID||g===jt.HOSTED_LID)return e;let c=`${r}${A!=="0"?`:${A}`:""}@${g===jt.HOSTED?"hosted":"s.whatsapp.net"}`,I=await o.getLIDForPN(c);if(I)return Fn(I).toString()}return e};return{loadSession:async e=>{try{let a=await i(e),{[a]:A}=await t.get("session",[a]);if(A)return Js.SessionRecord.deserialize(A)}catch{return null}return null},storeSession:async(e,a)=>{let A=await i(e);await t.set({session:{[A]:a.serialize()}})},isTrustedIdentity:()=>!0,loadIdentityKey:async e=>{let a=await i(e),{[a]:A}=await t.get("identity-key",[a]);return A||void 0},saveIdentity:async(e,a)=>{let A=await i(e),{[A]:r}=await t.get("identity-key",[A]),s=r?.length===a.length&&r.every((g,c)=>g===a[c]);return r&&!s?(await t.set({session:{[A]:null},"identity-key":{[A]:a}}),!0):r?!1:(await t.set({"identity-key":{[A]:a}}),!0)},loadPreKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("pre-key",[a]);if(A)return{privKey:Buffer.from(A.private),pubKey:Buffer.from(A.public)}},removePreKey:e=>t.set({"pre-key":{[e]:null}}),loadSignedPreKey:()=>{let e=n.signedPreKey;return{privKey:Buffer.from(e.keyPair.private),pubKey:Buffer.from(e.keyPair.public)}},loadSenderKey:async e=>{let a=e.toString(),{[a]:A}=await t.get("sender-key",[a]);return A?zg.deserialize(A):new zg},storeSenderKey:async(e,a)=>{let A=e.toString(),r=JSON.stringify(a.serialize());await t.set({"sender-key":{[A]:Buffer.from(r,"utf-8")}})},getOurRegistrationId:()=>n.registrationId,getOurIdentity:()=>{let{signedIdentityKey:e}=n;return{privKey:Buffer.from(e.private),pubKey:Buffer.from(Yo(e.public))}}}}var Ace=Je(ece(),1),vf=(0,Ace.default)({timestamp:()=>`,"time":"${new Date().toJSON()}"`});var O5e=[2,3e3,1043857760];var uf="https://web.whatsapp.com",boe="https://call.whatsapp.com/video/",Moe="https://call.whatsapp.com/voice/",pE="CB:",tce="TAG:";var Koe=Buffer.from([6,0]),xoe=Buffer.from([6,1]),tU=Buffer.from([6,5]),vkA=Buffer.from([6,6]),Qf=10080*60,rce=1440*60,ace=336*60*60,zoe="Noise_XX_25519_AESGCM_SHA256\0\0\0\0",b5e=3,Rg=Buffer.from([5]),ice=Buffer.from([87,65,6,b5e]),_oe=/https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g,aU={SERIAL:0,ISSUER:"WhatsAppLongTerm1",PUBLIC_KEY:Buffer.from("142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b","hex")},Pf=[oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,oe.HistorySync.HistorySyncType.PUSH_NAME,oe.HistorySync.HistorySyncType.RECENT,oe.HistorySync.HistorySyncType.FULL,oe.HistorySync.HistorySyncType.ON_DEMAND,oe.HistorySync.HistorySyncType.NON_BLOCKING_DATA,oe.HistorySync.HistorySyncType.INITIAL_STATUS_V3],dI={SIGNAL_STORE:300,MSG_RETRY:3600,CALL_OFFER:300,USER_DEVICES:300},oce={version:O5e,browser:wb.macOS("Chrome"),waWebSocketUrl:"wss://web.whatsapp.com/ws/chat",connectTimeoutMs:2e4,keepAliveIntervalMs:3e4,logger:vf.child({class:"baileys"}),emitOwnEvents:!0,defaultQueryTimeoutMs:6e4,customUploadHosts:[],retryRequestDelayMs:250,maxMsgRetryCount:5,fireInitQueries:!0,auth:void 0,markOnlineOnConnect:!0,syncFullHistory:!0,patchMessageBeforeSending:n=>n,shouldSyncHistoryMessage:({syncType:n})=>n!==oe.HistorySync.HistorySyncType.FULL,shouldIgnoreJid:()=>!1,linkPreviewImageThumbnailWidth:192,transactionOpts:{maxCommitRetries:10,delayBetweenTriesMs:3e3},generateHighQualityLinkPreview:!1,enableAutoSessionRecreation:!0,enableRecentMessageCache:!0,options:{},appStateMacVerification:{patch:!1,snapshot:!1},countryCode:"US",getMessage:async()=>{},cachedGroupMetadata:async()=>{},makeSignalRepository:xne},J2={image:"/mms/image",video:"/mms/video",document:"/mms/document",audio:"/mms/audio",sticker:"/mms/image","thumbnail-link":"/mms/image","product-catalog-image":"/product/image","md-app-state":"","md-msg-hist":"/mms/md-app-state","biz-cover-photo":"/pps/biz-cover-photo"},Coe={audio:"Audio",document:"Document",gif:"Video",image:"Image",ppic:"",product:"Image",ptt:"Audio",sticker:"Image",video:"Video","thumbnail-document":"Document Thumbnail","thumbnail-image":"Image Thumbnail","thumbnail-video":"Video Thumbnail","thumbnail-link":"Link Thumbnail","md-msg-hist":"History","md-app-state":"App State","product-catalog-image":"","payment-bg-image":"Payment Background",ptv:"Video","biz-cover-photo":"Image"},Toe=Object.keys(J2),nce=12e4,Gf=5,sce=812,gce=3e4,bH={Minute:60*1e3,Hour:3600*1e3,Day:1440*60*1e3,Week:10080*60*1e3};var cce=Je(Lr(),1);import{createHash as M5e}from"crypto";import{createWriteStream as _5e,promises as T5e}from"fs";import{tmpdir as N5e}from"os";import{join as R5e}from"path";var Ice=n=>{let t=le(n,"product_catalog"),o=kA(t,"product").map(Ff),i=le(t,"paging");return{products:o,nextPageCursor:i?YA(i,"after"):void 0}},lce=n=>{let t=le(n,"collections");return{collections:kA(t,"collection").map(i=>{let e=YA(i,"id"),a=YA(i,"name"),A=kA(i,"product").map(Ff);return{id:e,name:a,products:A,status:P5e(i)}})}},pce=n=>{let t=le(n,"order"),o=kA(t,"product").map(a=>{let A=le(a,"image");return{id:YA(a,"id"),name:YA(a,"name"),imageUrl:YA(A,"url"),price:+YA(a,"price"),currency:YA(a,"currency"),quantity:+YA(a,"quantity")}}),i=le(t,"price");return{price:{total:+YA(i,"total"),currency:YA(i,"currency")},products:o}},MH=(n,t)=>{let o={},i=[];return typeof n<"u"&&i.push({tag:"id",attrs:{},content:Buffer.from(n)}),typeof t.name<"u"&&i.push({tag:"name",attrs:{},content:Buffer.from(t.name)}),typeof t.description<"u"&&i.push({tag:"description",attrs:{},content:Buffer.from(t.description)}),typeof t.retailerId<"u"&&i.push({tag:"retailer_id",attrs:{},content:Buffer.from(t.retailerId)}),t.images.length&&i.push({tag:"media",attrs:{},content:t.images.map(a=>{if(!("url"in a))throw new cce.Boom("Expected img for product to already be uploaded",{statusCode:400});return{tag:"image",attrs:{},content:[{tag:"url",attrs:{},content:Buffer.from(a.url.toString())}]}})}),typeof t.price<"u"&&i.push({tag:"price",attrs:{},content:Buffer.from(t.price.toString())}),typeof t.currency<"u"&&i.push({tag:"currency",attrs:{},content:Buffer.from(t.currency)}),"originCountryCode"in t&&(typeof t.originCountryCode>"u"?o.compliance_category="COUNTRY_ORIGIN_EXEMPT":i.push({tag:"compliance_info",attrs:{},content:[{tag:"country_code_origin",attrs:{},content:Buffer.from(t.originCountryCode)}]})),typeof t.isHidden<"u"&&(o.is_hidden=t.isHidden.toString()),{tag:"product",attrs:o,content:i}},Ff=n=>{let t=n.attrs.is_hidden==="true",o=YA(n,"id"),i=le(n,"media"),e=le(n,"status_info");return{id:o,imageUrls:v5e(i),reviewStatus:{whatsapp:YA(e,"status")},availability:"in stock",name:YA(n,"name"),retailerId:YA(n,"retailer_id"),url:YA(n,"url"),description:YA(n,"description"),price:+YA(n,"price"),currency:YA(n,"currency"),isHidden:t}};async function _H(n,t,o=3e4){return n={...n,images:n.images?await k5e(n.images,t,o):n.images},n}var k5e=async(n,t,o=3e4)=>await Promise.all(n.map(async e=>{if("url"in e){let I=e.url.toString();if(I.includes(".whatsapp.net"))return{url:I}}let{stream:a}=await Ef(e),A=M5e("sha256"),r=R5e(N5e(),"img"+Kr()),s=_5e(r);for await(let I of a)A.update(I),s.write(I);let g=A.digest("base64"),{directPath:c}=await t(r,{mediaType:"product-catalog-image",fileEncSha256B64:g,timeoutMs:o});return await T5e.unlink(r).catch(I=>console.log("Error deleting temp file ",I)),{url:Cf(c)}})),v5e=n=>{let t=le(n,"image");return{requested:YA(t,"request_image_url"),original:YA(t,"original_image_url")}},P5e=n=>{let t=le(n,"status_info");return{status:YA(t,"status"),canAppeal:YA(t,"can_appeal")==="true"}};var Uf=Je(Lr(),1);import{randomBytes as PH}from"crypto";var rn=null;try{rn=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function kt(n,t,o){this.low=n|0,this.high=t|0,this.unsigned=!!o}kt.prototype.__isLong__;Object.defineProperty(kt.prototype,"__isLong__",{value:!0});function $a(n){return(n&&n.__isLong__)===!0}function dce(n){var t=Math.clz32(n&-n);return n?31-t:t}kt.isLong=$a;var hce={},Ece={};function cp(n,t){var o,i,e;return t?(n>>>=0,(e=0<=n&&n<256)&&(i=Ece[n],i)?i:(o=yt(n,0,!0),e&&(Ece[n]=o),o)):(n|=0,(e=-128<=n&&n<128)&&(i=hce[n],i)?i:(o=yt(n,n<0?-1:0,!1),e&&(hce[n]=o),o))}kt.fromInt=cp;function an(n,t){if(isNaN(n))return t?Wg:Hn;if(t){if(n<0)return Wg;if(n>=fce)return mce}else{if(n<=-uce)return Yi;if(n+1>=uce)return yce}return n<0?an(-n,t).neg():yt(n%hE|0,n/hE|0,t)}kt.fromNumber=an;function yt(n,t,o){return new kt(n,t,o)}kt.fromBits=yt;var zb=Math.pow;function NH(n,t,o){if(n.length===0)throw Error("empty string");if(typeof t=="number"?(o=t,t=!1):t=!!t,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return t?Wg:Hn;if(o=o||10,o<2||360)throw Error("interior hyphen");if(i===0)return NH(n.substring(1),t,o).neg();for(var e=an(zb(o,8)),a=Hn,A=0;A>>0:this.low};Fe.toNumber=function(){return this.unsigned?(this.high>>>0)*hE+(this.low>>>0):this.high*hE+(this.low>>>0)};Fe.toString=function(t){if(t=t||10,t<2||36>>0,c=g.toString(t);if(A=s,A.isZero())return c+r;for(;c.length<6;)c="0"+c;r=""+c+r}};Fe.getHighBits=function(){return this.high};Fe.getHighBitsUnsigned=function(){return this.high>>>0};Fe.getLowBits=function(){return this.low};Fe.getLowBitsUnsigned=function(){return this.low>>>0};Fe.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Yi)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,o=31;o>0&&(t&1<>21;return t?this.unsigned?!1:t===-1&&!(this.low===0&&this.high===-2097152):!0};Fe.isZero=function(){return this.high===0&&this.low===0};Fe.eqz=Fe.isZero;Fe.isNegative=function(){return!this.unsigned&&this.high<0};Fe.isPositive=function(){return this.unsigned||this.high>=0};Fe.isOdd=function(){return(this.low&1)===1};Fe.isEven=function(){return(this.low&1)===0};Fe.equals=function(t){return $a(t)||(t=on(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};Fe.eq=Fe.equals;Fe.notEquals=function(t){return!this.eq(t)};Fe.neq=Fe.notEquals;Fe.ne=Fe.notEquals;Fe.lessThan=function(t){return this.comp(t)<0};Fe.lt=Fe.lessThan;Fe.lessThanOrEqual=function(t){return this.comp(t)<=0};Fe.lte=Fe.lessThanOrEqual;Fe.le=Fe.lessThanOrEqual;Fe.greaterThan=function(t){return this.comp(t)>0};Fe.gt=Fe.greaterThan;Fe.greaterThanOrEqual=function(t){return this.comp(t)>=0};Fe.gte=Fe.greaterThanOrEqual;Fe.ge=Fe.greaterThanOrEqual;Fe.compare=function(t){if($a(t)||(t=on(t)),this.eq(t))return 0;var o=this.isNegative(),i=t.isNegative();return o&&!i?-1:!o&&i?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};Fe.comp=Fe.compare;Fe.negate=function(){return!this.unsigned&&this.eq(Yi)?Yi:this.not().add(dE)};Fe.neg=Fe.negate;Fe.add=function(t){$a(t)||(t=on(t));var o=this.high>>>16,i=this.high&65535,e=this.low>>>16,a=this.low&65535,A=t.high>>>16,r=t.high&65535,s=t.low>>>16,g=t.low&65535,c=0,I=0,d=0,B=0;return B+=a+g,d+=B>>>16,B&=65535,d+=e+s,I+=d>>>16,d&=65535,I+=i+r,c+=I>>>16,I&=65535,c+=o+A,c&=65535,yt(d<<16|B,c<<16|I,this.unsigned)};Fe.subtract=function(t){return $a(t)||(t=on(t)),this.add(t.neg())};Fe.sub=Fe.subtract;Fe.multiply=function(t){if(this.isZero())return this;if($a(t)||(t=on(t)),rn){var o=rn.mul(this.low,this.high,t.low,t.high);return yt(o,rn.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Wg:Hn;if(this.eq(Yi))return t.isOdd()?Yi:Hn;if(t.eq(Yi))return this.isOdd()?Yi:Hn;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Bce)&&t.lt(Bce))return an(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,e=this.high&65535,a=this.low>>>16,A=this.low&65535,r=t.high>>>16,s=t.high&65535,g=t.low>>>16,c=t.low&65535,I=0,d=0,B=0,f=0;return f+=A*c,B+=f>>>16,f&=65535,B+=a*c,d+=B>>>16,B&=65535,B+=A*g,d+=B>>>16,B&=65535,d+=e*c,I+=d>>>16,d&=65535,d+=a*g,I+=d>>>16,d&=65535,d+=A*s,I+=d>>>16,d&=65535,I+=i*c+e*g+a*s+A*r,I&=65535,yt(B<<16|f,I<<16|d,this.unsigned)};Fe.mul=Fe.multiply;Fe.divide=function(t){if($a(t)||(t=on(t)),t.isZero())throw Error("division by zero");if(rn){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var o=(this.unsigned?rn.div_u:rn.div_s)(this.low,this.high,t.low,t.high);return yt(o,rn.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Wg:Hn;var i,e,a;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Wg;if(t.gt(this.shru(1)))return Qce;a=Wg}else{if(this.eq(Yi)){if(t.eq(dE)||t.eq(TH))return Yi;if(t.eq(Yi))return dE;var A=this.shr(1);return i=A.div(t).shl(1),i.eq(Hn)?t.isNegative()?dE:TH:(e=this.sub(t.mul(i)),a=i.add(e.div(t)),a)}else if(t.eq(Yi))return this.unsigned?Wg:Hn;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();a=Hn}for(e=this;e.gte(t);){i=Math.max(1,Math.floor(e.toNumber()/t.toNumber()));for(var r=Math.ceil(Math.log(i)/Math.LN2),s=r<=48?1:zb(2,r-48),g=an(i),c=g.mul(t);c.isNegative()||c.gt(e);)i-=s,g=an(i,this.unsigned),c=g.mul(t);g.isZero()&&(g=dE),a=a.add(g),e=e.sub(c)}return a};Fe.div=Fe.divide;Fe.modulo=function(t){if($a(t)||(t=on(t)),rn){var o=(this.unsigned?rn.rem_u:rn.rem_s)(this.low,this.high,t.low,t.high);return yt(o,rn.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};Fe.mod=Fe.modulo;Fe.rem=Fe.modulo;Fe.not=function(){return yt(~this.low,~this.high,this.unsigned)};Fe.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};Fe.clz=Fe.countLeadingZeros;Fe.countTrailingZeros=function(){return this.low?dce(this.low):dce(this.high)+32};Fe.ctz=Fe.countTrailingZeros;Fe.and=function(t){return $a(t)||(t=on(t)),yt(this.low&t.low,this.high&t.high,this.unsigned)};Fe.or=function(t){return $a(t)||(t=on(t)),yt(this.low|t.low,this.high|t.high,this.unsigned)};Fe.xor=function(t){return $a(t)||(t=on(t)),yt(this.low^t.low,this.high^t.high,this.unsigned)};Fe.shiftLeft=function(t){return $a(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?yt(this.low<>>32-t,this.unsigned):yt(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):yt(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};Fe.shr=Fe.shiftRight;Fe.shiftRightUnsigned=function(t){return $a(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?yt(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?yt(this.high,0,this.unsigned):yt(this.high>>>t-32,0,this.unsigned)};Fe.shru=Fe.shiftRightUnsigned;Fe.shr_u=Fe.shiftRightUnsigned;Fe.rotateLeft=function(t){var o;return $a(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?yt(this.high,this.low,this.unsigned):t<32?(o=32-t,yt(this.low<>>o,this.high<>>o,this.unsigned)):(t-=32,o=32-t,yt(this.high<>>o,this.low<>>o,this.unsigned))};Fe.rotl=Fe.rotateLeft;Fe.rotateRight=function(t){var o;return $a(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?yt(this.high,this.low,this.unsigned):t<32?(o=32-t,yt(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,o=32-t,yt(this.low<>>t,this.high<>>t,this.unsigned))};Fe.rotr=Fe.rotateRight;Fe.toSigned=function(){return this.unsigned?yt(this.low,this.high,!1):this};Fe.toUnsigned=function(){return this.unsigned?this:yt(this.low,this.high,!0)};Fe.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};Fe.toBytesLE=function(){var t=this.high,o=this.low;return[o&255,o>>>8&255,o>>>16&255,o>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};Fe.toBytesBE=function(){var t=this.high,o=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,o>>>24,o>>>16&255,o>>>8&255,o&255]};kt.fromBytes=function(t,o,i){return i?kt.fromBytesLE(t,o):kt.fromBytesBE(t,o)};kt.fromBytesLE=function(t,o){return new kt(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,o)};kt.fromBytesBE=function(t,o){return new kt(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],o)};typeof BigInt=="function"&&(kt.fromBigInt=function(t,o){var i=Number(BigInt.asIntN(32,t)),e=Number(BigInt.asIntN(32,t>>BigInt(32)));return yt(i,e,o)},kt.fromValue=function(t,o){return typeof t=="bigint"?kt.fromBigInt(t,o):on(t,o)},Fe.toBigInt=function(){var t=BigInt(this.low>>>0),o=BigInt(this.unsigned?this.high>>>0:this.high);return o<{let n=new Jg;return{mutex(t){return n.runExclusive(t)}}},Sce=()=>{let n=new Map;return{async mutex(t,o){let i=n.get(t);i||(i={mutex:new Jg,refCount:0},n.set(t,i)),i.refCount++;try{return await i.mutex.runExclusive(o)}finally{i.refCount--,i.refCount===0&&n.get(t)===i&&n.delete(t)}}}};function wce(n,t,o=10){let i=[],e=!1;return{enqueue:(A,r)=>{if(i.push({type:A,node:r}),e)return;e=!0,(async()=>{let g=0;for(;i.length&&t.isWsOpen();){let{type:c,node:I}=i.shift(),d=n.get(c);if(!d){t.onUnexpectedError(new Error(`unknown offline node type: ${c}`),"processing offline node");continue}await d(I).catch(B=>t.onUnexpectedError(B,`processing offline ${c}`)),g++,g>=o&&(g=0,await t.yieldToEventLoop())}e=!1})().catch(g=>t.onUnexpectedError(g,"processing offline nodes"))}}}var iM=Je(Lr(),1);var CI=Je(Lr(),1);var Vb=class{constructor(){this.name="devices"}getQueryElement(){return{tag:"devices",attrs:{version:"2"}}}getUserElement(){return null}parser(t){let o=[],i;if(t.tag==="devices"){Li(t);let e=le(t,"device-list"),a=le(t,"key-index-list");if(Array.isArray(e?.content))for(let{tag:A,attrs:r}of e.content){let s=+r.id,g=+r["key-index"];A==="device"&&o.push({id:s,keyIndex:g,isHosted:!!(r.is_hosted&&r.is_hosted==="true")})}a?.tag==="key-index-list"&&(i={timestamp:+a.attrs.ts,signedKeyIndex:a?.content,expectedTimestamp:a.attrs.expected_ts?+a.attrs.expected_ts:void 0})}return{deviceList:o,keyIndex:i}}};var Vs=class{withId(t){return this.id=t,this}withLid(t){return this.lid=t,this}withPhone(t){return this.phone=t,this}withUsername(t){return this.username=t,this}withUsernameKey(t){return this.usernameKey=t,this}withType(t){return this.type=t,this}withPersonaId(t){return this.personaId=t,this}};var Wb=class{constructor(){this.name="contact"}getQueryElement(){return{tag:"contact",attrs:{}}}getUserElement(t){return t.phone?{tag:"contact",attrs:{},content:t.phone}:t.username?{tag:"contact",attrs:{username:t.username,...t.usernameKey?{pin:t.usernameKey}:{},...t.lid?{lid:t.lid}:{}}}:t.type?{tag:"contact",attrs:{type:t.type}}:{tag:"contact",attrs:{}}}parser(t){return t.tag==="contact"?(Li(t),t?.attrs?.type==="in"):!1}};var Zb=class{constructor(){this.name="status"}getQueryElement(){return{tag:"status",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="status"){Li(t);let o=t?.content?.toString()??null,i=new Date(+(t?.attrs.t||0)*1e3);return o?typeof o=="string"&&o.length===0&&(o=null):t.attrs?.code&&+t.attrs.code==401?o="":o=null,{status:o,setAt:i}}}};var Xb=class{constructor(){this.name="disappearing_mode"}getQueryElement(){return{tag:"disappearing_mode",attrs:{}}}getUserElement(){return null}parser(t){if(t.tag==="disappearing_mode"){Li(t);let o=+t?.attrs.duration,i=new Date(+(t?.attrs.t||0)*1e3);return{duration:o,setAt:i}}}};var $b=class{constructor(){this.name="username"}getQueryElement(){return{tag:"username",attrs:{}}}getUserElement(t){return null}parser(t){return t.tag==="username"?(Li(t),typeof t.content=="string"?t.content:null):null}};var eM=class{constructor(){this.name="bot"}getQueryElement(){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{v:"1"}}]}}getUserElement(t){return{tag:"bot",attrs:{},content:[{tag:"profile",attrs:{persona_id:t.personaId}}]}}parser(t){let o=le(t,"bot"),i=le(o,"profile"),e=le(i,"commands"),a=le(i,"prompts"),A=[],r=[];for(let s of kA(e,"command"))A.push({name:YA(s,"name"),description:YA(s,"description")});for(let s of kA(a,"prompt"))r.push(`${YA(s,"emoji")} ${YA(s,"text")}`);return{isDefault:!!le(i,"default"),jid:t.attrs.jid,name:YA(i,"name"),attributes:YA(i,"attributes"),description:YA(i,"description"),category:YA(i,"category"),personaId:i.attrs.persona_id,commandsDescription:YA(e,"description"),commands:A,prompts:r}}};var AM=class{constructor(){this.name="lid"}getQueryElement(){return{tag:"lid",attrs:{}}}getUserElement(t){return t.lid?{tag:"lid",attrs:{jid:t.lid}}:null}parser(t){return t.tag==="lid"?t.attrs.val:null}};var Ws=class{constructor(){this.protocols=[],this.users=[],this.context="interactive",this.mode="query"}withMode(t){return this.mode=t,this}withContext(t){return this.context=t,this}withUser(t){return this.users.push(t),this}parseUSyncQueryResult(t){if(t?.attrs.type!=="result")return;let o=Object.fromEntries(this.protocols.map(A=>[A.name,A.parser])),i={list:[],sideList:[]},e=le(t,"usync"),a=e?le(e,"list"):void 0;return a?.content&&Array.isArray(a.content)&&(i.list=a.content.reduce((A,r)=>{let s=r?.attrs.jid;if(s){let g=Array.isArray(r?.content)?Object.fromEntries(r.content.map(c=>{let I=c.tag,d=o[I];return d?[I,d(c)]:[I,null]}).filter(([,c])=>c!==null)):{};A.push({...g,id:s})}return A},[])),i}withDeviceProtocol(){return this.protocols.push(new Vb),this}withContactProtocol(){return this.protocols.push(new Wb),this}withStatusProtocol(){return this.protocols.push(new Zb),this}withDisappearingModeProtocol(){return this.protocols.push(new Xb),this}withBotProfileProtocol(){return this.protocols.push(new eM),this}withLIDProtocol(){return this.protocols.push(new AM),this}withUsernameProtocol(){return this.protocols.push(new $b),this}};var qr=Je(Lr(),1);import{randomBytes as kH}from"crypto";import{URL as U5e}from"url";import{promisify as H5e}from"util";var tM=class{constructor(t={}){this.protocolVersion=5,this.sequence=0,this.events=[],this.buffer=[],Object.assign(this,t)}};import{EventEmitter as F5e}from"events";var rM=class extends F5e{constructor(t,o){super(),this.url=t,this.config=o,this.setMaxListeners(0)}};var aM=class extends rM{constructor(){super(...arguments),this.socket=null}get isOpen(){return this.socket?.readyState===Ro.OPEN}get isClosed(){return this.socket===null||this.socket?.readyState===Ro.CLOSED}get isClosing(){return this.socket===null||this.socket?.readyState===Ro.CLOSING}get isConnecting(){return this.socket?.readyState===Ro.CONNECTING}connect(){if(this.socket)return;this.socket=new Ro(this.url,{origin:uf,headers:this.config.options?.headers,handshakeTimeout:this.config.connectTimeoutMs,timeout:this.config.connectTimeoutMs,agent:this.config.agent}),this.socket.setMaxListeners(0);let t=["close","error","upgrade","message","open","ping","pong","unexpected-response"];for(let o of t)this.socket?.on(o,(...i)=>this.emit(o,...i))}async close(){if(!this.socket)return;let t=new Promise(o=>{this.socket?.once("close",o)});this.socket.close(),await t,this.socket=null}send(t,o){return this.socket?.send(t,o),!!this.socket}};var RH=Je(Lr(),1);var L5e=(n,t,o,i)=>o({tag:"iq",attrs:{id:i(),type:"get",to:OA,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:t},content:Buffer.from(JSON.stringify({variables:n}),"utf-8")}]}),Lf=async(n,t,o,i,e)=>{let a=await L5e(n,t,i,e),A=le(a,"result");if(A?.content){let s=JSON.parse(A.content.toString());if(s.errors&&s.errors.length>0){let c=s.errors.map(B=>B.message||"Unknown error").join(", "),I=s.errors[0],d=I.extensions?.error_code||400;throw new RH.Boom(`GraphQL server error: ${c}`,{statusCode:d,data:I})}let g=o?s?.data?.[o]:s?.data;if(typeof g<"u")return g}let r=(o||"").startsWith("xwa2_")?o.substring(5).replace(/_/g," "):o?.replace(/_/g," ");throw new RH.Boom(`Failed to ${r}, unexpected response structure.`,{statusCode:400,data:a})};var Dce=n=>{let{waWebSocketUrl:t,connectTimeoutMs:o,logger:i,keepAliveIntervalMs:e,browser:a,auth:A,printQRInTerminal:r,defaultQueryTimeoutMs:s,transactionOpts:g,qrTimeout:c,makeSignalRepository:I}=n,d=new tM,B=0,f=S7(),Q=()=>`${f}${fe++}`;r&&i.warn({},"\u26A0\uFE0F The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version."),a[1].toLocaleLowerCase().includes("android")&&i.warn("\u26A0\uFE0F Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk."),Pf.map(pe=>n.shouldSyncHistoryMessage({syncType:pe})).filter(pe=>pe===!1).length===Pf.length&&i.warn("\u26A0\uFE0F DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS");let m=typeof t=="string"?new U5e(t):t;if(n.mobile||m.protocol==="tcp:")throw new qr.Boom("Mobile API is not supported anymore",{statusCode:$t.loggedOut});m.protocol==="wss"&&A?.creds?.routingInfo&&m.searchParams.append("ED",A.creds.routingInfo.toString("base64url"));let _=Br.generateKeyPair(),T=qoe({keyPair:_,NOISE_HEADER:ice,logger:i,routingInfo:A?.creds?.routingInfo}),R=new aM(m,n);R.connect();let L=H5e(R.send),U=async pe=>{if(!R.isOpen)throw new qr.Boom("Connection Closed",{statusCode:$t.connectionClosed});let Ie=T.encodeFrame(pe);await Ih(o,async(be,oA)=>{try{await L.call(R,Ie),be()}catch(dA){oA(dA)}})},F=pe=>{i.level==="trace"&&i.trace({xml:_n(pe),msg:"xml send"});let Ie=KX(pe);return U(Ie)},q=async(pe,Ie=s)=>{let be,oA;try{return await Ih(Ie,(PA,Ht)=>(be=st=>{PA(st)},oA=st=>{Ht(st||new qr.Boom("Connection Closed",{statusCode:$t.connectionClosed}))},R.on(`TAG:${pe}`,be),R.on("close",oA),R.on("error",oA),()=>Ht(new qr.Boom("Query Cancelled"))))}catch(dA){if(dA instanceof qr.Boom&&dA.output?.statusCode===$t.timedOut){i?.warn?.({msgId:pe},"timed out waiting for message");return}throw dA}finally{be&&R.off(`TAG:${pe}`,be),oA&&(R.off("close",oA),R.off("error",oA))}},z=async(pe,Ie)=>{pe.attrs.id||(pe.attrs.id=Q());let be=pe.attrs.id,oA=await Ih(Ie,async(dA,PA)=>{let Ht=q(be,Ie).catch(PA);F(pe).then(async()=>dA(await Ht)).catch(PA)});return oA&&"tag"in oA&&Li(oA),oA},j=async()=>{let pe=await z({tag:"iq",attrs:{to:OA,type:"get",xmlns:"encrypt"},content:[{tag:"digest",attrs:{}}]});if(!le(pe,"digest"))throw await We(),new Error("encrypt/get digest returned no digest node")},P=async()=>{let pe=(V.signedPreKey.keyId||0)+1,Ie=await aD(V.signedIdentityKey,pe);await z({tag:"iq",attrs:{to:OA,type:"set",xmlns:"encrypt"},content:[{tag:"rotate",attrs:{},content:[yf(Ie)]}]}),k.emit("creds.update",{signedPreKey:Ie})},J=async pe=>{if(pe.protocols.length===0)throw new qr.Boom("USyncQuery must have at least one protocol");let be=pe.users.map(st=>({tag:"user",attrs:{jid:st.phone?void 0:st.id},content:pe.protocols.map(Qr=>Qr.getUserElement(st)).filter(Qr=>Qr!==null)})),oA={tag:"list",attrs:{},content:be},dA={tag:"query",attrs:{},content:pe.protocols.map(st=>st.getQueryElement())},PA={tag:"iq",attrs:{to:OA,type:"get",xmlns:"usync"},content:[{tag:"usync",attrs:{context:pe.context,mode:pe.mode,sid:Q(),last:"true",index:"0"},content:[dA,oA]}]},Ht=await z(PA);return pe.parseUSyncQueryResult(Ht)},H=async(...pe)=>{let Ie=new Ws,be=!1;for(let dA of pe)if(qA(dA)){i?.warn("LIDs are not supported with onWhatsApp");continue}else{be||(be=!0,Ie=Ie.withContactProtocol());let PA=`+${dA.replace("+","").split("@")[0]?.split(":")[0]}`;Ie.withUser(new Vs().withPhone(PA))}if(Ie.users.length===0)return[];let oA=await J(Ie);if(oA)return oA.list.filter(dA=>!!dA.contact).map(({contact:dA,id:PA})=>({jid:PA,exists:dA}))},N=async pe=>{let Ie=new Ws().withLIDProtocol().withContext("background");for(let oA of pe)if(qA(oA)){i?.warn("LID user found in LID fetch call");continue}else Ie.withUser(new Vs().withId(oA));if(Ie.users.length===0)return[];let be=await J(Ie);return be?be.list.filter(oA=>!!oA.lid).map(({lid:oA,id:dA})=>({pn:dA,lid:oA})):[]},k=bne(i),{creds:V}=A,Ae=Bne(A.keys,i,g),ie=I({creds:V,keys:Ae},i,N),De,fe=1,_e,Ee,Qe=!1,Le=[],AA=(pe,Ie)=>{i.error({err:pe},`unexpected error in '${Ie}'`)},aA=async pe=>{if(!R.isOpen)throw new qr.Boom("Connection Closed",{statusCode:$t.connectionClosed});let Ie,be,oA=Ih(o,(dA,PA)=>{Ie=dA,be=vH(PA),R.on("frame",Ie),R.on("close",be),R.on("error",be)}).finally(()=>{R.off("frame",Ie),R.off("close",be),R.off("error",be)});return pe&&U(pe).catch(be),oA},He=async()=>{let pe={clientHello:{ephemeral:_.public}};pe=oe.HandshakeMessage.fromObject(pe),i.info({browser:a,helloMsg:pe},"connected to WA");let Ie=oe.HandshakeMessage.encode(pe).finish(),be=await aA(Ie),oA=oe.HandshakeMessage.decode(be);i.trace({handshake:oA},"handshake recv from WA");let dA=T.processHandshake(oA,V.noiseKey),PA;V.me?(PA=Loe(V.me.id,n),i.info({node:PA},"logging in...")):(PA=Uoe(V,n),i.info({node:PA},"not logged in, attempting registration..."));let Ht=T.encrypt(oe.ClientPayload.encode(PA).finish());await U(oe.HandshakeMessage.encode({clientFinish:{static:dA,payload:Ht}}).finish()),await T.finishInit(),WA()},ce=async()=>{let pe=await z({tag:"iq",attrs:{id:Q(),xmlns:"encrypt",type:"get",to:OA},content:[{tag:"count",attrs:{}}]});return+le(pe,"count").attrs.value},Be=null,We=async(pe=Gf)=>{if(Be){i.debug("Pre-key upload already in progress, waiting for completion"),await Be;return}let Ie=async be=>{i.info({count:pe,retryCount:be},"uploading pre-keys");let oA=await Ae.transaction(async()=>{i.debug({requestedCount:pe},"generating pre-keys with requested count");let{update:dA,node:PA}=await Poe({creds:V,keys:Ae},pe);return k.emit("creds.update",dA),PA},V?.me?.id||"upload-pre-keys");try{await z(oA),i.info({count:pe},"uploaded pre-keys successfully")}catch(dA){if(i.error({uploadError:dA.toString(),count:pe},"Failed to upload pre-keys to server"),be<3){let PA=Math.min(1e3*Math.pow(2,be),1e4);return i.info(`Retrying pre-key upload in ${PA}ms`),await new Promise(Ht=>setTimeout(Ht,PA)),Ie(be+1)}throw dA}};Be=Promise.race([Ie(0),new Promise((be,oA)=>setTimeout(()=>oA(new qr.Boom("Pre-key upload timeout",{statusCode:408})),gce))]);try{await Be}finally{Be=null}},Ye=async()=>{let pe=V.nextPreKeyId-1;return pe<=0?{exists:!1,currentPreKeyId:0}:{exists:!!(await Ae.get("pre-key",[pe.toString()]))[pe.toString()],currentPreKeyId:pe}},Re=async()=>{try{let pe=0,Ie=await ce();Ie===0?pe=sce:pe=Gf;let{exists:be,currentPreKeyId:oA}=await Ye();i.info(`${Ie} pre-keys found on server`),i.info(`Current prekey ID: ${oA}, exists in storage: ${be}`);let dA=Ie<=pe,PA=!be&&oA>0;if(dA||PA){let st=[];dA&&st.push(`server count low (${Ie})`),PA&&st.push(`current prekey ${oA} missing from storage`),i.info(`Uploading PreKeys due to: ${st.join(", ")}`),await We(pe)}else i.info(`PreKey validation passed - Server: ${Ie}, Current prekey ${oA} exists`)}catch(pe){i.error({error:pe},"Failed to check/upload pre-keys during initialization")}},Ze=async pe=>{await T.decodeFrame(pe,Ie=>{De=new Date;let be=!1;if(be=R.emit("frame",Ie),!(Ie instanceof Uint8Array)){let oA=Ie.attrs.id;i.level==="trace"&&i.trace({xml:_n(Ie),msg:"recv xml"}),be=R.emit(`${tce}${oA}`,Ie)||be;let dA=Ie.tag,PA=Ie.attrs||{},Ht=Array.isArray(Ie.content)?Ie.content[0]?.tag:"";for(let st of Object.keys(PA))be=R.emit(`${pE}${dA},${st}:${PA[st]},${Ht}`,Ie)||be,be=R.emit(`${pE}${dA},${st}:${PA[st]}`,Ie)||be,be=R.emit(`${pE}${dA},${st}`,Ie)||be;be=R.emit(`${pE}${dA},,${Ht}`,Ie)||be,be=R.emit(`${pE}${dA}`,Ie)||be,!be&&i.level==="debug"&&i.debug({unhandled:!0,msgId:oA,fromMe:!1,frame:Ie},"communication recv")}})},iA=async pe=>{if(Qe){i.trace({trace:pe?.stack},"connection already closed");return}if(Qe=!0,i.info({trace:pe?.stack},pe?"connection errored":"connection closed"),clearInterval(_e),clearTimeout(Ee),R.removeAllListeners("close"),R.removeAllListeners("open"),R.removeAllListeners("message"),ie.close?.(),!R.isClosed&&!R.isClosing)try{await R.close()}catch{}for(let Ie of Le)try{await Ie(pe)}catch(be){i.error({err:be},"error in socket end handler")}k.emit("connection.update",{connection:"close",lastDisconnect:{error:pe,date:new Date}}),k.removeAllListeners("connection.update"),k.destroy()},gA=async()=>{if(R.isOpen)return;if(R.isClosed||R.isClosing)throw new qr.Boom("Connection Closed",{statusCode:$t.connectionClosed});let pe,Ie;await new Promise((be,oA)=>{pe=()=>be(void 0),Ie=vH(oA),R.on("open",pe),R.on("close",Ie),R.on("error",Ie)}).finally(()=>{R.off("open",pe),R.off("close",Ie),R.off("error",Ie)})},WA=()=>_e=setInterval(()=>{De||(De=new Date),Date.now()-De.getTime()>e+5e3?iA(new qr.Boom("Connection was lost",{statusCode:$t.connectionLost})):R.isOpen?z({tag:"iq",attrs:{id:Q(),to:OA,type:"get",xmlns:"w:p"},content:[{tag:"ping",attrs:{}}]}).catch(Ie=>{i.error({trace:Ie.stack},"error in sending keep alive")}):i.warn("keep alive called when WS not open")},e),FA=pe=>z({tag:"iq",attrs:{to:OA,xmlns:"passive",type:"set"},content:[{tag:pe,attrs:{}}]}),Me=async pe=>{let Ie=A.creds.me?.id;Ie&&await F({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"remove-companion-device",attrs:{jid:Ie,reason:"user_initiated"}}]}),iA(new qr.Boom(pe||"Intentional Logout",{statusCode:$t.loggedOut}))},CA=async(pe,Ie)=>{let be=Ie??M7(kH(5));if(Ie&&Ie?.length!==8)throw new Error("Custom pairing code must be exactly 8 chars");return A.creds.pairingCode=be,A.creds.me={id:Cr(pe,"s.whatsapp.net"),name:"~"},k.emit("creds.update",A.creds),await F({tag:"iq",attrs:{to:OA,type:"set",id:Q(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:A.creds.me.id,stage:"companion_hello",should_show_push_notification:"true"},content:[{tag:"link_code_pairing_wrapped_companion_ephemeral_pub",attrs:{},content:await we()},{tag:"companion_server_auth_key_pub",attrs:{},content:A.creds.noiseKey.public},{tag:"companion_platform_id",attrs:{},content:TU(a)},{tag:"companion_platform_display",attrs:{},content:`${a[1]} (${a[0]})`},{tag:"link_code_pairing_nonce",attrs:{},content:"0"}]}]}),A.creds.pairingCode};async function we(){let pe=kH(32),Ie=kH(16),be=await iD(A.creds.pairingCode,pe),oA=l7(A.creds.pairingEphemeralKeyPair.public,be,Ie);return Buffer.concat([pe,Ie,oA])}let Ke=pe=>z({tag:"iq",attrs:{to:OA,id:Q(),xmlns:"w:stats"},content:[{tag:"add",attrs:{t:Math.round(Date.now()/1e3)+""},content:pe}]});R.on("message",Ze),R.on("open",async()=>{try{await He()}catch(pe){i.error({err:pe},"error in validating connection"),iA(pe)}}),R.on("error",vH(iA)),R.on("close",()=>void iA(new qr.Boom("Connection Terminated",{statusCode:$t.connectionClosed}))),R.on("CB:xmlstreamend",()=>void iA(new qr.Boom("Connection Terminated by Server",{statusCode:$t.connectionClosed}))),R.on("CB:iq,type:set,pair-device",async pe=>{let Ie={tag:"iq",attrs:{to:OA,type:"result",id:pe.attrs.id}};await F(Ie);let be=le(pe,"pair-device"),oA=kA(be,"ref"),dA=Buffer.from(V.noiseKey.public).toString("base64"),PA=Buffer.from(V.signedIdentityKey.public).toString("base64"),Ht=V.advSecretKey,st=c||6e4,Qr=()=>{if(!R.isOpen)return;let tr=oA.shift();if(!tr){iA(new qr.Boom("QR refs attempts ended",{statusCode:$t.timedOut}));return}let lo=tr.content.toString("utf-8"),ji=Tne(lo,dA,PA,Ht,a);k.emit("connection.update",{qr:ji}),Ee=setTimeout(Qr,st),st=c||2e4};Qr()}),R.on("CB:iq,,pair-success",async pe=>{i.debug("pair success recv");try{NA(pe);let{reply:Ie,creds:be}=Hoe(pe,V);i.info({me:be.me,platform:be.platform},"pairing configured successfully, expect to restart the connection..."),k.emit("creds.update",be),k.emit("connection.update",{isNewLogin:!0,qr:void 0}),await F(Ie),LA()}catch(Ie){i.info({trace:Ie.stack},"error in pairing"),iA(Ie)}}),R.on("CB:success",async pe=>{try{NA(pe),await Re(),await FA("active");try{await j()}catch(Ie){i.warn({e:Ie},"failed to run digest after login")}}catch(Ie){i.warn({err:Ie},"failed to send initial passive iq")}if(i.info("opened connection to WA"),clearTimeout(Ee),k.emit("creds.update",{me:{...A.creds.me,lid:pe.attrs.lid}}),k.emit("connection.update",{connection:"open"}),LA(),pe.attrs.lid&&A.creds.me?.id){let Ie=pe.attrs.lid;process.nextTick(async()=>{try{let be=A.creds.me.id;await ie.lidMapping.storeLIDPNMappings([{lid:Ie,pn:be}]);let{user:oA,device:dA}=yA(be);await A.keys.set({"device-list":{[oA]:[dA?.toString()||"0"]}}),await ie.migrateSession(be,Ie),i.info({myPN:be,myLID:Ie},"Own LID session created successfully")}catch(be){i.error({error:be,lid:Ie},"Failed to create own LID session")}})}}),R.on("CB:stream:error",pe=>{let[Ie]=ys(pe);i.error({reasonNode:Ie,fullErrorNode:pe},"stream errored out");let{reason:be,statusCode:oA}=D7(pe);iA(new qr.Boom(`Stream Errored (${be})`,{statusCode:oA,data:Ie||pe}))}),R.on("CB:failure",pe=>{let Ie=+(pe.attrs.reason||500);iA(new qr.Boom("Connection Failure",{statusCode:Ie,data:pe.attrs}))}),R.on("CB:ib,,downgrade_webclient",()=>{iA(new qr.Boom("Multi-device beta not joined",{statusCode:$t.multideviceMismatch}))}),R.on("CB:ib,,offline_preview",async pe=>{i.info("offline preview received",JSON.stringify(pe)),await F({tag:"ib",attrs:{},content:[{tag:"offline_batch",attrs:{count:"100"}}]})}),R.on("CB:ib,,edge_routing",pe=>{let Ie=le(pe,"edge_routing"),be=le(Ie,"routing_info");be?.content&&(A.creds.routingInfo=Buffer.from(be?.content),k.emit("creds.update",A.creds))});let Ve=!1;process.nextTick(()=>{V.me?.id&&(k.buffer(),Ve=!0),k.emit("connection.update",{connection:"connecting",receivedPendingNotifications:!1,qr:void 0})}),R.on("CB:ib,,offline",pe=>{let be=+(le(pe,"offline")?.attrs.count||0);i.info(`handled ${be} offline messages/notifications`),Ve&&(k.flush(),i.trace("flushed events for initial buffer")),k.emit("connection.update",{receivedPendingNotifications:!0})}),k.on("creds.update",pe=>{let Ie=pe.me?.name;V.me?.name!==Ie&&(i.debug({name:Ie},"updated pushName"),F({tag:"presence",attrs:{name:Ie}}).catch(be=>{i.warn({trace:be.stack},"error in sending presence update on name change")})),Object.assign(V,pe)});let NA=({attrs:pe})=>{let Ie=pe?.t;if(!Ie)return;let be=Number(Ie);if(Number.isNaN(be)||be<=0)return;let oA=Date.now();B=be*1e3-oA,i.debug({offset:B},"calculated server time offset")},wA=()=>{let pe=3*bH.Day;return((Date.now()+B+pe)%bH.Week).toString()},LA=async()=>{if(!R.isOpen)return;let pe={tag:"ib",attrs:{},content:[{tag:"unified_session",attrs:{id:wA()}}]};try{await F(pe)}catch(Ie){i.debug({error:Ie},"failed to send unified_session telemetry")}},JA=pe=>{Le.push(pe)},lt=async()=>{let pe=await Lf({},sa.REACHOUT_TIMELOCK,fa.xwa2_fetch_account_reachout_timelock,z,Q),Ie={isActive:!!pe?.is_active,timeEnforcementEnds:pe?.time_enforcement_ends&&pe?.time_enforcement_ends!=="0"?new Date(parseInt(pe.time_enforcement_ends,10)*1e3):void 0,enforcementType:pe?.enforcement_type??Hc.DEFAULT};return k.emit("connection.update",{reachoutTimeLock:Ie}),Ie},wt=async()=>Lf({input:{type:"INDIVIDUAL_NEW_CHAT_MSG"}},sa.MESSAGE_CAPPING_INFO,fa.xwa2_message_capping_info,z,Q);return{type:"md",ws:R,ev:k,authState:{creds:V,keys:Ae},signalRepository:ie,get user(){return A.creds.me},generateMessageTag:Q,query:z,waitForMessage:q,waitForSocketOpen:gA,sendRawMessage:U,sendNode:F,logout:Me,end:iA,registerSocketEndHandler:JA,onUnexpectedError:AA,uploadPreKeys:We,uploadPreKeysToServerIfRequired:Re,digestKeyBundle:j,rotateSignedPreKey:P,requestPairingCode:CA,updateServerTimeOffset:NA,sendUnifiedSession:LA,wamBuffer:d,waitForConnectionUpdate:m7(k),sendWAMBuffer:Ke,executeUSyncQuery:J,onWhatsApp:H,fetchAccountReachoutTimelock:lt,fetchNewChatMessageCap:wt}};function vH(n){return t=>{n(new qr.Boom(`WebSocket Error (${t?.message})`,{statusCode:b7(t),data:t}))}}var K5e=(n,t)=>{let o={tag:"picture",attrs:{type:n,query:"url"}};return t?.length&&(o.content=t),[o]},Oce=n=>{let{logger:t,markOnlineOnConnect:o,fireInitQueries:i,appStateMacVerification:e,shouldIgnoreJid:a,shouldSyncHistoryMessage:A,getMessage:r}=n,s=Dce(n),{ev:g,ws:c,authState:I,generateMessageTag:d,sendNode:B,query:f,signalRepository:Q,onUnexpectedError:y,sendUnifiedSession:m,registerSocketEndHandler:_}=s,T=Q.lidMapping.getLIDForPN.bind(Q.lidMapping),R,L={privacyTokenOn1to1:!0,profilePicPrivacyToken:!0,lidTrustedTokenIssueToLid:!1},U=na.Connecting,F=Zg(),q=Zg(),z=Zg(),j=Zg(),P,J={initialBootstrapComplete:!1,recentSyncComplete:!1},H,N=new Set,k=n.placeholderResendCache||new jg({stdTTL:dI.MSG_RETRY,useClones:!1}),V=async W=>{let{[W]:X}=await I.keys.get("app-state-sync-key",[W]);return X},Ae=async(W=!1)=>{if(!R||W){let{content:X}=await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"get"},content:[{tag:"privacy",attrs:{}}]});R=fF(X?.[0],"category")}return R},ie=async(W,X)=>{await f({tag:"iq",attrs:{xmlns:"privacy",to:OA,type:"set"},content:[{tag:"privacy",attrs:{},content:[{tag:"category",attrs:{name:W,value:X}}]}]})},De=async W=>{await ie("messages",W)},fe=async W=>{await ie("calladd",W)},_e=async W=>{await ie("last",W)},Ee=async W=>{await ie("online",W)},Qe=async W=>{await ie("profile",W)},Le=async W=>{await ie("status",W)},AA=async W=>{await ie("readreceipts",W)},aA=async W=>{await ie("groupadd",W)},He=async W=>{await f({tag:"iq",attrs:{xmlns:"disappearing_mode",to:OA,type:"set"},content:[{tag:"disappearing_mode",attrs:{duration:W.toString()}}]})},ce=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"bot",to:OA,type:"get"},content:[{tag:"bot",attrs:{v:"2"}}]}),X=le(W,"bot"),re=[];for(let ne of kA(X,"section"))if(ne.attrs.type==="all")for(let Oe of kA(ne,"bot"))re.push({jid:Oe.attrs.jid,personaId:Oe.attrs.persona_id});return re},Be=async(...W)=>{let X=new Ws().withStatusProtocol();for(let ne of W)X.withUser(new Vs().withId(ne));let re=await s.executeUSyncQuery(X);if(re)return re.list},We=async(...W)=>{let X=new Ws().withDisappearingModeProtocol();for(let ne of W)X.withUser(new Vs().withId(ne));let re=await s.executeUSyncQuery(X);if(re)return re.list},Ye=async(W,X,re)=>{let ne;if(!W)throw new CI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");uA(W)!==uA(I.creds.me.id)?ne=uA(W):ne=void 0;let{img:Oe}=await cb(X,re);await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...ne?{target:ne}:{}},content:[{tag:"picture",attrs:{type:"image"},content:Oe}]})},Re=async W=>{let X;if(!W)throw new CI.Boom("Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update");uA(W)!==uA(I.creds.me.id)?X=uA(W):X=void 0,await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:profile:picture",...X?{target:X}:{}}})},Ze=async W=>{await f({tag:"iq",attrs:{to:OA,type:"set",xmlns:"status"},content:[{tag:"status",attrs:{},content:Buffer.from(W,"utf-8")}]})},iA=async W=>{await wt({pushNameSetting:W},"")},gA=async()=>{let W=await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"get"}}),X=le(W,"list");return kA(X,"item").map(re=>re.attrs.jid)},WA=async(W,X)=>{let re=uA(W),ne,Oe;if(qA(re)||ga(re)){if(ne=re,X==="block"){let he=await Q.lidMapping.getPNForLID(re);if(!he)throw new CI.Boom(`Unable to resolve PN JID for LID: ${W}`,{statusCode:400});Oe=uA(he)}}else if(_t(re)||ur(re)){let he=await Q.lidMapping.getLIDForPN(re);if(!he)throw new CI.Boom(`Unable to resolve LID for PN JID: ${W}`,{statusCode:400});ne=he,X==="block"&&(Oe=uA(re))}else throw new CI.Boom(`Invalid jid: ${W}`,{statusCode:400});let Ce={action:X,jid:ne};if(X==="block"){if(!Oe)throw new CI.Boom(`pn_jid required for block: ${W}`,{statusCode:400});Ce.pn_jid=Oe}await f({tag:"iq",attrs:{xmlns:"blocklist",to:OA,type:"set"},content:[{tag:"item",attrs:Ce}]})},FA=async W=>{let X=await f({tag:"iq",attrs:{to:"s.whatsapp.net",xmlns:"w:biz",type:"get"},content:[{tag:"business_profile",attrs:{v:"244"},content:[{tag:"profile",attrs:{jid:W}}]}]}),re=le(X,"business_profile"),ne=le(re,"profile");if(ne){let Oe=le(ne,"address"),Ce=le(ne,"description"),he=le(ne,"website"),me=le(ne,"email"),je=le(le(ne,"categories"),"category"),lA=le(ne,"business_hours"),QA=lA?kA(lA,"business_hours_config"):void 0,$A=he?.content?.toString();return{wid:ne.attrs?.jid,address:Oe?.content?.toString(),description:Ce?.content?.toString()||"",website:$A?[$A]:[],email:me?.content?.toString(),category:je?.content?.toString(),business_hours:{timezone:lA?.attrs?.timezone,business_config:QA?.map(({attrs:RA})=>RA)}}}},Me=async(W,X)=>{t.info({fromTimestamp:X},"clean dirty bits "+W),await B({tag:"iq",attrs:{to:OA,type:"set",xmlns:"urn:xmpp:whatsapp:dirty",id:d()},content:[{tag:"clean",attrs:{type:W,...X?{timestamp:X.toString()}:null}}]})},CA=W=>({onMutation(X){cne(X,g,I.creds.me,W?{accountSettings:I.creds.accountSettings}:void 0,t)}}),we=g.createBufferedFunction(async(W,X)=>{let re=new Map,ne=async me=>{if(re.has(me))return re.get(me)??void 0;let je=await V(me);return re.set(me,je??null),je},Oe={},Ce={};await I.keys.transaction(async()=>{let me=new Set(W),je={},lA=new Set;for(;me.size;){let QA={},$A=[];for(let et of me){let tA=(await I.keys.get("app-state-sync-version",[et]))[et];tA?(tA=oU(tA),typeof Oe[et]>"u"&&(Oe[et]=tA.version)):tA=Eb(),QA[et]=tA;let At=lA.has(et);At&&lA.delete(et),t.info(`resyncing ${et} from v${tA.version}${At?" (forcing snapshot)":""}`),$A.push({tag:"collection",attrs:{name:et,version:tA.version.toString(),return_snapshot:(At||!tA.version).toString()}})}let RA=await f({tag:"iq",attrs:{to:OA,xmlns:"w:sync:app:state",type:"set"},content:[{tag:"sync",attrs:{},content:$A}]}),xA=await one(RA,n?.options);for(let et in xA){let ve=et,{patches:tA,hasMorePatches:At,snapshot:zr}=xA[ve];try{if(zr){let{state:rr,mutationMap:po}=await sne(ve,zr,ne,Oe[ve],e.snapshot,t);QA[ve]=rr,Object.assign(Ce,po),t.info(`restored state of ${ve} from snapshot to v${rr.version} with mutations`),await I.keys.set({"app-state-sync-version":{[ve]:rr}})}if(tA.length){let{state:rr,mutationMap:po}=await sU(ve,tA,QA[ve],ne,n.options,Oe[ve],t,e.patch);await I.keys.set({"app-state-sync-version":{[ve]:rr}}),t.info(`synced ${ve} to v${rr.version}`),Oe[ve]=rr.version,Object.assign(Ce,po)}At?t.info(`${ve} has more patches...`):me.delete(ve)}catch(rr){je[ve]=(je[ve]||0)+1;let po={name:ve,attempt:je[ve],version:QA[ve].version,statusCode:rr.output?.statusCode,errorType:rr.name,error:rr.stack};wf(rr)&&je[ve]>=nU?(t.warn(po,`${ve} blocked on missing key from v${QA[ve].version}, parking after ${je[ve]} attempts`),N.add(ve),me.delete(ve)):wf(rr)?(t.info(po,`${ve} blocked on missing key from v${QA[ve].version}, retrying with snapshot`),lA.add(ve)):rne(rr,je[ve])?(t.warn(po,`failed to sync ${ve} from v${QA[ve].version}, giving up`),me.delete(ve)):(t.info(po,`failed to sync ${ve} from v${QA[ve].version}, forcing snapshot retry`),lA.add(ve))}}}},I?.creds?.me?.id||"resync-app-state");let{onMutation:he}=CA(X);for(let me in Ce)he(Ce[me])}),Ke=async(W,X="preview",re)=>{let ne=uA(W),Oe=_t(ne)||qA(ne),Ce=I.creds.me,he=Ce&&(ne===uA(Ce.id)||Ce.lid&&ne===uA(Ce.lid)),me;L.profilePicPrivacyToken&&Oe&&!he&&(me=await wU({authState:I,jid:ne,getLIDForPN:T})),W=uA(W);let je=await f({tag:"iq",attrs:{target:W,to:OA,type:"get",xmlns:"w:profile:picture"},content:K5e(X,me)},re);return le(je,"picture")?.attrs?.url},Ve=async(W,X,re)=>{let ne=await f({tag:"call",attrs:{id:d(),to:"@call"},content:[{tag:"link_create",attrs:{media:W},content:X?[{tag:"event",attrs:{start_time:String(X.startTime)}}]:void 0}]},re);return le(ne,"link_create")?.attrs?.token},NA=async(W,X)=>{let re=I.creds.me,ne=W==="available";if(ne||W==="unavailable"){if(!re.name){t.warn("no name present, ignoring presence update request...");return}g.emit("connection.update",{isOnline:ne}),ne&&m(),await B({tag:"presence",attrs:{name:re.name.replace(/@/g,""),type:W}})}else{let{server:Oe}=yA(X);await B({tag:"chatstate",attrs:{from:Oe==="lid"?re.lid:re.id,to:X},content:[{tag:W==="recording"?"composing":W,attrs:W==="recording"?{media:"audio"}:{}}]})}},wA=async W=>{let X=uA(W),ne=_t(X)||qA(X)?await wU({authState:I,jid:X,getLIDForPN:T}):void 0;return B({tag:"presence",attrs:{to:W,id:d(),type:"subscribe"},content:ne})},LA=({tag:W,attrs:X,content:re})=>{let ne,Oe=X.from,Ce=X.participant||X.from;if(!(a(Oe)&&Oe!==OA)){if(W==="presence")ne={lastKnownPresence:X.type==="unavailable"?"unavailable":"available",lastSeen:X.last&&X.last!=="deny"?+X.last:void 0,groupOnlineCount:X.count?+X.count:void 0};else if(Array.isArray(re)){let[he]=re,me=he.tag;me==="paused"&&(me="available"),he.attrs?.media==="audio"&&(me="recording"),ne={lastKnownPresence:me}}else t.error({tag:W,attrs:X,content:re},"recv invalid presence node");ne&&g.emit("presence.update",{id:Oe,presences:{[Ce]:ne}})}},JA=async W=>{let X=W.type,re=I.creds.myAppStateKeyId;if(!re)throw new CI.Boom("App state key not present!",{statusCode:400});let ne,Oe;if(await z.mutex(async()=>{await I.keys.transaction(async()=>{t.debug({patch:W},"applying app patch"),await we([X],!1);let{[X]:Ce}=await I.keys.get("app-state-sync-version",[X]);ne=Ce?oU(Ce):Eb(),Oe=await ane(W,re,ne,V);let{patch:he,state:me}=Oe,je={tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:sync:app:state"},content:[{tag:"sync",attrs:{},content:[{tag:"collection",attrs:{name:X,version:(me.version-1).toString(),return_snapshot:"false"},content:[{tag:"patch",attrs:{},content:oe.SyncdPatch.encode(he).finish()}]}]}]};await f(je),await I.keys.set({"app-state-sync-version":{[X]:me}})},I?.creds?.me?.id||"app-patch")}),n.emitOwnEvents){let{onMutation:Ce}=CA(!1),{mutationMap:he}=await sU(X,[{...Oe.patch,version:{version:Oe.state.version}}],ne,V,n.options,void 0,t);for(let me in he)Ce(he[me])}},lt=async()=>{let W=await f({tag:"iq",attrs:{to:OA,xmlns:"abt",type:"get"},content:[{tag:"props",attrs:{protocol:"1",...I?.creds?.lastPropHash?{hash:I.creds.lastPropHash}:{}}}]}),X=le(W,"props"),re={};X&&(X.attrs?.hash&&(I.creds.lastPropHash=X?.attrs?.hash,g.emit("creds.update",I.creds)),re=fF(X,"prop"));let ne=re[10518]??re.privacy_token_sending_on_all_1_on_1_messages;ne!==void 0&&(L.privacyTokenOn1to1=ne==="true"||ne==="1");let Oe=re[9666]??re.profile_scraping_privacy_token_in_photo_iq;Oe!==void 0&&(L.profilePicPrivacyToken=Oe==="true"||Oe==="1");let Ce=re[14303]??re.lid_trusted_token_issue_to_lid;return Ce!==void 0&&(L.lidTrustedTokenIssueToLid=Ce==="true"||Ce==="1"),t.debug({serverProps:L},"fetched props"),re},wt=(W,X)=>{let re=gne(W,X);return JA(re)},pe=W=>wt({disableLinkPreviews:{isPreviewsDisabled:W}},""),Ie=(W,X,re)=>wt({star:{messages:X,star:re}},W),be=(W,X)=>wt({contact:X},W),oA=W=>wt({contact:null},W),dA=(W,X)=>wt({addLabel:{...X}},W),PA=(W,X)=>wt({addChatLabel:{labelId:X}},W),Ht=(W,X)=>wt({removeChatLabel:{labelId:X}},W),st=(W,X,re)=>wt({addMessageLabel:{messageId:X,labelId:re}},W),Qr=(W,X,re)=>wt({removeMessageLabel:{messageId:X,labelId:re}},W),tr=W=>wt({quickReply:W},""),lo=W=>wt({quickReply:{timestamp:W,deleted:!0}},""),ji=async()=>{await Promise.all([lt(),gA(),Ae()])},ee=g.createBufferedFunction(async(W,X)=>{if(g.emit("messages.upsert",{messages:[W],type:X}),W.pushName){let Ce=W.key.fromMe?I.creds.me.id:W.key.participant||W.key.remoteJid;Ce=uA(Ce),W.key.fromMe||g.emit("contacts.update",[{id:Ce,notify:W.pushName,verifiedName:W.verifiedBizName}]),W.key.fromMe&&W.pushName&&I.creds.me?.name!==W.pushName&&g.emit("creds.update",{me:{...I.creds.me,name:W.pushName}})}let re=hb(W.message),ne=re?A(re)&&Pf.includes(re.syncType):!1;if(re&&ne){let Ce=re.syncType;Ce===oe.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP&&!J.initialBootstrapComplete&&(J.initialBootstrapComplete=!0,g.emit("messaging-history.status",{syncType:Ce,status:"complete",explicit:!0})),Ce===oe.HistorySync.HistorySyncType.RECENT&&re.progress===100&&!J.recentSyncComplete&&(J.recentSyncComplete=!0,clearTimeout(H),H=void 0,g.emit("messaging-history.status",{syncType:Ce,status:"complete",explicit:!0})),Ce===oe.HistorySync.HistorySyncType.RECENT&&!J.recentSyncComplete&&(clearTimeout(H),H=setTimeout(()=>{J.recentSyncComplete||(J.recentSyncComplete=!0,g.emit("messaging-history.status",{syncType:oe.HistorySync.HistorySyncType.RECENT,status:"paused",explicit:!1})),H=void 0},nce))}re&&U===na.AwaitingInitialSync&&(P&&(clearTimeout(P),P=void 0),ne?(U=na.Syncing,t.info("Transitioned to Syncing state")):(U=na.Online,t.info("History sync skipped, transitioning to Online state and flushing buffer"),g.flush()));let Oe=async()=>{if(U===na.Syncing){N.clear(),t.info("Doing app state sync"),await we(NX,!0),U=na.Online,t.info("App state sync complete, transitioning to Online state and flushing buffer"),g.flush();let Ce=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:Ce})}};await Promise.all([(async()=>{ne&&await Oe()})(),One(W,{signalRepository:Q,shouldProcessHistoryMsg:ne,placeholderResendCache:k,ev:g,creds:I.creds,keyStore:I.keys,logger:t,options:n.options,getMessage:r})]),W.message?.protocolMessage?.appStateSyncKeyShare&&U===na.Syncing&&(t.info("App state sync key arrived, triggering app state sync"),await Oe())});return c.on("CB:presence",LA),c.on("CB:chatstate",LA),c.on("CB:ib,,dirty",async W=>{let{attrs:X}=le(W,"dirty");switch(X.type){case"account_sync":if(X.timestamp){let{lastAccountSyncTimestamp:ne}=I.creds;ne&&await Me("account_sync",ne),ne=+X.timestamp,g.emit("creds.update",{lastAccountSyncTimestamp:ne})}break;case"groups":break;default:t.info({node:W},"received unknown sync");break}}),g.on("connection.update",({connection:W,receivedPendingNotifications:X})=>{if(W==="close"&&(N.clear(),clearTimeout(H),H=void 0),W==="open"&&(i&&ji().catch(ne=>y(ne,"init queries")),NA(o?"available":"unavailable").catch(ne=>y(ne,"presence update requests"))),!X||U!==na.Connecting)return;if(J.initialBootstrapComplete=!1,J.recentSyncComplete=!1,clearTimeout(H),H=void 0,U=na.AwaitingInitialSync,t.info("Connection is now AwaitingInitialSync, buffering events"),g.buffer(),!A(oe.Message.HistorySyncNotification.create({syncType:oe.HistorySync.HistorySyncType.RECENT}))){t.info("History sync is disabled by config, not waiting for notification. Transitioning to Online."),U=na.Online,setTimeout(()=>g.flush(),0);return}if(I.creds.accountSyncCounter>0){t.info("Reconnection with existing sync data, skipping history sync wait. Transitioning to Online."),U=na.Online,setTimeout(()=>g.flush(),0);return}t.info("First connection, awaiting history sync notification with a 20s timeout."),P&&clearTimeout(P),P=setTimeout(()=>{if(U===na.AwaitingInitialSync){t.warn("Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer"),U=na.Online,g.flush();let ne=(I.creds.accountSyncCounter||0)+1;g.emit("creds.update",{accountSyncCounter:ne})}},2e4)}),g.on("creds.update",({myAppStateKeyId:W})=>{if(!W||N.size===0)return;if(U===na.Syncing){N.clear();return}let X=[...N];N.clear(),t.info({collections:X},"app state sync key arrived, re-syncing blocked collections"),we(X,!1).catch(re=>y(re,"blocked collections resync"))}),g.on("lid-mapping.update",async({lid:W,pn:X})=>{try{await Q.lidMapping.storeLIDPNMappings([{lid:W,pn:X}])}catch(re){t.warn({lid:W,pn:X,error:re},"Failed to store LID-PN mapping")}}),_(()=>{P&&(clearTimeout(P),P=void 0),!n.placeholderResendCache&&k.close&&k.close(),U=na.Connecting,R=void 0}),{...s,serverProps:L,createCallLink:Ve,getBotListV2:ce,messageMutex:F,receiptMutex:q,appStatePatchMutex:z,notificationMutex:j,fetchPrivacySettings:Ae,upsertMessage:ee,appPatch:JA,sendPresenceUpdate:NA,presenceSubscribe:wA,profilePictureUrl:Ke,fetchBlocklist:gA,fetchStatus:Be,fetchDisappearingDuration:We,updateProfilePicture:Ye,removeProfilePicture:Re,updateProfileStatus:Ze,updateProfileName:iA,updateBlockStatus:WA,updateDisableLinkPreviewsPrivacy:pe,updateCallPrivacy:fe,updateMessagesPrivacy:De,updateLastSeenPrivacy:_e,updateOnlinePrivacy:Ee,updateProfilePicturePrivacy:Qe,updateStatusPrivacy:Le,updateReadReceiptsPrivacy:AA,updateGroupsAddPrivacy:aA,updateDefaultDisappearingMode:He,getBusinessProfile:FA,resyncAppState:we,chatModify:wt,cleanDirtyBits:Me,addOrEditContact:be,removeContact:oA,placeholderResendCache:k,addLabel:dA,addChatLabel:PA,removeChatLabel:Ht,addMessageLabel:st,removeMessageLabel:Qr,star:Ie,addOrEditQuickReply:tr,removeQuickReply:lo}};var bce=n=>{let t=Oce(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(g,c,I)=>e({tag:"iq",attrs:{type:c,xmlns:"w:g2",to:g},content:I}),r=async g=>{let c=await A(g,"get",[{tag:"query",attrs:{request:"interactive"}}]);return EE(c)},s=async()=>{let g=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),c={},I=le(g,"groups");if(I){let d=kA(I,"group");for(let B of d){let f=EE({tag:"result",attrs:{},content:[B]});c[f.id]=f}}return t.ev.emit("groups.update",Object.values(c)),c};return t.ws.on("CB:ib,,dirty",async g=>{let{attrs:c}=le(g,"dirty");c.type==="groups"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,groupMetadata:r,groupCreate:async(g,c)=>{let I=Kr(),d=await A("@g.us","set",[{tag:"create",attrs:{subject:g,key:I},content:c.map(B=>({tag:"participant",attrs:{jid:B}}))}]);return EE(d)},groupLeave:async g=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"group",attrs:{id:g}}]}])},groupUpdateSubject:async(g,c)=>{await A(g,"set",[{tag:"subject",attrs:{},content:Buffer.from(c,"utf-8")}])},groupRequestParticipantsList:async g=>{let c=await A(g,"get",[{tag:"membership_approval_requests",attrs:{}}]),I=le(c,"membership_approval_requests");return kA(I,"membership_approval_request").map(B=>B.attrs)},groupRequestParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:I,attrs:{},content:c.map(y=>({tag:"participant",attrs:{jid:y}}))}]}]),B=le(d,"membership_requests_action"),f=le(B,I);return kA(f,"participant").map(y=>({status:y.attrs.error||"200",jid:y.attrs.jid}))},groupParticipantsUpdate:async(g,c,I)=>{let d=await A(g,"set",[{tag:I,attrs:{},content:c.map(Q=>({tag:"participant",attrs:{jid:Q}}))}]),B=le(d,I);return kA(B,"participant").map(Q=>({status:Q.attrs.error||"200",jid:Q.attrs.jid,content:Q}))},groupUpdateDescription:async(g,c)=>{let d=(await r(g)).descId??null;await A(g,"set",[{tag:"description",attrs:{...c?{id:Kr()}:{delete:"true"},...d?{prev:d}:{}},content:c?[{tag:"body",attrs:{},content:Buffer.from(c,"utf-8")}]:void 0}])},groupInviteCode:async g=>{let c=await A(g,"get",[{tag:"invite",attrs:{}}]);return le(c,"invite")?.attrs.code},groupRevokeInvite:async g=>{let c=await A(g,"set",[{tag:"invite",attrs:{}}]);return le(c,"invite")?.attrs.code},groupAcceptInvite:async g=>{let c=await A("@g.us","set",[{tag:"invite",attrs:{code:g}}]);return le(c,"group")?.attrs.jid},groupRevokeInviteV4:async(g,c)=>!!await A(g,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:c}}]}]),groupAcceptInviteV4:i.createBufferedFunction(async(g,c)=>{g=typeof g=="string"?{remoteJid:g}:g;let I=await A(c.groupJid,"set",[{tag:"accept",attrs:{code:c.inviteCode,expiration:c.inviteExpiration.toString(),admin:g.remoteJid}}]);return g.id&&(c=oe.Message.GroupInviteMessage.fromObject(c),c.inviteExpiration=0,c.inviteCode="",i.emit("messages.update",[{key:g,update:{message:{groupInviteMessage:c}}}])),await a({key:{remoteJid:c.groupJid,id:Kr(t.user?.id),fromMe:!1,participant:g.remoteJid},messageStubType:TA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:g.remoteJid,messageTimestamp:ya()},"notify"),I.attrs.from}),groupGetInviteInfo:async g=>{let c=await A("@g.us","get",[{tag:"invite",attrs:{code:g}}]);return EE(c)},groupToggleEphemeral:async(g,c)=>{let I=c?{tag:"ephemeral",attrs:{expiration:c.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(g,"set",[I])},groupSettingUpdate:async(g,c)=>{await A(g,"set",[{tag:c,attrs:{}}])},groupMemberAddMode:async(g,c)=>{await A(g,"set",[{tag:"member_add_mode",attrs:{},content:c}])},groupJoinApprovalMode:async(g,c)=>{await A(g,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"group_join",attrs:{state:c}}]}])},groupFetchAllParticipating:s}},EE=n=>{let t=le(n,"group");if(!t){let B=le(n,"error");if(B){let f=B.attrs.code?+B.attrs.code:500,Q=B.attrs.text||"group metadata query failed";throw new iM.Boom(Q,{statusCode:f,data:B})}throw new iM.Boom("Invalid group metadata response: missing node",{data:n})}if(!t.attrs.id)throw new iM.Boom("Invalid group metadata response: missing group id",{data:t});let o=le(t,"description"),i,e,a,A,r,s;o&&(i=YA(o,"body"),a=o.attrs.participant?uA(o.attrs.participant):void 0,A=o.attrs.participant_pn?uA(o.attrs.participant_pn):void 0,r=o.attrs.participant_username||void 0,s=+o.attrs.t,e=o.attrs.id);let g=t.attrs.id.includes("@")?t.attrs.id:Cr(t.attrs.id,"g.us"),c=le(t,"ephemeral")?.attrs.expiration,I=YA(t,"member_add_mode")==="all_member_add";return{id:g,notify:t.attrs.notify,addressingMode:t.attrs.addressing_mode==="lid"?dB.LID:dB.PN,subject:t.attrs.subject,subjectOwner:t.attrs.s_o,subjectOwnerPn:t.attrs.s_o_pn,subjectOwnerUsername:t.attrs.s_o_username,subjectTime:+t.attrs.s_t,size:t.attrs.size?+t.attrs.size:kA(t,"participant").length,creation:+t.attrs.creation,owner:t.attrs.creator?uA(t.attrs.creator):void 0,ownerPn:t.attrs.creator_pn?uA(t.attrs.creator_pn):void 0,ownerUsername:t.attrs.creator_username||void 0,owner_country_code:t.attrs.creator_country_code,desc:i,descId:e,descOwner:a,descOwnerPn:A,descOwnerUsername:r,descTime:s,linkedParent:le(t,"linked_parent")?.attrs.jid||void 0,restrict:!!le(t,"locked"),announce:!!le(t,"announcement"),isCommunity:!!le(t,"parent"),isCommunityAnnounce:!!le(t,"default_sub_group"),joinApprovalMode:!!le(t,"membership_approval_mode"),memberAddMode:I,participants:kA(t,"participant").map(({attrs:B})=>({id:B.jid,phoneNumber:qA(B.jid)&&_t(B.phone_number)?B.phone_number:void 0,lid:_t(B.jid)&&qA(B.lid)?B.lid:void 0,username:B.participant_username||B.username||void 0,admin:B.type||null})),ephemeralDuration:c?+c:void 0}};var CE=Je(Lr(),1);var x5e=n=>{let{id:t,thread_metadata:o,viewer_metadata:i}=n;return{id:t,owner:void 0,name:o.name.text,creation_time:parseInt(o.creation_time,10),description:o.description.text,invite:o.invite,subscribers:parseInt(o.subscribers_count,10),verification:o.verification,picture:{id:o.picture.id,directPath:o.picture.direct_path},mute_state:i.mute}},Y5e=n=>typeof n!="object"||n===null?null:"id"in n&&typeof n.id=="string"?n:"result"in n&&typeof n.result=="object"&&n.result!==null&&"id"in n.result?n.result:null,Mce=n=>{let t=bce(n),{query:o,generateMessageTag:i}=t,e=(A,r,s)=>Lf(A,r,s,o,i),a=async(A,r)=>{let s={newsletter_id:A,updates:{...r,settings:null}};return e(s,sa.UPDATE_METADATA,"xwa2_newsletter_update")};return{...t,newsletterCreate:async(A,r)=>{let g=await e({input:{name:A,description:r??null}},sa.CREATE,fa.xwa2_newsletter_create);return x5e(g)},newsletterUpdate:a,newsletterSubscribers:async A=>e({newsletter_id:A},sa.SUBSCRIBERS,fa.xwa2_newsletter_subscribers),newsletterMetadata:async(A,r)=>{let s={fetch_creation_time:!0,fetch_full_image:!0,fetch_viewer_metadata:!0,input:{key:r,type:A.toUpperCase()}},g=await e(s,sa.METADATA,fa.xwa2_newsletter_metadata);return Y5e(g)},newsletterFollow:A=>e({newsletter_id:A},sa.FOLLOW,fa.xwa2_newsletter_join_v2),newsletterUnfollow:A=>e({newsletter_id:A},sa.UNFOLLOW,fa.xwa2_newsletter_leave_v2),newsletterMute:A=>e({newsletter_id:A},sa.MUTE,fa.xwa2_newsletter_mute_v2),newsletterUnmute:A=>e({newsletter_id:A},sa.UNMUTE,fa.xwa2_newsletter_unmute_v2),newsletterUpdateName:async(A,r)=>await a(A,{name:r}),newsletterUpdateDescription:async(A,r)=>await a(A,{description:r}),newsletterUpdatePicture:async(A,r)=>{let{img:s}=await cb(r);return await a(A,{picture:s.toString("base64")})},newsletterRemovePicture:async A=>await a(A,{picture:""}),newsletterReactMessage:async(A,r,s)=>{await o({tag:"message",attrs:{to:A,...s?{}:{edit:"7"},type:"reaction",server_id:r,id:i()},content:[{tag:"reaction",attrs:s?{code:s}:{}}]})},newsletterFetchMessages:async(A,r,s,g)=>{let c={count:r.toString()};return typeof s=="number"&&(c.since=s.toString()),g&&(c.after=g.toString()),await o({tag:"iq",attrs:{id:i(),type:"get",xmlns:"newsletter",to:A},content:[{tag:"message_updates",attrs:c}]})},subscribeNewsletterUpdates:async A=>{let r=await o({tag:"iq",attrs:{id:i(),type:"set",xmlns:"newsletter",to:A},content:[{tag:"live_updates",attrs:{},content:[]}]}),g=le(r,"live_updates")?.attrs?.duration;return g?{duration:g}:null},newsletterAdminCount:async A=>(await e({newsletter_id:A},sa.ADMIN_COUNT,fa.xwa2_newsletter_admin_count)).admin_count,newsletterChangeOwner:async(A,r)=>{await e({newsletter_id:A,user_id:r},sa.CHANGE_OWNER,fa.xwa2_newsletter_change_owner)},newsletterDemote:async(A,r)=>{await e({newsletter_id:A,user_id:r},sa.DEMOTE,fa.xwa2_newsletter_demote)},newsletterDelete:async A=>{await e({newsletter_id:A},sa.DELETE,fa.xwa2_newsletter_delete_v2)}}};var _ce=n=>{let{logger:t,linkPreviewImageThumbnailWidth:o,generateHighQualityLinkPreview:i,options:e,patchMessageBeforeSending:a,cachedGroupMetadata:A,enableRecentMessageCache:r,maxMsgRetryCount:s}=n,g=Mce(n),{ev:c,authState:I,messageMutex:d,signalRepository:B,upsertMessage:f,query:Q,fetchPrivacySettings:y,sendNode:m,groupMetadata:_,groupToggleEphemeral:T,registerSocketEndHandler:R}=g,L=B.lidMapping.getLIDForPN.bind(B.lidMapping),U=new Set,F=n.userDevicesCache||new jg({stdTTL:dI.USER_DEVICES,useClones:!1}),q=Zg(),z=r?new Sb(t,s):null,j=Sce(),P,J=Y2,H=async(ce=!1)=>{let Be=await P;return(!Be||ce||new Date().getTime()-Be.fetchDate.getTime()>Be.ttl*1e3)&&(P=(async()=>{let We=await Q({tag:"iq",attrs:{type:"set",xmlns:"w:m",to:OA},content:[{tag:"media_conn",attrs:{}}]}),Ye=le(We,"media_conn"),Re={hosts:kA(Ye,"host").map(({attrs:Ze})=>({hostname:Ze.hostname,maxContentLengthBytes:+Ze.maxContentLengthBytes})),auth:Ye.attrs.auth,ttl:+Ye.attrs.ttl,fetchDate:new Date};return t.debug("fetched media conn"),Re.hosts[0]&&(J=Re.hosts[0].hostname),Re})()),P},N=async(ce,Be,We,Ye)=>{if(!We||We.length===0)throw new CE.Boom("missing ids in receipt");let Re={tag:"receipt",attrs:{id:We[0]}};(Ye==="read"||Ye==="read-self")&&(Re.attrs.t=ya().toString()),Ye==="sender"&&(_t(ce)||qA(ce))?(Re.attrs.recipient=ce,Re.attrs.to=Be):(Re.attrs.to=ce,Be&&(Re.attrs.participant=Be)),Ye&&(Re.attrs.type=Ye);let iA=We.slice(1);iA.length&&(Re.content=[{tag:"list",attrs:{},content:iA.map(gA=>({tag:"item",attrs:{id:gA}}))}]),t.debug({attrs:Re.attrs,messageIds:We},"sending receipt for messages"),await m(Re)},k=async(ce,Be)=>{let We=Doe(ce);for(let{jid:Ye,participant:Re,messageIds:Ze}of We)await N(Ye,Re,Ze,Be)},V=async ce=>{let We=(await y()).readreceipts==="all"?"read":"read-self";await k(ce,We)},Ae=async(ce,Be,We)=>{let Ye=[];Be||t.debug("not using cache for devices");let Re=[],Ze=ce.map(Me=>{let CA=yA(Me),we=CA?.user,Ke=CA?.device;return typeof Ke=="number"&&Ke>=0&&we?(Ye.push({user:we,device:Ke,jid:Me}),null):(Me=uA(Me),{jid:Me,user:we})}).filter(Me=>Me!==null),iA;if(Be&&F.mget){let Me=Ze.map(CA=>CA?.user).filter(Boolean);iA=await F.mget(Me)}for(let{jid:Me,user:CA}of Ze)if(Be){let we=iA?.[CA]||(F.mget?void 0:await F.get(CA));if(we){let Ke=we.map(Ve=>({...Ve,jid:Cr(Ve.user,Ve.server,Ve.device)}));Ye.push(...Ke),t.trace({user:CA},"using cache for devices")}else Re.push(Me)}else Re.push(Me);if(!Re.length)return Ye;let gA=new Set;for(let Me of Re)if(qA(Me)||ga(Me)){let CA=yA(Me)?.user;CA&&gA.add(CA)}let WA=new Ws().withContext("message").withDeviceProtocol().withLIDProtocol();for(let Me of Re)WA.withUser(new Vs().withId(Me));let FA=await g.executeUSyncQuery(WA);if(FA){let Me=FA.list.filter(Ve=>!!Ve.lid);if(Me.length>0){t.trace("Storing LID maps from device call"),await B.lidMapping.storeLIDPNMappings(Me.map(Ve=>({lid:Ve.lid,pn:Ve.id})));try{let Ve=Me.map(NA=>NA.lid);Ve.length&&await De(Ve,!0)}catch(Ve){t.warn({e:Ve,count:Me.length},"failed to assert sessions for newly mapped LIDs")}}let CA=voe(FA?.list,I.creds.me.id,I.creds.me.lid,We),we={};for(let Ve of CA)we[Ve.user]=we[Ve.user]||[],we[Ve.user]?.push(Ve);for(let[Ve,NA]of Object.entries(we)){let wA=gA.has(Ve);for(let LA of NA){let JA=wA?Cr(Ve,LA.server,LA.device):Cr(LA.user,LA.server,LA.device);Ye.push({...LA,jid:JA}),t.debug({user:LA.user,device:LA.device,finalJid:JA,usedLid:wA},"Processed device with LID priority")}}await q.mutex(async()=>{if(F.mset)await F.mset(Object.entries(we).map(([Ve,NA])=>({key:Ve,value:NA})));else for(let Ve in we)we[Ve]&&await F.set(Ve,we[Ve])});let Ke={};for(let[Ve,NA]of Object.entries(we))NA&&NA.length>0&&(Ke[Ve]=NA.map(wA=>wA.device?.toString()||"0"));if(Object.keys(Ke).length>0)try{await I.keys.set({"device-list":Ke}),t.debug({userCount:Object.keys(Ke).length},"stored user device lists for bulk migration")}catch(Ve){t.warn({error:Ve},"failed to store user device lists")}}return Ye},ie=(ce,Be)=>Ee(ce,{protocolMessage:{type:oe.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,memberLabel:{label:Be?.slice(0,30),labelTimestamp:ya()}}},{additionalNodes:[{tag:"meta",attrs:{tag_reason:"user_update",appdata:"member_tag"},content:void 0}]}),De=async(ce,Be)=>{let We=!1,Ye=[...new Set(ce)],Re=[];t.debug({jids:ce},"assertSessions call with jids");for(let Ze of Ye)!Be&&(await B.validateSession(Ze)).exists||Re.push(Ze);if(Re.length){let Ze=[...Re.filter(gA=>!!qA(gA)||!!ga(gA)),...(await B.lidMapping.getLIDsForPNs(Re.filter(gA=>!!_t(gA)||!!ur(gA)))||[]).map(gA=>gA.lid)];t.debug({jidsRequiringFetch:Re,wireJids:Ze},"fetching sessions");let iA=await Q({tag:"iq",attrs:{xmlns:"encrypt",type:"get",to:OA},content:[{tag:"key",attrs:{},content:Ze.map(gA=>{let WA={jid:gA};return Be&&(WA.reason="identity"),{tag:"user",attrs:WA}})}]});await koe(iA,B),We=!0}return We},fe=async ce=>{if(!I.creds.me?.id)throw new CE.Boom("Not authenticated");let Be={protocolMessage:{peerDataOperationRequestMessage:ce,type:oe.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE}},We=uA(I.creds.me.id);return await Ee(We,Be,{additionalAttributes:{category:"peer",push_priority:"high_force"},additionalNodes:[{tag:"meta",attrs:{appdata:"default"}}]})},_e=async(ce,Be,We,Ye)=>{if(!ce.length)return{nodes:[],shouldIncludeDeviceIdentity:!1};let Re=await a(Be,ce),Ze=Array.isArray(Re)?Re:ce.map(we=>({recipientJid:we,message:Re})),iA=!1,gA=I.creds.me.id,WA=I.creds.me?.lid,FA=WA?yA(WA)?.user:null,Me=Ze.map(async({recipientJid:we,message:Ke})=>{try{if(!we)return null;let Ve=Ke;if(Ye){let{user:JA}=yA(we),{user:lt}=yA(gA),wt=FA;(JA===lt||wt&&JA===wt)&&!(we===gA||WA&&we===WA)&&(Ve=Ye,t.debug({jid:we,targetUser:JA},"Using DSM for own device"))}let NA=ch(Ve),wA=we;return await j.mutex(wA,async()=>{let{type:JA,ciphertext:lt}=await B.encryptMessage({jid:we,data:NA});return JA==="pkmsg"&&(iA=!0),{tag:"to",attrs:{jid:we},content:[{tag:"enc",attrs:{v:"2",type:JA,...We||{}},content:lt}]}})}catch(Ve){return t.error({jid:we,err:Ve},"Failed to encrypt for recipient"),null}}),CA=(await Promise.all(Me)).filter(we=>we!==null);if(ce.length>0&&CA.length===0)throw new CE.Boom("All encryptions failed",{statusCode:500});return{nodes:CA,shouldIncludeDeviceIdentity:iA}},Ee=async(ce,Be,{messageId:We,participant:Ye,additionalAttributes:Re,additionalNodes:Ze,useUserDevicesCache:iA,useCachedGroupMetadata:gA,statusJidList:WA})=>{let FA=fne(I.creds),Me=I.creds.me?.lid,CA=!!Ye?.jid,we=CA,Ke="status@broadcast",{user:Ve,server:NA}=yA(ce),wA=NA==="g.us",LA=ce===Ke,JA=NA==="lid",lt=NA==="newsletter",wt=wA||LA,pe=ce;We=We||Kr(FA),iA=iA!==!1,gA=gA!==!1&&!LA;let Ie=[],be=LA?Ke:pe,oA=[],dA=[],PA,Ht={deviceSentMessage:{destinationJid:be,message:Be},messageContextInfo:Be.messageContextInfo},st={};if(Ye){!wA&&!LA&&(Re={...Re,device_fanout:"false"});let{user:Qr,device:tr}=yA(Ye.jid);dA.push({user:Qr,device:tr,jid:Ye.jid})}return await I.keys.transaction(async()=>{let Qr=Le(Be);if(Qr&&(st.mediatype=Qr),lt){let Ce=a?await a(Be,[]):Be,he=_7(Ce);oA.push({tag:"plaintext",attrs:{},content:he});let me={tag:"message",attrs:{to:ce,id:We,type:Qe(Be),...Re||{}},content:oA};t.debug({msgId:We},`sending newsletter message to ${ce}`),await m(me);return}if((Oa(Be)?.pinInChatMessage||Oa(Be)?.reactionMessage)&&(st["decrypt-fail"]="hide"),wt&&!CA){let[Ce,he]=await Promise.all([(async()=>{let tA=gA&&A?await A(ce):void 0;return tA&&Array.isArray(tA?.participants)?t.trace({jid:ce,participants:tA.participants.length},"using cached group metadata"):LA||(tA=await _(ce)),tA})(),(async()=>!Ye&&!LA?(await I.keys.get("sender-key-memory",[ce]))[ce]||{}:{})()]),me=Ce?Ce.participants.map(tA=>tA.id):[];Ce?.ephemeralDuration&&Ce.ephemeralDuration>0&&(Re={...Re,expiration:Ce.ephemeralDuration.toString()}),LA&&WA&&me.push(...WA);let je=await Ae(me,!!iA,!1);dA.push(...je),wA&&(Re={...Re,addressing_mode:Ce?.addressingMode||"lid"});let lA=await a(Be);if(Array.isArray(lA))throw new CE.Boom("Per-jid patching is not supported in groups");let QA=ch(lA);PA=lA;let RA=(Re?.addressing_mode||Ce?.addressingMode||"lid")==="lid"&&Me?Me:FA,{ciphertext:xA,senderKeyDistributionMessage:et}=await B.encryptGroupMessage({group:be,data:QA,meId:RA}),ve=[];for(let tA of dA){let At=tA.jid;(!!!he[At]||Ye)&&!ga(At)&&!ur(At)&&tA.device!==99&&(ve.push(At),he[At]=!0)}if(ve.length){t.debug({senderKeyJids:ve},"sending new sender key");let tA={senderKeyDistributionMessage:{axolotlSenderKeyDistributionMessage:et,groupId:be}};await De(ve);let zr=await _e(ve,tA,st);we=we||zr.shouldIncludeDeviceIdentity,Ie.push(...zr.nodes)}oA.push({tag:"enc",attrs:{v:"2",type:"skmsg",...st},content:xA}),await I.keys.set({"sender-key-memory":{[ce]:he}})}else{let Ce=FA;JA&&Me?(Ce=Me,t.debug({to:ce,ownId:Ce},"Using LID identity for @lid conversation")):t.debug({to:ce,ownId:Ce},"Using PN identity for @s.whatsapp.net conversation");let{user:he}=yA(Ce);if(!Ye){let tA=await a(Be,[ce]);PA=Array.isArray(tA)?tA.find(At=>At.recipientJid===ce)||tA[0]:tA}if(!CA){let tA=JA?"lid":"s.whatsapp.net";if(dA.push({user:Ve,device:0,jid:Cr(Ve,tA,0)}),Ve!==he){let At=JA?"lid":"s.whatsapp.net",zr=JA&&Me?yA(Me).user:yA(FA).user;dA.push({user:zr,device:0,jid:Cr(zr,At,0)})}if(Re?.category!=="peer"){dA.length=0;let At=JA&&Me?Cr(yA(Me)?.user,"lid",void 0):Cr(yA(FA)?.user,"s.whatsapp.net",void 0),zr=await Ae([At,ce],!0,!1);dA.push(...zr),t.debug({deviceCount:dA.length,devices:dA.map(rr=>`${rr.user}:${rr.device}@${yA(rr.jid)?.server}`)},"Device enumeration complete with unified addressing")}}let me=[],je=[],lA=[],{user:QA}=yA(FA),{user:$A}=Me?yA(Me):{user:null};for(let{user:tA,jid:At}of dA){if(At===FA||Me&&At===Me){t.debug({jid:At,meId:FA,meLid:Me},"Skipping exact sender device (whatsmeow pattern)");continue}tA===QA||tA===$A?je.push(At):lA.push(At),me.push(At)}await De(me);let[{nodes:RA,shouldIncludeDeviceIdentity:xA},{nodes:et,shouldIncludeDeviceIdentity:ve}]=await Promise.all([_e(je,Ht||Be,st),_e(lA,Be,st,Ht)]);Ie.push(...RA),Ie.push(...et),(je.length>0||lA.length>0)&&(st.phash=f7([...je,...lA])),we=we||xA||ve}if(CA){let Ce=qA(Ye.jid),he=Tt(Ye.jid,Ce?Me:FA),me=Be;if(wt){let $A;if(Me&&await B.hasSenderKey({group:be,meId:Me})?$A=Me:await B.hasSenderKey({group:be,meId:FA})&&($A=FA),$A)try{let RA=await B.getSenderKeyDistributionMessage({group:be,meId:$A});me={...Be,senderKeyDistributionMessage:{groupId:be,axolotlSenderKeyDistributionMessage:RA}}}catch(RA){t.warn({err:RA,jid:be},"failed to build SKDM for retry, sending without it")}}let je=he?ch({deviceSentMessage:{destinationJid:be,message:me}}):ch(me),{type:lA,ciphertext:QA}=await B.encryptMessage({data:je,jid:Ye.jid});oA.push({tag:"enc",attrs:{v:"2",type:lA,count:Ye.count.toString()},content:QA})}if(Ie.length)if(Re?.category==="peer"){let Ce=Ie[0]?.content?.[0];Ce&&oA.push(Ce)}else oA.push({tag:"participants",attrs:{},content:Ie});let tr={tag:"message",attrs:{id:We,to:be,type:Qe(Be),...Re||{}},content:oA};if(Ye?Ur(be)?(tr.attrs.to=be,tr.attrs.participant=Ye.jid):Tt(Ye.jid,FA)?(tr.attrs.to=Ye.jid,tr.attrs.recipient=be):tr.attrs.to=Ye.jid:tr.attrs.to=be,we&&(tr.content.push({tag:"device-identity",attrs:{},content:mf(I.creds.account,!0)}),t.debug({jid:ce},"adding device identity")),!lt&&!CA&&PA?.messageContextInfo?.messageSecret&&pb(PA))try{let Ce=ch(PA),he={id:We,fromMe:!0,remoteJid:be,participant:Ye?.jid},me=await Qoe(Ce,PA,he);me&&(tr.content.push(me),t.trace({jid:ce},"added reporting token to message"))}catch(Ce){t.warn({jid:ce,trace:Ce?.stack},"failed to attach reporting token")}let lo=Re?.category==="peer",ji=!wA&&!CA&&!LA&&!lt&&!lo,ee=ji?await js(be,L):be,X=(ji?await I.keys.get("tctoken",[ee]):{})[ee],re=X?.token;if(re?.length&&Ap(X?.timestamp)){t.debug({jid:be,timestamp:X?.timestamp},"tctoken expired, clearing"),re=void 0;let Ce=X?.senderTimestamp!==void 0?{token:Buffer.alloc(0),senderTimestamp:X.senderTimestamp}:null;try{await I.keys.set({tctoken:{[ee]:Ce}})}catch(he){t.debug({jid:be,err:he?.message},"failed to persist tctoken expiry cleanup")}}re?.length&&g.serverProps.privacyTokenOn1to1&&tr.content.push({tag:"tctoken",attrs:{},content:re}),Ze&&Ze.length>0&&tr.content.push(...Ze),t.debug({msgId:We},`sending message to ${Ie.length} devices`),await m(tr);let ne=!!Oa(Be)?.protocolMessage,Oe=be===FX||UX(be)||rh(be);if(ji&&!ne&&!Oe&&wne(X?.senderTimestamp)&&!U.has(ee)){U.add(ee);let Ce=ya(),he=B.lidMapping.getPNForLID.bind(B.lidMapping);bf(be,g.serverProps.lidTrustedTokenIssueToLid,L,he).then(me=>AA([me],Ce)).then(async me=>{await aE({result:me,fallbackJid:ee,keys:I.keys,getLIDForPN:L});let lA=(await I.keys.get("tctoken",[ee]))[ee],QA=await rE(I.keys,[ee]);await I.keys.set({tctoken:{[ee]:{token:Buffer.alloc(0),...lA,senderTimestamp:Ce},...QA}})}).catch(me=>{t.debug({jid:be,err:me?.message},"fire-and-forget tctoken issuance failed")}).finally(()=>{U.delete(ee)})}z&&!Ye&&z.addRecentMessage(be,We,Be)},FA),We},Qe=ce=>{let Be=Oa(ce);return Be?Be.reactionMessage||Be.encReactionMessage?"reaction":Be.pollCreationMessage||Be.pollCreationMessageV2||Be.pollCreationMessageV3||Be.pollUpdateMessage?"poll":Be.eventMessage?"event":Le(Be)!==""?"media":"text":"text"},Le=ce=>ce.imageMessage?"image":ce.videoMessage?ce.videoMessage.gifPlayback?"gif":"video":ce.audioMessage?ce.audioMessage.ptt?"ptt":"audio":ce.contactMessage?"vcard":ce.documentMessage?"document":ce.contactsArrayMessage?"contact_array":ce.liveLocationMessage?"livelocation":ce.stickerMessage?"sticker":ce.listMessage?"list":ce.listResponseMessage?"list_response":ce.buttonsResponseMessage?"buttons_response":ce.orderMessage?"order":ce.productMessage?"product":ce.interactiveResponseMessage?"native_flow_response":ce.groupInviteMessage?"url":"",AA=async(ce,Be)=>{let We=(Be??ya()).toString();return await Q({tag:"iq",attrs:{to:OA,type:"set",xmlns:"privacy"},content:[{tag:"tokens",attrs:{},content:ce.map(Re=>({tag:"token",attrs:{jid:uA(Re),t:We,type:"trusted_contact"}}))}]})},aA=loe(n,H),He=MF(c,"messages.media-update");return R(()=>{!n.userDevicesCache&&F.close&&F.close(),P=void 0,z&&z.clear()}),{...g,userDevicesCache:F,devicesMutex:q,issuePrivacyTokens:AA,assertSessions:De,relayMessage:Ee,sendReceipt:N,sendReceipts:k,readMessages:V,refreshMediaConn:H,getMediaHost:()=>J,waUploadToServer:aA,fetchPrivacySettings:y,sendPeerDataOperationMessage:fe,createParticipantNodes:_e,getUSyncDevices:Ae,messageRetryManager:z,updateMemberLabel:ie,updateMediaMessage:async ce=>{let Be=Ooe(ce.message),We=Be.mediaKey,Ye=I.creds.me.id,Re=doe(ce.key,We,Ye),Ze;if(await Promise.all([m(Re),He(async iA=>{let gA=iA.find(WA=>WA.key.id===ce.key.id);if(gA){if(gA.error)Ze=gA.error;else try{let WA=Eoe(gA.media,We,gA.key.id);if(WA.result!==oe.MediaRetryNotification.ResultType.SUCCESS){let FA=oe.MediaRetryNotification.ResultType[WA.result];throw new CE.Boom(`Media re-upload failed by device (${FA})`,{data:WA,statusCode:j2(WA.result)||404})}Be.directPath=WA.directPath,Be.url=Cf(Be.directPath,J),t.debug({directPath:WA.directPath,key:gA.key},"media update successful")}catch(WA){Ze=WA}return!0}})]),Ze)throw Ze;return c.emit("messages.update",[{key:ce.key,update:{message:ce.message}}]),ce},sendMessage:async(ce,Be,We={})=>{let Ye=I.creds.me.id;if(typeof Be=="object"&&"disappearingMessagesInChat"in Be&&typeof Be.disappearingMessagesInChat<"u"&&Ur(ce)){let{disappearingMessagesInChat:Re}=Be;await T(ce,typeof Re=="boolean"?Re?Qf:0:Re)}else{let Re=await Soe(ce,Be,{logger:t,userJid:Ye,getUrlInfo:we=>Sne(we,{thumbnailWidth:o,fetchOpts:{timeout:3e3,...e||{}},logger:t,uploadImage:i?aA:void 0}),getProfilePicUrl:g.profilePictureUrl,getCallLink:g.createCallLink,upload:aA,mediaCache:n.mediaCache,options:n.options,messageId:Kr(g.user?.id),...We}),Ze="event"in Be&&!!Be.event,iA="delete"in Be&&!!Be.delete,gA="edit"in Be&&!!Be.edit,WA="pin"in Be&&!!Be.pin,FA="poll"in Be&&!!Be.poll,Me={},CA=[];return iA?Ur(Be.delete?.remoteJid)&&!Be.delete?.fromMe?Me.edit="8":Me.edit="7":gA?Me.edit="1":WA?Me.edit="2":FA?CA.push({tag:"meta",attrs:{polltype:"creation"}}):Ze&&CA.push({tag:"meta",attrs:{event_type:"creation"}}),await Ee(ce,Re.message,{messageId:Re.key.id,useCachedGroupMetadata:We.useCachedGroupMetadata,additionalAttributes:Me,statusJidList:We.statusJidList,additionalNodes:CA}),n.emitOwnEvents&&process.nextTick(async()=>{await d.mutex(()=>f(Re,"append"))}),Re}}}};var j5e=new Set(Object.values(Hc));function J5e(n){return typeof n=="string"&&j5e.has(n)}var Tce=n=>{let{logger:t,retryRequestDelayMs:o,maxMsgRetryCount:i,getMessage:e,shouldIgnoreJid:a,enableAutoSessionRecreation:A}=n,r=_ce(n),{userDevicesCache:s,devicesMutex:g,ev:c,authState:I,ws:d,messageMutex:B,notificationMutex:f,receiptMutex:Q,signalRepository:y,query:m,upsertMessage:_,resyncAppState:T,onUnexpectedError:R,assertSessions:L,sendNode:U,relayMessage:F,sendReceipt:q,uploadPreKeys:z,sendPeerDataOperationMessage:j,messageRetryManager:P,registerSocketEndHandler:J,issuePrivacyTokens:H,fetchAccountReachoutTimelock:N,placeholderResendCache:k}=r,V=y.lidMapping.getLIDForPN.bind(y.lidMapping),Ae=Zg(),ie=n.msgRetryCounterCache||new jg({stdTTL:dI.MSG_RETRY,useClones:!1}),De=n.callOfferCache||new jg({stdTTL:dI.CALL_OFFER,useClones:!1}),fe=new jg({stdTTL:5,useClones:!1}),_e=!1,Ee=async(ee,W,X)=>{if(!I.creds.me?.id)throw new Uf.Boom("Not authenticated");let re={historySyncOnDemandRequest:{chatJid:W.remoteJid,oldestMsgFromMe:W.fromMe,oldestMsgId:W.id,oldestMsgTimestampMs:X,onDemandMsgCount:ee},peerDataOperationRequestType:oe.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND};return j(re)},Qe=async(ee,W)=>{if(!I.creds.me?.id)throw new Uf.Boom("Not authenticated");if(await k.get(ee?.id)){t.debug({messageKey:ee},"already requested resend");return}else await k.set(ee?.id,W||!0);if(await DB(2e3),!await k.get(ee?.id))return t.debug({messageKey:ee},"message received while resend requested"),"RESOLVED";let X={placeholderMessageResendRequest:[{messageKey:ee}],peerDataOperationRequestType:oe.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND};return setTimeout(async()=>{await k.get(ee?.id)&&(t.debug({messageKey:ee},"PDO message without response after 8 seconds. Phone possibly offline"),await k.del(ee?.id))},8e3),j(X)},Le=async ee=>{let W=le(ee,"update");if(W){let X=W.attrs?.op_name;if(!X){t.warn({node:_n(ee)},"mex notification missing op_name, fallback to legacy"),await He(ee);return}let re;try{re=JSON.parse(W.content.toString())}catch(Oe){t.error({err:Oe,opName:X},"failed to parse mex notification JSON");return}if(re.errors?.length){t.warn({errors:re.errors,opName:X},"mex notification has GQL errors");return}let ne=re.data;if(!ne){t.warn({opName:X},"mex notification has null data");return}switch(t.debug({opName:X},"processing mex notification"),X){case"NotificationUserReachoutTimelockUpdate":AA(ne);break;case"MessageCappingInfoNotification":aA(ne);break;case"NotificationNewsletterUpdate":case"NotificationLinkedProfilesUpdates":case"NotificationNewsletterAdminPromote":case"NotificationNewsletterAdminDemote":case"NotificationNewsletterUserSettingChange":case"NotificationNewsletterJoin":case"NotificationNewsletterLeave":case"NotificationNewsletterStateChange":case"NotificationNewsletterAdminMetadataUpdate":case"NotificationNewsletterOwnerUpdate":case"NotificationNewsletterAdminInviteRevoke":case"NotificationNewsletterWamoSubStatusChange":case"NotificationNewsletterBlockUser":case"NotificationNewsletterPaidPartnership":case"NotificationNewsletterMilestone":case"NewsletterResponseStateUpdate":await He(ee);break;default:t.debug({opName:X},"unhandled mex notification");break}return}await He(ee)},AA=ee=>{let W=ee.xwa2_notify_account_reachout_timelock;if(!W){t.warn("reachout timelock notification missing payload");return}if(!W.is_active){t.info("reachout timelock restriction lifted"),c.emit("connection.update",{reachoutTimeLock:{isActive:!1,enforcementType:Hc.DEFAULT}});return}let X=W.time_enforcement_ends?new Date(parseInt(W.time_enforcement_ends,10)*1e3):new Date(Date.now()+6e4),re=J5e(W.enforcement_type)?W.enforcement_type:Hc.DEFAULT;t.info({enforcementType:re,timeEnforcementEnds:X},"reachout timelock restriction set"),c.emit("connection.update",{reachoutTimeLock:{isActive:!0,timeEnforcementEnds:X,enforcementType:re}})},aA=ee=>{let W=ee.xwa2_notify_new_chat_messages_capping_info_update;if(!W){t.warn("message capping notification missing payload");return}t.info({payload:W},"received message capping update"),c.emit("message-capping.update",W)},He=async ee=>{let W=le(ee,"mex"),X=W?.content?null:le(ee,"update")||ys(ee)[0],re=W?.content?W:X;if(!re?.content){t.warn({node:_n(ee)},"invalid mex newsletter notification");return}let ne;try{let he=re.content;if(Array.isArray(he)){t.warn({payloadNode:re},"invalid mex newsletter notification payload format");return}let me=typeof he=="string"?Buffer.from(he,"binary"):Buffer.from(he);ne=JSON.parse(me.toString())}catch(he){t.error({err:he,node:_n(ee)},"failed to parse mex newsletter notification");return}let Oe=ne?.operation??re?.attrs?.op_name,Ce=ne?.updates;if(!Ce){let he=ne?.data?.xwa2_notify_linked_profiles;he&&(Ce=[he])}if(!Ce||!Oe){t.warn({data:ne},"invalid mex newsletter notification content");return}switch(t.info({operation:Oe,updates:Ce},"got mex newsletter notification"),Oe){case"NotificationNewsletterUpdate":for(let he of Ce)he.jid&&he.settings&&Object.keys(he.settings).length>0&&c.emit("newsletter-settings.update",{id:he.jid,update:he.settings});break;case"NotificationNewsletterAdminPromote":for(let he of Ce)he.jid&&he.user&&c.emit("newsletter-participants.update",{id:he.jid,author:ee.attrs.from,user:he.user,new_role:"ADMIN",action:"promote"});break;case"NotificationLinkedProfilesUpdates":for(let he of Ce){let me=he?.jid,je=Array.isArray(he?.added_profiles)?he.added_profiles:[],lA=[];for(let QA of je){let $A=typeof QA=="string"?QA:QA?.pn??QA?.jid??null;if(me&&$A){let RA={lid:me,pn:$A};c.emit("lid-mapping.update",RA),lA.push(RA)}}await y.lidMapping.storeLIDPNMappings(lA)}break;default:t.info({operation:Oe,data:ne},"unhandled mex newsletter notification");break}},ce=async ee=>{let W=ee.attrs.from,X=ys(ee),re=ee.attrs.participant;for(let ne of X)switch(t.debug({from:W,child:ne},"got newsletter notification"),ne.tag){case"reaction":{let Oe={id:W,server_id:ne.attrs.message_id,reaction:{code:YA(ne,"reaction"),count:1}};c.emit("newsletter.reaction",Oe);break}case"view":{let Oe={id:W,server_id:ne.attrs.message_id,count:parseInt(ne.content?.toString()||"0",10)};c.emit("newsletter.view",Oe);break}case"participant":{let Oe={id:W,author:re,user:ne.attrs.jid,action:ne.attrs.action,new_role:ne.attrs.role};c.emit("newsletter-participants.update",Oe);break}case"update":{let Oe=le(ne,"settings");if(Oe){let Ce={},he=le(Oe,"name");he?.content&&(Ce.name=he.content.toString());let me=le(Oe,"description");me?.content&&(Ce.description=me.content.toString()),c.emit("newsletter-settings.update",{id:W,update:Ce})}break}case"message":{let Oe=le(ne,"plaintext");if(Oe?.content)try{let Ce=typeof Oe.content=="string"?Buffer.from(Oe.content,"binary"):Buffer.from(Oe.content),he=oe.Message.decode(Ce).toJSON(),me=oe.WebMessageInfo.fromObject({key:{remoteJid:W,id:ne.attrs.message_id||ne.attrs.server_id,fromMe:!1},message:he,messageTimestamp:+ne.attrs.t}).toJSON();await _(me,"append"),t.debug("Processed plaintext newsletter message")}catch(Ce){t.error({error:Ce},"Failed to decode plaintext newsletter message")}break}default:t.warn({node:ee,child:ne},"Unknown newsletter notification child");break}},Be=async(ee,W)=>{let X=Rne(ee,W,I.creds.me.id);t.debug({recv:{tag:ee.tag,attrs:ee.attrs},sent:X.attrs},"sent ack"),await U(X)},We=async(ee,W)=>{let X={tag:"call",attrs:{from:I.creds.me.id,to:W},content:[{tag:"reject",attrs:{"call-id":ee,"call-creator":W,count:"0"},content:void 0}]};await m(X)},Ye=async(ee,W=!1)=>{let{fullMessage:X}=TF(ee,I.creds.me.id,I.creds.me.lid||""),{key:re}=X,ne=re.id;if(P){if(P.hasExceededMaxRetries(ne)){t.debug({msgId:ne},"reached retry limit with new retry manager, clearing"),P.markRetryFailed(ne);return}let xA=P.incrementRetryCount(ne),et=`${ne}:${re?.participant}`;await ie.set(et,xA)}else{let xA=`${ne}:${re?.participant}`,et=await ie.get(xA)||0;if(et>=i){t.debug({retryCount:et,msgId:ne},"reached retry limit, clearing"),await ie.del(xA);return}et+=1,await ie.set(xA,et)}let Oe=`${ne}:${re?.participant}`,Ce=await ie.get(Oe)||1,{account:he,signedPreKey:me,signedIdentityKey:je}=I.creds,lA=ee.attrs.from,QA=!1,$A="";if(A&&P&&Ce>1)try{let xA=y.jidToSignalProtocolAddress(lA),et=await y.validateSession(lA),ve=P.shouldRecreateSession(lA,et.exists);QA=ve.recreate,$A=ve.reason,QA&&(t.debug({fromJid:lA,retryCount:Ce,reason:$A},"recreating session for retry"),await I.keys.set({session:{[xA]:null}}),W=!0)}catch(xA){t.warn({error:xA,fromJid:lA},"failed to check session recreation")}if(Ce<=2)if(P)P.schedulePhoneRequest(ne,async()=>{try{let xA=await Qe(re);t.debug(`sendRetryRequest: requested placeholder resend (${xA}) for message ${ne} (scheduled)`)}catch(xA){t.warn({error:xA,msgId:ne},"failed to send scheduled phone request")}});else{let xA=await Qe(re);t.debug(`sendRetryRequest: requested placeholder resend for message ${xA}`)}let RA=mf(he,!0);await I.keys.transaction(async()=>{let xA={tag:"receipt",attrs:{id:ne,type:"retry",to:ee.attrs.from},content:[{tag:"retry",attrs:{count:Ce.toString(),id:ee.attrs.id,t:ee.attrs.t,v:"1",error:"0"}},{tag:"registration",attrs:{},content:kg(I.creds.registrationId)}]};if(ee.attrs.recipient&&(xA.attrs.recipient=ee.attrs.recipient),ee.attrs.participant&&(xA.attrs.participant=ee.attrs.participant),Ce>1||W||QA){let{update:et,preKeys:ve}=await AU(I,1),[tA]=Object.keys(ve),At=ve[+tA];xA.content.push({tag:"keys",attrs:{},content:[{tag:"type",attrs:{},content:Buffer.from(Rg)},{tag:"identity",attrs:{},content:je.public},eU(At,+tA),yf(me),{tag:"device-identity",attrs:{},content:RA}]}),c.emit("creds.update",et)}await U(xA),t.info({msgAttrs:ee.attrs,retryCount:Ce},"sent retry receipt")},I?.creds?.me?.id||"sendRetryRequest")},Re=new Set,Ze=ee=>{(async()=>{let W=uA(ee),X=await js(W,V),ne=(await I.keys.get("tctoken",[X]))?.[X]?.senderTimestamp;if(ne==null||Ap(ne))return;t.debug({jid:W,senderTimestamp:ne},"identity changed, re-issuing tctoken");let Oe=y.lidMapping.getPNForLID.bind(y.lidMapping),Ce=await bf(W,r.serverProps.lidTrustedTokenIssueToLid,V,Oe),he=await H([Ce],ne);await aE({result:he,fallbackJid:X,keys:I.keys,getLIDForPN:V,onNewJidStored:NA})})().catch(W=>{t.debug({jid:ee,err:W?.message},"failed to re-issue tctoken after identity change")})},iA=async ee=>{if(ee.attrs.from===OA){let X=ee.attrs.id;if(X&&Re.has(X))return;let ne=+le(ee,"count").attrs.value,Oe=ne{let re=ee.attrs.participant,ne=ee.attrs.participant_pn,Oe=ee.attrs.participant_username,Ce=le(W,"participant")?.attrs?.jid||re,he=le(W,"participant")?.attrs?.phone_number||ne;switch(W?.tag){case"create":let me=EE(W);X.messageStubType=TA.GROUP_CREATE,X.messageStubParameters=[me.subject],X.key={participant:me.owner,participantAlt:me.ownerPn},c.emit("chats.upsert",[{id:me.id,name:me.subject,conversationTimestamp:me.creation}]),c.emit("groups.upsert",[{...me,author:re,authorPn:ne,authorUsername:Oe}]);break;case"ephemeral":case"not_ephemeral":X.message={protocolMessage:{type:oe.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,ephemeralExpiration:+(W.attrs.expiration||0)}};break;case"modify":let je=kA(W,"participant").map(ve=>ve.attrs.jid);X.messageStubParameters=je||[],X.messageStubType=TA.GROUP_PARTICIPANT_CHANGE_NUMBER;break;case"promote":case"demote":case"remove":case"add":case"leave":let lA=`GROUP_PARTICIPANT_${W.tag.toUpperCase()}`;X.messageStubType=TA[lA];let QA=kA(W,"participant").map(({attrs:ve})=>({id:ve.jid,phoneNumber:qA(ve.jid)&&_t(ve.phone_number)?ve.phone_number:void 0,lid:_t(ve.jid)&&qA(ve.lid)?ve.lid:void 0,username:ve.participant_username||ve.username||void 0,admin:ve.type||null}));QA.length===1&&(Tt(QA[0].id,re)||Tt(QA[0].id,ne))&&W.tag==="remove"&&(X.messageStubType=TA.GROUP_PARTICIPANT_LEAVE),X.messageStubParameters=QA.map(ve=>JSON.stringify(ve));break;case"subject":X.messageStubType=TA.GROUP_CHANGE_SUBJECT,X.messageStubParameters=[W.attrs.subject];break;case"description":let $A=le(W,"body")?.content?.toString();X.messageStubType=TA.GROUP_CHANGE_DESCRIPTION,X.messageStubParameters=$A?[$A]:void 0;break;case"announcement":case"not_announcement":X.messageStubType=TA.GROUP_CHANGE_ANNOUNCE,X.messageStubParameters=[W.tag==="announcement"?"on":"off"];break;case"locked":case"unlocked":X.messageStubType=TA.GROUP_CHANGE_RESTRICT,X.messageStubParameters=[W.tag==="locked"?"on":"off"];break;case"invite":X.messageStubType=TA.GROUP_CHANGE_INVITE_LINK,X.messageStubParameters=[W.attrs.code];break;case"member_add_mode":let RA=W.content;RA&&(X.messageStubType=TA.GROUP_MEMBER_ADD_MODE,X.messageStubParameters=[RA.toString()]);break;case"membership_approval_mode":let xA=le(W,"group_join");xA&&(X.messageStubType=TA.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE,X.messageStubParameters=[xA.attrs.state]);break;case"created_membership_requests":X.messageStubType=TA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,X.messageStubParameters=[JSON.stringify({lid:Ce,pn:he}),"created",W.attrs.request_method];break;case"revoked_membership_requests":let et=Tt(Ce,re);X.messageStubType=TA.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD,X.messageStubParameters=[JSON.stringify({lid:Ce,pn:he}),et?"revoked":"rejected"];break}},WA=async ee=>{let[W]=ys(ee),X=uA(ee.attrs.from);if(!W){t.debug({from:X},"devices notification missing child, skipping");return}let re=W.tag,ne=W.attrs.device_hash,Oe=kA(W,"device");if(Tt(X,I.creds.me.id)||Tt(X,I.creds.me.lid)){let he=Oe.map(me=>me.attrs.jid);t.info({deviceJids:he},"got my own devices")}if(!Oe.length){t.debug({from:X,tag:re},"no devices in notification, skipping");return}let Ce=[];for(let he of Oe){let me=he.attrs.jid;if(!me)continue;let je=yA(me);if(!je){t.debug({jid:me},"failed to decode device jid, skipping");continue}Ce.push({jid:me,user:je.user,server:je.server,device:je.device})}Ce.length&&await g.mutex(async()=>{let he=new Map;for(let me of Ce){let je=he.get(me.user)||[];je.push(me),he.set(me.user,je)}for(let[me,je]of he){if(re==="update"){t.debug({user:me},`${me}'s device list updated, dropping cached devices`),await s?.del(me);continue}re==="remove"&&await y.deleteSession(je.map(RA=>RA.jid));let lA=await s?.get(me)||[];if(!lA.length){t.debug({user:me,tag:re},"device list not cached, deferring to USync refresh");continue}let QA=new Set(je.map(RA=>RA.device)),$A;switch(re){case"add":t.info({deviceHash:ne,count:je.length},"devices added"),$A=[...lA.filter(RA=>!QA.has(RA.device)),...je.map(RA=>({user:RA.user,server:RA.server,device:RA.device}))];break;case"remove":t.info({deviceHash:ne,count:je.length},"devices removed"),$A=lA.filter(RA=>!QA.has(RA.device));break;default:t.debug({tag:re},"Unknown device list change tag");continue}$A.length===0?await s?.del(me):await s?.set(me,$A)}})},FA=async ee=>{let W={},[X]=ys(ee),re=ee.attrs.type,ne=uA(ee.attrs.from);switch(re){case"newsletter":await ce(ee);break;case"mex":await Le(ee);break;case"w:gp2":gA(ee,X,W);break;case"mediaretry":let Oe=hoe(ee);c.emit("messages.media-update",[Oe]);break;case"encrypt":await iA(ee);break;case"devices":try{await WA(ee)}catch(ho){t.error({error:ho,node:ee},"failed to handle devices notification")}break;case"server_sync":let Ce=le(ee,"collection");if(Ce){let ho=Ce.attrs.name;await T([ho],!1)}break;case"picture":let he=le(ee,"set"),me=le(ee,"delete");if(c.emit("contacts.update",[{id:uA(ee?.attrs?.from)||(he||me)?.attrs?.hash||"",imgUrl:he?"changed":"removed"}]),Ur(ne)){let ho=he||me;W.messageStubType=TA.GROUP_CHANGE_ICON,he&&(W.messageStubParameters=[he.attrs.id]),W.participant=ho?.attrs.author,W.key={...W.key||{},participant:he?.attrs.author}}break;case"account_sync":if(X.tag==="disappearing_mode"){let ho=+X.attrs.duration,dp=+X.attrs.t;t.info({newDuration:ho},"updated account disappearing mode"),c.emit("creds.update",{accountSettings:{...I.creds.accountSettings,defaultDisappearingMode:{ephemeralExpiration:ho,ephemeralSettingTimestamp:dp}}})}else if(X.tag==="blocklist"){let ho=kA(X,"item");for(let{attrs:dp}of ho){let EM=[dp.jid],CM=dp.action==="block"?"add":"remove";c.emit("blocklist.update",{blocklist:EM,type:CM})}}break;case"link_code_companion_reg":let je=le(ee,"link_code_companion_reg"),lA=JA(Qa(je,"link_code_pairing_ref")),QA=JA(Qa(je,"primary_identity_pub")),$A=JA(Qa(je,"link_code_pairing_wrapped_primary_ephemeral_pub")),RA=await LA($A),xA=Br.sharedKey(I.creds.pairingEphemeralKeyPair.private,RA),et=PH(32),ve=PH(32),tA=Rn(xA,32,{salt:ve,info:"link_code_pairing_key_bundle_encryption_key"}),At=Buffer.concat([Buffer.from(I.creds.signedIdentityKey.public),QA,et]),zr=PH(12),rr=Dl(At,tA,zr,Buffer.alloc(0)),po=Buffer.concat([ve,zr,rr]),dM=Br.sharedKey(I.creds.signedIdentityKey.private,QA),hM=Buffer.concat([xA,dM,et]);I.creds.advSecretKey=Buffer.from(Rn(hM,32,{info:"adv_secret"})).toString("base64"),await m({tag:"iq",attrs:{to:OA,type:"set",id:r.generateMessageTag(),xmlns:"md"},content:[{tag:"link_code_companion_reg",attrs:{jid:I.creds.me.id,stage:"companion_finish"},content:[{tag:"link_code_pairing_wrapped_key_bundle",attrs:{},content:po},{tag:"companion_identity_public",attrs:{},content:I.creds.signedIdentityKey.public},{tag:"link_code_pairing_ref",attrs:{},content:lA}]}]}),I.creds.registered=!0,c.emit("creds.update",I.creds);break;case"privacy_token":await wA(ee);break}if(Object.keys(W).length)return W},Me=new Set,CA=(async()=>{try{let ee=await yb(I.keys);for(let W of ee)Me.add(W);t.debug({count:Me.size},"loaded tctoken index")}catch(ee){t.warn({err:ee?.message},"failed to load tctoken index")}})(),we;async function Ke(){we&&(clearTimeout(we),we=void 0);let ee=await rE(I.keys,Me);return I.keys.set({tctoken:ee})}function Ve(){we&&clearTimeout(we),we=setTimeout(()=>{we=void 0,Ke().catch(ee=>{t.warn({err:ee?.message},"failed to save tctoken index")})},5e3)}function NA(ee){ee&&ee!==hI&&!Me.has(ee)&&(Me.add(ee),Ve())}let wA=async ee=>{if(!le(ee,"tokens"))return;let X=uA(ee.attrs.from),ne=(ee.attrs.sender_lid&&qA(uA(ee.attrs.sender_lid))?uA(ee.attrs.sender_lid):void 0)??await js(X,V);t.debug({from:X,storageJid:ne},"processing privacy token notification"),await aE({result:ee,fallbackJid:ne,keys:I.keys,getLIDForPN:V,onNewJidStored:NA})};async function LA(ee){let W=JA(ee),X=W.slice(0,32),re=await iD(I.creds.pairingCode,X),ne=W.slice(32,48),Oe=W.slice(48,80);return p7(Oe,re,ne)}function JA(ee){if(ee===void 0)throw new Uf.Boom("Invalid buffer",{statusCode:400});return ee instanceof Buffer?ee:Buffer.from(ee)}let lt=async(ee,W)=>{let X=`${ee}:${W}`;return(await ie.get(X)||0){let X=`${ee}:${W}`,re=(await ie.get(X)||0)+1;await ie.set(X,re)},pe=async(ee,W,X,re)=>{let ne=ee.remoteJid,Oe=ee.participant||ne,Ce=+X.attrs.count||1,he=W[0],me=[];for(let ve of W){let tA;if(P){let At=P.getRecentMessage(ne,ve);At&&(tA=At.message,t.debug({jid:ne,id:ve},"found message in retry cache"),P.markRetrySuccess(ve))}tA||(tA=await e({...ee,id:ve}),tA&&(t.debug({jid:ne,id:ve},"found message via getMessage"),P&&P.markRetrySuccess(ve))),me.push(tA)}let je=!yA(Oe)?.device,lA=y.jidToSignalProtocolAddress(Oe),QA=!1,$A=Roe(re);if($A)try{await y.injectE2ESession({jid:Oe,session:$A}),QA=!0,t.debug({participant:Oe,retryCount:Ce},"injected session from retry receipt key bundle")}catch(ve){t.warn({error:ve,participant:Oe},"failed to inject session from retry receipt")}if(!QA){let ve=xc(re,"registration",4);if(typeof ve=="number"&&Number.isInteger(ve)){let tA=await y.getSessionInfo(Oe);tA&&tA.registrationId!==0&&tA.registrationId!==ve&&(t.info({participant:Oe,stored:tA.registrationId,received:ve},"reg id mismatch on retry without bundle, deleting session"),await I.keys.set({session:{[lA]:null}}))}}let RA=2;if(he&&P){let ve=await y.getSessionInfo(Oe);ve&&(Ce===RA?P.saveBaseKey(lA,he,ve.baseKey):Ce>RA&&(P.hasSameBaseKey(lA,he,ve.baseKey)&&(t.warn({participant:Oe,retryCount:Ce},"base key collision on retry, forcing fresh session"),await I.keys.set({session:{[lA]:null}})),P.deleteBaseKey(lA,he)))}let xA=!1,et="";if(A&&P&&Ce>1&&!QA)try{let ve=await y.validateSession(Oe),tA=P.shouldRecreateSession(Oe,ve.exists);xA=tA.recreate,et=tA.reason,xA&&(t.debug({participant:Oe,retryCount:Ce,reason:et},"recreating session for outgoing retry"),await I.keys.set({session:{[lA]:null}}))}catch(ve){t.warn({error:ve,participant:Oe},"failed to check session recreation for outgoing retry")}QA||await L([Oe],!0),Ur(ne)&&await I.keys.set({"sender-key-memory":{[ne]:null}}),t.debug({participant:Oe,sendToAll:je,shouldRecreateSession:xA,recreateReason:et,injectedFromBundle:QA},"prepared session for retry resend");for(let[ve,tA]of me.entries())if(W[ve])if(tA&&await lt(W[ve],Oe)){await wt(W[ve],Oe);let At={messageId:W[ve]};je?At.useUserDevicesCache=!1:At.participant={jid:Oe,count:+X.attrs.count},await F(ee.remoteJid,tA,At)}else t.debug({jid:ee.remoteJid,id:W[ve]},"recv retry request, but message not available")},Ie=async ee=>{let{attrs:W,content:X}=ee,re=W.from.includes("lid"),ne=Tt(W.participant||W.from,re?I.creds.me?.lid:I.creds.me?.id),Oe=!ne||Ur(W.from)?W.from:W.recipient,Ce=!W.recipient||(W.type==="retry"||W.type==="sender")&&ne,he={remoteJid:Oe,id:"",fromMe:Ce,participant:W.participant},me=[W.id];if(Array.isArray(X)){let je=kA(X[0],"item");me.push(...je.map(lA=>lA.attrs.id))}try{await Promise.all([Q.mutex(async()=>{let je=w7(W.type);if(typeof je<"u"&&(je>=oe.WebMessageInfo.Status.SERVER_ACK||!ne))if(Ur(Oe)||Tg(Oe)){if(W.participant){let lA=je===oe.WebMessageInfo.Status.DELIVERY_ACK?"receiptTimestamp":"readTimestamp";c.emit("message-receipt.update",me.map(QA=>({key:{...he,id:QA},receipt:{userJid:uA(W.participant),[lA]:+W.t}})))}}else c.emit("messages.update",me.map(lA=>({key:{...he,id:lA},update:{status:je,messageTimestamp:Hr(+(W.t??0))}})));if(W.type==="retry"){he.participant=he.participant||W.from;let lA=le(ee,"retry");if(me[0]&&he.participant&&await lt(me[0],he.participant))if(he.fromMe)try{await wt(me[0],he.participant),t.debug({attrs:W,key:he},"recv retry request"),await pe(he,me,lA,ee)}catch(QA){t.error({key:he,ids:me,trace:QA instanceof Error?QA.stack:"Unknown error"},"error in sending message again")}else t.info({attrs:W,key:he},"recv retry for not fromMe message");else t.info({attrs:W,key:he},"will not send message again, as sent too many times")}})])}finally{await Be(ee).catch(je=>t.error({ackErr:je},"failed to ack receipt"))}},be=async ee=>{let W=ee.attrs.from;try{await Promise.all([f.mutex(async()=>{let X=await FA(ee);if(X){let re=Tt(ee.attrs.participant||W,I.creds.me.id),{senderAlt:ne,addressingMode:Oe}=gD(ee);X.key={remoteJid:W,fromMe:re,participant:ee.attrs.participant,participantAlt:ne,participantUsername:ee.attrs.participant_username,addressingMode:Oe,id:ee.attrs.id,...X.key||{}},X.participant??(X.participant=ee.attrs.participant),X.messageTimestamp=+ee.attrs.t;let Ce=oe.WebMessageInfo.fromObject(X);await _(Ce,"append")}})])}finally{await Be(ee).catch(X=>t.error({ackErr:X},"failed to ack notification"))}},oA=async ee=>{if(le(ee,"enc")?.attrs.type==="msmsg"){t.debug({key:ee.attrs.key},"ignored msmsg"),await Be(ee,Ml.MissingMessageSecret);return}let X=!1;try{let{fullMessage:re,category:ne,author:Oe,decrypt:Ce}=R7(ee,I.creds.me.id,I.creds.me.lid||"",y,t),he=re.key.participantAlt||re.key.remoteJidAlt;if(he){let me=yA(he)?.server,je=re.key.participant||re.key.remoteJid;me==="lid"?await y.lidMapping.getPNForLID(he)||(await y.lidMapping.storeLIDPNMappings([{lid:he,pn:je}]),await y.migrateSession(je,he)):(await y.lidMapping.storeLIDPNMappings([{lid:je,pn:he}]),await y.migrateSession(he,je))}await B.mutex(async()=>{if(await Ce(),re.key?.remoteJid&&re.key?.id&&re.message&&P&&P.addRecentMessage(re.key.remoteJid,re.key.id,re.message),re.messageStubType===oe.WebMessageInfo.StubType.CIPHERTEXT&&re.category!=="peer"){if(re?.messageStubParameters?.[0]===T7)return X=!0,Be(ee,Ml.ParsingError);if(re.messageStubParameters?.[0]===sD){let je=le(ee,"unavailable")?.attrs?.type;if(je==="bot_unavailable_fanout"||je==="hosted_unavailable_fanout"||je==="view_once_unavailable_fanout")return t.debug({msgId:re.key.id,unavailableType:je},"skipping placeholder resend for excluded unavailable type"),X=!0,Be(ee);let lA=ya()-Hr(re.messageTimestamp);if(lA>ace)return t.debug({msgId:re.key.id,messageAge:lA},"skipping placeholder resend for old message"),X=!0,Be(ee);let QA={remoteJid:re.key.remoteJid,fromMe:re.key.fromMe,id:re.key.id,participant:re.key.participant},$A={key:re.key,messageTimestamp:re.messageTimestamp,pushName:re.pushName,participant:re.participant,verifiedBizName:re.verifiedBizName};Qe(QA,$A).then(RA=>{RA&&RA!=="RESOLVED"&&(t.debug({msgId:re.key.id,requestId:RA},"requested placeholder resend for unavailable message"),c.emit("messages.update",[{key:re.key,update:{messageStubParameters:[sD,RA]}}]))}).catch(RA=>{t.warn({err:RA,msgId:re.key.id},"failed to request placeholder resend for unavailable message")}),X=!0,await Be(ee)}else{if(Tg(re.key.remoteJid)){let me=ya()-Hr(re.messageTimestamp);if(me>rce)return t.debug({msgId:re.key.id,messageAge:me,remoteJid:re.key.remoteJid},"skipping retry for expired status message"),X=!0,Be(ee)}t.debug("[handleMessage] Attempting retry request for failed decryption"),await Ae.mutex(async()=>{try{if(!d.isOpen){t.debug({node:ee},"Connection closed, skipping retry");return}let me=le(ee,"enc");await Ye(ee,!me),o&&await DB(o)}catch(me){t.error({err:me},"Failed to send retry")}X=!0,await Be(ee,Ml.UnhandledError)})}}else if(P&&re.key.id&&P.cancelPendingPhoneRequest(re.key.id),Kc(re.key.remoteJid))X=!0,await Be(ee),t.debug({key:re.key},"processed newsletter message without receipts");else{let je,lA=re.key.participant;if(ne==="peer"?je="peer_msg":re.key.fromMe?(je="sender",(qA(re.key.remoteJid)||qA(re.key.remoteJidAlt))&&(lA=Oe)):_e||(je="inactive"),X=!0,await q(re.key.remoteJid,lA,[re.key.id],je),hb(re.message)){let $A=uA(re.key.remoteJid);await q($A,void 0,[re.key.id],"hist_sync")}}Dne(re,I.creds.me.id,I.creds.me.lid),await _(re,ee.attrs.offline?"append":"notify")})}catch(re){t.error({error:re,node:_n(ee)},"error in handling message"),X||await Be(ee,Ml.UnhandledError).catch(ne=>t.error({ackErr:ne},"failed to ack message after error"))}},dA=async ee=>{try{let{attrs:W}=ee,[X]=ys(ee);if(!X)throw new Uf.Boom("Missing call info in call node");let re=O7(X),ne=X.attrs["call-id"],Oe=X.attrs.from||X.attrs["call-creator"],Ce={chatId:W.from,from:Oe,callerPn:X.attrs.caller_pn,id:ne,date:new Date(+W.t*1e3),offline:!!W.offline,status:re};if(re==="relaylatency"){let me=X.attrs.latency||X.attrs.latency_ms||X.attrs["latency-ms"],je=me?Number(me):void 0;Number.isFinite(je)&&(Ce.latencyMs=je)}re==="offer"&&(Ce.isVideo=!!le(X,"video"),Ce.isGroup=X.attrs.type==="group"||!!X.attrs["group-jid"],Ce.groupJid=X.attrs["group-jid"],await De.set(Ce.id,Ce));let he=await De.get(Ce.id);he&&(Ce.isVideo=he.isVideo,Ce.isGroup=he.isGroup,Ce.callerPn=Ce.callerPn||he.callerPn),(re==="reject"||re==="accept"||re==="timeout"||re==="terminate")&&await De.del(Ce.id),c.emit("call",[Ce])}catch(W){t.error({error:W,node:_n(ee)},"error in handling call")}finally{await Be(ee).catch(W=>t.error({ackErr:W},"failed to ack call"))}},PA=async({attrs:ee})=>{let W={remoteJid:ee.from,fromMe:!0,id:ee.id};if(ee.error){let X=ee.error===String(Ml.SenderReachoutTimelocked);if(ee.error===_F.MessageAccountRestriction){t.warn({msgId:ee.id,from:ee.from},"error 463: account restricted or missing tctoken for contact");let re=ee.from;re&&!lo.has(re)&&(lo.add(re),(async()=>{try{let ne=y.lidMapping.getPNForLID.bind(y.lidMapping),Oe=await js(re,V),Ce=await bf(re,r.serverProps.lidTrustedTokenIssueToLid,V,ne),he=await H([Ce],ya());await aE({result:he,fallbackJid:Oe,keys:I.keys,getLIDForPN:V,onNewJidStored:NA}),t.debug({from:re},"completed 463 token recovery issuance")}catch(ne){t.debug({from:re,err:ne?.message},"failed 463 token recovery issuance")}finally{lo.delete(re)}})())}else ee.error===_F.SmaxInvalid?t.warn({msgId:ee.id,from:ee.from},"smax-invalid (479): stanza rejected by server \u2014 likely stale device session or malformed addressing"):X?(await N().catch(re=>t.warn({err:re},"failed to fetch reachout timelock")),t.warn({attrs:ee},"received error in ack")):t.warn({attrs:ee},"received error in ack");c.emit("messages.update",[{key:W,update:{status:th.ERROR,messageStubParameters:X?[ee.error,N7]:[ee.error]}}])}},Ht=async(ee,W,X)=>{c.buffer(),await re(),c.flush();function re(){return X(ee,!1).catch(ne=>R(ne,W))}},st=wce(new Map([["message",oA],["call",dA],["receipt",Ie],["notification",be]]),{isWsOpen:()=>d.isOpen,onUnexpectedError:R,yieldToEventLoop:()=>new Promise(ee=>setImmediate(ee))}),Qr=async(ee,W,X,re)=>{let ne=W.attrs.from,Oe=ne;if(ee==="receipt"&&ne){let he=W.attrs,me=he.from.includes("lid");Oe=!Tt(he.participant||he.from,me?I.creds.me?.lid:I.creds.me?.id)||Ur(he.from)?he.from:he.recipient}if(Oe&&Oe!==OA&&a(Oe)){await Be(W,ee==="message"?Ml.UnhandledError:void 0);return}!!W.attrs.offline?st.enqueue(ee,W):await Ht(W,X,re)};d.on("CB:message",async ee=>{await Qr("message",ee,"processing message",oA)}),d.on("CB:call",async ee=>{await Qr("call",ee,"handling call",dA)}),d.on("CB:receipt",async ee=>{await Qr("receipt",ee,"handling receipt",Ie)}),d.on("CB:notification",async ee=>{await Qr("notification",ee,"handling notification",be)}),d.on("CB:ack,class:message",ee=>{PA(ee).catch(W=>R(W,"handling bad ack"))}),c.on("call",async([ee])=>{if(ee&&(ee.status==="timeout"||ee.status==="offer"&&ee.isGroup)){let W={key:{remoteJid:ee.chatId,id:ee.id,fromMe:!1},messageTimestamp:ya(ee.date)};ee.status==="timeout"?ee.isGroup?W.messageStubType=ee.isVideo?TA.CALL_MISSED_GROUP_VIDEO:TA.CALL_MISSED_GROUP_VOICE:W.messageStubType=ee.isVideo?TA.CALL_MISSED_VIDEO:TA.CALL_MISSED_VOICE:W.message={call:{callKey:Buffer.from(ee.id)}};let X=oe.WebMessageInfo.fromObject(W);await _(X,ee.offline?"append":"notify")}});let tr=0,lo=new Set;c.on("connection.update",({isOnline:ee,connection:W})=>{if(typeof ee<"u"&&(_e=ee,t.trace(`sendActiveReceipts set to "${_e}"`)),W==="close"&&we){clearTimeout(we),we=void 0;try{Promise.resolve(Ke()).catch(()=>{})}catch{}}if(ee){let X=Date.now(),re=1440*60*1e3;X-tr>=re&&(tr=X,ji())}}),J(()=>{!n.msgRetryCounterCache&&ie.close&&ie.close(),!n.callOfferCache&&De.close&&De.close(),fe.close(),_e=!1});async function ji(){try{await CA;let ee=await yb(I.keys),W=new Set(Me);for(let he of ee)W.add(he);if(!W.size)return;let X=[...W],re=await I.keys.get("tctoken",X),ne={},Oe=new Set,Ce=0;for(let he of X){let me=re[he];if(!me){Ce++;continue}let je=!!me.token?.length,lA=je&&Ap(me.timestamp),QA=me.senderTimestamp!==void 0,$A=QA&&Ap(me.senderTimestamp),RA=je&&!lA,xA=QA&&!$A;!RA&&!xA?(ne[he]=null,Ce++):lA&&xA?(ne[he]={token:Buffer.alloc(0),senderTimestamp:me.senderTimestamp},Oe.add(he),Ce++):Oe.add(he)}if(Ce===0)return;await I.keys.set({tctoken:{...ne,[hI]:{token:Buffer.from(JSON.stringify([...Oe]))}}}),Me.clear();for(let he of Oe)Me.add(he);t.debug({mutated:Ce,remaining:Oe.size},"pruned expired tctokens")}catch(ee){t.warn({err:ee?.message},"failed to prune expired tctokens")}}return{...r,sendMessageAck:Be,sendRetryRequest:Ye,rejectCall:We,fetchMessageHistory:Ee,requestPlaceholderResend:Qe,messageRetryManager:P}};var Nce=n=>{let t=Tce(n),{authState:o,query:i,waUploadToServer:e}=t,a=async f=>{let Q=[],y=["address","email","description"];return Q.push(...y.filter(_=>f[_]!==void 0&&f[_]!==null).map(_=>({tag:_,attrs:{},content:f[_]}))),f.websites!==void 0&&Q.push(...f.websites.map(_=>({tag:"website",attrs:{},content:_}))),f.hours!==void 0&&Q.push({tag:"business_hours",attrs:{timezone:f.hours.timezone},content:f.hours.days.map(_=>{let T={tag:"business_hours_config",attrs:{day_of_week:_.day,mode:_.mode}};return _.mode==="specific_hours"?{...T,attrs:{...T.attrs,open_time:_.openTimeInMinutes,close_time:_.closeTimeInMinutes}}:T})}),await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:Q}]})},A=async f=>{let{fileSha256:Q,filePath:y}=await gb(f,"biz-cover-photo"),m=Q.toString("base64"),{meta_hmac:_,fbid:T,ts:R}=await e(y,{fileEncSha256B64:m,mediaType:"biz-cover-photo"});return await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{id:String(T),op:"update",token:_,ts:String(R)}}]}]}),T},r=async f=>await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz"},content:[{tag:"business_profile",attrs:{v:"3",mutation_type:"delta"},content:[{tag:"cover_photo",attrs:{op:"delete",id:f}}]}]}),s=async({jid:f,limit:Q,cursor:y})=>{f=f||o.creds.me?.id,f=uA(f);let m=[{tag:"limit",attrs:{},content:Buffer.from((Q||10).toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}];y&&m.push({tag:"after",attrs:{},content:y});let _=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog",attrs:{jid:f,allow_shop_source:"true"},content:m}]});return Ice(_)},g=async(f,Q=51)=>{f=f||o.creds.me?.id,f=uA(f);let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"w:biz:catalog",smax_id:"35"},content:[{tag:"collections",attrs:{biz_jid:f},content:[{tag:"collection_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"item_limit",attrs:{},content:Buffer.from(Q.toString())},{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]}]});return lce(y)},c=async(f,Q)=>{let y=await i({tag:"iq",attrs:{to:OA,type:"get",xmlns:"fb:thrift_iq",smax_id:"5"},content:[{tag:"order",attrs:{op:"get",id:f},content:[{tag:"image_dimensions",attrs:{},content:[{tag:"width",attrs:{},content:Buffer.from("100")},{tag:"height",attrs:{},content:Buffer.from("100")}]},{tag:"token",attrs:{},content:Buffer.from(Q)}]}]});return pce(y)},I=async(f,Q)=>{Q=await _H(Q,e);let y=MH(f,Q),m=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_edit",attrs:{v:"1"},content:[y,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),_=le(m,"product_catalog_edit"),T=le(_,"product");return Ff(T)},d=async f=>{f.isHidden=!!f.isHidden,f=await _H(f,e);let Q=MH(void 0,f),y=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_add",attrs:{v:"1"},content:[Q,{tag:"width",attrs:{},content:"100"},{tag:"height",attrs:{},content:"100"}]}]}),m=le(y,"product_catalog_add"),_=le(m,"product");return Ff(_)},B=async f=>{let Q=await i({tag:"iq",attrs:{to:OA,type:"set",xmlns:"w:biz:catalog"},content:[{tag:"product_catalog_delete",attrs:{v:"1"},content:f.map(m=>({tag:"product",attrs:{},content:[{tag:"id",attrs:{},content:Buffer.from(m)}]}))}]});return{deleted:+(le(Q,"product_catalog_delete")?.attrs.deleted_count||0)}};return{...t,logger:n.logger,getOrderDetails:c,getCatalog:s,getCollections:g,productCreate:d,productDelete:B,productUpdate:I,updateBussinesProfile:a,updateCoverPhoto:A,removeCoverPhoto:r}};var Rce=n=>{let t=Nce(n),{authState:o,ev:i,query:e,upsertMessage:a}=t,A=async(I,d,B)=>e({tag:"iq",attrs:{type:d,xmlns:"w:g2",to:I},content:B}),r=async I=>{let d=await A(I,"get",[{tag:"query",attrs:{request:"interactive"}}]);return GH(d)},s=async()=>{let I=await e({tag:"iq",attrs:{to:"@g.us",xmlns:"w:g2",type:"get"},content:[{tag:"participating",attrs:{},content:[{tag:"participants",attrs:{}},{tag:"description",attrs:{}}]}]}),d={},B=le(I,"communities");if(B){let f=kA(B,"community");for(let Q of f){let y=GH({tag:"result",attrs:{},content:[Q]});d[y.id]=y}}return t.ev.emit("groups.update",Object.values(d)),d};async function g(I){vf.info({node:I},"parseGroupResult");let d=le(I,"group");if(d)try{vf.info({groupNode:d},"groupNode");let B=await t.groupMetadata(`${d.attrs.id}@g.us`);return B||c.empty()}catch(B){return console.error("Error parsing group metadata:",B),c.empty()}return c.empty()}let c={empty:()=>null,of:I=>I!==null?{value:I}:null};return t.ws.on("CB:ib,,dirty",async I=>{let{attrs:d}=le(I,"dirty");d.type==="communities"&&(await s(),await t.cleanDirtyBits("groups"))}),{...t,communityMetadata:r,communityCreate:async(I,d)=>{let B=bF().substring(0,12),f=await A("@g.us","set",[{tag:"create",attrs:{subject:I},content:[{tag:"description",attrs:{id:B},content:[{tag:"body",attrs:{},content:Buffer.from(d||"","utf-8")}]},{tag:"parent",attrs:{default_membership_approval_mode:"request_required"}},{tag:"allow_non_admin_sub_group_creation",attrs:{}},{tag:"create_general_chat",attrs:{}}]}]);return await g(f)},communityCreateGroup:async(I,d,B)=>{let f=Kr(),Q=await A("@g.us","set",[{tag:"create",attrs:{subject:I,key:f},content:[...d.map(y=>({tag:"participant",attrs:{jid:y}})),{tag:"linked_parent",attrs:{jid:B}}]}]);return await g(Q)},communityLeave:async I=>{await A("@g.us","set",[{tag:"leave",attrs:{},content:[{tag:"community",attrs:{id:I}}]}])},communityUpdateSubject:async(I,d)=>{await A(I,"set",[{tag:"subject",attrs:{},content:Buffer.from(d,"utf-8")}])},communityLinkGroup:async(I,d)=>{await A(d,"set",[{tag:"links",attrs:{},content:[{tag:"link",attrs:{link_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}]}])},communityUnlinkGroup:async(I,d)=>{await A(d,"set",[{tag:"unlink",attrs:{unlink_type:"sub_group"},content:[{tag:"group",attrs:{jid:I}}]}])},communityFetchLinkedGroups:async I=>{let d=I,B=!1,f=await t.groupMetadata(I);f.linkedParent?d=f.linkedParent:B=!0;let Q=await A(d,"get",[{tag:"sub_groups",attrs:{}}]),y=[],m=le(Q,"sub_groups");if(m){let _=kA(m,"group");for(let T of _)y.push({id:T.attrs.id?Cr(T.attrs.id,"g.us"):void 0,subject:T.attrs.subject||"",creation:T.attrs.creation?Number(T.attrs.creation):void 0,owner:T.attrs.creator?uA(T.attrs.creator):void 0,size:T.attrs.size?Number(T.attrs.size):void 0})}return{communityJid:d,isCommunity:B,linkedGroups:y}},communityRequestParticipantsList:async I=>{let d=await A(I,"get",[{tag:"membership_approval_requests",attrs:{}}]),B=le(d,"membership_approval_requests");return kA(B,"membership_approval_request").map(Q=>Q.attrs)},communityRequestParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:"membership_requests_action",attrs:{},content:[{tag:B,attrs:{},content:d.map(_=>({tag:"participant",attrs:{jid:_}}))}]}]),Q=le(f,"membership_requests_action"),y=le(Q,B);return kA(y,"participant").map(_=>({status:_.attrs.error||"200",jid:_.attrs.jid}))},communityParticipantsUpdate:async(I,d,B)=>{let f=await A(I,"set",[{tag:B,attrs:B==="remove"?{linked_groups:"true"}:{},content:d.map(m=>({tag:"participant",attrs:{jid:m}}))}]),Q=le(f,B);return kA(Q,"participant").map(m=>({status:m.attrs.error||"200",jid:m.attrs.jid,content:m}))},communityUpdateDescription:async(I,d)=>{let f=(await r(I)).descId??null;await A(I,"set",[{tag:"description",attrs:{...d?{id:bF()}:{delete:"true"},...f?{prev:f}:{}},content:d?[{tag:"body",attrs:{},content:Buffer.from(d,"utf-8")}]:void 0}])},communityInviteCode:async I=>{let d=await A(I,"get",[{tag:"invite",attrs:{}}]);return le(d,"invite")?.attrs.code},communityRevokeInvite:async I=>{let d=await A(I,"set",[{tag:"invite",attrs:{}}]);return le(d,"invite")?.attrs.code},communityAcceptInvite:async I=>{let d=await A("@g.us","set",[{tag:"invite",attrs:{code:I}}]);return le(d,"community")?.attrs.jid},communityRevokeInviteV4:async(I,d)=>!!await A(I,"set",[{tag:"revoke",attrs:{},content:[{tag:"participant",attrs:{jid:d}}]}]),communityAcceptInviteV4:i.createBufferedFunction(async(I,d)=>{I=typeof I=="string"?{remoteJid:I}:I;let B=await A(d.groupJid,"set",[{tag:"accept",attrs:{code:d.inviteCode,expiration:d.inviteExpiration.toString(),admin:I.remoteJid}}]);return I.id&&(d=oe.Message.GroupInviteMessage.fromObject(d),d.inviteExpiration=0,d.inviteCode="",i.emit("messages.update",[{key:I,update:{message:{groupInviteMessage:d}}}])),await a({key:{remoteJid:d.groupJid,id:Kr(t.user?.id),fromMe:!1,participant:I.remoteJid},messageStubType:TA.GROUP_PARTICIPANT_ADD,messageStubParameters:[JSON.stringify(o.creds.me)],participant:I.remoteJid,messageTimestamp:ya()},"notify"),B.attrs.from}),communityGetInviteInfo:async I=>{let d=await A("@g.us","get",[{tag:"invite",attrs:{code:I}}]);return GH(d)},communityToggleEphemeral:async(I,d)=>{let B=d?{tag:"ephemeral",attrs:{expiration:d.toString()}}:{tag:"not_ephemeral",attrs:{}};await A(I,"set",[B])},communitySettingUpdate:async(I,d)=>{await A(I,"set",[{tag:d,attrs:{}}])},communityMemberAddMode:async(I,d)=>{await A(I,"set",[{tag:"member_add_mode",attrs:{},content:d}])},communityJoinApprovalMode:async(I,d)=>{await A(I,"set",[{tag:"membership_approval_mode",attrs:{},content:[{tag:"community_join",attrs:{state:d}}]}])},communityFetchAllParticipating:s}},GH=n=>{let t=le(n,"community"),o=le(t,"description"),i,e;o&&(i=YA(o,"body"),e=o.attrs.id);let a=t.attrs.id?.includes("@")?t.attrs.id:Cr(t.attrs.id||"","g.us"),A=le(t,"ephemeral")?.attrs.expiration,r=YA(t,"member_add_mode")==="all_member_add";return{id:a,subject:t.attrs.subject||"",subjectOwner:t.attrs.s_o,subjectTime:Number(t.attrs.s_t||0),size:kA(t,"participant").length,creation:Number(t.attrs.creation||0),owner:t.attrs.creator?uA(t.attrs.creator):void 0,desc:i,descId:e,linkedParent:le(t,"linked_parent")?.attrs.jid||void 0,restrict:!!le(t,"locked"),announce:!!le(t,"announcement"),isCommunity:!!le(t,"parent"),isCommunityAnnounce:!!le(t,"default_sub_community"),joinApprovalMode:!!le(t,"membership_approval_mode"),memberAddMode:r,participants:kA(t,"participant").map(({attrs:g})=>({id:g.jid,admin:g.type||null})),ephemeralDuration:A?+A:void 0,addressingMode:YA(t,"addressing_mode")}};var q5e=n=>{let t={...oce,...n};return Rce(t)},kce=q5e;var vce=kce;var z5e=Object.freeze({key:"whatsapp",label:"WhatsApp",get connectionLabel(){return w(" Web \u5173\u8054\u8BBE\u5907")},reactions:Object.freeze({processing:"\u{1F440}",success:"\u2705",error:"\u274C"})}),oM=class extends $n{constructor(t){super({...t,descriptor:z5e})}};import{chmod as Pce,mkdir as V5e,readdir as W5e}from"node:fs/promises";var Z5e=Object.freeze({level:"silent",trace(){},debug(){},info(){},warn(){},error(){},fatal(){},child(){return this}}),X5e=6e4;function Gce(){return Object.assign(new Error("WhatsApp connection was cancelled"),{name:"AbortError"})}function $5e(n){return n?.output?.statusCode??n?.data?.statusCode??n?.statusCode??null}function eZe(n){let t=n;if(typeof t=="string"){if(!/^\d+$/.test(t))return null;t=Number(t)}else typeof t=="bigint"?t=Number(t):t&&typeof t=="object"&&(t=Number(t.valueOf()));return Number.isFinite(t)&&t>=0?t*1e3:null}async function FH(n){await V5e(n,{recursive:!0,mode:448}),await Pce(n,448);let t=await W5e(n,{withFileTypes:!0}).catch(()=>[]);await Promise.all(t.filter(o=>o.isFile()).map(o=>Pce(`${n}/${o.name}`,384).catch(()=>{})))}function AZe(n,t){let o=n.user??t.creds.me,i=uA(o?.id);if(!/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(i??""))throw new Error("WhatsApp did not return a valid linked account");return{accountJid:i,name:typeof o?.name=="string"&&o.name.trim()?o.name.trim().slice(0,100):w("WhatsApp\u673A\u5668\u4EBA")}}async function nM({authDir:n,onQr:t,onMessage:o,onDisconnect:i,signal:e,logger:a=console,makeSocket:A=vce,loadAuthState:r=mne}={}){if(!n||typeof t!="function")throw new TypeError("WhatsApp Web session requires an auth directory and QR callback");await FH(n);let s=Date.now(),{state:g,saveCreds:c}=await r(n),I=g.keys.set.bind(g.keys);g.keys.set=async z=>{await I(z),await FH(n)};let d=!1,B=!1,f,Q,y=Promise.resolve(),m=null,_=0,T=null,R=new Promise((z,j)=>{f=z,Q=j}),L=z=>{B||(B=!0,Q(z))},U=async()=>{d||(d=!0,_+=1,L(Gce()),await T?.catch(()=>{}),await y.catch(()=>{}),await m?.end(void 0).catch(()=>{}))},F=async()=>{d||(d=!0,_+=1,L(Gce()),await T?.catch(()=>{}),await y.catch(()=>{}),await m?.logout("Removed from DeepSeek Harness").catch(()=>{}))},q=()=>{let z=++_,j=!1,P=A({auth:g,browser:wb.macOS("DeepSeek Harness"),logger:Z5e,markOnlineOnConnect:!1,syncFullHistory:!1,shouldSyncHistoryMessage:()=>!1,getMessage:async()=>{},generateHighQualityLinkPreview:!1});m=P;let J=()=>{!j||!g.creds.me||B||y.then(()=>{d||B||z!==_||!j||!g.creds.me||(B=!0,f(AZe(P,g)))}).catch(H=>L(H))};P.ev.on("creds.update",()=>{d||z!==_||(y=y.then(async()=>{await c(),await FH(n)}),y.catch(()=>a.error?.("[dsh-im:whatsapp] failed to persist linked-device state")),J())}),P.ev.on("connection.update",H=>{if(!(d||z!==_)&&(typeof H.qr=="string"&&H.qr&&t(H.qr),H.connection==="open"&&(j=!0,J()),H.connection==="close")){let N=$5e(H.lastDisconnect?.error);if(N===$t.restartRequired){T??=y.then(async()=>{d||z!==_||(await P.end(void 0).catch(()=>{}),!(d||z!==_)&&q())}).catch(Ae=>L(Ae)).finally(()=>{T=null});return}let k=N===$t.loggedOut,V=Object.assign(new Error(k?"WhatsApp linked device was removed from the phone":"WhatsApp Web connection closed"),{code:k?"logged-out":"connection-closed"});B?i?.({error:V,loggedOut:k}):L(V)}}),P.ev.on("messages.upsert",({messages:H,type:N})=>{if(!(d||z!==_||N!=="notify"&&N!=="append"||typeof o!="function"))for(let k of Array.isArray(H)?H:[]){if(N==="append"){let V=eZe(k?.messageTimestamp);if(V===null||V{a.error?.("[dsh-im:whatsapp] failed to process an inbound WhatsApp message")})}})};return q(),e&&(e.aborted?await U():e.addEventListener("abort",()=>void U(),{once:!0})),Object.freeze({get socket(){return m},ready:R,close:U,logout:F})}var UH=new Set(["image/jpeg","image/png","image/webp","image/gif"]),rZe=5*1024*1024,LH=15e3,HH=12e4,aZe=["ephemeralMessage","viewOnceMessage","documentWithCaptionMessage","viewOnceMessageV2","viewOnceMessageV2Extension","editedMessage","associatedChildMessage","groupStatusMessage","groupStatusMessageV2"],iZe=new Set(["viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension"]);function oZe(n){let t=n;for(let o=0;o<5&&t&&typeof t=="object";o+=1){let i=aZe.find(e=>t[e]?.message);if(!i)return!1;if(iZe.has(i))return!0;t=t[i].message}return!1}function nZe(n){return n?.extendedTextMessage?.contextInfo??n?.imageMessage?.contextInfo??n?.videoMessage?.contextInfo??n?.documentMessage?.contextInfo??null}function sZe(n){return n?.conversation??n?.extendedTextMessage?.text??n?.imageMessage?.caption??n?.videoMessage?.caption??n?.documentMessage?.caption??""}function Uce(n){if(Number.isSafeInteger(n)&&n>=0)return n;let t;try{t=Number(n?.toString?.())}catch{return}return Number.isSafeInteger(t)&&t>=0?t:void 0}async function gZe(n,t,{signal:o,maxBytes:i=rZe}={}){o?.throwIfAborted();let e=AbortSignal.timeout(LH),a=o?AbortSignal.any([o,e]):e,A=Promise.resolve().then(()=>t(n,"stream",{options:{signal:a}})),r=await new Promise((I,d)=>{let B=!1,f=(y,m)=>B?!1:(B=!0,a.removeEventListener("abort",Q),y(m),!0),Q=()=>f(d,a.reason);a.addEventListener("abort",Q,{once:!0}),A.then(y=>{f(I,y)||y?.destroy?.()},y=>f(d,y)),a.aborted&&Q()}).catch(I=>{throw o?.aborted?o.reason??I:e.aborted?new Bt("image-download-failed",`WhatsApp image download timed out after ${LH} ms`,w("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}),s=[],g=0,c=()=>r?.destroy?.(a.reason);a.addEventListener("abort",c,{once:!0});try{for await(let I of r){a.throwIfAborted();let d=Buffer.from(I);if(g+=d.length,g>i)throw r.destroy?.(),new Bt("image-too-large",`WhatsApp image exceeded ${i} bytes`,w("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));s.push(d)}}catch(I){throw o?.aborted?o.reason??I:e.aborted?new Bt("image-download-failed",`WhatsApp image stream timed out after ${LH} ms`,w("\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002")):I}finally{a.removeEventListener("abort",c)}return Buffer.concat(s,g)}function cZe(n,t,o,{viewOnce:i=!1}={}){let e,a;if(!i&&t?.imageMessage&&t.imageMessage.viewOnce!==!0)e=t.imageMessage;else if(t?.documentMessage){let r=typeof t.documentMessage.mimetype=="string"?t.documentMessage.mimetype.toLowerCase():"";if(!UH.has(r))return null;e=t.documentMessage,a=typeof e.fileName=="string"?e.fileName:void 0}if(!e)return null;let A=typeof e.mimetype=="string"?e.mimetype.toLowerCase():"";return UH.has(A)?{name:a,mediaType:A,size:Uce(e.fileLength),load:r=>gZe(n,o,r)}:null}function IZe(n,t,o){let i=t?.documentMessage;if(!i)return null;let e=typeof i.mimetype=="string"&&i.mimetype?i.mimetype.toLowerCase():void 0;return UH.has(e)?null:{name:typeof i.fileName=="string"&&i.fileName?i.fileName:"whatsapp-file",...e?{mediaType:e}:{},size:Uce(i.fileLength),async load({signal:a}={}){a?.throwIfAborted();let A=await o(n,"stream",{options:{signal:a}});return a?.throwIfAborted(),{stream:A}}}}function lZe({socket:n,logger:t=console,download:o=X2}={}){if(typeof o!="function")throw new TypeError("WhatsApp media downloader is required");return typeof n?.updateMediaMessage!="function"?o:(i,e,a)=>o(i,e,a,{logger:t,reuploadRequest:A=>n.updateMediaMessage(A)})}function pZe(n,t,{download:o=X2}={}){let i=typeof n?.key?.remoteJid=="string"?n.key.remoteJid:"",e=typeof n?.key?.remoteJidAlt=="string"?n.key.remoteJidAlt:"",a=typeof n?.key?.id=="string"?n.key.id:"";if(!i||!a||i==="status@broadcast"||i.endsWith("@newsletter"))return null;let A=i.endsWith("@g.us"),r=n.key.fromMe===!0,s=r&&!A&&[i,e].some(_=>_&&Tt(_,t));if(r&&!s&&!A)return null;let g=r?t:A?n.key.participant:i,c=A&&!r?n.key.participantAlt:e;if(typeof g!="string"||!g)return null;let I=oZe(n.message),d=Oa(n.message),B=nZe(d),f=Array.isArray(B?.mentionedJid)&&B.mentionedJid.some(_=>Tt(_,t)),Q=typeof B?.participant=="string"&&Tt(B.participant,t),y=cZe(n,d,o,{viewOnce:I}),m=IZe(n,d,o);return{messageId:`${i}:${a}`,providerMessageId:a,senderId:g,contextSource:()=>({senderName:n.pushName}),senderAlternateId:typeof c=="string"?c:"",senderIsBot:!1,kind:A?"group":"direct",conversationId:i,content:sZe(d),plainText:typeof d?.conversation=="string"||typeof d?.extendedTextMessage?.text=="string",images:y?[y]:[],files:m?[m]:[],addressed:!A||r||f||Q,selfChat:s,replyTarget:{jid:i,quoted:n,selfChat:s},reactionTarget:{jid:i,key:n.key}}}function dZe(n,{accessMode:t=zd.selfOnly,allowedNumbers:o=new Set}={}){if(t===zd.open)return!0;if(n?.kind!=="direct")return!1;if(n.selfChat===!0)return!0;if(t!==zd.privateAllowlist||!(o instanceof Set))return!1;let i=[n.senderId,n.senderAlternateId].filter(e=>typeof e=="string"&&e.endsWith("@s.whatsapp.net"));return[...o].some(e=>i.some(a=>Tt(a,`${e}@s.whatsapp.net`)))}var KH=class{#e=new Map;has(t){return this.#t(),this.#e.has(t)}remember(t){this.#A(t)}reserve(t){this.#A(t)}#A(t){if(!(typeof t!="string"||!t))for(this.#t(),this.#e.set(t,Date.now()+5*6e4);this.#e.size>256;)this.#e.delete(this.#e.keys().next().value)}#t(){let t=Date.now();for(let[o,i]of this.#e)i>t||this.#e.delete(o)}};function Hce(n){return n?.reason??new DOMException("The operation was aborted.","AbortError")}function Lce(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,Hce(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}function hZe(n){if(n?.code==="artifact-delivery-uncertain")return n;let t=new Error("WhatsApp could not confirm artifact delivery.");return t.code="artifact-delivery-uncertain",t.cause=n,t}function EZe(n){if(n?.code?.startsWith?.("artifact-"))return n;let t=n?.output?.statusCode??n?.data?.statusCode??n?.statusCode,o;if(t===401||t===403?o="artifact-permission-required":t===413?o="artifact-too-large":t===429?o="artifact-rate-limited":[400,404,405,406,410,415,422].includes(t)&&(o="artifact-provider-rejected"),!o)return hZe(n);let i=new Error("WhatsApp rejected artifact delivery.");return i.code=o,i.cause=n,i}var xH=class{#e;#A;#t;#r;#g=new Map;constructor(t,o,{signal:i,mediaUploadTimeoutMs:e=HH}={}){this.#e=t,this.#A=o,this.#t=i,this.#r=e}async sendText(t,o){await this.#i(t.jid);let i=[];for(let[e,a]of es(o,4e3).entries()){let A=Fce(10).toString("hex").toUpperCase(),r={...e===0&&t.quoted?{quoted:t.quoted}:{},messageId:A};typeof this.#A.reserve=="function"?this.#A.reserve(A):this.#A.remember(A);let s=await this.#e.sendMessage(t.jid,{text:a},r);this.#A.remember(s?.key?.id),typeof s?.key?.id=="string"&&s.key.id&&i.push(s.key.id)}return{providerMessageIds:i}}async sendFile(t,o){return this.#n(t,o,{document:o.bytes,mimetype:o.mediaType??"application/octet-stream",fileName:o.fileName},"file")}async sendImage(t,o){return this.#n(t,o,{image:o.bytes,mimetype:o.mediaType??"image/jpeg"},"image")}async addReaction(t,o,{signal:i}={}){if(typeof o!="string"||!o.trim())throw new TypeError("A WhatsApp reaction emoji is required");let e=o.trim();return await this.#a(t,e,i),e}removeReaction(t,o,{signal:i}={}){return this.#a(t,"",i)}async#a(t,o,i){if(typeof t?.jid!="string"||!t.jid||!t.key?.id)throw new TypeError("A WhatsApp reaction target is required");let e=i??this.#t;e?.throwIfAborted();let a=Fce(10).toString("hex").toUpperCase();typeof this.#A.reserve=="function"?this.#A.reserve(a):this.#A.remember(a);let A=this.#e.sendMessage(t.jid,{react:{text:o,key:t.key}},{messageId:a}),r=await Lce(A,e);return this.#A.remember(r?.key?.id),r}async#n(t,o,i,e){this.#t?.throwIfAborted(),await this.#i(t.jid),this.#t?.throwIfAborted();let a=typeof o.deliveryKey=="string"&&o.deliveryKey?o.deliveryKey:o.artifactId,A=e==="image"?`${a}:image`:a,r=typeof A=="string"&&A?tZe("sha256").update(A).digest("hex").slice(0,20).toUpperCase():void 0,s={...t.quoted?{quoted:t.quoted}:{},...r?{messageId:r}:{},mediaUploadTimeoutMs:this.#r};this.#A.remember(r);let g;try{let c=this.#e.sendMessage(t.jid,i,s);ln(o,c);let I=AbortSignal.timeout(this.#r),d=this.#t?AbortSignal.any([this.#t,I]):I;g=await Lce(c,d)}catch(c){throw this.#t?.aborted?Hce(this.#t):EZe(c)}return this.#t?.throwIfAborted(),this.#A.remember(g?.key?.id),g}async sendTyping(t){!t.selfChat&&t.quoted?.key&&await this.#e.readMessages([t.quoted.key]).catch(()=>{}),await this.#e.sendPresenceUpdate("composing",t.jid),await this.#i(t.jid,!1);let o=setInterval(()=>{this.#e.sendPresenceUpdate("composing",t.jid).catch(()=>{this.#i(t.jid)})},2e4);o.unref?.(),this.#g.set(t.jid,o)}async close(){let t=[...this.#g.keys()];await Promise.allSettled(t.map(o=>this.#i(o)))}async#i(t,o=!0){let i=this.#g.get(t);i&&clearInterval(i),this.#g.delete(t),o&&await this.#e.sendPresenceUpdate("paused",t).catch(()=>{})}};function CZe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...Xi()}}var Hf=class{#e;#A;#t;#r;#g;#a;#n;#i;#I;#l;#o;#s;#c=CZe();#p=null;#d=null;#h=null;#E=null;#C=null;constructor({config:t,authDir:o,harness:i,state:e,contextEnhancement:a,logger:A=console,replyTimeoutMs:r=6e5,connectTimeoutMs:s=3e4,mediaUploadTimeoutMs:g=HH,createSession:c=nM}){if(!t||!o||!i||!e||typeof c!="function")throw new TypeError("WhatsappRuntime requires config, auth directory, Harness, state, and session factory");if(this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#a=A,this.#n=r,this.#i=s,!Number.isSafeInteger(g)||g<=0)throw new TypeError("mediaUploadTimeoutMs must be a positive safe integer");this.#I=Math.min(g,HH),this.#s=c,this.setAccessPolicy(t)}get status(){return structuredClone(this.#c)}setAccessPolicy(t){let o=wg(t);return this.#l=o.accessMode,this.#o=new Set(o.allowedNumbers),this.#e={...this.#e,...o},o}async start(){return this.#c.ready&&this.#d?this.status:this.#C?this.#C:(this.#C=this.#f().finally(()=>{this.#C=null}),this.#C)}async#f(){await this.stop(),this.#c.startedAt=new Date().toISOString(),this.#c.connectionState="connecting",this.#c.lastError=null,await this.#t.ensureRunning(),this.#c.harnessReachable=!0;let t=new AbortController;this.#p=t;let o=new KH,i,e=new Promise((a,A)=>{i=A});e.catch(()=>{});try{let a=await this.#s({authDir:this.#A,signal:t.signal,logger:this.#a,onQr:()=>i(Object.assign(new Error("WhatsApp linked-device session must be scanned again"),{code:"relink-required"})),onMessage:async(c,I)=>{let d=pZe(c,this.#e.accountJid,{download:lZe({socket:I?.socket,logger:this.#a})});if(!(!d||o.has(d.providerMessageId)||!this.#E)){if(this.#c.lastCheckedAt=Date.now(),!dZe(d,{accessMode:this.#l,allowedNumbers:this.#o})){this.#c.messagesRejected+=1,this.#c.lastRejectedAt=new Date().toISOString();return}await this.#E.accept(d)}},onDisconnect:({error:c})=>{t.signal.aborted||(this.#c.ready=!1,this.#c.connectionState="failed",this.#c.lastError=c?.message??"WhatsApp Web connection closed")}});this.#d=a;let A,r=await Promise.race([a.ready,e,new Promise((c,I)=>{A=setTimeout(()=>I(new Error("WhatsApp Web did not connect in time")),this.#i)})]).finally(()=>clearTimeout(A));if(!Tt(r.accountJid,this.#e.accountJid))throw new Error("WhatsApp linked account does not match the saved bot");let s=new xH(a.socket,o,{signal:t.signal,mediaUploadTimeoutMs:this.#I});this.#h=s,this.#E=new oM({bot:s,harness:this.#t,state:this.#r,contextEnhancement:this.#g,status:this.#c,logger:this.#a,replyTimeoutMs:this.#n,signal:t.signal});let g=Date.now();return this.#c.ready=!0,this.#c.connectionState="connected",this.#c.lastCheckedAt=g,this.#c.lastConnectedAt=g,this.status}catch(a){throw this.#c.ready=!1,this.#c.connectionState="failed",this.#c.lastError=a?.message??String(a),await this.stop(),a}}async logout(){return await this.#d?.logout().catch(()=>{}),this.stop()}async sendConnectionTest(t){if(!this.#c.ready||!this.#h){let o=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw o.code="test-target-unavailable",o}if(typeof t!="string"||!t.trim())throw new TypeError("WhatsApp connection test text is required");return await this.#h.sendText({jid:this.#e.accountJid,selfChat:!0},t),{sent:!0}}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.jid=="string"?t.route.jid.trim():"",a=t?.kind==="user"&&/^[^@\s]+@(s\.whatsapp\.net|lid)$/.test(e),A=t?.kind==="group"&&/^[^@\s]+@g\.us$/.test(e);if(!a&&!A){let r=new TypeError("Invalid WhatsApp proactive delivery target");throw r.code="invalid-target",r}if(!this.#c.ready||!this.#h){let r=new Error(w("WhatsApp\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw r.code="bot-not-connected",r}return i?.throwIfAborted(),this.#h.sendText({jid:e},o)}async stop(){let t=this.#d,o=this.#h,i=this.#E;return this.#p?.abort(),this.#p=null,this.#d=null,this.#h=null,this.#E=null,await o?.close().catch(()=>{}),await t?.close().catch(()=>{}),await Promise.race([i?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),this.#c.ready=!1,this.#c.connectionState="idle",this.status}};var QZe=/^[a-f0-9-]{36}$/;function yZe(n){let t=Xg(n.dshHome??process.env.DSH_HOME??uE(fZe(),".dsh")),o=Xg(n.dataDir??uE(t,"integrations","dsh-whatsapp")),i=Xg(n.authDir??uE(o,"auth")),e=a=>{if(!QZe.test(a??""))throw new TypeError("Invalid WhatsApp auth directory");return Xg(i,a)};return{config:Xg(n.configPath??uE(o,"config.json")),bots:Xg(n.botsDir??uE(o,"bots")),workspaces:Xg(n.workspacesPath??uE(o,"workspaces.json")),authPath:e}}async function YH(n,t={},o={}){let i=Aa(n,t),e=typeof n.logger=="function"?n.logger("dsh-im:whatsapp"):n.logger??console,a=()=>Ra(n),A=o.ConfigStore??ww,r=o.StateStore??Ow,s=o.HarnessClient??Dw,g=o.Controller??oB,c=o.Runtime??Hf,I=o.createSession??nM,d=o.createConnectionSupervisor??vp,B=yZe(t),f=await new A(B.config).load(),Q=Xg(t.workspace??process.cwd()),y=o.WorkspaceStore??ea,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),_=f.list();await m.reconcile(_.map(k=>k.botId)),await Promise.all(_.map(k=>m.ensure(k.botId,{defaultAgentPreset:t.agentPreset})));let T=typeof f.remove=="function"?Pa(f,{workspaces:m}):f,R=new Map,L=k=>Xg(B.bots,k,"state.json"),U=async k=>{let V=R.get(k);return V||(V=await new r(L(k)).load(),R.set(k,V)),V},F=Ua(n,o.commandExecutor),{controlExecutor:q,sessionMaintenanceExecutor:z,fileIngressExecutor:j}=Ha(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),P=new s({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...F?{commandExecutor:F}:{},...q?{controlExecutor:q}:{},...z?{sessionMaintenanceExecutor:z}:{},...j?{fileIngressExecutor:j}:{}}),J=new g({configStore:T,authPath:B.authPath,createSession:I,logger:e,createRuntime:async({botId:k,config:V,authDir:Ae})=>{let ie=await U(k);await m.ensure(k,{defaultAgentPreset:t.agentPreset});let De=Ga(P,{botId:k,workspaces:m,state:ie,agentPresetCatalog:a});return new c({config:V,authDir:Ae,harness:De.harness,state:De.state,contextEnhancement:{botId:k,getSettings:()=>m.contextEnhancementFor(k)},replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??3e4,createSession:I,logger:{error:(...fe)=>e.error?.(`[${k}]`,...fe),warn:(...fe)=>e.warn?.(`[${k}]`,...fe),info:(...fe)=>e.info?.(`[${k}]`,...fe),debug:(...fe)=>e.debug?.(`[${k}]`,...fe)}})},deleteAuth:k=>uZe(B.authPath(k),{recursive:!0,force:!0}),deleteState:async({botId:k})=>{let V=R.get(k);if(R.delete(k),V&&typeof V.remove=="function")await V.remove();else try{await BZe(L(k))}catch(Ae){if(Ae?.code!=="ENOENT")throw Ae}}}),H=Fa(J,{workspaces:m,stateFor:U,agentPresetCatalog:a}),N=d({channel:"whatsapp",controller:H,harness:P,logger:e,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:H,deliveryAdapter:La({channel:"whatsapp",workspaces:m,coreController:J,stateFor:U}),ready:N.ready,async close(){await N.close(),await H.close(),P.stopManagedProcess()}}}import mZe from"qrcode";var Kce="/whatsapp",Or=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setAccessPolicy:"bot.access-policy.set",setWorkspace:Di,setAgentPreset:Oi,setContextEnhancement:wi}),xce=Object.freeze(Object.values(Or)),SZe=new Set(["qrValue","accountJid","authDirectory"]);function JH(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Kf(n,t){return JH(n)&&Object.keys(n).every(o=>t.includes(o))}function sM(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function wZe(n,t){if(!JH(t))return"Payload must be an object.";if([Or.status,Or.beginProvisioning].includes(n))return Kf(t,[])?null:`${n} does not accept fields.`;if([Or.pollProvisioning,Or.cancelProvisioning].includes(n))return Kf(t,["attemptId"])&&sM(t.attemptId)?null:`${n} requires an attemptId.`;if(n===Or.reconnectBot)return Kf(t,["botId","sendTest"])&&sM(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId and optional sendTest flag.";if(n===Or.deleteBot)return Kf(t,["botId","confirm"])&&sM(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.";if(n===Or.setAccessPolicy){if(!Kf(t,["botId","accessMode","allowedNumbers"])||Object.keys(t).length!==3||!sM(t.botId))return"\u8BF7\u8F93\u5165\u6709\u6548\u7684 WhatsApp \u8BBF\u95EE\u6A21\u5F0F\u548C\u7535\u8BDD\u53F7\u7801\u3002";try{return wg(t),null}catch{return"\u8BF7\u8F93\u5165\u6709\u6548\u7684 WhatsApp \u8BBF\u95EE\u6A21\u5F0F\u548C\u7535\u8BDD\u53F7\u7801\u3002"}}return n===Or.setWorkspace?xa(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Or.setAgentPreset?ja(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===Or.setContextEnhancement?Ka(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":"Unknown WhatsApp endpoint."}function BE(n){if(Array.isArray(n))return n.map(BE);if(!JH(n))return n;let t={};for(let[o,i]of Object.entries(n))SZe.has(o)||(t[o]=BE(i));return t}async function DZe(n){return mZe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function jH(n,t){return!n||typeof n.qrValue!="string"?BE(n):BE({...n,qrCodeDataUrl:await t(n.qrValue)})}async function Ip(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await jH(o.provisioning,t)),BE(o)}function Yce(n,{encodeQr:t=DZe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","reconnectBot","deleteBot","setAccessPolicy"])if(typeof n?.[e]!="function")throw new TypeError(`A complete WhatsApp controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!xce.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown WhatsApp endpoint."}};let r=wZe(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===Or.status)s=await Ip(await n.status(),i);else if(e===Or.beginProvisioning)s=await jH(await n.startProvisioning(),i);else if(e===Or.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await jH(g,i)}else if(e===Or.cancelProvisioning)s=BE(await n.cancelProvisioning(a.attemptId));else if(e===Or.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(s=await Ip(g,i),a.sendTest===!0){let c=null;if(!(g?.bots?.some(d=>d?.botId===a.botId&&d.connected===!0)===!0))c=new Error("WhatsApp bot is not connected"),c.code="test-target-unavailable";else try{if(typeof n.sendConnectionTest!="function"){let d=new Error("Connection test is unavailable");throw d.code="test-target-unavailable",d}await n.sendConnectionTest(a.botId)}catch(d){c=d}s={...s,testMessage:ir(c)}}}else if(e===Or.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await Ip(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===Or.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>Ip(g,i))}else if(e===Or.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await Ip(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else e===Or.setAccessPolicy?s=await Ip(await n.setAccessPolicy(a.botId,wg(a)),i):s=await Ip(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"whatsapp-operation-failed",message:"WhatsApp \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function gM(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(Kce,Yce(t,o),{authority:hr(i)})}async function jce(n,t={}){if(t?.controller)return gM(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await YH(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=gM(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close WhatsApp Web connections"),e}var OZe="/dsh-im-delivery",bZe="DSH-IM \u4E3B\u52A8\u6295\u9012\u6D4B\u8BD5\u6210\u529F\u3002",pi=Object.freeze({send:"message.send",listTargets:"target.list",listSuggestions:"target.suggestion.list",createTarget:"target.create",updateTarget:"target.update",deleteTarget:"target.delete",testTarget:"target.test"}),MZe=new Set(Object.values(pi)),_Ze=new Set(["bad-request","unknown-bot","unknown-target","target-conflict","invalid-target","bot-not-connected","target-rejected","delivery-failed","cancelled"]);function Yf(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function uI(n,t){return Yf(n)&&Object.keys(n).length===t.length&&Object.keys(n).every(o=>t.includes(o))}function lp(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function xf(n){return typeof n=="string"&&/^[A-Za-z0-9._:@-]{1,128}$/.test(n)}function Jce(n,{targetId:t}){let o=t?["targetId","name","kind","route"]:["name","kind","route"];return!Yf(n)||Object.keys(n).some(i=>!o.includes(i))||t&&!xf(n.targetId)||n.name!==void 0&&(typeof n.name!="string"||!n.name.trim()||n.name.trim().length>80)?!1:typeof n.kind=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(n.kind)&&Yf(n.route)}function TZe(n){return uI(n,["kind","route"])&&typeof n.kind=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(n.kind)&&Yf(n.route)}function NZe(n,t){return!MZe.has(n)||!Yf(t)?!1:n===pi.send?uI(t,["botId","targetId","text"])&&lp(t.botId)&&xf(t.targetId)&&typeof t.text=="string"&&!!t.text.trim():n===pi.listTargets||n===pi.listSuggestions?uI(t,["botId"])&&lp(t.botId):n===pi.createTarget?uI(t,["botId","target"])&&lp(t.botId)&&Jce(t.target,{targetId:!0}):n===pi.updateTarget?uI(t,["botId","targetId","target"])&&lp(t.botId)&&xf(t.targetId)&&Jce(t.target,{targetId:!1}):n===pi.testTarget?uI(t,["botId","targetId"])&&lp(t.botId)&&xf(t.targetId)||uI(t,["botId","target"])&&lp(t.botId)&&TZe(t.target):uI(t,["botId","targetId"])&&lp(t.botId)&&xf(t.targetId)}function RZe(n){let t=_Ze.has(n?.code)?n.code:"delivery-failed";return{code:t,message:t,details:{}}}function qH(n){for(let t of["send","listTargets","listSuggestions","createTarget","updateTarget","deleteTarget"])if(typeof n?.[t]!="function")throw new TypeError(`A complete delivery service is required (${t})`);return async(t,o,i)=>{if(!NZe(t,o))return{ok:!1,error:{code:"bad-request",message:"Invalid delivery request.",details:{}}};if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"cancelled",details:{}}};try{let e;return t===pi.send?e=await n.send(o.botId,o.targetId,o.text,{signal:i}):t===pi.listTargets?e=await n.listTargets(o.botId):t===pi.listSuggestions?e=await n.listSuggestions(o.botId):t===pi.createTarget?e=await n.createTarget(o.botId,o.target):t===pi.updateTarget?e=await n.updateTarget(o.botId,o.targetId,o.target):t===pi.deleteTarget?e=await n.deleteTarget(o.botId,o.targetId):e=await n.send(o.botId,Object.hasOwn(o,"target")?o.target:o.targetId,bZe,{signal:i}),{ok:!0,value:e}}catch(e){return{ok:!1,error:RZe(e)}}}}function qce(n,t,{authority:o}={}){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(OZe,qH(t),{authority:hr(o)})}var zce="/api/dsh-im/delivery/messages",Vce=1024*1024,kZe=Object.freeze({"bad-request":400,"unknown-bot":404,"unknown-target":404,"target-conflict":409,"invalid-target":422,"bot-not-connected":503,"target-rejected":422,"delivery-failed":502,cancelled:408}),QE=class extends Error{constructor(t,o){super(o),this.status=t,this.code=o}};function fE(n,t,o,i={}){if(n.destroyed||n.writableEnded)return;let e=JSON.stringify(o);n.writeHead(t,{"cache-control":"no-store","content-type":"application/json; charset=utf-8","content-length":String(Buffer.byteLength(e)),...i}),n.end(e)}function vZe(n){return typeof n=="string"&&n.split(";",1)[0].trim().toLowerCase()==="application/json"}async function PZe(n){let t=Number(n.headers["content-length"]);if(Number.isFinite(t)&&t>Vce)throw new QE(413,"payload-too-large");let o=[],i=0;for await(let e of n){let a=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=a.length,i>Vce)throw new QE(413,"payload-too-large");o.push(a)}try{return JSON.parse(Buffer.concat(o,i).toString("utf8"))}catch{throw new QE(400,"bad-request")}}function GZe(n){let t=qH(n);return async(o,i)=>{if(o.method!=="POST"){fE(i,405,{error:{code:"method-not-allowed",message:"method-not-allowed",details:{}}},{allow:"POST"});return}if(!vZe(o.headers["content-type"])){fE(i,415,{error:{code:"unsupported-media-type",message:"unsupported-media-type",details:{}}});return}let e=new AbortController,a=()=>e.abort(),A=()=>{i.writableEnded||a()};o.once("aborted",a),i.once("close",A);try{let r=await PZe(o),s=await t(pi.send,r,e.signal);if(s.ok){fE(i,200,s.value);return}fE(i,kZe[s.error.code]??500,{error:s.error})}catch(r){if(r instanceof QE){fE(i,r.status,{error:{code:r.code,message:r.code,details:{}}});return}fE(i,500,{error:{code:"delivery-failed",message:"delivery-failed",details:{}}})}finally{o.off("aborted",a),i.off("close",A)}}}function Wce(n,t){if(!n?.webServer||typeof n.webServer.register!="function"||typeof n.effect!="function")throw new TypeError("DSH Host WebServer is required");let o={kind:"exact",path:zce,handler:GZe(t)};return n.effect(()=>n.webServer.register(o),`dsh-im: ${zce}`)}var FZe=/^[A-Za-z0-9_-]{1,128}$/,LZe=/^[A-Za-z0-9._:@-]{1,128}$/,UZe=/^[a-z][a-z0-9-]{0,31}$/,HZe="__test__",KZe=Object.freeze(["ownsBot","listTargets","listSuggestions","createTarget","updateTarget","deleteTarget","sendText"]),xZe=new Set(["bad-request","unknown-bot","unknown-target","target-conflict","invalid-target","bot-not-connected","target-rejected","delivery-failed","cancelled"]);function nn(n,t=n,o){let i=new Error(t,o);return i.code=n,i}function yE(n){if(typeof n!="string"||!FZe.test(n))throw nn("bad-request","Invalid bot id");return n}function cM(n){if(typeof n!="string"||!LZe.test(n))throw nn("bad-request","Invalid target id");return n}function zH(n,{includesTargetId:t}={}){if(!n||typeof n!="object"||Array.isArray(n))throw nn("bad-request","Invalid target");if(t)cM(n.targetId);else if(Object.hasOwn(n,"targetId"))throw nn("bad-request","A target id cannot be changed");return n}function YZe(n){zH(n);let t=Object.keys(n);if(t.length!==2||!t.includes("kind")||!t.includes("route"))throw nn("bad-request","Invalid draft target");return n}function Zce(n){if(n?.aborted)throw nn("cancelled","Request cancelled")}function pp(n,t="delivery-failed"){return n?.code==="workspace-bot-not-found"?nn("unknown-bot","Unknown bot",{cause:n}):xZe.has(n?.code)?n:nn(t,t,{cause:n})}function jZe(n){if(!n||typeof n!="object"||typeof n.channel!="string"||!UZe.test(n.channel))throw new TypeError("A delivery adapter with a valid channel is required");for(let t of KZe)if(typeof n[t]!="function")throw new TypeError(`A complete delivery adapter is required (${t})`);return n}var VH=class{#e=new Map;registerAdapter(t){let o=jZe(t),i=Object.freeze({adapter:o});return this.#e.set(o.channel,i),()=>this.#e.get(o.channel)!==i?!1:(this.#e.delete(o.channel),!0)}async listTargets(t){let o=yE(t),i=await this.#A(o);try{let e=await i.listTargets(o);if(!Array.isArray(e))throw new TypeError("Adapter returned invalid targets");return{botId:o,channel:i.channel,targets:e}}catch(e){throw pp(e)}}async listSuggestions(t){let o=yE(t),i=await this.#A(o);try{let e=await i.listSuggestions(o);if(!Array.isArray(e))throw new TypeError("Adapter returned invalid suggestions");return{botId:o,channel:i.channel,suggestions:e.map(a=>_p(i.channel,a,{targetIdRequired:!1}))}}catch(e){throw pp(e)}}async createTarget(t,o){let i=yE(t);zH(o,{includesTargetId:!0});let e=await this.#A(i);try{return await e.createTarget(i,o)}catch(a){throw pp(a)}}async updateTarget(t,o,i){let e=yE(t),a=cM(o);zH(i);let A=await this.#A(e);try{return await A.updateTarget(e,a,i)}catch(r){throw pp(r)}}async deleteTarget(t,o){let i=yE(t),e=cM(o),a=await this.#A(i);try{return await a.deleteTarget(i,e),{deleted:!0}}catch(A){throw pp(A)}}async send(t,o,i,{signal:e}={}){let a=yE(t),A=typeof o=="string"?cM(o):null,r=A===null?YZe(o):null;if(typeof i!="string"||!i.trim())throw nn("bad-request","Message text is required");Zce(e);let s=await this.#A(a);try{let g;if(r)g={targetId:HZe,...r};else{let c=await s.listTargets(a);if(!Array.isArray(c))throw new TypeError("Adapter returned invalid targets");if(g=c.find(I=>I?.targetId===A),!g)throw nn("unknown-target","Unknown target")}return Zce(e),await s.sendText(a,g,i,{signal:e}),{sent:!0}}catch(g){throw e?.aborted||g?.name==="AbortError"||g?.code==="ABORT_ERR"?nn("cancelled","Request cancelled",{cause:g}):pp(g)}}async#A(t){for(let{adapter:o}of this.#e.values()){let i;try{i=await o.ownsBot(t)}catch(e){throw pp(e)}if(i)return o}throw nn("unknown-bot","Unknown bot")}};function Xce(){return new VH}var jf=Je(DD(),1);import{createHash as JZe}from"node:crypto";import{readFile as AIe,realpath as Kn,stat as qZe}from"node:fs/promises";import{homedir as zZe}from"node:os";import{basename as VZe,dirname as ZH,isAbsolute as eK,join as $g,relative as WZe,resolve as lM,sep as ZZe}from"node:path";import{fileURLToPath as XZe}from"node:url";var BI="@xmanrui/dsh-im",Jf="https://registry.npmjs.org/",$Ze=15*6e4,e9e=1e4,$ce=16*1024;function xn(n,t={}){return Object.assign(new Error(n),{code:n,...t})}function IM(n,t){return typeof n?.get=="function"?n.get(t):n?.[t]}function XH(n,t){let o=WZe(n,t);return o!==".."&&!o.startsWith(`..${ZZe}`)&&!eK(o)}async function A9e(n){try{return await AIe(n,"utf8")}catch(t){if(t.code==="ENOENT")return"";throw t}}async function $H(n){let t=await AIe($g(n,"package.json"),"utf8");return{directory:await Kn(n),manifest:JSON.parse(t),contents:t}}async function WH(n,t){let o=ZH(await Kn(n));for(;;){try{let e=await $H(o);return e.manifest?.name===t?e:null}catch(e){if(e.code!=="ENOENT")throw e}let i=ZH(o);if(i===o)return null;o=i}}function t9e(n){return typeof n=="string"&&n.length>0&&Buffer.byteLength(n)<=255&&!n.startsWith("-")&&![".","..","node_modules"].includes(n)&&!/[\\/\x00-\x1f\x7f<>:"|?*]/u.test(n)}function r9e(n){if(n[0]==="web")return"web";let t;for(let o=0;o0&&(jf.default.validRange(n)!==null||/^[A-Za-z][A-Za-z0-9._-]*$/u.test(n))}async function o9e(n){if(n.manifest?.name!==BI||jf.default.valid(n.manifest.version)===null)return!1;let t=[n.manifest.main,n.manifest.exports?.["./client"],n.manifest.dsh?.bundle?.patch];for(let o of t){if(typeof o!="string"||!o||eK(o)||o.includes("\0"))return!1;let i=lM(n.directory,o);if(!XH(n.directory,i)||!XH(n.directory,await Kn(i))||!(await qZe(i)).isFile())return!1}return!0}function n9e(n){if(n==null||n==="")return!0;if(typeof n!="string")return!1;try{return new URL(n).href===Jf}catch{return!1}}async function eIe(n,{signal:t,timeoutMs:o,errorCode:i,capture:e=!1}){if(t?.aborted)throw xn("install-interrupted");let a=new AbortController,A,r,s=B=>{A??=B,a.abort(),r?.cancel?.()},g=()=>s("install-interrupted");t?.addEventListener("abort",g,{once:!0});let c=setTimeout(()=>s("install-timeout"),o),I="",d="";try{r=n(a.signal),r.stdout?.on("data",f=>{e&&(I=(I+f.toString()).slice(-$ce))}),r.stderr?.on("data",f=>{d=(d+f.toString()).slice(-$ce)}),r.stdout?.on("error",()=>s(i)),r.stderr?.on("error",()=>s(i));let B=await r.done;if(A)throw xn(A);if(B.exitCode!==0||B.signal)throw xn(i,{exitCode:B.exitCode,diagnosticCode:d.match(/\bERR_PNPM_[A-Z0-9_]+\b/u)?.[0]});return{exitCode:0,signal:null,...e?{stdout:I}:{}}}catch(B){throw A?xn(A):B.code===i?B:xn(i)}finally{clearTimeout(c),t?.removeEventListener("abort",g)}}function tIe(n={}){let t=n.ctx,o=n.env??process.env,i=n.argv??process.argv,e=n.execArgv??process.execArgv,a=n.execPath??process.execPath,A=n.cwd??process.cwd(),r=n.platform??process.platform,s=n.osHome??zZe(),g=n.electron??process.versions.electron,c=n.moduleUrl??import.meta.url,I=WH(XZe(c),BI).catch(()=>null),d;async function B(){let _=IM(t,"desktopProfiles"),T=IM(t,"desktopPnpm"),R=IM(t,"desktopPnpmBootstrap"),L=!!(g||_||T||R),U=_?.current,F=L?U?.name:r9e(i.slice(2)),q=L&&R?.homeDir?lM(R.homeDir):a9e(o,s),z={environmentKind:L?"desktop":"cli",homeDir:q,profileName:F};if(!t9e(F))return{...z,blockedReason:"unknown-profile"};let j=await Kn($g(q,"profiles",F)),P=await Kn(q),J={...z,homeDir:P,profileDir:j};if(L)try{if(typeof T?.runPlugin!="function"||typeof T?.run!="function"||!R||!U?.dir||R.activeProfileName!==F||await Kn(U.dir)!==j||await Kn(R.activeProfileDir)!==j||await Kn(R.appExecutable)!==await Kn(a))return{...J,blockedReason:"executor-unavailable"};let N=await WH(R.dshBootstrapPath,"dsh-plugin-desktop");return!N||VZe(R.dshBootstrapPath)!=="desktop-cli.js"||ZH(await Kn(R.dshBootstrapPath))!==$g(N.directory,"lib")?{...J,blockedReason:"executor-unavailable"}:{...J,desktop:T,executable:a,cliEntry:R.dshBootstrapPath}}catch{return{...J,blockedReason:"executor-unavailable"}}let H=IM(t,"subprocess");if(typeof H?.spawn!="function"||typeof i[1]!="string"||!eK(i[1])||r==="win32")return{...J,blockedReason:"executor-unavailable"};try{let N=await WH(i[1],"@deepseek-ai/dsh");if(!N)return{...J,blockedReason:"executor-unavailable"};let k=await Kn(i[1]),V=typeof N.manifest.bin=="string"?N.manifest.bin:N.manifest.bin?.dsh,Ae=typeof V=="string"?lM(N.directory,V):"";return k!==Ae&&k!==$g(N.directory,"src","bin.ts")?{...J,blockedReason:"executor-unavailable"}:{...J,subprocess:H,executable:a,cliEntry:k}}catch{return{...J,blockedReason:"executor-unavailable"}}}function f(_,T,R,L=!1){let U=_.subprocess.spawn({argv:L?["pnpm",...T]:[a,...e,_.cliEntry,...T],cwd:L?_.profileDir:A,env:{DSH_HOME:_.homeDir,CI:"true"},stdio:{stdin:"ignore",stdout:"pipe",stderr:"pipe"},graceMs:3e3,signal:R});return{stdout:U.stdout,stderr:U.stderr,cancel:()=>U.terminate(),done:(async()=>{try{return await U.done}finally{await U.waitForExit()}})()}}async function Q(_,T){let R=["config","get","@xmanrui:registry","--json"],U=(await eIe(q=>_.desktop?_.desktop.run(R,q):f(_,R,q,!0),{signal:T,timeoutMs:n.configTimeoutMs??e9e,errorCode:"registry-check-failed",capture:!0})).stdout.trim(),F;try{F=U===""||U==="undefined"?void 0:JSON.parse(U)}catch{throw xn("registry-check-failed")}if(!n9e(F))throw xn("registry-conflict")}async function y({preflight:_=!1}={}){let T,R={installedVersion:null,packageValid:!1,eligible:!1,installationKey:null};try{T=await B();for(let P of["homeDir","profileDir","profileName","environmentKind","executable","cliEntry"])R[P]=T[P]??null;if(!T.profileDir)return{...R,blockedReason:T.blockedReason??"unknown-profile"};let L=await $H(T.profileDir),U=await $H($g(T.profileDir,"node_modules",BI));R.sourceInstall=!i9e(L.manifest.dependencies?.[BI])||!XH($g(T.profileDir,"node_modules"),U.directory),R.installedVersion=typeof U.manifest.version=="string"?U.manifest.version:null,R.packageValid=await o9e(U);let F=await I,q=`${T.homeDir}\0${T.profileDir}\0${T.profileName}`,z=F?.directory===U.directory&&F?.manifest.version===U.manifest.version;d===void 0&&z&&R.packageValid&&(d=q);let j=await Promise.all(["pnpm-lock.yaml","pnpm-workspace.yaml","package-lock.json"].map(P=>A9e($g(T.profileDir,P))));return R.installationKey=JZe("sha256").update(JSON.stringify([q,L.contents,U.directory,U.contents,T.cliEntry,T.executable,...j])).digest("hex"),d!==void 0&&d!==q||!z&&d===void 0?R.blockedReason="installation-changed":R.packageValid?R.sourceInstall?R.blockedReason="source-install":T.blockedReason?R.blockedReason=T.blockedReason:z?_&&await Q(T):R.blockedReason="pending-restart":R.blockedReason="invalid-installation",R.eligible=!R.blockedReason,{...R,blockedReason:R.blockedReason??null}}catch(L){return{...R,blockedReason:["registry-conflict","registry-check-failed","install-timeout","install-interrupted"].includes(L.code)?L.code:T?.profileDir?"invalid-installation":"unknown-profile"}}}async function m(_,{signal:T,expectedInstallationKey:R}={}){if(jf.default.valid(_)!==_||jf.default.prerelease(_))throw xn("invalid-version");let L=await y();if(R!==void 0&&L.installationKey!==R)throw xn("installation-changed");if(!L.eligible)throw xn(L.blockedReason);let U=await B();await Q(U,T);let F=await y();if(!F.eligible||F.installationKey!==L.installationKey)throw xn("installation-changed");let q=["add","-w","--save-exact",`${BI}@${_}`,`--registry=${Jf}`];return eIe(z=>U.desktop?U.desktop.runPlugin(q,U.profileDir,z):f(U,["plugin","--profile",U.profileName,...q],z),{signal:T,timeoutMs:n.installTimeoutMs??$Ze,errorCode:"install-failed"})}return Object.freeze({inspect:y,install:m})}var fI=Je(DD(),1);import{createHash as s9e,randomUUID as tK}from"node:crypto";import{mkdir as g9e,open as c9e,readFile as nIe,rename as I9e,stat as sIe,unlink as gIe,writeFile as l9e}from"node:fs/promises";import{isAbsolute as rIe,join as zf}from"node:path";var Vf=new Set(["installing","verifying"]),p9e=new Set([...Vf,"restart-required","completed","failed","interrupted"]),aIe=256*1024,d9e=["package.json","pnpm-lock.yaml","pnpm-workspace.yaml"],pM=Symbol("no update lock");function Ot(n){return Object.assign(new Error(n),{code:n})}async function iIe(n=globalThis.fetch,t=1e4){let o;try{if(o=await n(`${Jf}${encodeURIComponent(BI)}/latest`,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(t)}),!o.ok)throw Ot("check-failed");if(Number(o.headers.get("content-length"))>aIe)throw Ot("invalid-release");let i=[],e=0;for await(let c of o.body){if(e+=c.byteLength,e>aIe)throw Ot("invalid-release");i.push(Buffer.from(c))}let a=JSON.parse(Buffer.concat(i).toString("utf8")),A=a.version;if(a.name!==BI||typeof A!="string"||fI.default.valid(A)!==A||fI.default.prerelease(A))throw Ot("invalid-release");let r=a.engines?.node;if(r!==void 0&&(typeof r!="string"||!fI.default.validRange(r)))throw Ot("invalid-release");let s=new URL(a.dist?.tarball),g=a.dist?.integrity;if(s.origin!==new URL(Jf).origin||s.username||s.password||s.search||s.hash||s.pathname!==`/@xmanrui/dsh-im/-/dsh-im-${A}.tgz`||typeof g!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(g))throw Ot("invalid-release");return{version:A,nodeRange:r??"*",integrity:g,tarball:s.href}}catch(i){throw i?.code==="invalid-release"||i instanceof SyntaxError||i instanceof TypeError&&o?.ok?Ot("invalid-release"):Ot("check-failed")}}function oIe(n){if(!rIe(n.homeDir??"")||!rIe(n.profileDir??""))return null;let t=s9e("sha256").update(n.profileDir).digest("hex").slice(0,24),o=zf(n.homeDir,"updates","dsh-im",t);return{directory:o,state:zf(o,"state.json"),lock:zf(o,"install.lock"),backup:zf(o,"before.json")}}async function AK(n,t=null){try{if((await sIe(n)).size>10*1024*1024)throw Ot("state-unavailable");return JSON.parse(await nIe(n,"utf8"))}catch(o){if(o.code==="ENOENT")return t;throw Ot("state-unavailable")}}async function qf(n,t){let o=`${n}.${tK()}.tmp`;try{await l9e(o,`${JSON.stringify(t,null,2)} +`,{mode:384,flag:"wx"}),await I9e(o,n)}catch{throw Ot("state-unavailable")}finally{await gIe(o).catch(i=>{if(i.code!=="ENOENT")throw Ot("state-unavailable")})}}function h9e(n){if(!Number.isSafeInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return t.code!=="ESRCH"}}function E9e(n){if(!n)return null;let{id:t,state:o,targetVersion:i,message:e}=n;return{id:t,state:o,targetVersion:i,message:e}}function cIe({runtime:n,runningVersion:t=IQ.version,nodeVersion:o=process.versions.node,fetchImpl:i=globalThis.fetch,now:e=Date.now,checkTimeoutMs:a=1e4,confirmationTtlMs:A=10*6e4,installTimeoutMs:r=15*6e4}={}){let s={},g=null,c=null,I=-1/0,d=null,B=null,f=null,Q=null,y=!1;function m(){if(y)throw Ot("disposed")}async function _(J){let H=oIe(J);if(!H)return null;if(Q?.statePath===H.state)return Q.job;let N=await AK(H.state),k=await AK(H.lock,pM);if(!N)return k!==pM?{id:"locked",state:"interrupted",message:"recovery-required",targetVersion:null}:null;if(!p9e.has(N.state)||typeof N.id!="string"||!fI.default.valid(N.targetVersion))throw Ot("state-unavailable");if(Vf.has(N.state)&&N.id!==d?.id&&(k===pM||k?.id!==N.id||!h9e(k?.pid))&&(N={...N,state:"interrupted",message:"recovery-required"}),N.id!==d?.id&&!Vf.has(N.state)){if(k!==pM)return{...N,state:"interrupted",message:"recovery-required"};if(["failed","interrupted"].includes(N.state)&&J.packageValid===!0&&J.installedVersion===t&&!J.blockedReason)return N.targetVersion===t?{...N,state:"completed",message:"recovered"}:{...N,recoverable:!0}}return N.state==="restart-required"||N.state==="completed"?J.installedVersion!==N.targetVersion||J.packageValid!==!0?{...N,state:"interrupted",message:"installation-changed"}:{...N,state:t===N.targetVersion?"completed":"restart-required"}:N}function T(J,H){let N=J.blockedReason??g?.blockedReason??null;H?.state==="interrupted"&&!H.recoverable||H?.state==="failed"&&J.installedVersion!==t?N="recovery-required":(H?.state==="restart-required"||J.installedVersion&&J.installedVersion!==t)&&(N="pending-restart");let k=Vf.has(H?.state),V=!!(J.eligible&&!N&&!k&&g?.checkId&&e(){try{let J=await n.inspect({preflight:!0}),H=await iIe(i,a);return m(),g={release:H,checkId:tK(),checkedAt:e(),expiresAt:e()+A,installationKey:J.installationKey,profileDir:J.profileDir,blockedReason:J.blockedReason??(fI.default.satisfies(o,H.nodeRange)?null:"incompatible-node")},T(J,await _(J))}catch(J){throw g&&(g={...g,checkId:null,expiresAt:0}),J}finally{c=null}})(),c))}async function U(J,H){(await AK(J.lock))?.id===H&&await gIe(J.lock)}async function F(J,H,N){let k={};for(let V of d9e)try{let Ae=zf(J.profileDir,V);if((await sIe(Ae)).size>3*1024*1024)throw Ot("state-unavailable");k[V]=await nIe(Ae,"utf8")}catch(Ae){if(Ae.code!=="ENOENT")throw Ot("state-unavailable")}await qf(H.backup,{jobId:N.id,previousVersion:N.previousVersion,files:k})}function q(J){d={...d,state:"interrupted",message:"state-unavailable"},Q={statePath:J.state,job:d}}async function z(J,H,N){let k=AbortSignal.timeout(r);try{if(await n.install(H.targetVersion,{signal:AbortSignal.any([f.signal,k]),expectedInstallationKey:N.installationKey}),y)throw Ot("interrupted");d={...d,state:"verifying",updatedAt:e()},await qf(J.state,d);let V=await n.inspect();if(V.homeDir!==N.homeDir||V.profileDir!==N.profileDir||V.profileName!==N.profileName||V.blockedReason==="installation-changed")throw Ot("installation-changed");if(V.installedVersion!==H.targetVersion||V.packageValid!==!0||V.blockedReason&&V.blockedReason!=="pending-restart")throw Ot("verify-failed");d={...d,state:"restart-required",message:null,updatedAt:e()},await qf(J.state,d)}catch(V){let Ae=k.aborted||V.code==="install-timeout",ie=y||f.signal.aborted||!Ae&&["interrupted","install-interrupted"].includes(V.code);d={...d,state:ie?"interrupted":"failed",message:ie?"interrupted":Ae?"install-timeout":["verify-failed","state-unavailable","installation-changed","registry-conflict"].includes(V.code)?V.code:"install-failed",updatedAt:e()};try{await qf(J.state,d)}catch{q(J);return}}await U(J,H.id)}function j({checkId:J,requestId:H}){return Zs(s,"install",async()=>{m();let N=await n.inspect({preflight:!0}),k=await _(N);if(k?.requestId===H)return T(N,k);if(Vf.has(k?.state)||k?.state==="restart-required")throw Ot("update-busy");let V=g;if(!V||!J||V.checkId!==J||e()>=V.expiresAt)throw Ot("check-expired");if(N.profileDir!==V.profileDir||N.installationKey!==V.installationKey)throw Ot("installation-changed");if(!T(N,k).canInstall)throw Ot(N.blockedReason??"update-busy");let Ae=oIe(N);if(!Ae)throw Ot("state-unavailable");let ie={id:tK(),requestId:H,state:"installing",message:null,targetVersion:V.release.version,previousVersion:N.installedVersion,startedAt:e(),updatedAt:e()},De=!1;try{await g9e(Ae.directory,{recursive:!0,mode:448});let fe=await c9e(Ae.lock,"wx",384);De=!0;try{await fe.writeFile(JSON.stringify({id:ie.id,pid:process.pid,startedAt:e()}))}finally{await fe.close()}let _e=await iIe(i,a);if(JSON.stringify(_e)!==JSON.stringify(V.release))throw Ot("check-expired");if(N=await n.inspect({preflight:!0}),N.profileDir!==V.profileDir||N.installationKey!==V.installationKey)throw Ot("installation-changed");if(!N.eligible||N.blockedReason)throw Ot(N.blockedReason??"update-busy");m(),await F(N,Ae,ie),await qf(Ae.state,ie),m()}catch(fe){throw De&&await U(Ae,ie.id),fe.code==="EEXIST"?Ot("update-busy"):fe.code?.startsWith("E")?Ot("state-unavailable"):fe}return d=ie,f=new AbortController,B=z(Ae,ie,N).catch(()=>{q(Ae)}),T(N,ie)})}async function P(){y=!0,f?.abort(),B&&await B}return Object.freeze({status:R,check:L,install:j,close:P})}var C9e="/dsh-im",u9e=Object.freeze(["update.status","update.check","update.install"]);function B9e(n,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let o=Object.keys(t);return n!=="update.install"?o.length===0:o.length===2&&o.every(i=>i==="checkId"||i==="requestId")&&["checkId","requestId"].every(i=>typeof t[i]=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(t[i]))}var f9e=new Set(["check-failed","invalid-release","check-expired","installation-changed","update-busy","install-failed","verify-failed","state-unavailable","interrupted","disposed","source-install","unknown-profile","unsupported-runtime","registry-conflict","incompatible-node","pending-restart","recovery-required","executor-unavailable","invalid-installation","registry-check-failed","install-timeout","install-interrupted","invalid-version"]);function Q9e(n){return async(t,o,i)=>{if(!u9e.includes(t)||!B9e(t,o))return{ok:!1,error:{code:"bad-request",message:"Invalid update request."}};if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"Request cancelled."}};try{return{ok:!0,value:t==="update.install"?await n.install(o):t==="update.check"?await n.check():await n.status()}}catch(e){let a=f9e.has(e?.code)?e.code:"update-failed";return{ok:!1,error:{code:a,message:a}}}}}function IIe(n,t={}){let o=t.runtime??tIe({ctx:n,moduleUrl:import.meta.url}),i=t.service??cIe({runtime:o}),e=n.connection.rpc.handle(C9e,Q9e(i),{authority:"loopback"});return n.effect(()=>()=>i.close(),"dsh-im: close update installer"),e}var lIe="dsh-im-host",y9e=["connection","credentials","typertGateway"];function m9e(n,t,o){let i=n[t]??{},e=n.rpcAuthority===void 0?i:{...i,rpcAuthority:n.rpcAuthority};return t==="office"?e:{...e,deliveryService:o}}function S9e(n={}){let t=n.installUpdateRpc??IIe,o=n.installDeliveryRpc??qce,i=n.installDeliveryHttp??Wce,e=n.createDeliveryService??Xce,a=n.applyFeishu??A5,A=n.applyWeixin??JZ,r=n.applyDingtalk??a1,s=n.applyWecom??EZ,g=n.applyQq??f5,c=n.applySlack??G5,I=n.applyTelegram??eZ,d=n.applyDiscord??M1,B=n.applyOffice??v1,f=n.applyWhatsapp??jce,Q=[["feishu",a],["weixin",A],["dingtalk",r],["wecom",s],["qq",g],["slack",c],["telegram",I],["discord",d],["whatsapp",f],["office",B]];return Object.freeze({name:lIe,inject:y9e,async apply(m,_={}){let T=e();typeof m?.provide=="function"&&m.provide("dshIm",Object.freeze({send:(L,U,F,q)=>T.send(L,U,F,q),listTargets:async L=>(await T.listTargets(L)).targets}));let R=async L=>{await y(L,_,T)};if(typeof m?.inject=="function"){let L=typeof m?.typertGateway?.stream=="function";await m.inject(L?["sessionController","workspaceController"]:["apiProxy"],R),m.inject(["webServer"],U=>{i(U,T)});return}await R(m),m?.webServer?.register&&typeof m?.effect=="function"&&i(m,T)}});async function y(m,_,T){KK(_.language??process.env.DSH_IM_LANGUAGE),typeof m?.inject=="function"?m.inject(["tools","systemPrompt"],U=>{o_(U)}):o_(m);let R=typeof m?.logger=="function"?m.logger(lIe):m?.logger??console;if(m?.connection?.rpc){try{t(m)}catch(U){R.error?.("[dsh-im] failed to activate update management; continuing with channels",U)}try{o(m,T,{authority:_.rpcAuthority})}catch(U){R.error?.("[dsh-im] failed to activate delivery management; continuing with channels",U)}}let L=[];for(let[U,F]of Q)try{await F(m,m9e(_,U,T))}catch(q){L.push(q),R.error?.(`[dsh-im] failed to activate ${U}; continuing with the remaining channels`,q)}if(L.length===Q.length)throw new AggregateError(L,"dsh-im failed to activate every channel")}}async function mLA(n,t={}){return S9e().apply(n,t)}export{mLA as apply,S9e as createImHostPlugin,y9e as inject,lIe as name}; /*! Bundled license information: mime-db/index.js: diff --git a/src/channels/feishu/bridge.mjs b/src/channels/feishu/bridge.mjs index a64e677..fca0276 100644 --- a/src/channels/feishu/bridge.mjs +++ b/src/channels/feishu/bridge.mjs @@ -686,7 +686,7 @@ export class FeishuHarnessBridge { ? pending.queue : null, isQuestionPending: () => this.#pendingInteractions.has(key), - send: (text) => this.#send(event.message.chat_id, text), + send: (text) => this.#send(event.message.chat_id, text, { replyTo: event.message.message_id }), }); if (approvalReply) { const processing = approvalReply.process(async () => { @@ -851,7 +851,7 @@ export class FeishuHarnessBridge { if (error?.code === 'turn-stopped') { await this.#removeProcessingReaction(messageId, processingReaction); if (error?.batchInputMessage) { - await this.#send(event.message.chat_id, error.batchInputMessage).catch(() => undefined); + await this.#send(event.message.chat_id, error.batchInputMessage, { replyTo: event.message.message_id }).catch(() => undefined); } return; } @@ -940,7 +940,7 @@ export class FeishuHarnessBridge { ]); } for (const reply of result?.messages ?? [result?.message]) { - if (reply) await this.#send(event.message.chat_id, reply); + if (reply) await this.#send(event.message.chat_id, reply, { replyTo: event.message.message_id }); } this.#status.lastError = null; } @@ -964,7 +964,7 @@ export class FeishuHarnessBridge { // accept() 侧已用 nonEmptyString(content) 判定,两侧保持一致。 const commandText = !hasImages && !hasFiles && text ? text.trim() : null; if (!text && !hasImages && !hasFiles) { - await this.#send(event.message.chat_id, t('目前支持文字、图片和文件消息。')); + await this.#send(event.message.chat_id, t('目前支持文字、图片和文件消息。'), { replyTo: event.message.message_id }); return; } @@ -973,11 +973,11 @@ export class FeishuHarnessBridge { return; } if (commandText === '/help') { - await this.#send(event.message.chat_id, menuHelpText()); + await this.#send(event.message.chat_id, menuHelpText(), { replyTo: event.message.message_id }); return; } if (MENU_COMMAND.test(commandText)) { - await this.#sendMenuCard(key, event.message.chat_id); + await this.#sendMenuCard(key, event.message.chat_id, { replyTo: event.message.message_id }); return; } if (commandText === '/new') { @@ -985,53 +985,54 @@ export class FeishuHarnessBridge { await this.#send( event.message.chat_id, t('当前任务仍在运行,请先停止任务或等待任务完成后再开启新会话。'), + { replyTo: event.message.message_id }, ); return; } await this.#state.clearSession(key); - await this.#send(event.message.chat_id, t('已开启全新 Harness 会话。')); - await this.#sendMenuCard(key, event.message.chat_id); + await this.#send(event.message.chat_id, t('已开启全新 Harness 会话。'), { replyTo: event.message.message_id }); + await this.#sendMenuCard(key, event.message.chat_id, { replyTo: event.message.message_id }); return; } if (commandText === '/status') { - await this.#showStatusText(key, event.message.chat_id); + await this.#showStatusText(key, event.message.chat_id, event.message.message_id); return; } if (commandText === '/compact') { const compactCommand = await runCompactCommand(commandText, this.#harness, this.#state, key, { signal: this.#signal }); if (compactCommand) { - await this.#send(event.message.chat_id, compactCommand.message); + await this.#send(event.message.chat_id, compactCommand.message, { replyTo: event.message.message_id }); } return; } if (SESSION_LIST_PREFIX.test(commandText)) { const selector = commandText.replace(/^\/(?:sessionlist|sessions)/i, '').trim() || null; - await this.#showSessions({ chatId: event.message.chat_id, key }, selector, 0); + await this.#showSessions({ chatId: event.message.chat_id, key, replyTo: event.message.message_id }, selector, 0); return; } if (WORKSPACE_LIST_COMMAND.test(commandText)) { - await this.#showWorkspaces({ chatId: event.message.chat_id, key }); + await this.#showWorkspaces({ chatId: event.message.chat_id, key, replyTo: event.message.message_id }); return; } if (WATCH_COMMAND.test(commandText)) { const target = (WATCH_COMMAND.exec(commandText)?.[1] ?? '').trim() || null; - await this.#runWatch(key, event.message.chat_id, target); + await this.#runWatch(key, event.message.chat_id, target, { replyTo: event.message.message_id }); return; } if (UNWATCH_COMMAND.test(commandText)) { const target = (UNWATCH_COMMAND.exec(commandText)?.[1] ?? '').trim() || null; - await this.#runUnwatch(key, event.message.chat_id, target); + await this.#runUnwatch(key, event.message.chat_id, target, { replyTo: event.message.message_id }); return; } if (WATCHLIST_COMMAND.test(commandText)) { - await this.#showWatchList(key, event.message.chat_id); + await this.#showWatchList(key, event.message.chat_id, { replyTo: event.message.message_id }); return; } if (ARCHIVED_COMMAND.test(commandText)) { const match = ARCHIVED_COMMAND.exec(commandText); const value = match[1]?.toLowerCase(); if (value !== 'on' && value !== 'off') { - await this.#send(event.message.chat_id, t('用法:/archived on(包含归档会话)或 /archived off(隐藏归档会话)')); + await this.#send(event.message.chat_id, t('用法:/archived on(包含归档会话)或 /archived off(隐藏归档会话)'), { replyTo: event.message.message_id }); return; } if (typeof this.#state?.setIncludeArchivedSessions === 'function') { @@ -1040,6 +1041,7 @@ export class FeishuHarnessBridge { await this.#send( event.message.chat_id, value === 'on' ? t('已开启:会话列表包含归档会话。') : t('已关闭:会话列表隐藏归档会话。'), + { replyTo: event.message.message_id }, ); return; } @@ -1059,7 +1061,7 @@ export class FeishuHarnessBridge { : await runWorkspaceCommand(text, this.#harness, key); if (workspaceCommand) { for (const reply of workspaceCommand.messages ?? [workspaceCommand.message]) { - await this.#send(event.message.chat_id, reply); + await this.#send(event.message.chat_id, reply, { replyTo: event.message.message_id }); } return; } @@ -1073,7 +1075,7 @@ export class FeishuHarnessBridge { { signal: this.#signal }, ); if (compactCommand) { - await this.#send(event.message.chat_id, compactCommand.message); + await this.#send(event.message.chat_id, compactCommand.message, { replyTo: event.message.message_id }); return; } @@ -2030,7 +2032,7 @@ export class FeishuHarnessBridge { } async #showSessions( - { chatId, key }, + { chatId, key, replyTo = null }, selector, page = 0, { updateMessageId = null } = {}, @@ -2039,14 +2041,14 @@ export class FeishuHarnessBridge { const signal = this.#cardDataSignal(); const resolved = await resolveSessionListWorkspace(selector ?? '', this.#harness, { signal }); if (resolved.error) { - await this.#send(chatId, resolved.error); + await this.#send(chatId, resolved.error, { replyTo }); return; } const listed = await this.#harness.listWorkspaceSessions(resolved.workspace, { signal }); const sessions = this.#visibleSessions(Array.isArray(listed?.sessions) ? listed.sessions : []); const workspace = listed?.workspace ?? resolved.workspace; if (sessions.length === 0) { - await this.#send(chatId, t('工作区:{workspace}\n该工作区暂无会话。', { workspace })); + await this.#send(chatId, t('工作区:{workspace}\n该工作区暂无会话。', { workspace }), { replyTo }); return; } const pageCount = Math.ceil(sessions.length / MENU_PAGE_SIZE); @@ -2065,6 +2067,7 @@ export class FeishuHarnessBridge { { key, updateMessageId, + replyTo, // Keep the canonical selector result for later page callbacks. The // list response's workspace is display data and is not authoritative. sessionWorkspace: resolved.workspace, @@ -2076,7 +2079,7 @@ export class FeishuHarnessBridge { } } - async #showWorkspaces({ chatId, key }, { updateMessageId = null } = {}) { + async #showWorkspaces({ chatId, key, replyTo = null }, { updateMessageId = null } = {}) { try { const { current, paths } = await workspacePathSnapshot( this.#harness, @@ -2086,7 +2089,7 @@ export class FeishuHarnessBridge { await this.#sendCard( chatId, workspaceListCard(paths, current), - { key, updateMessageId }, + { key, updateMessageId, replyTo }, ); } catch (error) { await this.#sendFailure(chatId, error, { logLabel: 'workspace list' }); @@ -2144,6 +2147,7 @@ export class FeishuHarnessBridge { async #sendCard(chatId, cardJson, options = {}) { const updateMessageId = nonEmptyString(options.updateMessageId); + const replyTo = nonEmptyString(options.replyTo); if (updateMessageId) { try { @@ -2161,6 +2165,28 @@ export class FeishuHarnessBridge { } } + // A brand-new card triggered by an inbound message is delivered as a + // threaded reply so it lands inside the same Feishu topic. Falls back to + // a plain chat message when the referenced message is gone. + const content = cardJson; + if (replyTo) { + try { + const response = await this.#client.im.v1.message.reply({ + path: { message_id: replyTo }, + data: { msg_type: 'interactive', content }, + }); + if (response?.code && response.code !== 0) { + throw new Error(`Feishu card reply failed: ${response.msg || response.code}`); + } + const repliedMessageId = nonEmptyString(response?.data?.message_id); + if (repliedMessageId) { + this.#rememberCardRoute(repliedMessageId, chatId, options); + return repliedMessageId; + } + } catch (error) { + this.#logger.warn?.('[dsh-feishu] threaded card reply failed; sending a plain card:', error?.message ?? String(error)); + } + } const response = await this.#client.im.v1.message.create({ params: { receive_id_type: 'chat_id' }, data: { receive_id: chatId, msg_type: 'interactive', content: cardJson }, @@ -2173,7 +2199,7 @@ export class FeishuHarnessBridge { return messageId; } - async #sendMenuCard(key, chatId, { updateMessageId = null } = {}) { + async #sendMenuCard(key, chatId, { updateMessageId = null, replyTo = null } = {}) { let currentSessionId = null; let directSessionTitle = null; try { @@ -2268,7 +2294,7 @@ export class FeishuHarnessBridge { currentSession: currentSessionId ? { id: currentSessionId, title: currentSessionTitle } : null, sessions, archiveVisible, presetCatalog, modelCatalog, }), - { key, updateMessageId }, + { key, updateMessageId, replyTo }, ); } @@ -2350,7 +2376,7 @@ export class FeishuHarnessBridge { /** * Gather system status and show the status card. */ - async #showStatusText(key, chatId) { + async #showStatusText(key, chatId, replyTo = null) { try { await this.#harness.ensureRunning({ signal: this.#signal }); const lines = [t('连接正常')]; @@ -2369,7 +2395,7 @@ export class FeishuHarnessBridge { : (settings.agentPreset || t('跟随默认')), })); } - await this.#send(chatId, lines.join('\n')); + await this.#send(chatId, lines.join('\n'), { replyTo }); } catch (error) { await this.#sendFailure(chatId, error, { logLabel: 'status text' }); } @@ -2787,11 +2813,12 @@ export class FeishuHarnessBridge { notify = true, validatedTarget = null, workspaceHint = null, + replyTo = null, } = {}) { const watchRequestedAt = Date.now(); const reply = async (message) => { if (!notify) return; - await this.#send(chatId, message).catch((error) => { + await this.#send(chatId, message, { replyTo }).catch((error) => { this.#logger.warn?.('[dsh-feishu] watch notification failed:', error.message); }); }; @@ -2854,10 +2881,10 @@ export class FeishuHarnessBridge { return { ok: true, changed: !existingEntry, entry: this.#state.watchEntry?.(key, resolved.sessionId) }; } - async #runUnwatch(key, chatId, target, { notify = true } = {}) { + async #runUnwatch(key, chatId, target, { notify = true, replyTo = null } = {}) { const reply = async (message) => { if (!notify) return; - await this.#send(chatId, message).catch((error) => { + await this.#send(chatId, message, { replyTo }).catch((error) => { this.#logger.warn?.('[dsh-feishu] unwatch notification failed:', error.message); }); }; @@ -2883,7 +2910,7 @@ export class FeishuHarnessBridge { return { ok: true, changed: true, entry }; } - async #showWatchList(key, chatId, { updateMessageId = null } = {}) { + async #showWatchList(key, chatId, { updateMessageId = null, replyTo = null } = {}) { const entries = this.#state.watchEntries?.(key) ?? []; // 收集可选会话(用于「添加关注」多选下拉);失败则传空数组 → 只渲染移除/列表。 let availableSessions = []; @@ -2913,6 +2940,7 @@ export class FeishuHarnessBridge { { key, updateMessageId, + replyTo, sessionWorkspace: currentWorkspace, }, ); @@ -3075,11 +3103,11 @@ export class FeishuHarnessBridge { }; } - async #sendAnswerText(chatId, answer, { deliveryId, presentation }) { + async #sendAnswerText(chatId, answer, { deliveryId, presentation, replyTo = null }) { const providerMessageIds = []; for (const chunk of splitText(answer)) { this.#signal?.throwIfAborted(); - const messageId = await this.#send(chatId, chunk); + const messageId = await this.#send(chatId, chunk, { replyTo }); if (messageId) providerMessageIds.push(messageId); } return createDeliveryReceipt({ @@ -3183,6 +3211,7 @@ export class FeishuHarnessBridge { { deliveryId: messageId, presentation: 'feishu-text', + replyTo: messageId, }, ); } catch (error) { @@ -3253,6 +3282,7 @@ export class FeishuHarnessBridge { { deliveryId: messageId, presentation: 'feishu-text-fallback', + replyTo: messageId, }, ); } catch (fallbackError) { @@ -3303,6 +3333,7 @@ export class FeishuHarnessBridge { { deliveryId: messageId, presentation: 'feishu-text-fallback', + replyTo: messageId, }, ); } catch (fallbackError) { @@ -3455,7 +3486,7 @@ export class FeishuHarnessBridge { key, actor, requiresMention, - send: (text) => this.#send(chatId, text), + send: (text) => this.#send(chatId, text, { replyTo: replyToMessageId }), })) return; // Approval requests return above; the existing question state machine stays unchanged. diff --git a/test/channels/feishu/bridge.test.mjs b/test/channels/feishu/bridge.test.mjs index 0ed693f..4ff078f 100644 --- a/test/channels/feishu/bridge.test.mjs +++ b/test/channels/feishu/bridge.test.mjs @@ -1335,6 +1335,83 @@ test('a Harness question is presented as a threaded reply inside a topic group', assert.equal(streamed.at(-1), '已完成'); }); +test('command replies in a topic group are threaded to the triggering message', async () => { + const created = []; + const replied = []; + const seen = new Set(); + const sessions = new Map([['group:oc_topic:thread:omt_cmd', 'session-cmd']]); + const bridge = new FeishuHarnessBridge({ + client: { + im: { v1: { message: { + create: async (request) => { + created.push({ + type: request.data.msg_type, + text: request.data.msg_type === 'text' + ? JSON.parse(request.data.content).text + : null, + }); + return { code: 0, data: { message_id: `om_created_${created.length}` } }; + }, + reply: async (request) => { + replied.push({ + to: request.path.message_id, + type: request.data.msg_type, + text: request.data.msg_type === 'text' + ? JSON.parse(request.data.content).text + : null, + }); + return { code: 0, data: { message_id: `om_replied_${replied.length}` } }; + }, + } } }, + }, + harness: { + ensureRunning: async () => true, + sessionExists: async () => true, + }, + state: { + hasSeen: (id) => seen.has(id), + markSeen: async (id) => seen.add(id), + sessionFor: (key) => sessions.get(key) ?? null, + setSession: async (key, sessionId) => sessions.set(key, sessionId), + clearSession: async (key) => sessions.delete(key), + }, + status: { + messagesReceived: 0, + messagesReplied: 0, + messagesRejected: 0, + lastMessageAt: null, + lastReplyAt: null, + lastRejectedAt: null, + lastError: null, + }, + allowedSenderOpenIds: new Set(['ou_user']), + }); + + bridge.accept(event('om_cmd', '/new', { + chat_type: 'group', + chat_id: 'oc_topic', + thread_id: 'omt_cmd', + })); + await eventually( + () => replied.length >= 2, + 'the /new replies were not presented as threaded replies', + ); + + assert.ok( + replied.some(({ to, text }) => to === 'om_cmd' && text?.includes('已开启全新')), + 'the /new confirmation must be delivered through the reply API targeting the command message', + ); + assert.ok( + replied.some(({ to, type }) => to === 'om_cmd' && type === 'interactive'), + 'the menu card must also be threaded to the command message', + ); + assert.equal( + created.some(({ text }) => text?.includes('已开启全新')), + false, + 'the /new confirmation must not be sent as a plain chat message outside the topic', + ); +}); + test('pending Harness questions are isolated by Feishu conversation', async () => { const fixture = stateFixture([ ['p2p:ou_a', 'session-a'],